⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 requesthandler.java

📁 轻量级Http代理服务器
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                    outEx.write(outStr.getBytes());
                }
                else {
                    log(DEBUG,"Content is non HTML; just send it");
                    outEx.write(outStream.toByteArray());
                }
                log(DEBUG,"internal response data sent to external socket");
            }
            else {
                log(INFO,"no internal response data available");
                sendBadRequestResponse(outEx,"No data received");
                
                // let's reset the logger back to the original
                logger = oldLogger;
                return;
            }
            
            outEx.flush();
            outEx.close();
        }
        catch(HTTPFormatException e) {
            log(e);
            sendBadRequestResponse(outEx,"HTTP request received not valid");
            // let's reset the logger back to the original
            logger = oldLogger;
            return;
        }
        catch(IOException e) {
            log(e);
            sendBadRequestResponse(outEx,"IOException");
            // let's reset the logger back to the original
            logger = oldLogger;
            return;
        }
        catch(Exception e) {
            log(e);
            sendBadRequestResponse(outEx,"No data received");
            // let's reset the logger back to the original
            logger = oldLogger;
            return;
        }
        
        // let's reset the logger back to the original
        logger = oldLogger;
    }
    
    /** 
     * Handles a external socket connection by requesting a pool instance
     * and executing the requesthandler thread code
     * 
     * @param socket the socket instance representing the incoming connection
     */
    public synchronized void handle(Socket socket) throws Exception {
        log(METHOD,"--handle--");
        this.socket = socket;
        manager.run(this);
    }
    
    public void log(Throwable e) {
        if(logger != null)
            logger.log(e);
    }
    
    public void log(int level, String str) {
        if(logger != null)
            logger.log(level,"[RequestHandler] " + str);
    }
    
    public void log(ILog logger,Throwable e) {
        if(logger != null)
            logger.log(e);
    }
    
    public void log(ILog logger, int level, String str) {
        if(logger != null)
            logger.log(level,"[RequestHandler] " + str);
    }
    
    public void setRuleset(Ruleset ruleset) {
        this.ruleset = ruleset;
    }
    
    /**
     * Send an HTML message indicating that the user does not have enough privileges to get the requested info
     * @param out the outputstream to which the message has to be send
     */
    private void sendNotAuthorizedResponse(OutputStream out) {
        log(METHOD,"--sendNotAuthorizedResponse--");
        
        try {
            out.write("HTTP/1.0 200 OK\r\n".getBytes());
            out.write("Content-Type:text/html\r\n\r\n".getBytes());
            StringBuffer buf = new StringBuffer();
            buf.append("\r\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\r\n");
            buf.append("<HTML><HEAD><TITLE>JRevProxy</TITLE></HEAD>\r\n");
            buf.append("<FONT face=\"Verdana,Arial,Arial Bold\">\r\n");
            buf.append("<H1>Access Denied!</H1>\r\n");
            buf.append("<BODY><p><H2>You do not enough priviliges to access the requested resource</H2></p>\r\n");
            buf.append("</FONT>\r\n");
            buf.append("</BODY></HTML>");
            out.write(new String(buf).getBytes());
            out.flush();
            out.close();
        }
        catch(IOException ioe){}
    }
    
    private void sendBadRequestResponse(OutputStream out, String description) {
        log(METHOD,"--sendBadRequestResponse--");
        sendErrorResponse(out,400, description);
    }
    
    private void sendNotFoundResponse(OutputStream out, String description) {
        log(METHOD,"--sendNotFoundResponse--");
        sendErrorResponse(out,404, description);
    }
    
    private void sendErrorResponse(OutputStream out, int errorcode, String description) {
        log(METHOD,"--sendErrorResponse--");
        try {
            out.write(("HTTP/1.0 " + errorcode +" "+ description + "\r\n").getBytes());
            out.write("Content-Type:text/html\r\n\r\n".getBytes());
            out.flush();
            out.close();
        }
        catch(IOException ioe){}
        
    }
    
    private ByteArrayOutputStream readRequest(InputStream inEx) {
        return read(inEx,false);
    }
    
    private ByteArrayOutputStream readResponse(InputStream inEx) {
        return read(inEx,true);
    }
    
    /**
     * Reads bytes from the provided socket; The read operation stop when one of the following condition are triggered: <p>
     * * SocketTimeOutException
     * * Read operation time out
     * * EOF (End of File)
     * * The total request indicated by the "Content-Length" header has been read (only in case of HTTP Responses)
     *
     * @param inEx InputStream
     * @param isResponse true if the info to be read is a HTTPResponse, false in the other case
     * @return the bytearray holding the information read
     **/
    private ByteArrayOutputStream read(InputStream inEx, boolean isResponse) {
        log(METHOD,"--read--");
        // create a temporary read buffer and a stream where we will put all our read information
        byte[] buffer = new byte[512];
        boolean readOn = false;
        int nBytes = 0, totalRequestLength = 0;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        
        // calculate our starttime; used to calculate if we get a timeout
        long startTime = System.currentTimeMillis();
        do {
            try {
                nBytes = inEx.read(buffer, 0, buffer.length);
            }
            catch (SocketTimeoutException st) {
                // will jump here in case we have a read timeout
                log(DEBUG,"inEx.read-> SocketTimeoutException");
                //     log(st);
                // we assume that this is the end of the request and jump out of the loop
                // in case we have already some data
                // otherwise we wait for additional data
                if(outStream.size() == 0 || (isResponse && (outStream.size() < totalRequestLength)))
                    continue;
                else
                    break;
            }
            catch (IOException e) {
                // will jump here in case we have end of stream
                log(DEBUG,"inEx.read-> IOException");
                log(e);
                // we assume that this is the end of the request and jump out of the loop
                break;
            }
            // we do not have any data anymore so we stop reading
            if (nBytes <= 0) {
                log(DEBUG,"inEx -> nBytes <= 0");
            }
            else {
                // append what we read to the stream
                outStream.write(buffer, 0, nBytes);
            }
            
            // if it takes too much time the we will stop reading
            if (timeout >= 0)
                if (System.currentTimeMillis() - startTime >= timeout) {
                    log(INFO,"external request read timeout");
                    break;
                }
            
            if(isResponse) {
                if(totalRequestLength == 0) {
                    totalRequestLength = HTTPResponse.getTotalResponseLength(outStream.toString());
                    log(DEBUG,"nr bytes to be read: " + totalRequestLength);
                }
                // nBytes == -1 means EOF
                if(totalRequestLength > 0)
                    readOn = nBytes > 0 && (outStream.size() < totalRequestLength);
                else
                    readOn = nBytes > 0;
            }
            else
                readOn = nBytes > 0;
            log(DEBUG,"nBytes: " + nBytes + " already read: " + outStream.size());
        }
        while (readOn);
        
        return outStream;
    }
}

/**
 * HTTP return codes
 * Status-Code    =    "200"   ; OK
 * | "201"   ; Created
 * | "202"   ; Accepted
 * | "204"   ; No Content
 * | "301"   ; Moved Permanently
 * | "302"   ; Moved Temporarily
 * | "304"   ; Not Modified
 * | "400"   ; Bad Request
 * | "401"   ; Unauthorized
 * | "403"   ; Forbidden
 * | "404"   ; Not Found
 * | "500"   ; Internal Server Error
 * | "501"   ; Not Implemented
 * | "502"   ; Bad Gateway
 * | "503"   ; Service Unavailable
 *
 */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -