KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > filesrv > CommandHandler


1 /*
2  * This file is part of the QuickServer library
3  * Copyright (C) 2003-2005 QuickServer.org
4  *
5  * Use, modification, copying and distribution of this software is subject to
6  * the terms and conditions of the GNU Lesser General Public License.
7  * You should have received a copy of the GNU LGP License along with this
8  * library; if not, you can download a copy from <http://www.quickserver.org/>.
9  *
10  * For questions, suggestions, bug-reports, enhancement-requests etc.
11  * visit http://www.quickserver.org
12  *
13  */

14
15 package filesrv;
16
17 import java.net.*;
18 import java.io.*;
19 import java.util.*;
20 import org.quickserver.net.server.*;
21 import java.util.logging.*;
22 import org.quickserver.util.MyString;
23
24 /**
25  * FileServer Example
26  * @author Akshathkumar Shetty
27  */

28 public class CommandHandler
29         implements ClientEventHandler, ClientCommandHandler, ClientWriteHandler {
30     private static Logger logger =
31         Logger.getLogger(CommandHandler.class.getName());
32
33     public void gotConnected(ClientHandler handler)
34             throws SocketTimeoutException, IOException {
35         logger.fine("Connection opened: "+handler.getSocket().getInetAddress());
36         //handler.setDataMode(DataMode.BYTE, DataType.OUT); //pick from xml
37
}
38
39     public void lostConnection(ClientHandler handler) throws IOException {
40         cleanByteBuffer(handler);
41         logger.fine("Connection lost: "+handler.getSocket().getInetAddress());
42     }
43     public void closingConnection(ClientHandler handler) throws IOException {
44         cleanByteBuffer(handler);
45         logger.fine("Connection closed: "+handler.getSocket().getInetAddress());
46     }
47     private void cleanByteBuffer(ClientHandler handler) {
48         Data data = (Data)handler.getClientData();
49         data.cleanPooledByteBuffer(handler.getServer());
50     }
51
52
53     public void handleCommand(ClientHandler handler, String JavaDoc command)
54             throws SocketTimeoutException, IOException {
55
56         Data data = (Data)handler.getClientData();
57         try {
58              if(data.isHeaderReady()==false) {
59                  if(command.startsWith("GET /")) {
60                      data.initHeader(command);
61                  } else {
62                     serveBadRequest(handler, BAD_REQUEST);
63                     handler.closeConnection();
64                  }
65                  return;
66              }
67
68              if(data.addHeader(command)==false) {
69                  return;
70              }
71
72             if(data.isDirList()) {
73                 listDir(handler, data);
74             } else {
75                 if(handler.getServer().getConfig().getServerMode().getBlocking()) {
76                     data.sendFileBlocking(handler);
77                 } else {
78                     data.sendFileNonBlocking(handler);
79                 }
80             }
81         } catch(BadRequestException e) {
82             logger.fine("BadRequestException : "+e);
83             serveBadRequest(handler, ERROR_HEADER+"Bad Req: "+e.getMessage()+
84                 ERROR_FOOTER, "400 Bad Request");
85             handler.closeConnection();
86         } catch(Exception JavaDoc e) {
87             logger.info("Error processing : "+MyString.getStackTrace(e));
88             try {
89                 serveBadRequest(handler, ERROR_HEADER+"Bad Req: "+e.getMessage()+
90                     ERROR_FOOTER);
91             } catch(Exception JavaDoc err) {
92                 logger.warning("Error processing error: "+err);
93             }
94             handler.closeConnection();
95         }
96     }
97
98     private void listDir(ClientHandler handler, Data data)
99             throws IOException {
100         String JavaDoc content = data.getDirList();
101
102         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
103         sb.append("HTTP/1.1 200 OK\r\n");
104         sb.append("Server: ").append(handler.getServer().getName()).append("\r\n");
105         sb.append("Content-Type: text/html").append("\r\n");;
106         sb.append("Content-Length: "+content.length()).append("\r\n");;
107         sb.append("\r\n");
108         sb.append(content);
109
110         if(handler.getServer().getConfig().getServerMode().getBlocking()) {
111             handler.sendClientBytes(sb.toString());
112             handler.closeConnection();
113         } else {
114             logger.fine("Will Send: \n"+sb.toString());
115             data.makeNonBlockingWrite(handler, sb.toString().getBytes(),
116                 false, "Sending HTTP header with dir list.", true);
117         }
118     }
119
120     private void serveBadRequest(ClientHandler handler, String JavaDoc error) throws IOException {
121         serveBadRequest(handler, error, "500 Internal Server Error");
122     }
123
124     private void serveBadRequest(ClientHandler handler, String JavaDoc error, String JavaDoc msg) throws IOException {
125         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
126
127         sb.append("HTTP/1.1 ").append(msg).append("\r\n");
128         sb.append("Server: ").append(handler.getServer().getName()).append("\r\n");
129         sb.append("Content-Type: text/html").append("\r\n");;
130         sb.append("Content-Length: "+error.length()).append("\r\n");;
131         sb.append("\r\n");
132         sb.append(error);
133         handler.sendClientBytes(sb.toString());
134     }
135
136     public void handleWrite(ClientHandler handler)
137             throws IOException {
138         handler.isConnected();
139         Data data = (Data)handler.getClientData();
140         try {
141             data.writeData(handler);
142         } catch(Exception JavaDoc e) {
143             logger.fine("Error processing: "+e);
144             if(data.getWroteFileHttpHeader()==false) {
145                 try {
146                     serveBadRequest(handler, ERROR_HEADER+"Error processing: "+e.getMessage()+
147                         ERROR_FOOTER);
148                 } catch(Exception JavaDoc err) {
149                     logger.warning("Error processing error: "+err);
150                 }
151             }
152             handler.closeConnection();
153         }
154         
155     }
156
157     //-- ERRORS--
158
private static final String JavaDoc ERROR_HEADER = "<html>\r\n<head>\r\n<title>HFtp Server - Error</title>\r\n</head>\r\n"+
159         "<body>"+"<H3>HFtp Server - Error</H3><hr/><font color=\"red\">";
160     private static final String JavaDoc ERROR_FOOTER = "</font><hr/>\r\n</body>\r\n</html>";
161     private static final String JavaDoc BAD_REQUEST = ERROR_HEADER+
162         "HTTP GET requests are only supported!"+ERROR_FOOTER;
163         
164 }
165
Popular Tags