Collage

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

java

Path with “WEB-INF” or “META-INF”
The spring boot error Path with “WEB-INF” or “META-INF” occurs when the jsp page url is invoked and the tomcat jasper dependency is not configured in the application. The jsp files are compiled and rendered using the tomcat embedded jasper maven dependency. If the maven dependency is not configured in the spring boot application, the “path with WEB-INF or META-INF” error will be shown in the console. In the spring boot application, when you access a jsp page in browser, it shows “Whitelabel Error Page, There was an unexpected error (type=Not Found, status=404).” error in the browser. The exception to this is “HTTP 404 – page not found”. In the spring boot console log, the error is shown as ‘Path with ‘WEB-INF’ or ‘META-INF’. The ResourceHttpRequestHandler class will throw the error as “o.s.w.s.r.ResourceHttpRequestHandler : Path with “WEB-INF” or “META-INF”:”   Exception The exception stack trace will be shown below. This will be displayed in the console when a jsp page is invoked. 2019-10-03 13:17:57.140 WARN 3200 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Path with "WEB-INF" or "META-INF": [WEB-INF/jsp/helloworld.jsp] 2019-10-03 13:17:57.154 WARN 3200 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Path with "WEB-INF" or "META-INF": [WEB-INF/jsp/error.jsp]   How to reproduce this issue This error can be replicated in the mvc spring boot application. Follow the steps below to reproduce this issue. Create a spring boot mvc project in the Spring Tool Suite editor. Set up the jsp folder in the application.properties file as shown below. application.properties spring.mvc.view.prefix:/WEB-INF/jsp/ spring.mvc.view.suffix:.jsp Create a rest controller class to configure and invoke a url that will map to jsp file. Create a method in the controller class and configure the request mapping url to invoke. Configure a jsp file in the method that will be rendered when the url is invoked. HelloWorldController.java package com.yawintutor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloWorldController { @RequestMapping("/HelloWorld") public ModelAndView firstPage() { return new ModelAndView("helloworld"); } } Create a jsp file that is configured in the controller class. In this example, a helloworld.jsp file is created in the src / main / webapp / WEB-INF / jsp / folder. The jsp file contains a simple message. src/main/webapp/WEB-INF/jsp/helloworld .jsp <h1>Welcome to Hello World!</h1> Open a browser and call the url as “http://localhost:8080/HelloWorld”. This url should invoke firstPage method in HelloWorldController class. The model view is configured with helloworld. the file in src/main/webapp/WEB-INF/jsp/helloworld.jsp should be rendered.   Root Cause The jsp path resolving class is available in tomcat jasper package. The dependency of tomcat jasper is not added in pom.xml. So the jsp path is not resolved by spring boot application   Solution The dependent jars are available in tomcat jasper. Add tomcat jasper dependency in pom.xml file <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency>   Ref. Path with “WEB-INF” or “META-INF” – Yawin Tutor Skip to content Home Java C Spring Boot Issues Spring Boot Python Database Others Technicals Contact Us Home Java C Spring Boot Issues Spring Boot Python Database Others Technicals Contact Us Path with “WEB-INF” or “META-INF” The spring boot error Path wi https://www.yawintutor.com/warn-3200-path-with-web-inf-or-meta-inf/  
java · Aug. 3, 2023, 9:02 a.m.
java spring
Spring Boot @WebServlet Annotation Example
TestServlet.java package com.blood.money.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet( name = "Example", description = "Example Servlet", urlPatterns = {"/Example"} ) public class TestServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); String html = "<html>"; html += "<body>"; html += "<div>THIS IS NOT A TEST</div>"; html += "</body>"; html += "</html>"; writer.println(html); } }   How do I get Spring Boot to auto-load all @WebServlet annotated servlets and honor their url mappings? Add @ServletComponentScan in your bootstrap class. such as @SpringBootApplication @ServletComponentScan public class BadApplication { public static void main(String[] args) { SpringApplication.run(BadApplication.class, args); } }  
java · June 22, 2023, 7:56 p.m.
spring Servlet
Jsoup - Working with URLs
Following example will showcase methods which can provide relative as well as absolute URLs present in the html page. Syntax String url = "http://www.tutorialspoint.com/"; Document document = Jsoup.connect(url).get(); Element link = document.select("a").first(); System.out.println("Relative Link: " + link.attr("href")); System.out.println("Absolute Link: " + link.attr("abs:href")); System.out.println("Absolute Link: " + link.absUrl("href")); Where document − document object represents the HTML DOM. Jsoup − main class to connect to a url and get the html content. link − Element object represent the html node element representing anchor tag. link.attr("href") − provides the value of href present in anchor tag. It may be relative or absolute. link.attr("abs:href") − provides the absolute url after resolving against the document's base URI. link.absUrl("href") − provides the absolute url after resolving against the document's base URI. Description Element object represent a dom elment and provides methods to get relative as well as absolute URLs present in the html page. Example 1. sample html <html> <head> <title></title> <script type="text/javascript" src="/resource/js/jquery-1.7.1.min.js"></script> <link type="text/css" href="/resource/css/admin/general.css" rel="stylesheet" /> </head> <body> <span id="navi"> <img src="https://www.phenomena.com/media/xstorage/banner/2022-03-17_PM1109_L46DRH2Y8P.png" alt="" /> </span> </body> </html> 2. code package com.bad.blood.test; import java.io.IOException; import java.net.URL; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Test { public static void main(final String[] args) throws IOException{ Document doc = Jsoup.parse( new URL("http://127.0.0.1:8080/index.html").openConnection().getInputStream(), "UTF-8", "http://127.0.0.1:8080/"); Elements elems = doc.select("[src]"); for( Element elem : elems ){ if( !elem.attr("src").equals(elem.attr("abs:src")) ){ elem.attr("src", elem.attr("abs:src")); } } elems = doc.select("[href]"); for( Element elem : elems ){ if( !elem.attr("href").equals(elem.attr("abs:href")) ){ elem.attr("href", elem.attr("abs:href")); } } System.out.println(doc.toString()); } } 3. result html <html> <head> <title></title> <script type="text/javascript" src="http://127.0.0.1:8080/resource/js/jquery-1.7.1.min.js"></script> <link type="text/css" href="http://127.0.0.1:8080/resource/css/admin/general.css" rel="stylesheet" /> </head> <body> <span id="navi"> <img src="https://www.phenomena.com/media/xstorage/banner/2022-03-17_PM1109_L46DRH2Y8P.png" alt="" /></span> </body> </html>   jsoup: Java HTML parser, built for HTML editing, cleaning, scraping, and XSS safety jsoup News Bugs Discussion Download API Reference Cookbook Try jsoup jsoup » jsoup: Java HTML Parser jsoup: Java HTML Parser jsoup is a Java library for working with real-world HTML. It provides a very convenient API for fetching URLs and extracting and m https://jsoup.org/  
java · Feb. 3, 2023, 7:10 a.m.
jsoup
Java's DecimalFormat method rounds up by force. How do we prevent that?
In https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html Customizing Formats (The Java™ Tutorials > Internationalization > Formatting) A browser with JavaScript enabled is required for this page to operate properly. Documentation The Java™ Tutorials Hide TOC Formatting Numbers and Currencies Using Predefined Formats Customizing Formats Dates and Times Using Predefined Formats Customizing https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html value: 123456.789 pattern: ###.## output: 123456.79 The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.   We can prevent that like this. package com.bad.blood.test; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; public class Test { public static void main(String args[]) { double irr = 9.7485232; DecimalFormat df = new DecimalFormat("###.00"); String str = df.format(irr); System.out.println(str); // 9.75 // method 1 String str2 = String.valueOf(irr); System.out.println(str2.substring(0, str2.indexOf('.') + 3)); // 9.74 // method 2 System.out.println( (double)(int)(irr * 100) / 100 ); // 9.74 // method 3 NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setRoundingMode(RoundingMode.DOWN); nf.setGroupingUsed(true); System.out.println(nf.format(irr)); // 9.74 } } output: 9.75 9.74 9.74 9.74  
java · Feb. 3, 2023, 6:35 a.m.
Type conversion in Java
Converting int to string String myString = Integer.toString(my int value) or  String str = "" + i   Converting String to int int i = Integer.parseInt(str); or  int i = Integer.valueOf(str).intValue();   Double to String : String str = Double.toString(i);   Long to String : String str = Long.toString(l);   Float to String : String str = Float.toString(f);   String to double : double d = Double.valueOf(str).doubleValue();   String to long : long l = Long.valueOf(str).longValue(); or long l = Long.parseLong(str);   String to float : float f = Float.valueOf(str).floatValue(); Decimal to binary : int i = 42; String binstr = Integer.toBinaryString(i); Decimal to hexadecimal : int i = 42; String hexstr = Integer.toString(i, 16); or String hexstr = Integer.toHexString(i); or (with leading zeroes and uppercase) public class Hex {      public static void main(String args[]){        int i = 42;        System.out.print        (Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());       } }   Hexadecimal (String) to integer : int i = Integer.valueOf("B8DA3", 16).intValue(); or int i = Integer.parseInt("B8DA3", 16);     ASCII code to String int asciiVal = 87; String str = new Character((char) asciiVal).toString();   Float to integer (Round off the decimal place) float a = 1.1f; float b = 2.1f; int i = ((int)(100-a/b*100)); System.out.println(i); // 47  
java · Feb. 3, 2023, 5:55 a.m.
How does one display progress of a file copy operation in Java. without using Swing e.g. in a Web app?
Here is how to copy a file in java and monitor progress on the commandline: package com.bad.blood.test; import java.io.*; import org.springframework.util.ResourceUtils; public class FileCopyProgress { public static void main(String[] args) throws FileNotFoundException { System.out.println("copying file"); File filein = ResourceUtils.getFile("classpath:static/images/5941188.png"); File fileout = new File("src/main/resources/static/images/5941188_copy.png"); FileInputStream fin = null; FileOutputStream fout = null; long length = filein.length(); long counter = 0; int r = 0; byte[] b = new byte[1024]; try { fin = new FileInputStream(filein); fout = new FileOutputStream(fileout); while( (r = fin.read(b)) != -1) { counter += r; System.out.println( 1.0 * counter / length ); fout.write(b, 0, r); } } catch(Exception e){ System.out.println("foo"); } } } Result: copying file 0.0012724448586517551 0.0025448897173035103 0.0038173345759552656 0.0050897794346070205 0.006362224293258776 ... 0.9950518794656725 0.9963243243243243 0.9975967691829761 0.9988692140416279 1.0 ref. https://www.baeldung.com/java-copy-file https://stackoverflow.com/questions/44399422/read-file-from-resources-folder-in-spring-boot https://stackoverflow.com/questions/11182114/how-does-one-display-progress-of-a-file-copy-operation-in-java-without-using-sw
java · Jan. 16, 2023, 9:01 p.m.
Encoding URL query parameters in Java
Q: How does one encode query parameters to go on a url in Java? A: java.net.URLEncoder.encode(String s, String encoding) can help too. It follows the HTML form encoding application/x-www-form-urlencoded. URLEncoder.encode(query, "UTF-8"); On the other hand, Percent-encoding (also known as URL encoding) encodes space with %20. Colon is a reserved character, so : will still remain a colon, after encoding. ref. https://stackoverflow.com/questions/5330104/encoding-url-query-parameters-in-java
java · Jan. 16, 2023, 8:34 p.m.
urlencode
Parse Alexa API XML Response
1. Send a request to the following Alexa API. https://data.alexa.com/data?cli=10&url=phenomena.com 2. The Alexa API will return the following XML response. The Alexa ranking is inside the POPULARITY element, the TEXT attribute. <!-- Need more Alexa data? Find our APIs here: https://aws.amazon.com/marketplace/seller-profile?id=4a9dbf38-88b1-4e87-a459-271154a77d2e --> <ALEXA VER="0.9" URL="phenomena.com/" HOME="0" AID="=" IDN="phenomena.com/"> <SD> <POPULARITY URL="phenomena.com/" TEXT="3713994" SOURCE="panel"/> <REACH RANK="3404850"/> <RANK DELTA="+652325"/> </SD> </ALEXA> 3. We use a DOM parser to directly select the POPULARITY element and print out the value of the TEXT attribute. package com.bad.blood.test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class ReadXmlAlexaApi { private static final String ALEXA_API = "http://data.alexa.com/data?cli=10&url="; private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); public static void main(String[] args) { ReadXmlAlexaApi obj = new ReadXmlAlexaApi(); int alexaRanking = obj.getAlexaRanking("phenomena.com"); System.out.println("Ranking: " + alexaRanking); } public int getAlexaRanking(String domain) { int result = 0; String url = ALEXA_API + domain; try { URLConnection conn = new URL(url).openConnection(); try (InputStream is = conn.getInputStream()) { // unknown XML better turn on this dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); Document doc = dBuilder.parse(is); Element element = doc.getDocumentElement(); // find this tag "POPULARITY" NodeList nodeList = element.getElementsByTagName("POPULARITY"); if (nodeList.getLength() > 0) { Element elementAttribute = (Element) nodeList.item(0); String ranking = elementAttribute.getAttribute("TEXT"); if (!"".equals(ranking)) { result = Integer.parseInt(ranking); } } } } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("Invalid request for domain : " + domain); } return result; } } The domain phenomena.com ranked 3713994. Ranking: 3713994 ref. https://mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
java · Jan. 16, 2023, 8:24 p.m.
XML
A simple way to read an XML file in Java
1. XML File <book> <person> <first>Kiran</first> <last>Pai</last> <age>22</age> </person> <person> <first>Bill</first> <last>Gates</last> <age>46</age> </person> <person> <first>Steve</first> <last>Jobs</last> <age>40</age> </person> </book> 2. Program Listing import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class ReadAndPrintXMLFile{ public static void main (String argv []){ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("book.xml")); // normalize text representation doc.getDocumentElement ().normalize (); System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName()); NodeList listOfPersons = doc.getElementsByTagName("person"); int totalPersons = listOfPersons.getLength(); System.out.println("Total no of people : " + totalPersons); for(int s=0; s<listOfPersons.getLength() ; s++){ Node firstPersonNode = listOfPersons.item(s); if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){ Element firstPersonElement = (Element)firstPersonNode; //------- NodeList firstNameList = firstPersonElement.getElementsByTagName("first"); Element firstNameElement = (Element)firstNameList.item(0); NodeList textFNList = firstNameElement.getChildNodes(); System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim()); //------- NodeList lastNameList = firstPersonElement.getElementsByTagName("last"); Element lastNameElement = (Element)lastNameList.item(0); NodeList textLNList = lastNameElement.getChildNodes(); System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim()); //---- NodeList ageList = firstPersonElement.getElementsByTagName("age"); Element ageElement = (Element)ageList.item(0); NodeList textAgeList = ageElement.getChildNodes(); System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim()); //------ }//end of if clause }//end of for loop with s var }catch (SAXParseException err) { System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ()); System.out.println(" " + err.getMessage ()); }catch (SAXException e) { Exception x = e.getException (); ((x == null) ? e : x).printStackTrace (); }catch (Throwable t) { t.printStackTrace (); } //System.exit (0); }//end of main } 3. Program Output Root element of the doc is book Total no of people : 3 First Name : Kiran Last Name : Pai Age : 22 First Name : Bill Last Name : Gates Age : 46 First Name : Steve Last Name : Jobs Age : 40 https://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/
java · Jan. 16, 2023, 8:15 p.m.
XML
Get MD5 Base64 : MD5 Message Digest algorithm
package com.bad.blood.test; /* * $Header: /cvsroot/mvnforum/mvnforum/contrib/phpbb2mvnforum/src/org/mvnforum/util/MD5.java,v 1.6 2007/01/15 10:27:31 dungbtm Exp $ * $Author: dungbtm $ * $Revision: 1.6 $ * $Date: 2007/01/15 10:27:31 $ * * * Copyright (C) 2002-2007 by MyVietnam.net * * All copyright notices regarding mvnForum MUST remain * intact in the scripts and in the outputted HTML. * The "powered by" text/logo with a link back to * http://www.mvnForum.com and http://www.MyVietnam.net in * the footer of the pages MUST remain visible when the pages * are viewed on the internet or intranet. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Support can be obtained from support forums at: * http://www.mvnForum.com/mvnforum/index * * Correspondence and Marketing Questions can be sent to: * info at MyVietnam net * * @author: */ import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; // The JavaReference.com Software License, Version 1.0 // Copyright (c) 2002-2005 JavaReference.com. All rights reserved. // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. The end-user documentation included with the redistribution, if any, must // include the following acknowlegement: // // "This product includes software developed by the Javareference.com // (http://www.javareference.com/)." // // Alternately, this acknowlegement may appear in the software itself, if and // wherever such third-party acknowlegements normally appear. // // 4. The names "JavaReference" and "Javareference.com", must not be used to // endorse or promote products derived from this software without prior written // permission. For written permission, please contact webmaster@javareference.com. // // 5. Products derived from this software may not be called "Javareference" nor may // "Javareference" appear in their names without prior written permission of // Javareference.com. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // JAVAREFERENCE.COM OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Software from this site consists of contributions made by various individuals // on behalf of Javareference.com. For more information on Javareference.com, // please see http://www.javareference.com /** * @author anandh */ public class MD5 { static char[] carr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String getBase64FromHEX(String input) { byte barr[] = new byte[16]; int bcnt = 0; for (int i = 0; i < 32; i += 2) { char c1 = input.charAt(i); char c2 = input.charAt(i + 1); int i1 = intFromChar(c1); int i2 = intFromChar(c2); barr[bcnt] = 0; barr[bcnt] |= (byte) ((i1 & 0x0F) << 4); barr[bcnt] |= (byte) (i2 & 0x0F); bcnt++; } return new String(Base64.getEncoder().encode(barr)); } public static synchronized String getMD5_Base64(String input) { // please note that we dont use digest, because if we // cannot get digest, then the second time we have to call it // again, which will fail again MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception ex) { ex.printStackTrace(); } if (digest == null) return input; // now everything is ok, go ahead try { digest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] rawData = digest.digest(); return new String(Base64.getEncoder().encode(rawData)); } private static int intFromChar(char c) { char clower = Character.toLowerCase(c); for (int i = 0; i < carr.length; i++) { if (clower == carr[i]) { return i; } } return 0; } public static void main(String[] args) { //String password = args[0]; String password = "phenomena"; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { digest.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] rawData = digest.digest(); StringBuffer printable = new StringBuffer(); for (int i = 0; i < rawData.length; i++) { printable.append(carr[((rawData[i] & 0xF0) >> 4)]); printable.append(carr[(rawData[i] & 0x0F)]); } String phpbbPassword = printable.toString(); System.out.println("PHPBB : " + phpbbPassword); System.out.println("MVNFORUM : " + getMD5_Base64(password)); System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword)); } } result: PHPBB : 93625b136e47b789af88d9c766b40064 MVNFORUM : k2JbE25Ht4mviNnHZrQAZA== PHPBB->MVNFORUM : k2JbE25Ht4mviNnHZrQAZA== ref. http://www.java2s.com/Tutorial/Java/0490__Security/GetMD5Base64.htm
java · Jan. 16, 2023, 8:19 a.m.
MD5
Encoding / Decoding as Base64 in 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
java · Jan. 16, 2023, 8:06 a.m.
base64 encode decode
Play with JSoup
Removing Html tags except few specific ones from String in java public String clean(String unsafe){ Whitelist whitelist = Whitelist.none(); whitelist.addTags(new String[]{"p","br","ul"}); String safe = Jsoup.clean(unsafe, whitelist); return StringEscapeUtils.unescapeXml(safe); } For input string String unsafe = "<p class='p1'>paragraph</p>< this is not html > <a link='#'>Link</a> <![CDATA[<sender>John Smith</sender>]]>"; I get following output which is pretty much I require. <p>paragraph</p>< this is not html > Link <sender>John Smith</sender>
java · Jan. 14, 2023, 2:24 a.m.
jsoup
  • 1 (current)
  • 2
Recommended for you