Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package nl.reader.csv;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Date;
- import java.util.StringTokenizer;
- import nl.valori.stubstore.customer.edsn.CKIdentification;
- // The tutorial can be found just here on the SSaurel's Blog :
- // https://www.ssaurel.com/blog/create-a-simple-http-web-server-in-java
- // Each Client Connection will be managed in a dedicated Thread
- public class JavaHTTPServer implements Runnable{
- //public ReadXML getXML = new ReadXML();
- static final String StubStore = System.getenv("StubStore");
- static final File WEB_ROOT = new File(StubStore +"stubstore/Templates");
- static final String DEFAULT_FILE = "/Output/index.html";
- static final String XML_FILE = "/Output/index.xml";
- static final String FILE_NOT_FOUND = "/Output/404.html";
- static final String METHOD_NOT_SUPPORTED = "/Output/not_supported.html";
- static final String METHOD_COMING_SOON = "/Output/coming_soon.html";
- static final String EDSN = "EDSN/CAR/CKIdentification.xml";
- // port to listen connection
- private static final int PORT = 8082;
- // verbose mode
- private static final boolean verbose = true;
- // Client Connection via Socket Class
- private Socket connect;
- /**
- * ServerSocket object. Manages client connections.
- * @param c is the name of the socket
- */
- private JavaHTTPServer(Socket c) {
- connect = c;
- }
- /**
- * Method that listens on port until server halts server execution. When a connection is created,
- * the Socket object is passed in the parameter of our javaHTTPServer class and then start
- * a dedicated Thread object
- * @param args
- */
- public static void main(String[] args) {
- try {
- ServerSocket serverConnect = new ServerSocket(PORT);
- System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");
- while (true) {
- JavaHTTPServer myServer = new JavaHTTPServer(serverConnect.accept());
- if (verbose) {
- System.out.println("Connection opened. (" + new Date() + ")");
- }
- Thread thread = new Thread(myServer);
- thread.start();
- }
- } catch (IOException e) {
- System.err.println("Server Connection error : " + e.getMessage());
- }
- }
- /**
- * For each Thread instance created, this method reads characters from the client via the getInputStream method
- * of the Socket instance. Then gets one character output stream to client for headers.
- * It also gets a binary output stream to client for requested data.
- * Only GET and HEAD methods are supported, else 'not implemented' file gets sent
- * connection finally gets closed
- */
- @Override
- public void run() {
- BufferedReader in = null; PrintWriter out = null; BufferedOutputStream dataOut = null;
- String fileRequested = null;
- try {
- in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
- out = new PrintWriter(connect.getOutputStream());
- dataOut = new BufferedOutputStream(connect.getOutputStream());
- String input = in.readLine();
- StringTokenizer parse = new StringTokenizer(input);
- String method = parse.nextToken().toUpperCase();
- fileRequested = parse.nextToken().toLowerCase();
- String payLoad = null;
- // we support only GET and HEAD methods, we check
- if (!method.equals("GET") && !method.equals("HEAD")) {
- if (verbose) {
- System.out.println("501 Not Implemented : " + method + " method.");
- }
- if(method.equals("POST")) {
- File file = new File(WEB_ROOT, METHOD_COMING_SOON);
- int fileLength = (int) file.length();
- String contentMimeType = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 501 Not Implemented");
- out.println("Server: Java HTTP Server from SSaurel : 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + contentMimeType);
- out.println("Content-length: " + fileLength);
- out.println(); // blank line between headers and content, very important !
- out.flush(); // flush character output stream buffer file
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- } else {
- // we return the not supported file to the client
- File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
- int fileLength = (int) file.length();
- String contentMimeType = "text/html";
- //read content to return to client
- byte[] fileData = readFileData(file, fileLength);
- // we send HTTP Headers with data to client
- out.println("HTTP/1.1 501 Not Implemented");
- out.println("Server: Java HTTP Server from SSaurel : 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + contentMimeType);
- out.println("Content-length: " + fileLength);
- out.println(); // blank line between headers and content, very important !
- out.flush(); // flush character output stream buffer
- // file
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- } else {
- String client;
- String urlSplit[] = fileRequested.split("/");
- if (fileRequested.endsWith("/")) {
- client = "default";
- }else {
- client = urlSplit[1];
- }
- switch (client) {
- case "default" :
- fileRequested += DEFAULT_FILE;
- break;
- case "user":
- payLoad= ReadXML.getUser(urlSplit[2]);
- fileRequested = XML_FILE;
- break;
- case "edsn":
- payLoad= CKIdentification.getCKId();
- System.out.println(payLoad);
- fileRequested = EDSN;
- break;
- }
- File file = new File(WEB_ROOT, fileRequested);
- int fileLength = (int) file.length();
- String content = null;
- if(getContentType(fileRequested)== "text/plain") {
- content = "text/xml";
- }else {
- content = getContentType(fileRequested);
- }
- if (method.equals("GET")) { // GET method so we return content
- byte[] fileData = readFileData(file, fileLength);
- // send HTTP Headers
- out.println("HTTP/1.1 200 OK");
- out.println("Server: Java HTTP Server from SSaurel : 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println(); // blank line between headers and content, very important !
- out.println(payLoad);
- out.flush(); // flush character output stream buffer
- //dataOut.write(fileData, 0, fileLength);
- //dataOut.flush();
- }
- if (verbose) {
- System.out.println("File " + fileRequested + " of type " + content + " returned");
- }
- }
- } catch (FileNotFoundException fnfe) {
- try {
- fileNotFound(out, dataOut, fileRequested);
- } catch (IOException ioe) {
- System.err.println("Error with file not found exception : " + ioe.getMessage());
- }
- } catch (IOException ioe) {
- System.err.println("Server error : " + ioe);
- } finally {
- try {
- in.close();
- out.close();
- dataOut.close();
- connect.close(); // we close socket connection
- } catch (Exception e) {
- System.err.println("Error closing stream : " + e.getMessage());
- }
- if (verbose) {
- System.out.println("Connection closed.\n");
- }
- }
- }
- /**
- *
- * @param file file that's being returned
- * @param fileLength length of the file being returned
- * @return returns the fileData
- * @throws IOException
- */
- private byte[] readFileData(File file, int fileLength) throws IOException {
- FileInputStream fileIn = null;
- byte[] fileData = new byte[fileLength];
- try {
- fileIn = new FileInputStream(file);
- fileIn.read(fileData);
- } finally {
- if (fileIn != null)
- fileIn.close();
- }
- return fileData;
- }
- /**
- * Returns the supported MIME type
- * @param fileRequested the file that needs to be checked for MIME type
- * @return MIME type corresponding with fileRequested
- */
- private String getContentType(String fileRequested) {
- if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
- return "text/html";
- else
- return "text/plain";
- }
- /**
- * Method that gets called when the file is not found
- * @param out print writer to print to console
- * @param dataOut the outputstream that gets written to the file
- * @param fileRequested the requested file, to print out in message when it's not found
- * @throws IOException
- */
- private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, FILE_NOT_FOUND);
- //File file = new File("index.html");
- int fileLength = (int) file.length();
- String content = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 404 File Not Found");
- out.println("Server: Java HTTP Server from SSaurel : 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println(); // blank line between headers and content, very important !
- out.flush(); // flush character output stream buffer
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- if (verbose) {
- System.out.println("File " + fileRequested + " not found");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement