1 17 18 package tutorial; 19 20 import java.io.ByteArrayOutputStream ; 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.net.ProtocolException ; 24 import java.net.Socket ; 25 import java.nio.ByteBuffer ; 26 27 import org.apache.avalon.cornerstone.services.connection.ConnectionHandler; 28 import org.apache.avalon.framework.logger.Logger; 29 30 41 public class SimpleConnectionHandler 42 implements ConnectionHandler { 43 46 private Logger m_logger; 47 48 57 public void handleConnection(Socket socket) throws IOException , 58 ProtocolException { 59 Request req; 60 61 String remoteHost = socket.getInetAddress().getHostName(); 63 String remoteIP = socket.getInetAddress().getHostAddress(); 64 getLogger().info("Connection received on port " + socket.getLocalPort() 65 + " from " + remoteHost + " (" + remoteIP + ")"); 66 67 InputStream input = socket.getInputStream(); 69 ByteArrayOutputStream output = new ByteArrayOutputStream (); 70 byte[] bytes = new byte[1024]; 71 int count = input.read(bytes); 72 while (count > -1) { 73 output.write(bytes, 0, count); 74 if (input.available() == 0) { 75 break; 76 } 77 count = input.read(bytes); 78 } 79 output.flush(); 80 output.close(); 81 82 getLogger().debug("Preparing byte buffer..."); 83 ByteBuffer bb = ByteBuffer.allocate(output.size()); 84 bb.put(output.toByteArray()); 85 bb.flip(); 86 getLogger().debug("Byte buffer prepared"); 87 try { 88 getLogger().debug("Parsing request..."); 89 req = Request.parse(bb); 90 } 91 catch (MalformedRequestException e) { 92 getLogger().error(e.getMessage(), e); 93 throw new ProtocolException (e.getMessage()); 94 } 95 96 if (!req.isGet()) { 98 getLogger().debug("Sending HTTP 405..."); 99 Reply.sendHttpReply(socket.getOutputStream(), Reply.HTTP_405, 100 "This server only accepts GET"); 101 } 102 else { 103 getLogger().debug("Sending HTTP 200..."); 104 Reply.sendHttpReply(socket.getOutputStream(), Reply.HTTP_200, 105 "Hello, World!"); 106 } 107 } 108 109 112 public void setLogger(Logger logger) { 113 m_logger = logger; 114 } 115 116 120 private Logger getLogger() { 121 return m_logger; 122 } 123 } 124 | Popular Tags |