Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * Clasa ce implementeaza parsarea header-elor HTTP.
- * Se interpreteaza cererea utilizatorului.
- *Se livreaza pagina ceruta, in cazul in care aceasta exista.
- * @author Apostol Ioana
- */
- public class HTTP_parser{
- /**
- * Declararea si instantierea membrilor clasei Parser
- * Realizarea administrarii conexiunii clientului
- */
- static final File WEB_ROOT = new File(".");
- static final String DEFAULT_FILE = "index.html";
- static final String MOVED_PERMANENTLY = "301.html";
- static final String BAD_REQUEST = "400.html";
- static final String UNAUTHORIZED= "401.html";
- static final String FILE_NOT_FOUND = "404.html";
- static final String INTERNAL_SERVER_ERR = "500.html";
- static final String NOT_IMPLEMENTED = "501.html";
- static final String HTTPversion_NOTsupported = "505.html";
- static final boolean verbose = true;
- static String fileRequested=null;
- static Logger a = Logger.getInstance();
- static String mod = ReadFile.getLoglevel();
- private static int PortClient;
- public static void Parser(Socket connect) {
- PortClient=JavaHTTPServer.getPortClient();
- BufferedReader in = null;
- PrintWriter out = null;
- BufferedOutputStream dataOut = null;
- // String fileRequested = null;
- try {
- // Se citesc caracterele de la client prin intermediul stream-ului de input din socket
- in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
- // Se obtine stream-ul de output de caractere catre client (pentru headere)
- out = new PrintWriter(connect.getOutputStream());
- // Se obtine stream-ul binar de output catre client (pentru datele cerute)
- dataOut = new BufferedOutputStream(connect.getOutputStream());
- // Se citeste prima linie din cererea clientului
- String input = in.readLine();
- // se interpreteaza cererea cu un string tokenizer
- StringTokenizer parse = new StringTokenizer(input);
- String method = parse.nextToken().toUpperCase(); //Se obtine metoda HTTP a clientului
- // Se obtine pagina ceruta
- fileRequested = parse.nextToken().toLowerCase();
- if (!method.equals("GET") && !method.equals("POST")) {
- NotImplemented(out, dataOut, fileRequested);
- } else {
- if (fileRequested.endsWith("/")) {
- fileRequested += DEFAULT_FILE;
- }
- File file = new File(WEB_ROOT, fileRequested);
- int fileLength = (int) file.length();
- //Se returneaza tipul MIME(Multipurpose Internet Mail Extensions)
- String content = GetMimeType.getType(fileRequested);
- String[] phpCode;
- if (method.equals("GET")) {
- /*if(content.equals("text/html")){
- if(SenderPHP.PHP_identifier(fileRequested))
- phpCode = SenderPHP.SendFileRequested(fileRequested);
- } */
- byte[] fileData = readFileData(file, fileLength);
- // Se trimit header-ele HTTP
- out.println("HTTP/1.1 200 OK");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice= " ";
- Logger.notice += PortClient;
- Logger.notice += " GET ";
- Logger.notice += fileRequested ;
- Logger.notice += " 200 Ok ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"verbose"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- if(method.equals("POST")){
- File fileToRead = new File(WEB_ROOT, fileRequested);
- int fileLen = (int) file.length();
- if(fileToRead.isDirectory()){
- try {
- BadRequest(out,dataOut,fileRequested);
- } catch (IOException ioe1) {
- System.err.println("Bad Request : ");
- }
- }
- String contentType = GetMimeType.getType(fileRequested);
- if(contentType == null || !contentType.equals("application/x-www-form-urlencoded")){
- try {
- InternalServerError(out, dataOut, fileRequested);
- } catch (IOException ioe1) {
- Logger.error = "Server error";
- if(Objects.equals(mod,"error"))
- a.WriteFile1();
- }
- }
- String extension = fileRequested.substring(fileRequested.lastIndexOf('.') + 1);
- if(!extension.equalsIgnoreCase("cgi")){
- try {
- Unauthorized(out, dataOut, fileRequested);
- } catch (IOException ioe1) {
- System.err.println("Unauthorized : ");
- Logger.error = "Unauthorized ";
- if(Objects.equals(mod,"error"))
- a.WriteFile1(); }
- }
- ProcessBuilder pb = new ProcessBuilder(fileToRead.getAbsoluteFile().toString());
- Map<String, String> env = pb.environment();
- env.put("SCRIPT_NAME", fileRequested);
- ((Map) env).put("CONTENT_LENGTH", "" + fileLen);
- env.put("SERVER_NAME", connect.getInetAddress().toString());
- env.put("SERVER_PORT", "" + connect.getPort());
- String responsePayload = readInputStream(connect.getInputStream());
- String status;
- if(responsePayload.equals("")){
- status = "HTTP/1.0 204 No Content";
- }
- else status = "HTTP/1.0 200 OK";
- //set headers again
- String headerLines = addHeaders(fileToRead, responsePayload.length(),contentType);
- }
- }
- } catch (FileNotFoundException fnfe) {
- try {
- fileNotFound(out, dataOut, fileRequested);
- } catch (IOException ioe) {
- System.err.println("Error with file not found exception : " + ioe.getMessage());
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- in.close();
- out.close();
- dataOut.close();
- connect.close(); // Se inchide conexiunea
- } catch (Exception e) {
- System.err.println("Error closing stream : " + e.getMessage());
- }
- }
- }
- /**
- * Se citeste si se returneaza marimea paginii cerute, in cazul in care aceasta exista.
- * In caz contrar, se arunca o exceptie si se inchide fisierul.
- */
- static 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;
- }
- /**
- * Se trateaza cazul in care utilizatorul cere o pagina care nu exista.
- * Pentru aceasta situatie, codul de return este "404 File Not Found".
- */
- private static void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- Logger a = Logger.getInstance();
- File file = new File(WEB_ROOT, FILE_NOT_FOUND);
- 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: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice += " GET ";
- Logger.notice += "404 ";
- Logger.notice += fileRequested ;
- Logger.notice += " File Not Found ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- }
- /**
- * Codul de raspuns al statusului de redirect indica faptul ca resursa ceruta a fost mutata definitiv catre alt URL.
- * Browser-ul redirecteaza utilizatorul la aceasta pagina si cauta sa updateze link-urile catre resura ceruta.
- */
- private static void movedPermanently(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, MOVED_PERMANENTLY);
- int fileLength = (int) file.length();
- String content = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 301 Moved Permanently");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice += " GET ";
- Logger.notice += "301 ";
- Logger.notice += fileRequested ;
- Logger.notice += " Moved Permanently ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- /**
- * Cererea nu poate fi aplicata, deoarece lipsesc credentialele valide pentru autentificare, necesare resursei cerute.
- */
- private static void Unauthorized(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, UNAUTHORIZED);
- int fileLength = (int) file.length();
- String content = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 401 Unauthorized");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice += " GET ";
- Logger.notice += "401 ";
- Logger.notice += fileRequested ;
- Logger.notice += " Unauthorized ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- /**
- * Se indica faptul ca serverul nu a putut procesa cererea trimisa de catre client din cauza sintaxei invalide
- */
- private static void BadRequest(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, BAD_REQUEST);
- int fileLength = (int) file.length();
- String content = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 400 Bad Request");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice += " GET ";
- Logger.notice += "400 ";
- Logger.notice += fileRequested ;
- Logger.notice += " Bad Request ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- /**
- * Apare in momentul in care ceva nu functioneaza pe serverul site-ului, dar serverul nu poate specifica exact ce anume.
- */
- private static void InternalServerError(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, INTERNAL_SERVER_ERR);
- int fileLength = (int) file.length();
- String content = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 500 Internal Server Error");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice += " GET ";
- Logger.notice += "500 ";
- Logger.notice += fileRequested ;
- Logger.notice += " Internal Server Error ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- /**
- * Este tratat cazul in care serverul nu poate realiza functionalitatea ceruta pentru a indeplini cererea facuta de catre utilizator
- */
- private static void NotImplemented(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, NOT_IMPLEMENTED);
- int fileLength = (int) file.length();
- String content = "text/html";
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 501 Not Implemented");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + content);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice = " GET ";
- Logger.notice += "501 ";
- Logger.notice += fileRequested ;
- Logger.notice += " Not Implemented ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- /**
- * Se indica faptul ca serverul nu lucreaza cu versiunea de HTTP folosita in request
- */
- private static void NotSupported(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
- File file = new File(WEB_ROOT, HTTPversion_NOTsupported);
- int fileLength = (int) file.length();
- String contentMimeType = "text/html";
- //read content to return to client
- byte[] fileData = readFileData(file, fileLength);
- out.println("HTTP/1.1 505 Not Supported");
- out.println("Server: Java HTTP Server: 1.0");
- out.println("Date: " + new Date());
- out.println("Content-type: " + contentMimeType);
- out.println("Content-length: " + fileLength);
- out.println();
- out.flush();
- Logger.notice = " ";
- Logger.notice += PortClient;
- Logger.notice = " 505 ";
- Logger.notice += "400 ";
- Logger.notice += fileRequested ;
- Logger.notice += " Not Supported ";
- Logger.notice += new Date();
- Logger.notice += "\n";
- if(Objects.equals(mod,"error"))
- a.WriteFile();
- dataOut.write(fileData, 0, fileLength);
- dataOut.flush();
- }
- public String getFrom(String request) throws IOException{
- String [] lines = request.split("\r\n");
- for(String i: lines){
- String field = i.split(" ")[0];
- if(field.equals("From:")){
- return i.substring(6);
- }
- }
- return null;
- }
- public static String readInputStream(InputStream is) throws IOException{
- String retval = "";
- BufferedReader buff = new BufferedReader(new InputStreamReader(is));
- while(buff.ready()){
- retval += (char)buff.read();
- }
- return retval;
- }
- public static String addHeaders(File fileToRead, int CL, String type){
- String typeLine = "Content-Type: ";
- typeLine += type + '\r' + '\n';
- String lengthLine = "Content-Length: "+ CL + '\r' + '\n';
- long time = fileToRead.lastModified();
- String modifiedLine = "Last-Modified: " + getFormattedTime(time) + '\r' + '\n';
- String encodingLine = "Content-Encoding: identity" + '\r' + '\n';
- String allowLine = "Allow: GET, POST" + '\r' + '\n';
- String expireLine = "Expires: " + getFormattedTime(System.currentTimeMillis() + 525600) + '\r' + '\n';
- return typeLine + lengthLine + modifiedLine + encodingLine + allowLine + expireLine;
- }
- public static String getFormattedTime(long millis){
- DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
- Calendar calendar = Calendar.getInstance();
- calendar.setTimeInMillis(millis);
- String s = formatter.format(calendar.getTime());
- return s;
- }
- public static String getFileRequested(){
- return fileRequested;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement