Collage

n. A piece of art made by sticking various different materials, aka PHENOMENA Magazine
Department
java

java

package com.bad.blood.test; import java.security.InvalidKeyException; import java.security.Key; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; public class LocalEncrypter { private static String algorithm = "DESede"; private static Key key = null; private static Cipher cipher = null; private static void setUp() throws Exception { key = KeyGenerator.getInstance( algorithm ).generateKey(); cipher = Cipher.getInstance( algorithm ); } public static void main(String [] args) throws Exception { setUp(); byte [] encryptionBytes = null; String input = "phenomena"; System.out.println( "Entered: " + input ); encryptionBytes = encrypt( input ); String encodeString = new String(Base64.getEncoder().encode(encryptionBytes)); System.out.println( "Base64 Encode: " + encodeString ); System.out.println( "Recovered: " + decrypt( Base64.getDecoder().decode(encodeString) ) ); } private static byte [] encrypt(String input) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException { cipher.init( Cipher.ENCRYPT_MODE, key ); byte [] inputBytes = input.getBytes(); return cipher.doFinal(inputBytes); } private static String decrypt(byte [] encryptionBytes) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException { cipher.init( Cipher.DECRYPT_MODE, key ); byte [] recoveredBytes = cipher.doFinal( encryptionBytes ); String recovered = new String( recoveredBytes ); return recovered; } } result: Entered: phenomena Base64 Encode: lfE0CaaNbx1sGUJk6dwgjQ== Recovered: phenomena ref. https://stackoverflow.com/questions/13109588/encoding-as-base64-in-java   * Image to Base64 String Conversion package com.bad.blood.test; import java.io.File; import java.io.IOException; import java.util.Base64; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; import static org.junit.Assert.assertTrue; public class FileToBase64StringConversionUnitTest { private String inputFilePath = "test_image.jpg"; private String outputFilePath = "test_image_copy.jpg"; @Test public void fileToBase64StringConversion() throws IOException { // load file from /src/test/resources ClassLoader classLoader = getClass().getClassLoader(); File inputFile = new File(classLoader .getResource(inputFilePath) .getFile()); byte[] fileContent = FileUtils.readFileToByteArray(inputFile); String encodedString = Base64 .getEncoder() .encodeToString(fileContent); // create output file File outputFile = new File(inputFile .getParentFile() .getAbsolutePath() + File.pathSeparator + outputFilePath); // decode the string and write to file byte[] decodedBytes = Base64 .getDecoder() .decode(encodedString); FileUtils.writeByteArrayToFile(outputFile, decodedBytes); assertTrue(FileUtils.contentEquals(inputFile, outputFile)); } } ref. https://www.baeldung.com/java-base64-image-string
John Doe · Jan. 16, 2023, 8:06 a.m.
base64 encode decode
Removing everything but numbers from String String value = string.replaceAll("[^0-9]",""); String clean1 = string1.replaceAll("[^0-9]", ""); or String clean2 = string2.replaceAll("[^\\d]", ""); Where \d is a shortcut to [0-9] character class, or String clean3 = string1.replaceAll("\\D", ""); Where \D is a negation of the \d class (which means [^0-9])   Using Match, Pattern class in java.util.regex boolean bln = Pattern.matches("^[a-zA-Z0-9]*$", this.input); ^ : 문자열의 시작 $ : 문자열의 종료 . : 임의의 한 문자(문자의 종류는 가리지 않음) | : or ? : 앞 문자가 없거나 하나있음. + : 앞 문자가 하나 이상임. * : 앞 문자가 없을 수도 무한정 많을 수도 있음을 나타냄. 만약, .* 으로 정규식이 시작한다면 시작하는 문자열과 같은 문자열이 뒤에 없거나 많을 수도 있는 경우에만 일치를 시킨다. 즉, abc 일 경우 시작문자인 a를 기준으로 a가 없을경우와 a가 무한정 많은 경우에도 true를 반환하기 때문에 abc의 경우는 true를 반환한다. [] : 문자 클래스를 지정할 때 사용. 문자의 집합이나 범위를 나타내면 두 문자 사이는 '-' 기호로 범위를 나타낸다. []내에서 ^ 가 선행하여 나타나면 not를 나타낸다. {} : 선행문자가 나타나는 횟수 또는 범위 a{3} 인 경우 a가 3번 반복된 경우 / a{3,}이면 a가 3번 이상 반복인 경우. 또한 a{3,5}인 경우 a가 3번 이상 5번 이하 반복된 경우를 나타냄 \w : 알파벳이나 숫자 \W : 알파벳이나 숫자를 제외한 문자 \d : 숫자 [0-9]와 동일 \D : 숫자를 제외한 모든 문자 ^[0-9]*$ : only number ^[a-zA-Z]*$ : only English ^[가-힣]*$ : only Korean ^[a-zA-Z0-9]*$ : English/number   e.g. 1) email : ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$  or  ^[_0-9a-zA-Z-]+@[0-9a-zA-Z-]+(.[_0-9a-zA-Z-]+)*$ cellphone :  ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$ phone : ^\d{2,3} - \d{3,4} - \d{4}$ id : \d{6} \- [1-4]\d{6} IP addr : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) https://stackoverflow.com/questions/6883579/java-regular-expression-removing-everything-but-numbers-from-string   2) How to test if a String contains both letters and numbers .matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$") The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.   3) How can I de-duplicate repeated characters in a Java string? how________are_______you to how_are_you string.replaceAll("_+", "_")
John Doe · Jan. 12, 2023, 2:56 a.m.
regex
Q : Where can I download JSTL taglibs? i.e. jstl.jar and standard.jar A : If you're running a Servlet 2.5 compatible container and the web.xml is declared as at least Servlet 2.5, then you should be able to use the new JSTL 1.2 instead. Note that JSTL 1.2 does not require a standard.jar. Q : The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path A : Add a runtime first and select project properties. Then check the server name from the 'Runtimes' tab Q : Remove html tags from string using java A :  String noHTMLString = htmlString.replaceAll("\\<.*?>",""); Using Jsoup public static String html2text(String html) { return Jsoup.parse(html).text(); } https://stackoverflow.com/questions/4432560/remove-html-tags-from-string-using-java Q : JSPX A : https://jspx-bay.sourceforge.net/ Q : Apache Jakarta A : http://archive.apache.org/dist/jakarta/ Q : Prevent download attempts of videos in a video server A : Silverlight might be an idea to start with. Q : mp3 header information reader not working A : import org.farng.mp3.MP3File; you need to call mp3file.seekMP3Frame(); before attempting to retrieve bitrate, this method will read the file headers including the bitrate. or use http://www.jthink.net/jaudiotagger/examples_id3.jsp Q : How to get the message in a custom error page (Tomcat)? A : <c:out value="${requestScope['javax.servlet.error.message']}"/> javax.servlet.error.status_code java.lang.Integer javax.servlet.error.exception_type java.lang.Class javax.servlet.error.message java.lang.String javax.servlet.error.exception java.lang.Throwable javax.servlet.error.request_uri java.lang.String javax.servlet.error.servlet_name java.lang.String * <c:catch> Tag <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title><c:catch> Tag Example</title> </head> <body> <c:catch var ="catchException"> <% int x = 5/0;%> </c:catch> <c:if test = "${catchException != null}"> <p>The exception is : ${catchException} <br /> There is an exception: ${catchException.message}</p> </c:if> </body> </html> Q : Get current action in jsp - struts2 A :  <s:url forceAddSchemeHostAndPort="true" includeParams="all"/> Q : Oracle date to Java date A : little h for "Hour in am/pm (1-12)" and H for "Hour in day (0-23)" see here: SimpleDateFormat SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); Date date = dateFormat.parse("2011-08-19 06:11:03.0"); Q : How to get previous URL? A :  HttpServletRequest.getHeader("Referer"); Q : [JSP] 파일 다운로드창에서 한글깨짐 방지? A : response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8") + ";");
John Doe · Jan. 12, 2023, 2:03 a.m.
This is a proof of concept only Disclaimer: Before I get a bunch of hate mail about the, obviously, horrible things I've done to make this work, I stole most of the painting code straight out of the source, this is how it's actually done within the look and feel code itself :P I've also gone to the nth degree, meaning that I've literally assumed that you wanted the row headers to look like the column headers. If this isn't a requirement, it would be SO much easier to do... Okay, this is a basic proof of concept, which provides the means to generate the row header and render them the same way as they are normally, just as row headers instead. Things that need to be added/supported: Detect when the table model is changed (that is, a new table model is set to the table) Detect when the column model is changed (that is, a new column model is set to the table) Much of this functionality would probably need to be added to the TableWithRowHeader implementation... Basically, what this "tries" to do, is create a custom row header, based on a JTableHeader, remove the existing column header and add itself into the row header view position of the enclosing JScrollPane. import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; public class TableRowHeaderTest { public static void main(String[] args) { new TableRowHeaderTest(); } public TableRowHeaderTest() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } Object rowData1[][] = { {"", "", "", ""}, {"", "", "", ""}, {"", "", "", ""}, {"", "", "", ""} }; Object columnNames1[] = {"HEADER 1", "HEADER 2", "HEADER 3", "HEADER 4"}; JTable table1 = new TableWithRowHeader(rowData1, columnNames1); table1.getColumnModel().getColumn(0).setPreferredWidth(120); JScrollPane scrollPane1 = new JScrollPane(table1); scrollPane1.setColumnHeaderView(null); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(scrollPane1); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TableWithRowHeader extends JTable { private TableRowHeader rowHeader; public TableWithRowHeader(final Object[][] rowData, final Object[] columnNames) { super(rowData, columnNames); rowHeader = new TableRowHeader(this); } @Override protected void configureEnclosingScrollPane() { // This is required as it calls a private method... super.configureEnclosingScrollPane(); Container parent = SwingUtilities.getUnwrappedParent(this); if (parent instanceof JViewport) { JViewport port = (JViewport) parent; Container gp = port.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; JViewport viewport = scrollPane.getViewport(); if (viewport == null || SwingUtilities.getUnwrappedView(viewport) != this) { return; } scrollPane.setColumnHeaderView(null); scrollPane.setRowHeaderView(rowHeader); } } } } public class TableRowHeader extends JTableHeader { private JTable table; public TableRowHeader(JTable table) { super(table.getColumnModel()); this.table = table; table.getColumnModel().addColumnModelListener(new TableColumnModelListener() { @Override public void columnAdded(TableColumnModelEvent e) { repaint(); } @Override public void columnRemoved(TableColumnModelEvent e) { repaint(); } @Override public void columnMoved(TableColumnModelEvent e) { repaint(); } @Override public void columnMarginChanged(ChangeEvent e) { repaint(); } @Override public void columnSelectionChanged(ListSelectionEvent e) { // Don't care about this, want to highlight the row... } }); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { repaint(); } }); } public JTable getTable() { return table; } @Override public Dimension getPreferredSize() { Dimension size = new Dimension(); JTable table = getTable(); if (table != null) { TableColumnModel model = table.getColumnModel(); if (model != null) { for (int index = 0; index < model.getColumnCount(); index++) { TableColumn column = model.getColumn(index); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, index); size.width = Math.max(comp.getPreferredSize().width, size.width); size.height += table.getRowHeight(index); } } } return size; } /** * Overridden to avoid propagating a invalidate up the tree when the * cell renderer child is configured. */ @Override public void invalidate() { } /** * If the specified component is already a child of this then we don't bother doing anything - stacking order doesn't matter for cell renderer components * (CellRendererPane doesn't paint anyway). */ @Override protected void addImpl(Component x, Object constraints, int index) { if (x.getParent() == this) { return; } else { super.addImpl(x, constraints, index); } } @Override protected void paintComponent(Graphics g) { // super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(getBackground()); g2d.fillRect(0, 0, getWidth(), getHeight()); JTable table = getTable(); if (table != null) { int width = getWidth(); TableColumnModel model = table.getColumnModel(); if (model != null) { for (int index = 0; index < model.getColumnCount(); index++) { TableColumn column = model.getColumn(index); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = getDefaultRenderer(); } boolean selected = table.getSelectedRow() == index; Component comp = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), selected, false, 0, index); add(comp); comp.validate(); int height = table.getRowHeight(index) - 1; comp.setBounds(0, 0, width, height); comp.paint(g2d); comp.setBounds(-width, -height, 0, 0); g2d.setColor(table.getGridColor()); g2d.drawLine(0, height, width, height); g2d.translate(0, height + 1); } } } g2d.dispose(); removeAll(); } } } Disclaimer: This is likely to blow up in your face. I make no checks for preventing the header from responding to things like changes to the column row sortering and ... in theory ... it shouldn't try and "resize" the column but I didn't test that... https://stackoverflow.com/questions/26248084/how-to-display-row-header-on-jtable-instead-of-column-header
John Doe · Jan. 12, 2023, 1:36 a.m.
JTable swing
  • 1
  • 2 (current)