Simple HTTP Server with Response Action(Java)


ConnectorTest.java
~~~~~~~~~~~~~~~
package com.anils.test;

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

/**
 * Simulator HTTP Server, can accept user request, according request send
 * response, ConnectorTest where main ServerSocket
 *
 *
 */
public class ConnectorTest implements Runnable {

    private final int port;
    private ServerSocket serverSocket;

    public ConnectorTest(int port) {
        this.port = port;

        try {
            /*
             * create serverSocket, listen on special port
             */
            serverSocket = new ServerSocket(port);
            new Thread(this).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            try {
                /*
                 * wait client connection
                 */
                Socket socket = serverSocket.accept();
                new HttpdTest(socket);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * main method, entry of system
     */
    public static void main(String[] args) {
        new ConnectorTest(8888);
    }
}



HttpdTest.java
~~~~~~~~~~~~~~

package com.anils.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Simulator HTTP Server, can accept user request, according request send
 * response, HttpdTest were access thread
 *
 */
public class HttpdTest implements Runnable {
    private final Socket socket;
    public static final String BASE_PATH = "d:/root";

    /**
     * construct method
     *
     * @param socket
     *            , client connect socket
     */
    public HttpdTest(Socket socket) {
        this.socket = socket;
        new Thread(this).start();
    }

    /*
     * main access method, access request, send response, then close
     */
    public void run() {

        // access request
        // access response
        // close
        try {

            /*
             * get input stream and output stream
             */
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);

            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream);

            /*
             * get first line, http head message
             */
            String headLine = reader.readLine();

            /*
             * split head message, get method, request file and HTTP protocol
             */
            String[] split = headLine.split(" ");

            /*
             * if is not GET method, can't access
             */
            if (!"GET".equals(split[0])) {
                // can't access
            }

            String path = split[1];

            /*
             * if end folder where '/', then add default index.html to path
             */
            if (path.endsWith("/")) {
                path = path + "index.html";
            }

            /*
             * get absolute path of file
             */
            String filename = BASE_PATH + path;

            File file = new File(filename);

            /*
             * check request file exist, if not exist, response not found page
             * message
             */
            if (!file.exists() || file.isDirectory()) {

                /*
                 * send http response head format
                 */
                writer.println("HTTP/1.1 404 ok");
                writer.println();
                writer.flush();
                socket.close();
                return;
            }

            /*
             * send request file found message
             */
            writer.println("HTTP/1.1 200 ok");
            String lowerName = filename.toLowerCase();

            /*
             * according file extention, send http head message
             */
            if (lowerName.endsWith(".txt") || lowerName.endsWith(".html")) {
                writer.println("Content-Type: text/html");
            } else if (lowerName.endsWith(".jpg")) {
                writer.println("Content-Type: image/jpeg");
            }
            writer.println();

            if (lowerName.endsWith(".txt") || lowerName.endsWith(".html")) {
                /*
                 * if file ends with .txt or .html, get request file, read file
                 * content, and send content to client
                 */
                FileReader fileReader = new FileReader(file);
                char[] buf = new char[256];
                int count = 0;
                while ((count = fileReader.read(buf)) != -1) {
                    writer.write(buf, 0, count);
                }
                fileReader.close();

            } else if (lowerName.endsWith(".jpg")) {
                /*
                 * if file ends with .jpg, get request jpg file, read file
                 * content, and send content to client
                 */
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] buf = new byte[250];
                int count = 0;
                while ((count = fileInputStream.read(buf)) != -1) {
                    outputStream.write(buf, 0, count);
                }
                outputStream.flush();
            }

            /*
             * remember call flush method
             */
            writer.flush();

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Simple simulator HTTP Server and Browser(Java)

SimulatorTest.java
~~~~~~~~~~~~~~~~~~

package com.anil.test;

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

/**
 *  Simulator of HTTP server
 *
 *
 */
public class SimulatorTest implements Runnable {

    private Socket socket;

    /**
     * construct method, create server socket, accept at 8888 port
     */
    public SimulatorTest() {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            socket = serverSocket.accept();

        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
         * create new thread and it
         */
        new Thread(this).start();
    }

    public void run() {
        try {

            /*
             * get input information from browser, and output get request
             * information
             */
            InputStream inputStream = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            char[] buf = new char[512];
            int count = 0;

            System.out.println("---------start-------------");
            while ((count = reader.read(buf)) != -1) {
                for (int i = 0; i < count; i++) {
                    System.out.print(buf[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("---------end-------------");
    }

    /**
     * main method
     */
    public static void main(String[] args) {
        new SimulatorTest();
    }
}



BrowserTest.java
~~~~~~~~~~~~~~~

package com.anil.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Simulator browser request HTTP
 *
 *
 */
public class BrowserTest implements Runnable {
    private Socket socket;

    public BrowserTest() {
        try {

            /*
             * create new socket, connect to web site
             */
            socket = new Socket("www.google.com", 80);

            /*
             * simulator browser request HTTP information
             */
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream);
            writer.println("GET / HTTP/1.1");
            writer.println("Connection: Keep-Alive");
            writer.println();
            writer.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

        new Thread(this).start();
    }

    public void run() {

        try {

            /*
             * get HTTP response from web site, and output get information
             */
            InputStream inputStream = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            char[] buf = new char[512];
            int count = 0;
            System.out.println("---------start-------------");
            while ((count = reader.read(buf)) != -1) {
                for (int i = 0; i < count; i++) {
                    System.out.print(buf[i]);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("---------end-------------");
    }

    /**
     * main method
     */
    public static void main(String[] args) {
        new BrowserTest();
    }
}

XML Processing using SAX Parser

SAXTest.java
~~~~~~~~~~~~
package com.anil;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
* Simple XML process use SAX method, SAX simple API for XML
*
*/
public class SAXTest extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
   super.startDocument();
}

@Override
public void endDocument() throws SAXException {
   super.endDocument();
}

@Override
public void startElement(String uri, String localName, String name,
    Attributes attributes) throws SAXException {
   System.out.println("uri: " + uri);
   System.out.println("localName: " + localName);
   System.out.println("name: " + name);
   for (int i = 0; i < attributes.getLength(); i++) {
    System.out.println(i + " attributes: " + attributes.getValue(i));
   }
   if ("display".equals(name)) {
    String value = attributes.getValue("size");
    System.out.println(value);
   }
   if ("ram".equals(name)) {
    String value = attributes.getValue("type");
    System.out.println(value);
   }
}

@Override
public void endElement(String uri, String localName, String name)
    throws SAXException {
   super.endElement(uri, localName, name);
}

// SAX simple API for XML
public static void main(String[] args) {
   try {
    /*
    * get SAXParser then parse XML file
    */
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse("anil.xml", new SAXTest());

   } catch (ParserConfigurationException e) {
    e.printStackTrace();
   } catch (SAXException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
}

}
--------------------------------------------------------------------------------------------------------------
anil.xml
~~~~~~~~
 <?xml version="1.0" encoding="utf-8"?>
<computer>
<display size="17">Samsung</display>
<box>
   <motherboard>
    <cpu>E8300</cpu>
    <ram type="DDR2">2G</ram>
    <displaycard>nVidia</displaycard>
   </motherboard>
   <harddisk>320G</harddisk>
   <dvdrom>16X</dvdrom>
</box>
</computer>




XML Processing by DOM parser

DOMTest.java
~~~~~~~~~~~~
package com.anil;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.Text;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Simple XML process use DOM Method, DOM document object model
 *
 */
public class DOMTest {
    public static void main(String[] args) {

        // DOM document object model
        try {
            /*
             * get documentBuilder and parse XML file
             */
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document document = documentBuilder.parse("anil.xml");

            /*
             * get first element in XML file, this were root element
             */
            Element element = document.getDocumentElement();
            String tagName = element.getTagName();
            System.out.println("root element: " + tagName);

            /*
             * add new element to XML and save it to new file
             */
            Element power = document.createElement("Power");
            element.appendChild(power);

            try {
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.transform(new DOMSource(document),new StreamResult("newAnil.xml"));
                System.out.println("Create new XML file success!");
                System.out.println("----------------------------");
            } catch (TransformerConfigurationException e1) {
                e1.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            }

            /*
             * search for special element item, and print item value
             */
            NodeList nodeList = element.getElementsByTagName("display");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element item = (Element) nodeList.item(i);
                String size = item.getAttribute("size");
                System.out.println("Display size: " + size);
                System.out.println("-----------------------------");
            }

            /*
             * get sub nodes of element
             */
            NodeList childNodes = element.getChildNodes();
            System.out.println("childNodes size: " + childNodes.getLength());

            /*
             * iterator sub element in XML file
             */
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                // System.out.println(item);

                /*
                 * access Text in XML file
                 */
                if (item instanceof Text) {
                    Text text = (Text) item;
                    String data = text.getData();
                    System.out.println("text: " + data);
                }

                /*
                 * access element in XML file
                 */
                if (item instanceof Element) {
                    Element e = (Element) item;
                    String tagName2 = e.getTagName();
                    System.out.println("sub tag name: " + tagName2);

                    /*
                     * get attributes of element
                     */
                    NamedNodeMap attributes = e.getAttributes();
                    for (int j = 0; j < attributes.getLength(); j++) {
                        Node item2 = attributes.item(j);
                        System.out.println("sub item: " + item2);
                    }
                }
            }

            System.out.println("----------End------------");

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

--------------------------------------------------------------------------------------------------------------
anil.xml
~~~~~~
<?xml version="1.0" encoding="utf-8"?>
<computer>
<display size="17">Samsung</display>
<box>
   <motherboard>
    <cpu>E8300</cpu>
    <ram type="DDR2">2G</ram>
    <displaycard>nVidia</displaycard>
   </motherboard>
   <harddisk>320G</harddisk>
   <dvdrom>16X</dvdrom>
</box>
</computer>