A Developer's Diary

Nov 11, 2012

A simple http server in java

A web server is an application which delivers web pages using HTTP protocol
The application explained below is a simple http server application which runs on port 8080 and serves contents from the directory C:/Web. The server handles each client request in a new worker thread.
package com.pankaj.webserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * File: WebServer.java
 */
public class WebServer
{
    private static final int PORT = 8080;
    private static ServerSocket listenerSocket = null;
    private static int requestId = 0;

    public static void main(String[] args) throws IOException
    {
        ConsoleLogger.LogMessage("Starting simple http server");
        listenerSocket = new ServerSocket(PORT);

        ConsoleLogger.LogMessage("Server started on port " + listenerSocket.getLocalPort());
        while (true) {
            Socket socket = listenerSocket.accept();
            ConsoleLogger.LogMessage("Client connected on port " + socket.getPort());
            new Worker(new RequestHandler(++requestId, socket));
        }
    }
}

Read more ...

Nov 4, 2012

Removing BOM character from a string in Java

The below code checks if the BOM character is present in a string. If present, removes and prints the string with skipped bom.

import java.io.UnsupportedEncodingException;

/**
 * File: BOM.java
 * 
 * check if the bom character is present in the given string print the string
 * after skipping the utf-8 bom characters print the string as utf-8 string on a
 * utf-8 console
 */

public class BOM
{
    private final static String BOM_STRING = "Hello World";
    private final static String ISO_ENCODING = "ISO-8859-1";
    private final static String UTF8_ENCODING = "UTF-8";
    private final static int UTF8_BOM_LENGTH = 3;

    public static void main(String[] args) throws UnsupportedEncodingException {
        final byte[] bytes = BOM_STRING.getBytes(ISO_ENCODING);
        if (isUTF8(bytes)) {
            printSkippedBomString(bytes);
            printUTF8String(bytes);
        }
    }

    private static void printSkippedBomString(final byte[] bytes) throws UnsupportedEncodingException {
        int length = bytes.length - UTF8_BOM_LENGTH;
        byte[] barray = new byte[length];
        System.arraycopy(bytes, UTF8_BOM_LENGTH, barray, 0, barray.length);
        System.out.println(new String(barray, ISO_ENCODING));
    }

    private static void printUTF8String(final byte[] bytes) throws UnsupportedEncodingException {
        System.out.println(new String(bytes, UTF8_ENCODING));
    }

    private static boolean isUTF8(byte[] bytes) {
        if ((bytes[0] & 0xFF) == 0xEF && 
            (bytes[1] & 0xFF) == 0xBB && 
            (bytes[2] & 0xFF) == 0xBF) {
            return true;
        }
        return false;
    }
}


The following stackoverflow article talks in detail about detecting and skipping the BOM

Read more ...

Byte Order Mark (BOM) character

BOM character
1. BOM is a Unicode character used to identify the endianness of the text file or stream.
2. The UTF-8 representation of the BOM is the byte sequence 0xEF, 0xBB, 0xBF.
3. A text editor using ISO-8859-1 as character encoding will display the characters  for BOM.
4. BOM has no meaning in UTF-8 apart from signalling that the byte stream that follows is encoded in UTF-8

import java.nio.charset.Charset;

/**
 * File: BOM.java
 * 
 * The following class converts a string having bom character
 * from ISO-8859-1 encoding type to UTF-8 and back
 */
public class BOM
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("Default Encoding: " + Charset.defaultCharset());

        //
        // Displays a simple string with bom prepended.
        // Uses system default character encoding
        //
        String bomString = "Hello World";
        System.out.println(bomString + " Length: " + bomString.length());

        //
        // convert string with bom character to utf string
        //
        byte[] byteArrayISO = bomString.getBytes("ISO-8859-1");
        String utfString = new String(byteArrayISO, "UTF-8");
        System.out.println(utfString + " Length: " + utfString.length());

        //
        // convert the utf string back to windows character encoding
        //
        byte[] byteArrayUTF = utfString.getBytes("UTF-8");
        String winString = new String(byteArrayUTF, "ISO-8859-1");
        System.out.println(winString + " Length: " + winString.length());
    }
}

Output of the above program when run on a UTF-8 supported console
$ java BOM
Default Encoding: windows-1252
Hello World Length: 17
Hello World Length: 14
Hello World Length: 17

Read more ...

Oct 29, 2012

Visitor Design Pattern

Definition
A behavioral pattern which lets you define new methods to a class hierarchy without changing the class hierarchy on which it operates
Applicability
1. When the primary class hierarchy is fixed or it is coming from a different vendor and you cannot make any changes to that hierarchy
2. Several different operations have to be performed on all or some of the classes in the hierarchy

Visitor and Composite Pattern normally go hand in hand together. First, we will try to create an example of composite pattern. A composite pattern is a structural pattern which helps to create tree like hierarchial structures. Consider a linux filesystem where every element is considered as a file. We are trying to achieve the same tree structure using Directory, File and Link elements. All of these classes implement the interface FileSystemElement

Read more ...

Oct 26, 2012

A Servlet Refresher

A Servlet is a dynamic web component developed in Java technology, loaded and run by Java technology enabled web server. The Servlet interface is the core of the Java Servlet API. The two classes which implement the Servlet interface are the GenericServlet and the HttpServlet. The Servlet interface defines the init(), service() and the destroy() methods which are implemented by GenericServlet class. The HttpServlet is an abstract class extending GenericServlet and basically helps in processing HTTP requests.

Servlet Life Cycle
The Servlet life cycle is expressed in the API by the init, service and destroy methods of the Servlet interface

Read more ...