Wednesday, November 19, 2014

Java - Websockets (for the uninitiated) using Tomcat 7



What is a Websocket?

For the protocol agnostic, websocket is an improved web request that allows sending multiple requests over a period of time without having to reconnect with the server. It is more or less like a network socket in Java. Once a connection is established between two entities (initiated by the client), both entities can freely communicate with each other.


For a more detailed explanation on the subject, please visit http://en.wikipedia.org/wiki/WebSocket

Below is a pictographic representation of websockets 




How does this help an application?
  1. The server can push messages to the client rather than waiting for the client to pull data.
    • Once the client initiates connections, the server will be able to push notifications to the client at any time. This enables notifications from the server
  2. Reduced network I/O
    • Only the first request is a HTTP request. Once the connection is established, the messages are sent as a simple TCP message. This removes most of the HTTP overheads thus reducing the I/O between the entities.
  3. Reduced overheads of authenticating every request from the same client
    • When the connection is established, the connection can be authenticated one time. One authenticated, further messages can be trusted and there is no need for authenticating further messages. This hugely improves performance of chatty systems
Support on browsers

Web applications can now use websockets to communicate with servers. Most modern browsers support the protocol and can be implemented with simple javascript.

A secure version of the WebSocket protocol is implemented in Firefox 6, Safari 6, Google Chrome 14, Opera 12.10 and Internet Explorer 10

Websockets in Java (using tomcat 7's implementation)

With respect to the Java community, websocket implementations are based on JSR356. Being only a reference, there are many implementations each requiring support for several other features.

  1. Tomcat provides support for websockets with its own implementation since version 7.0.27
  2. JavaEE 7 provides a default implementation for Websockets that can be used on applications using and running on JavaEE7.
In this post, we will talk about using Tomcat's implementation. Since most of our apps do not need a full fledged application server, a simple Servlet container such as Tomcat is more than sufficient for most of our apps. So this blog would elaborate on this.

Server example

Steps
  1. Setup the application
    • Create a Java Web app.
    • Create a simple Servlet class that extends "WebSocketServlet" rather than the "HttpServlet"
    • Add the below entry to "web.xml" to route URL hits to the websocket server.
      • <servlet>
                <servlet-name>Server</servlet-name>
                <servlet-class>
                    com.corenttech.websocket.Server
                    <servlet-class>
            </servlet>
            <servlet-mapping>
                <servlet-name>Server</servlet-name>
                <url-pattern>/Server</url-pattern>
            </servlet-mapping>
      •  Since this is a servlet, Tomcat decides if a HTTP request is a WebSocket request based on the URL that you have mapped to your servlet in web.xml or using annotations.
  2. Implementing a message listener.
    • WebSocketServlet is an abstract class that would require the below method to be implemented.
      • protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr)
      • return a message listener (sample given below) in this method
        • return new MessageListener();
      • So, the servlet code should look like this
      • public class Server extends WebSocketServlet {
            @Override
            protected StreamInbound createWebSocketInbound(String protocol, HttpServletRequest hsr) {
                return new MessageListener();
            }  
        }
    • Assuming that the messages are going to be simple text, create the message listener class.
    • import java.io.IOException;
      import java.nio.ByteBuffer;
      import java.nio.CharBuffer;
      import org.apache.catalina.websocket.MessageInbound;

      public class MessageListener extends MessageInbound {

          @Override
          protected void onBinaryMessage(ByteBuffer bb) throws IOException {
              throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          protected void onTextMessage(CharBuffer message) throws IOException {
              String msg = message.toString();
              //modify the message by adding a timestamp
              handleMessage(msg);
          }

          private void handleMessage(String msg) {
              msg = "(" + System.currentTimeMillis()+") "+ msg;
              System.out.println("Received Message " + msg);
          }
         
      }
    • If you wish to be notified when a WebSocket connection is opened or closed, simply override the onOpen and onClose methods in the MessageListener class
      @Override
      protected void onOpen(WsOutbound outbound);
      @Override
      protected void onClose(int status);
  3. Testing the server implementation
    1. We will concentrate only on the server side of the implementation as there are numerous examples of the client side code using javascript and also the client.
    2. For testing our implementation, we can use the chrome app named Simple WebSocket Client
    3. The URL of the websocket server will be
      1. ws://localhost:8080/WebsocketServer/Server

Thursday, November 13, 2014

Java - How to generate and read QR codes

What is a QR Code?

http://en.wikipedia.org/wiki/QR_code


How can it be used?

QR code is a machine format of a text or a url or a contact. and becomes a single entity. The entity can be easily scanned by mobile phones using their cameras to get the original content.

Sample code

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.imageio.ImageIO;

/**
 *
 * @author opell
 */
public class QRCodeUtility {

    public static void main(String[] args) throws WriterException, IOException, NotFoundException, ChecksumException, FormatException {
        String message = "Hello world";
        File file = new File("d:/testqr2.png");
        int width = 125;
        int height = 125;
        QRCodeUtility qrCoderead = new QRCodeUtility();
        QRCodeUtility.createQRImage(message, file, width, height);
        System.out.println(qrCoderead.readQRImage(file));
    }

    public static String readQRImage(File file) throws NotFoundException, ChecksumException, FormatException, IOException {
        LuminanceSource ls = new BufferedImageLuminanceSource(
                ImageIO.read(file));
        Result result = new QRCodeReader().decode(
                new BinaryBitmap(new HybridBinarizer(ls)));
        Vector byteSegments = (Vector) result.getResultMetadata()
                .get(ResultMetadataType.BYTE_SEGMENTS);
        int i = 0;
        int tam = 0;
        for (Object o : byteSegments) {
            byte[] bs = (byte[]) o;
            tam += bs.length;
        }
        byte[] resultBytes = new byte[tam];
        i = 0;
        for (Object o : byteSegments) {
            byte[] bs = (byte[]) o;
            for (byte b : bs) {
                resultBytes[i++] = b;
            }
        }
        String s = new String(resultBytes);
        return s;
    }

    public static BufferedImage createQRImage(String message, File file,
            int width, int height) throws WriterException, IOException {
        // Create the ByteMatrix for the QR-Code that encodes the given String
        Hashtable hintMap = new Hashtable();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(message,
                BarcodeFormat.QR_CODE, width, height, hintMap);
        // Make the BufferedImage that are to hold the QRCode
        int matrixWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(matrixWidth, matrixWidth,
                BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);
        // Paint and save the image using the ByteMatrix
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < matrixWidth; i++) {
            for (int j = 0; j < matrixWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }
        ImageIO.write(image, "PNG", file);
        return image;
    }

}



Monday, November 10, 2014

Java - Date handling examples and code.

A simple class to deal with most date functions. The methods give a general idea about using dates in Java. I guess this is would be useful to beginners trying to deal with the Date object.

Feel free to use this code anywhere required.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author String
 */
public class DateUtility {

    private static SimpleDateFormat mmddyyyyDateFormat = new SimpleDateFormat("MM-dd-yyyy");
    private static SimpleDateFormat yyyymmddDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static Locale locale = Locale.ENGLISH;

    public static String getCurrentDay() {
        Calendar cal = Calendar.getInstance();
        return yyyymmddDateFormat.format(cal.getTime()).toString();
    }

    public static Date getCurrentDate() {
        return new Date(Calendar.getInstance().getTimeInMillis());
    }

    public static java.sql.Date getCurrentSQLDate() {
        return new java.sql.Date(Calendar.getInstance().getTimeInMillis());
    }

    public static java.sql.Timestamp getCurrentTimestamp() {
        return new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis());
    }

    public static int getCurrentHour() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    public static int getCurrentWeek() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.WEEK_OF_YEAR);
    }

    public static int getCurrentMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.MONTH);
    }

    public static int getCurrentYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    public static int getDaysInCurrentMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static int getDaysInCurrentYear() {
        Calendar cal = Calendar.getInstance();
        return cal.getActualMaximum(Calendar.DAY_OF_YEAR);
    }

    public static java.sql.Date getFirstDayOfCurrentWeek() {
        // Get calendar set to current date and time
        Calendar cal = Calendar.getInstance();
        // Set the calendar to monday of the current week
        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_WEEK));
        java.sql.Date dt = new java.sql.Date(cal.getTimeInMillis());
        return dt;
    }

    public static java.sql.Date getFirstDayOfMonth() {
        // Get calendar set to current date and time
        Calendar cal = Calendar.getInstance();
        // Set the calendar to first day of the current month
        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_MONTH));
        java.sql.Date dt = new java.sql.Date(cal.getTimeInMillis());
        return dt;
    }

    public static long diffDays(Date stDate, Date endDate) {
        long milsecs1 = stDate.getTime();
        long milsecs2 = endDate.getTime();
        long diff = milsecs2 - milsecs1;
        long ddays = diff / (24 * 60 * 60 * 1000);
        return ddays;
    }

    public static long diffHours(Date stDate, Date endDate) {
        long milsecs1 = stDate.getTime();
        long milsecs2 = endDate.getTime();
        long diff = milsecs2 - milsecs1;
        long dhours = diff / (60 * 60 * 1000);
        return dhours;
    }

    public static Date getCalendarDate(String stringDate) {
        Calendar calendar = Calendar.getInstance();
        String sDate[] = stringDate.split("-");
        calendar.set(Integer.parseInt(sDate[0]), Integer.parseInt(sDate[1]), Integer.parseInt(sDate[2]));
        return calendar.getTime();
    }

    public static Date getDateAfterDurationInDays(int duration) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, duration);
        return calendar.getTime();
    }
}

Sunday, November 9, 2014

Java - Basic Encryption & Decryption using

The below code is a simple way to do encryption and decryption in Java. Contrary to Hashing, encryption algorithms are reversible and the original string can be retrieved from the encrypted string using the right key and algorithm. The below code uses "AES/ECB/PKCS5Padding" to encrypt and decrypt.


Feel free to use the below code anywhere you like



import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;


public class EncryptUtils {

    public static final String DEFAULT_ENCODING = "UTF-8";
    public static final String DEFAULT_KEY = "";
   
    /**
     * Encrypts a String with a key based on the "AES/ECB/PKCS5Padding" algorithm
     *
     * @param key - The key to be used to encrypt the String
     * @param strToEncrypt - The value to be encrypted
     * @return String Encrypted Value
     * @exception NoSuchAlgorithmException
     * @exception InvalidKeyException
     * @exception IllegalBlockSizeException
     * @exception BadPaddingException
     * @exception NoSuchPaddingException
     */
    public static String encryptString(String key, String strToEncrypt) throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        final SecretKeySpec secretKey = new SecretKeySpec(getKeyAsBytes(key), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        final String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
        return encryptedString;
    }

    /**
     * Decrypts an encrypted value with a key based on the "AES/ECB/PKCS5Padding" algorithm
     *
     * @param key - The key to be used to decrypt the String
     * @param strToDecrypt - The value to be decrypted
     * @return String Encrypted Value
     * @exception NoSuchAlgorithmException
     * @exception InvalidKeyException
     * @exception IllegalBlockSizeException
     * @exception BadPaddingException
     * @exception NoSuchPaddingException
     */
    public static String decryptString(String key, String strToDecrypt)  throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException  {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        final SecretKeySpec secretKey = new SecretKeySpec(getKeyAsBytes(key), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
        return decryptedString;
    }

    /**
     * Converts a String Key into bytes.
     * The output of this value is used internally for encryption & Decryption
     * @param key - Encryption key
     * @return byte[] - The key value as a byte array
     * @throws IllegalArgumentException
     */
    private static byte[] getKeyAsBytes(String key) throws IllegalArgumentException {
        byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
        if (raw.length != 16) {
            throw new IllegalArgumentException("Invalid key size.");
        }
        return raw;
    }

}

File Utilities - Java


The below class holds methods that can be used to perform most of the routine actions on files and folders. Feel free to use the code anywhere required.

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Utility class that holds all methods related to File handling
 *
 * @author Sridhar
 */
public class FileUtility {

    /**
     * Deletes a given directory under the current working folder. If the
     * directory is in a sub folder, the path relative to the current folder
     * needs to be given. All subfolders and files under this directory will be
     * deleted.
     *
     * @param directoryName The directory along with the path relative to the
     * current directory.
     * @return boolean true if deleted successfully
     * @throws java.io.IOException
     */
    public static boolean deleteDirectory(String directoryName) throws IOException {
        File file = new File(directoryName);
        return deleteDirectory(file);
    }

    /**
     * Overridden method with the parameter changed to File.
     *
     * @param path The File object of the directory.
     * @return boolean true if deleted successfully
     */
    public static boolean deleteDirectory(File path) {
        boolean success = true;
        if (path.exists()) {
            File[] files = path.listFiles();
            for (File file : files) {
                if (success) {
                    if (file.isDirectory()) {
                        success = deleteDirectory(file);
                    } else {
                        success = file.delete();
                    }
                }
            }
        }
        return (path.delete());
    }

    /**
     * deletes a file given by the input String
     *
     * @param fileName The filename along with the path relative to the current
     * directory.
     * @return boolean true if deleted successfully
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        boolean success = file.delete();
        return success;
    }

    /**
     * creates a directory as given by the input String
     *
     * @param location The directory along with the path relative to the current
     * directory.
     * @return boolean true if created successfully
     */
    public static boolean createDirectory(String location) {
        File file = new File(location);
        boolean success = file.mkdirs();
        return success;
    }

    /**
     * removes the file extension from a given file name and returns the rest of
     * the name.
     *
     * @param str input file name along with extension of the file.
     * @return String file name without the extension.
     */
    public static String stripExtension(String str) {
        if (str == null) {
            return null;
        }
        int pos = str.lastIndexOf(".");
        if (pos == -1) {
            return str;
        }
        return str.substring(0, pos);
    }

    /**
     * Retrieves the file extension
     *
     * @param str input file name along with extension of the file.
     * @return String file name without the extension.
     */
    public static String getFileExtension(String str) {
        if (str == null) {
            return null;
        }
        int pos = str.lastIndexOf(".");
        if (pos == -1) {
            return str;
        }
        return str.substring(pos, str.length());
    }

    /**
     * Checks if a given file exists in the file system.
     *
     * @param fileString The file along with the path relative to the current
     * directory.
     * @return boolean true if found else, returns false.
     */
    public static boolean fileExists(String fileString) {
        File file = new File(fileString);
        return file.exists();
    }

    /**
     * Writes the given message to the input file. Also closes the file at the
     * end of it.
     *
     * @param fle A file object where the message needs to be written to.
     * @param message the content to be written to the file.
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void writeToFile(File fle, String message)
            throws FileNotFoundException, IOException {
        FileOutputStream fos;
        fos = new FileOutputStream(fle, true);
        fos.write(message.getBytes());
        fos.write(("\n").getBytes());
        fos.flush();
        fos.close();
    }

    /**
     *
     * @param fileName name of the file to be created
     * @param fileContent content to be written to the created file.
     * @return File. a reference to the file object created
     * @throws java.io.IOException
     */
    public static File createFile(String fileName, String fileContent) throws IOException {
        FileWriter fstream = null;
        File file = null;
        try {
            file = new File(fileName);
            fstream = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(fileContent);
            out.flush();
            out.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (fstream != null) {
                fstream.close();
            }
        }
        return file;
    }

    /**
     * Starts a windows ".bat" file in a new command prompt. Works only when run
     * on Windows.
     *
     * @param runnableFile path to the runnable file.
     * @param folderName
     * @throws java.io.IOException
     */
    public static void runWindowsFile(String runnableFile, String folderName) throws IOException {
        File file = new File(FileUtility.stripExtension(folderName));
        String filePath = runnableFile;
        Map<String, String> env = new HashMap<String, String>(System.getenv());
        env.put("Path", env.get("Path") + ";" + file.getAbsolutePath());
        Runtime.getRuntime().exec("cmd /c start " + filePath);

    }

    /**
     * Starts a ".sh" file in a terminal. Works only when run on Linux based
     * Operating systems.
     *
     * @param runnableFile - path to the runnableFile
     * @throws java.io.IOException
     */
    public static void runShellScript(String runnableFile) throws IOException {
        Runtime.getRuntime().exec(runnableFile);
    }

    /**
     * Reads contents of a text file.
     *
     * @param fileNameWithPath - Path to the file
     * @return String - Content of the file.
     * @throws IOException
     */
    public static String readFileContent(String fileNameWithPath) throws IOException {
        InputStream is = FileUtility.class.getClassLoader().getResourceAsStream(fileNameWithPath);
        return readContentFromInputStream(is);
    }

    public static String readContentFromInputStream(InputStream is) throws IOException {
        if (is != null) {
            StringBuilder stringBuilder = new StringBuilder();
            BufferedInputStream stream = new BufferedInputStream(is);
            byte[] contents = new byte[1024];
            int bytesRead;
            while ((bytesRead = stream.read(contents)) != -1) {
                stringBuilder.append(new String(contents, 0, bytesRead));
            }
            stream.close();
            is.close();
            return stringBuilder.toString();
        }
        return null;
    }

    public static String readFileContent(File file) throws IOException {
        return readContentFromInputStream(new FileInputStream(file));
    }

    public static String getFileFolder(String absolutePath) {
        if (StringUtility.isNullOrEmpty(absolutePath)) {
            return null;
        } else if (absolutePath.indexOf(File.separator) <= 0) {
            return absolutePath;
        }
        return absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
    }

    public static String[] getFilesInFolder(String absolutePath) {
        if (!StringUtility.isNullOrEmpty(absolutePath)) {
            File file = new File(absolutePath);
            ArrayList<String> filesList = new ArrayList<String>();
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File fl : files) {
                    if (fl.isFile()) {
                        double bytes = fl.length();
                        double kilobytes = (bytes / 1024);
                        double megabytes = (kilobytes / 1024);
                        filesList.add(fl.getName() + "," + megabytes + "");
                    }
                }
                return filesList.toArray(new String[filesList.size()]);
            } else {
                return null;
            }
        }
        return null;
    }

}