MULTI THREADED WEB SERVER IN JAVA SOURCE CODE(LODE PAGES FROM GIVEN FOLDER LOCATION AND PUBLISH THEM)

//  THIS IS THE  HTTPREQUEST CLASS TO HANDLES REQUEST FROM THE USER

import java.io.*;
import java.net.*;
import java.util.regex.*;
import java.util.*;

final class HttpRequest implements Runnable
    {
        private static final Pattern REQUEST_PATTERN = Pattern.compile("^GET (/.*) HTTP/1.[01]$");
        private final File documentDir;
        private final Socket socket;
    //------------------------------------------------------------
    //CONSTRUCTOR METHOD OF HttpRequest TWO ARGUMENTS
    // socket and documentDir FOR NEW REQUEST
        public HttpRequest(Socket socket, File documentDir)
        {
        this.socket = socket;
        this.documentDir = documentDir;
        }
    //---------------------------------------------------------------------------
    //METHOD TO REQUEST THE PATH FROM BROWSER
        private String readRequestPath() throws IOException
        {    //READ THE REQUEST
            BufferedReader reader = new BufferedReader(new InputStreamReader(
            this.socket.getInputStream()));
            String firstLine = reader.readLine();
            if (firstLine == null)
                {
                return null;
                }
        //COMPILE THE CODE
        //THIS PART OF CODE TAKEN FROM INTERNET (SUN JAVA).INSTEAD OF THIS WE CAN USE SRTING
        //TOKENIZER ALSO BUT THAT SPENTS LOT OF CODE
        Matcher matcher = REQUEST_PATTERN.matcher(firstLine);
        return matcher.matches() ? matcher.group(1) : null;
        }
    //-------------------------------------------------------------------------------------
    //THIS METHOD USED FOR SEND RESPONSE
    //IN THIS CASE I USED STRING BUFFER AND APPEND NECESSERY PARTS OF IT
        private OutputStream sendResponseHeaders(int status, String message,long len) throws IOException
        {
        StringBuffer response = new StringBuffer();
        response.append("HTTP/1.0 ");
        response.append(status).append(' ').append(message).append("\r\n");
        response.append("Content-Length: ").append(len).append("\r\n\r\n");
        OutputStream out = this.socket.getOutputStream();
        //SEND response TO THE OUT PUT STREAM OF CURRENT SOCKET
        //WHEN WE NEED TO PRINT THE MESSAGE ON WEB BROESER WE CAN USE THIS
        out.write(response.toString().getBytes());
        out.flush();
        return out;
        }
    //--------------------------------------------------------------------------------
    //THIS METHOD USED TO SEND ERROR MESSAGE TO THE BROWSER WHEN WE GIVE ERROR
    //NUMBER AND MESSAGE THAT WILL PRIN USING ABOVE METHOD (sendResponseHeaders)
       private int sendErrorResponse(int status, String message) throws IOException
        {
        OutputStream out = sendResponseHeaders(status, message,message.length());
        out.write((message+"\nerror number :"+status).getBytes());
        out.flush();
        return status;
        }
    //------------------------------------------------------------------------------
    //THIS METHOD IS USED FOR READ FILE IN THE DOCUMENT DIRECTORY AND SEND THE CONTENT
    // OF THE FILE TO THE SOCKET.THEN WEB BROWSER CAN ACCES THEM VIA PORT
    // OF THE FILE TO THE SOCKET.THEN WEB BROWSER CAN ACCES THEM VIA PORT
        private long sendFile(File file) throws IOException
        {
        long len = file.length();
        OutputStream out = sendResponseHeaders(200, "OK", len);
        InputStream in = new FileInputStream(file);
        try {
            byte[] buffer = new byte[1024];
            int nread = 0;
            while ((nread = in.read(buffer)) > 0)
                {
                out.write(buffer, 0, nread);
                }
            }
        finally
            {
                in.close();
            }
        out.flush();
        return len;
        }
    //----------------------------------------------------------------------------
    //THIS IS THE MAIN ENTRY TO THIS HttpRequest
        public void run()
        {
        //IN THIS PART INITIALIZE LOGIN INFOMATION
        int status = 200;
        long len = 0;
        String path = null;
        //TRY TO HANDLE THE REQUEST
        try {
            path = readRequestPath();
            //THIS IS FOR BONUS MARK ,IF PATH CONTAINSONLY"/"
            //THAT TAKES AS index.html FILE BELOW IF LOOP CHECK THAT
            //THIS ALSO DISPLAYS THE CURRENTLY SHOWING FILE NAME AT COMMAND LINE
                if(path.equals("/"))
                {
                    path=path+"index.html";
                    System.out.println("RETTEIVING FILE IS "+this.documentDir.getAbsolutePath()+path);
                }
                //IF PATH NOT AVAILABLE SEND ERROR MESSAGE TO THE BROWSER
                if (path == null)
                {
                    status = sendErrorResponse(400, "Bad Request");
                }
                //IF HAS SOME PATH TRY TO ACCCESS GIVEN PATH
                else
                {
                    File file = new File(this.documentDir, path);
                    //CHECK GIVEN FILE IS AVAILABLE IN THE GIVEN DOCUMENT AND CHECK WETHER IT CAN READ  OR NOT
                    //ONLY FOR READABLE FILES IN THE CORRECT PATH GIVEN
                        if (!file.getAbsolutePath().startsWith(this.documentDir.getAbsolutePath())|| (file.exists() && (!file.isFile() || !file.canRead())))
                        {
                        status = sendErrorResponse(403, "Forbidden");
                        }
                        //IF FILE DOES NOT FOUN SEN MESSAGE TO AWARE THATS NOT AVAILABLE
                        else if (!file.exists())
                        {
                        status = sendErrorResponse(404, "Not Found");
                        }
                        //IF NO ANY ISSUE SEND THE FILE
                        else
                        {
                        len = sendFile(file);
                        }
                }
            }
            //ERROR HANDLING PART
            catch (IOException e)
                {
                System.out.println("Error while serving request for " + e.getMessage());
                e.printStackTrace();
                }
            finally
                {
                    try
                        {
                        this.socket.close();
                        }
                    catch (IOException e)
                        {
                            System.out.println("Error while closing socket to " + e.getMessage());
                        }
                }
        }
    }
//================================




//    THIS IS THE  WEB SERVER CLASS TO ACCEPT AND PARSE THE REQUEST
//**************************************************

import java.io.*;
import java.net.*;
import java.util.*;

public class WebServer
    {
    public static void main(String[] args)
        {
         int port = 8080;
        //SET THE PORT NUMBER
         File documentDir = new File("localhost");
        //NAME OF THE DOCUMENT DIRECTORY
        //IF DOCUMENT DIRECTORY DOES NOT CONTAIN OR ITS NOT DIRECTORY PRINT ERR MESSAGE
        if (!documentDir.exists()&&!documentDir.isDirectory())
        {
            System.out.println("No such directory exists make directory named ["
            + documentDir.getAbsolutePath()+ " ] localhost and put files");
        }
        //ELSE RUN THE SERVER
    else
        {
            System.out.println("web server is running");
        try {
            //STABILISH A NEW SOCKET TO START CONNECTION
            ServerSocket serverSocket = new ServerSocket(port);
            try {
                //INFINITE LOOP TO PROCESS REQUESTS
                while (true)
                    {
                    // wait for the next client to connect and get its socket connection
                    Socket socket = serverSocket.accept();
                    // handle the socket connection by a handler in a new thread
                    new Thread(new HttpRequest(socket, documentDir)).start();
                    }
                }
                //IF ERROR OCCURED WHEN CONNECT TO PORT
                catch (IOException e)
                    {
                    System.err.println("Error while accepting connection on port "+ port);
                    }
                    finally
                    {
                        serverSocket.close();
                    }
            }
            //IF ERROR OCCURED WHEN BIND TO THE PORT
            catch (IOException e)
            {
            System.err.println("Failed to bind to port " + port);
            }
        }
    }
}
//==============end of the class==

3 comments:

  1. thank you so much
    [my ID:sudheesh077@yahoo.co.in]

    ReplyDelete
  2. hi Sanjeewa, hi i am totally novice to java programming and as part of lab for one course at university i have to complie and run the multithread webserver. at my machine i have downloaded netbeans ide 7.1. and i am creating new project by clicking on Java and Java
    application and giving Project name WebServer and in the main class i m typing Webserver.Webserver. and the source code is as given

    ReplyDelete

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...