Web Server

0 respostas
bpinheiro
Boa Noite Pessoal. Sera que alguem pode me ajudar a comentar o codigo abaixo por favor:
package Teste4;

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

class WebServer {
	
	static boolean metodoGET (boolean isGET,StringTokenizer tokenizedLine, 
							  DataOutputStream outToClient, Socket connectionSocket,
							  BufferedReader inFromClient) {
		String fileName = tokenizedLine.nextToken();
        if (fileName.startsWith("/") == true) {
            if (fileName.endsWith("/"))
               	fileName += "index.html";
            fileName = fileName.substring(1);
        }
        fileName = ajustaEspacos(fileName);
        try {
	        if (fileName.equals("home.htm")) {
    	     	outToClient.writeBytes("HTTP/1.0 301 Moved Permanently\r\n");
        	   	outToClient.writeBytes("Location: index.htm\r\n");
   	    	}
        
            File file = new File(fileName);
            if (file.exists()) {
            	                    
				getLastModified(file.lastModified());
					
	            int numOfBytes = (int) file.length();
   		        FileInputStream inFile = new FileInputStream(fileName);
        	    byte[] fileInBytes = new byte[numOfBytes];
            	inFile.read(fileInBytes);
       	    	outToClient.writeBytes(
           	    	"HTTP/1.0 200 Document Follows\r\n");
                   	 	
       	    	if (fileName.endsWith(".jpg"))
        	         outToClient.writeBytes("Content-Type: image/jpeg\r\n");
        	    if (fileName.endsWith(".bmp"))
        	         outToClient.writeBytes("Content-Type: image/x-xbitmap\r\n");
        	    if (fileName.endsWith(".xls"))
        	         outToClient.writeBytes("Content-Type: application/vnd.ms-excel\r\n");
        	    if (fileName.endsWith(".ppt") || fileName.endsWith(".pps"))
        	         outToClient.writeBytes("Content-Type: application/vnd.ms-powerpoint\r\n");
        	    if (fileName.endsWith(".doc"))
        	         outToClient.writeBytes("Content-Type: application/msword\r\n");
        	    if (fileName.endsWith(".swf"))
        	         outToClient.writeBytes("Content-Type: application/x-shockwave-flash\r\n");
            	if (fileName.endsWith(".gif"))
                	 outToClient.writeBytes("Content-Type: image/gif\r\n");
                 	    
                 	        
	            outToClient.writeBytes("Last-Modified: "+
    	        						getLastModified(file.lastModified())
        	     						+"\r\n");
       	    	outToClient.writeBytes("Content-Length: " +
	                        	    numOfBytes + "\r\n");
	            outToClient.writeBytes("\r\n");
   		        
   		        if (isGET)
       		    	outToClient.write(fileInBytes, 0, numOfBytes);
       		    	
       		} else {
       			System.out.println("Nao Existe!!");
            	outToClient.writeBytes(
                   	"HTTP/1.1 404 File Not Found\r\n");
                connectionSocket.close();
            }
        } catch (Exception fne) {
        	try {
           	outToClient.writeBytes(
                	"HTTP/1.0 404 File Not Found\r\n");
                } catch (Exception e) {
                }
        }	  
        return false;
	}
	
	static void metodoPOST (StringTokenizer tokenizedLine, DataOutputStream outToClient,
							Socket connectionSocket, BufferedReader inFromClient) {
		try {
			String nome = null;
			int idade = 0;
			outToClient.writeBytes(
    	       	    	"HTTP/1.0 200 Document Follows\r\n");
    	    String dados = null;
            while (inFromClient.ready()) {
            	dados = inFromClient.readLine();
            	System.out.println(dados);
            	if (dados.startsWith("nome")) {
            		StringTokenizer token = new StringTokenizer(dados,"=&");
            		token.nextToken();
            		nome = token.nextToken();
            		String resultado = "";
            		for (int i = 0; i < nome.length(); i++)
						if (nome.charAt(i) == '+') {
							resultado += ' ';
						} else 
							resultado += nome.charAt(i);
					nome = resultado;
            	}
            }
	        outToClient.writeBytes("\r\n");
    	    outToClient.writeBytes("<HTML>\n<BODY>\n\n<table border=\"0\" width=\"100%\">"+
  			"<td width=\"100%\">\n<p ><b><font color=\"#0000FF\" size=\"5\">"+nome+"</font></b></p>"
			+"</td>\n</table>\n<p > <font size=\"4\"> <font color=\"#FF0000\">Lamento Informar"+
			" Mas você irá MORRER em "+nome.hashCode()%20+" ano(s)!! Aproveite as Farras!!!</font></font></p>\n</BODY>\n</HTML>");
  		} catch (Exception e) {
  		}
	}
	static void metodoDELETE(StringTokenizer tokenizedLine,DataOutputStream outToClient){
		String nomeArquivo = tokenizedLine.nextToken();
		if (this.nomeArquivo.startsWith("/")) 
			this.nomeArquivo = nomeArquivo.substring(1);
		
		try{
			File arquivo = new File(nomeArquivo); // tem que ficcar pq se der bad request o arquivo naunseria criado e no metodo erro da nullpointer
			arquivo = new File(nomeArquivo);
			arquivo.delete();
		}catch(Exception e){
			outToClient.writeBytes("HTTP/1.0 400 Bad Request Message\r\n");
		}
	}

	static String getLastModified (long dados) 
	{
	    StringTokenizer extenso = new StringTokenizer(new Date(dados).toString());
	    String retorno = extenso.nextToken();
	    String mes = extenso.nextToken();
    	retorno = retorno + ", " + extenso.nextToken() + " " + mes + " ";
	  	String hora = extenso.nextToken();
//	  	Date d = new Date(new Date().parse("Wed, 12 Aug 1998 15:39:29"));
	  	
	   	extenso.nextToken();
	    retorno += extenso.nextToken() + " " + hora;
//	   	System.out.println(retorno);
        return retorno;
	}
	
	static String ajustaEspacos (String nome) {
		String retorno = "";
		int tamanho = nome.length();
		for (int i = 0; i < nome.length() - 3; i++) {
			if (nome.substring(i, i+3).equals("%20")) {
				retorno += " ";
				i += 2;
			} else if (nome.substring(i, i+3).equals("%27")) {
				retorno += "'";
				i += 2;
			} else {
				retorno += nome.charAt(i);
			}
		}
		retorno += nome.substring(tamanho-3, tamanho);
		return retorno;		
	}
	
    public static void main(String argv[]) throws Exception {

        String requestMessageLine;
        String fileName;

        ServerSocket listenSocket = new ServerSocket(6789);
        while (true) {
            Socket connectionSocket = listenSocket.accept();

            BufferedReader inFromClient =
                new BufferedReader(new InputStreamReader(
                connectionSocket.getInputStream()));

            DataOutputStream outToClient =
                new DataOutputStream(
                connectionSocket.getOutputStream());

            requestMessageLine = inFromClient.readLine();
            System.out.println(requestMessageLine+"\n");
            StringTokenizer tokenizedLine =
                new StringTokenizer(requestMessageLine);
			
			String metodo = tokenizedLine.nextToken();
			
/*			while (inFromClient.ready())
				System.out.println(inFromClient.readLine());
*/
            if (metodo.equals("GET") && (requestMessageLine.endsWith("HTTP/0.9")
            || requestMessageLine.endsWith("HTTP/1.0") || requestMessageLine.endsWith("HTTP/1.1"))) {
            	
	            metodoGET(true,tokenizedLine, outToClient, connectionSocket, inFromClient);
	            
            } else if (metodo.equals("HEAD")&& (requestMessageLine.endsWith("HTTP/0.9")
            || requestMessageLine.endsWith("HTTP/1.0") || requestMessageLine.endsWith("HTTP/1.1"))) {
            	
            	metodoGET(false,tokenizedLine, outToClient, connectionSocket, inFromClient);
            	
			} else if (metodo.equals("POST") && (requestMessageLine.endsWith("HTTP/0.9")
				|| requestMessageLine.endsWith("HTTP/1.0") || requestMessageLine.endsWith("HTTP/1.1"))) {
            	
				metodoPOST(tokenizedLine, outToClient, connectionSocket, inFromClient);
            	
			} else if (metodo.equals("DELETE") && (requestMessageLine.endsWith("HTTP/0.9")
						|| requestMessageLine.endsWith("HTTP/1.0") || requestMessageLine.endsWith("HTTP/1.1"))) {
            	
						metodoDELETE(tokenizedLine, outToClient);
            	
			}else{
            	outToClient.writeBytes("HTTP/1.0 400 Bad Request");
            }


       		connectionSocket.close();
        }
    }
}
Criado 2 de junho de 2009
Respostas 0
Participantes 1