Tuesday, February 16, 2016

Image Resizing by java, Change JPEG image quality

I have seen sample code from others to resize image and change jpeg quality by java. It was pretty good. but, just I didn't like one thing that most of them didn't close the stream of file reading or writing. So, The image files were not able to removed or rewrited. I guess probably, it will cause to create jomby process which is never die unless restart JVM. Thease kind of things must be avoided to make a stable application. It will not be visible for now. but, It will capture the application one day and make difficult to find out why application is not stable.

Add Maven Dependendy to resize image

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.imgscalr.Scalr.Mode;

public class ImageUtil {

    public static void downsizeJpg(Path sourcePath, Path targetPath, int targetWidth) throws IOException {

        try (InputStream isSrc = new FileInputStream(sourcePath.toFile())) {

            // Don't Use "ImageIO.read(File file)". It will not close the stream
            // Use Stream to close the resource    
            BufferedImage sourceImage = ImageIO.read(isSrc);

            double width = sourceImage.getWidth();
            double height = sourceImage.getHeight();
            double ratio = width / height;
            int trgHeight = (int) (targetWidth / ratio);

            // If taget width is smaller than source width, start to downsize
            if (targetWidth < width) {

                BufferedImage targetImage = Scalr.resize(sourceImage, Method.QUALITY, Mode.FIT_EXACT, targetWidth,
                saveImage(targetImage, targetPath, 0.7f);

                // prevent upsizing. just copy the source image to target image
            } else {

                saveImage(sourceImage, targetPath, 0.7f);

    private static void saveImage(RenderedImage image, Path targetPath, float quality) throws FileNotFoundException,
            IOException {

        // set compression level 
        JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);

        final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();

        try (FileImageOutputStream fios = new FileImageOutputStream(targetPath.toFile())) {

            // specifies where the jpg image has to be written

            // save the image
            writer.write(null, new IIOImage(image, null, null), jpegParams);


quality can be fromo 0f to 1f. 1 is the highst quality and file size get big. 0 is lowest quality and file size get small.

Thursday, May 28, 2015

Print current JVM's Java System Property

It print out all System Properties on console.
package com.devtrigger;

public class SystemProperty {

    public static void main(String... args) {


Then you pick up one property which you need and use it.
package com.devtrigger;

public class SystemProperty {

    public static void main(String... args) {



        // create file object which is under user's home directory
        File file = new File (System.getProperty("user.home") + System.getProperty("file.separator") + "setting.xml");

Referred from : System Properties

Wednesday, May 20, 2015

a Java Class which scans ports in an IP

I had to run port scanner software for security check reason, before deliver the product. I tried to get one utilillity from internet. but, the Websites were blocked in my company to download. so, I just made a Java Class which can do the port scanning. it takes around 20 min to run throught all the ports. If I increase Thread size and shorten the timeout, it will take less then 5 min.

Fornow, I have a little problem. When I let it run quickly, Firewall or security software get activated and deny to response if the port is opened. So, I had to let it run slowly to find all the opened port.

package com.devtrigger;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class PortScanner {

    public static void main(final String... args) throws InterruptedException, ExecutionException {
        final ExecutorService es = Executors.newFixedThreadPool(15);

        final String ip = "";

        final int timeout = 200;
        final List<Future<ScanResult>> futures = new ArrayList<>();
        for (int port = 1; port <= 65535; port++) {
            futures.add(portIsOpen(es, ip, port, timeout));
        es.awaitTermination(200L, TimeUnit.MILLISECONDS);
        int openPorts = 0;
        for (final Future<ScanResult> f : futures) {
            if (f.get().isOpen()) {
        System.out.println("There are " + openPorts + " open ports on host " + ip + " (probed with a timeout of "
                + timeout + "ms)");

    public static Future<ScanResult> portIsOpen(final ExecutorService es, final String ip, final int port,
            final int timeout) {
        return es.submit(new Callable<ScanResult>() {
            public ScanResult call() {
                try {
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress(ip, port), timeout);
                    return new ScanResult(port, true);
                } catch (Exception ex) {
                    return new ScanResult(port, false);

    public static class ScanResult {
        private int port;

        private boolean isOpen;

        public ScanResult(int port, boolean isOpen) {
            this.port = port;
            this.isOpen = isOpen;

        public int getPort() {
            return port;

        public void setPort(int port) {
            this.port = port;

        public boolean isOpen() {
            return isOpen;

        public void setOpen(boolean isOpen) {
            this.isOpen = isOpen;


Friday, February 6, 2015

How to create and run Apache JMeter Test Scripts from a Java program

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">



 <name>Zug Portal Load Test Tool</name>


package myportal.loadtest;

import java.net.URL;

import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.SetupThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;

public class SampleJmeter {

    public static void main(String[] args) {
        // Engine
        StandardJMeterEngine jm = new StandardJMeterEngine();
        URL property = SampleJmeter.class.getClassLoader().getResource("jmeter.properties");

        // jmeter.properties

        HashTree hashTree = new HashTree();

        // HTTP Sampler
        HTTPSampler httpSampler = new HTTPSampler();

        // Loop Controller
        TestElement loopCtrl = new LoopController();
        ((LoopController) loopCtrl).setLoops(1);
        ((LoopController) loopCtrl).addTestElement(httpSampler);
        ((LoopController) loopCtrl).setFirst(true);

        // Thread Group
        SetupThreadGroup threadGroup = new SetupThreadGroup();
        threadGroup.setSamplerController((LoopController) loopCtrl);

        // Test plan
        TestPlan testPlan = new TestPlan("MY TEST PLAN");

        hashTree.add("testPlan", testPlan);
        hashTree.add("loopCtrl", loopCtrl);
        hashTree.add("threadGroup", threadGroup);
        hashTree.add("httpSampler", httpSampler);



meter.properties file is from the JMeter installation /bin directory.

Monday, May 5, 2014

Android infrared (IR) transmitter code sample for Kitkat and Jelly Bean

There are many remote controller application in Google play store. But, I was not able to find an app that I can put my own IR pattern. For some reason, I need to transmit my own pattern.

So, I made a remote controller application. Now I can reach my purpose. It was easy to make for Kitkat OS. but, I wanted to make it run for Jelly Bean OS. Despite of Android API officially offer IR API from Kitkat(4.4). apparently, I see few Samsung Android device has IR transmitter which is running Jelly Bean OS(4.2).

When I run the same app which is using IR API. It didn't run on Jelly Bean as expected. I was wonder how I can control the IR from Jelly Bean OS. Luckily, I found a code sample from https://github.com/rngtng/IrDude thanks to him.

There are list of manufactur IR pattern. Please refer http://www.remotecentral.com/cgi-bin/codes/

Just make sure that minSdkVersion is 17 and target version is 19. as well it needs a permission and feature to handle IR transmitter.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.TRANSMIT_IR"
    android:required="false" />
    <uses-feature android:name="android.hardware.consumerir" />
        android:targetSdkVersion="19" />

        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


There are just power , Channel up and down button.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" >

        android:text="Power" />

        android:text="CH +" />

        android:text="CH -" />


I just removed my own pattern to generalize it and share it on my blog. I put Samsung TV IR pattern on below sample and this Class works find for my Samsung Android device. I have test Galaxy S4 mini Jelly Bean and Galaxy S4 Kitkat.
package com.devtrigger.remotecontrol;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.hardware.ConsumerIrManager;
import android.os.Build;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

    Object irdaService;
    Method irWrite;    
    SparseArray<String> irData;
    TextView mFreqsText;
    ConsumerIrManager mCIR;

    protected void onCreate(Bundle savedInstanceState) {
        // Be sure to call the super class.


        irData = new SparseArray<String>();
    hex2dec("0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e"));
    hex2dec("0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 003f 0015 003f 0015 0015 0015 0040 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e"));
    hex2dec("0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 003f 0015 0015 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e"));

    public void irInit4KitKat() {
     // Get a reference to the ConsumerIrManager
        mCIR = (ConsumerIrManager)getSystemService(Context.CONSUMER_IR_SERVICE);

 public void irInit4JellyBean() {
  irdaService = this.getSystemService("irda");
  Class c = irdaService.getClass();
  Class p[] = { String.class };
  try {
   irWrite = c.getMethod("write_irsend", p);
  } catch (NoSuchMethodException e) {

 public void irSend(View view) {
 private void irSend4Kitkat(View view) {

  String data = irData.get(view.getId());
  if (data != null) {
   String values[] = data.split(",");
   int[] pattern = new int[values.length-1];
   for (int i=0; i<pattern.length; i++){
    pattern[i] = Integer.parseInt(values[i+1]);
   mCIR.transmit(Integer.parseInt(values[0]), pattern);
 private void irSend4JellyBean(View view) {
  String data = irData.get(view.getId());
  if (data != null) {
   try {
    irWrite.invoke(irdaService, data);
   } catch (IllegalArgumentException e) {
   } catch (IllegalAccessException e) {
   } catch (InvocationTargetException e) {

 protected String hex2dec(String irData) {
  List<String> list = new ArrayList<String>(Arrays.asList(irData
    .split(" ")));
  list.remove(0); // dummy
  int frequency = Integer.parseInt(list.remove(0), 16); // frequency
  list.remove(0); // seq1
  list.remove(0); // seq2

  for (int i = 0; i < list.size(); i++) {
   list.set(i, Integer.toString(Integer.parseInt(list.get(i), 16)));

  frequency = (int) (1000000 / (frequency * 0.241246));
  list.add(0, Integer.toString(frequency));

  irData = "";
  for (String s : list) {
   irData += s + ",";
  return irData;

Friday, March 14, 2014

Reversed Binary Numbers (Difficulty Level: Easy)

My friend sent me a quiz how to make a reverse binary from input number and put it back as number.
It is easy level though, I had fun of it
If you are interested to get more quiz, please check this https://code.google.com/codejam/
There are many programing quiz in Internet. I see there are so many genius in the world.
I wonder when I can resolve the difficult level of quiz. I must study math again.


Your task will be to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11.


The input contains a single line with an integer N, 1 ≤ N ≤ 1000000000.


Output one line with one integer, the number we get by reversing the binary representation of N.

Sample input 1
Sample output 1
Sample input 2
Sample output 2

package puzzle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

 * @author jack
public class Reversebinary {

     * @param args the command line arguments
    public static void main(String args[]) {

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String input;

            while ((input = br.readLine()) != null) {
                int inputValue = Integer.parseInt(input);

//                System.out.println(Integer.toBinaryString(inputValue));

                StringBuffer revertedString = new StringBuffer();

//                System.out.println(revertedString);
                System.out.println(Long.parseLong(revertedString.toString(), 2));


        } catch (java.lang.NumberFormatException ne) {
            System.out.println("Please type numbers");
        } catch (IOException io) {


How to get the apk out of the non-rooted Android device

I got a request to test updated Android application. but, it often happens that I need to test without apk file.
Due to complicated commpany rules, politics and security, the requester can't send me the apk file.. But, they push me to do..
To resolve this situation, luckily I had one Android device which is installed the latest apk. but, I need to test it on another device.
I can extract the apk from an Anroid device and install it on the other devices.

To do this step, Android SDK is required. so that you will be able use 'adb' command.

Step to extract apk file from an Android device.
1. Connect the device to the computer
2. start command prompt or shell
3. adb shell pm list package -f -3 (to display all the installed apps on the device)
C:\>adb shell pm list package -f -3

4. adb pull {apk name} (This will save the required apk on the current directory of the computer)
C:\>adb pull /data/app/uk.amazon.mShop.android-2.apk

If you remove '-3' option, it will show all apk which is pre-loaded app on your device. I used 'adb shell pm list package -f -3' command.
If you like to know more about 'pm list package' filter option, please refer below.
pm list packages: prints all packages, optionally only
  those whose package name contains the text in FILTER.  Options:
    -f: see their associated file.
    -d: filter to only show disbled packages.
    -e: filter to only show enabled packages.
    -s: filter to only show system packages.
    -3: filter to only show third party packages.
    -i: see the installer for the packages.
    -u: also include uninstalled packages.