スキップしてメイン コンテンツに移動

投稿

ラベル(Java)が付いた投稿を表示しています

Encode Java Object to XML and Decode XML to Java Object

In current software development world, serializing object to some human readable format such as "XML", "JSON" is quite common. In this post I will show you a small code snippet for encoding Java Object to XML and decoding XML to Java Object only using Java Standard API. I think this approach is suitable if you need to quick and simple solution to encoding and decoding java object to XML string. Actually code is very simple. Please see the code below :) If you need to input or output XML to file, you should pass FileOutputStream or FileInputStream instead of ByteArrayOutputStream or ByteArrayInputStream. package com.dukesoftware.utils.xml; import java.beans.XMLDecoder; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; public class XMLUtils { public final static Object decodeToXML(String file) throws FileNotFoundException{ try(XMLDecoder decoder =

Java: Joining String Array with Separator (Equilvarent to PHP implode)

If you would like to join array with a separator, what will you do? e.g. Joining "a","b","c" with separator "," to "a,b,c". In PHP, you just use implode function. Actually PHP has a lot of functions like manipulating, converting string and array. In java, these kind of functions are not provided in official JDK. If you are familiar with Java Libraries, you just use them. - Joiner in google Guava, StringUtils in Apache Coommons. I will show you quick code snippet for jonining or imploding java string array with a separator. private static String join(String[] pieces, String separator) { if(pieces.length == 0) return ""; StringBuilder sb = new StringBuilder(pieces[0]); for(int i = 1; i < pieces.length; i++) { sb.append(separator).append(pieces[i]); } return sb.toString(); } If the number of array elements is zero, the method returns empty string, but if you would not prefer this

Treat XPath Only Using Library Provided by Java SDK

Have you ever treated XML only using library provided in Java SDK? I think many people use external library for treating XML in Java. To be honest, I would prefer to use JDom ;P But I think it's good thing to know how to treat XML only using Java SDK. I will show you small code snippet for treating XML especially from XPath usage. The classes you should remember for treating XML is: DocumentBuilderFactory DocumentBuilder Document XPathFactory XPath XPathExpression XPathConstants NodeList Node Oops, a bit quite too much. Anyway I will show you an example code for reading XML string and select nodes by XPath. package com.dulesoftware.xpath; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax

Java 8 Lambda Expression

I am very excited about new Java 8 features, especially lambda expression. I am jealous that C# had lambda expression when it was introduced in C# 3.0 loooong time ago. Let me show you a power of lambda expression by simple code example - FileFiter. Why I choose this example? Well, I have been so frustrated that I always had to write a bit redundant code even if for very simple FileFilter. Please see following example code. Hope the example attracts you... package com.dukesoftware.io; import java.io.File; import java.io.FileFilter; public class FileFilters { // legacy file filter - no lambda expression public static final FileFilter DIRECTORY_FILTER_BEFORE_JAVA8_NO_LAMBDA = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }; // basic lambda expression introduced since java 8 public static final FileFilter DIRECTORY_FILTER_JAVA8_LAMBDA_FIRST = (File pathname) -&g

Java: Create Index PNG Using PNGJ 2.1.1

Introduction I have written java code for generating indexed png using pngj version 0.94. Now pngj version 2.1.1 has been released on 2014/6/1. So I have refined the code for generating indexed png so that the code suits with pngj version 2.1.1. Code package com.dukesoftware.utils.image.pngj; import ar.com.hjg.pngj.IImageLine; import ar.com.hjg.pngj.ImageInfo; import ar.com.hjg.pngj.ImageLineInt; import ar.com.hjg.pngj.PngReader; import ar.com.hjg.pngj.PngWriter; import ar.com.hjg.pngj.chunks.ChunkCopyBehaviour; import ar.com.hjg.pngj.chunks.PngChunkSingle; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public final class PngUtils { private static final int _1K_BYTES = 1024; public static void toIndexed256Colors(File input, File output) throws IOException { PngReader png1 = new PngReader(input); ImageInfo pnginfo1 = png1.imgInf

Java: Create Indexed PNG Image Using Standard Java Image API

Hello guys! I have written Java: How to Create Indexed PNG Using PNGJ Library a few years ago. Recently I investigated how to create indexed png by standard Java image API. I have googled and tested various methods, finally I figureed out how to create indexed png image. Still my program is not perfect (of course most of the case it worked well), I believe that this program gives you the hint to creating indexed png and image manipulation on standard Java API. Code Actually the method is quite straigt forward. Please see the code below :) The advantedge of this code is the code doesn't require any library. The code below contains all of the stuffs needed for creating indexed png image! package com.dukesoftware.util.image; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.IndexColorModel; import java.io.File; import java.

Check Youtube Video Existance by ID

I have managed a lot of youtube videos (not owned by me) by youtube video ID to show them on my web page. But sometimes videos were unavailable suddenly (because of copyright issues or simply deleted etc.) So I have created tiny program for check availablitiy of youtube videos by youtube video ID. Here is the code. // print out unavailable videos String[] ids = new String[]{"id1", "id2"}; for(String id : ids) { Thread.sleep(1000); if(!checkExistance(id)) { System.out.println(id); } } public static String checkExistance(String id) { try{ // any method is fine as long as you can get contents from url getStringContentsFromURL("https://gdata.youtube.com/feeds/api/videos/"+id, "utf-8"); } catch(Exception e) { return false; } return true; } Example implementation for getStringContentsFromURL method. Sorry the implementation is a bit circumlocutory because I designed the co

Java: Shuffling Elements in Array

I will show you java code for shuffling order of elements in array randomly. Only one thing you should notice is generating random is quite sensitive problem in a precise sense. I use java Random class which is provided by JDK. However if you need to use more proper randomness, you may implement class for generate random number sequence yourself. Anyway, the code is below. package com.dukesoftware.utils.math; import java.util.Random; public class Shuffler { private final Random random; public Shuffler(Random random) { this.random = random; } public void shuffle(int[] a) { for (int i = a.length - 1; i > 0; i--) { int j = random.nextInt(i + 1); // 0 <= j <= i int swap = a[i]; a[i] = a[j]; a[j] = swap; } } public void shuffle(double[] a) { for (int i = a.length - 1; i > 0; i--) { int j = random.nextInt(i + 1); // 0 <= j <= i double swap =

Drag & Drop Image File onto Java Swing Component

In this post I will show you how to achieve drag and drop image file onto Java Swing Component. In short, implment TransferHandler which can transfer image file. Code Here is the code I wrote. I defined common closure interface in order to give implementation flexibility. The exec method of imageAcceptor will be called with Image object when drag & drop is succeeded. package com.dukesoftware.utils.swing.drag; import java.awt.Image; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.imageio.ImageIO; import javax.swing.TransferHandler; import com.dukesoftware.utils.common.Closure; public class ImageFileTransferHandler extends TransferHandler { private final static Set<String> SUPPORTED_SUFIXES = new HashSet<>(Arr

Java Customize Serialization - Using Externalizable

I will show you how to customize Java serialization (Externalization), performance comparison default serialization vs my externalization implmentation in this post. In the most cases, you don't have to care about the serialization performance of default implementation. But the default implementation uses reflection so it might be a problem if you develop performance critical application. Externalizable Implement your own serialization is very simple. Just implements Externailizable interface into the class. Here is the example code - simple pojo class and TreeMap which implements Externalizable. package com.dukesoftware.demos.externalizable; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.List; public class ExternalizableClass implements Externalizable{ private String field1; private Double field2; private List<String> field3; public S

Render FPS Text on Java Swing Component

In the previous post , I showed helper class for 2D animation on Java Swing component. If we can measure the frame rate of animation, it is very great, isn't it? In this post, I will show you that kind of class - rendering FPS text on swing component. Showing code is fast and snappy :p Here is the code - count frame per 1 sec. package com.dukesoftware.utils.awt.graphics; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.text.DecimalFormat; public class FPSText { protected static final String FPS = "FPS: "; private static final int FONT_SIZE = 24; private static final int FONT_STYLE = Font.BOLD; private static final String FONT_NAME = "SansSerif"; protected final static Color COLOR = new Color(0.55f,0.55f,0.55f); protected double frameCount; protected final DecimalFormat format = new DecimalFormat("####.00"); protected String fpsText; protected fin

Java 2D Animation on Swing

In this post, I will show you some tips (or tools) for 2D animation on Java Swing component. There are 2 ways to rendering animation on Swing compinent - Thread vs Timer. I think Swing rendering is based on single thread model, so we should use Timer. But I have used separate thread for executing animation and it works fine, so should be fine for not critical application. Animator class Ok then, I can show you a simple animator canvas class I created. The class takes Model2D for actual animate model and render it. One thing you should remember - AnimateCanvas calculate model of animation (coodinates or position or whatever) on animation rendering process, so if the calculation takes takes log time, the animation cannot meet the frame per second passed to constructor. package com.dukesoftware.utils.swing.others; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.aw

Java: Get Exchange Rate From Yahoo Finance Api

In this post, I will show you how to retrieve currency exchange rate from yahoo finance api by Java program. There are some apis for getting exchange rate - reuters, bloomberg, yahoo finance etc. If you don't have to get high-ratency realtime exchange rate, the most simple and free api - yahoo finance api - is enough. Okay, here is the actual code. The api returns exchange rate as a Rate object. package com.dukesoftware.exchangerate.api; import static java.lang.String.format; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; public class YahooExchangeRateApi implements ExchangeRateApi { // url for yahoo finance api private final static String URL_FORMAT = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=%s%s=X"; public Rate getRate(String ccy1, String ccy2) { assertNotNull(ccy1, "

Get Root Cause of Java Exception

I think sometimes you would like to simply extract root cause of exception. The following method will help you. public final static Throwable getRootCause(Throwable t){ for(Throwable s = t.getCause() ;s != null;){ s = t.getCause(); t = s; } return t; }

Create Stack Trace String from Java Exception

Maybe many times you would like to generate stack trace string from Exception thrown. The code below will help you! public final static String createStackTraceString(Exception e){ StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw, false); e.printStackTrace(writer); return sw.toString(); }

Java: Extract img src from HTML

Here is an code snippet for extracting image src from html. private static final Pattern IMG_SRC_PATTERN = Pattern.compile("<img\\s+.*src\\s*=\\s*('|\")(.+?)\\1.+?>"); public static List<String> extractImgSrces(final String content) { List<String> list = new ArrayList<>(); final Matcher matcher = IMG_SRC_PATTERN.matcher(content); while(matcher.find()){ list.add(matcher.group(2)); } return list; } The example usage is below. In this example, you should only prepare HttpUtils.getStringContentsFromURL method, which is getting html from given url, for your self. public static void main(String[] args) throws URISyntaxException, IOException { extractImgSrces(HttpUtils.getStringContentsFromURL("http://www.google.com/", "utf-8")).stream().forEach(System.out::println); }

Get Original Hi-res image from Zoomable image on Amazon

Some pages in amazon provide images which user can zoom on, like this page. The question is "Where is the original hi-resolution image?". You can easily find the explanation page for how to construct url for original hi-res image. (See this stack overflow page .) In this post I will show you the code snippet for getting original hires imgae from ASIN code. Note!: This method might be unavailable if amazon change the implementation of zoom and hires image url construnction. Code Actually code is nothing special. Just find " DynAPI.addZoomViewer( " . // pattern for extracting image code used for retrieving original image. private static Pattern AMAZON_ZOOM_IMAGE_PATTERN = Pattern.compile("DynAPI\\.addZoomViewer\\(\".+/(.+?)\",\\s*(.+?),\\s*(.+?),\\s*(.+?),\\s*(.+?),\\s*(.+?),.*\\)"); public static String findOriginalZoomImageUrl(String asin, String country) { String url = getAmazonZoomImageWindowUrl(asin, country); try{

How to pick up Hi-Resolution Image from Amazon product page

Recently I realized that Amazon offers high resolution photos in some products. I have found the way to extract these hires images. Note Note!: This method might be unavailable in the future because Amazon may not like this kind of hack or change the implementation :P Basic Strategy For example, this page: http://www.amazon.com/Silver-Violin-Nicola-Benedetti/dp/B008CYV046/ If you see the html source of this page, you can find the following json string. var colorImages = {"initial":[{"large":"http://ecx.images-amazon.com/images/I/XXXXXXX.jpg",.... It represents the urls of various size of images. If you would like to see the hi-resolution image, you should pick up the url which is defined in hiRes property. Source Code You know I still like Java, I will show you the simple Java code. I use Jackson for parsing JSon string. import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; imp