File: PluggableHTTPServer.java

package info (click to toggle)
apache-log4j1.2 1.2.17-7%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 4,880 kB
  • sloc: java: 35,228; xml: 4,813; cpp: 252; perl: 69; makefile: 30; sh: 14
file content (262 lines) | stat: -rw-r--r-- 8,170 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.psibt.framework.net;

import java.net.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;

/**
 * This class implements a HTTP-server frame. All HTTP-requests are handled by HTTPRequestHandler
 * classes which implement the <code>HTTPRequestHandler</code> interface. Every RequestHandler has
 * to be registered in the PluggableHTTPServer with the <code>addRequestHandler</code> method.
 * A new thread is created for each connection to handle the request. If all reply data are sent
 * to the client the connection is closed and the thread ends.
 * An example how to use the PluggableHTTPServer class can be found in the <code>main</code> method
 * at the end of the source file.
 *
 * @author <a HREF="mailto:V.Mentzner@psi-bt.de">Volker Mentzner</a>
 */
public class PluggableHTTPServer implements Runnable {

  public static final int DEFAULT_PORT = 80;
  static Category cat = Category.getInstance("PluggableHTTPServer");
  private int port;
  private Vector handler;
  private ServerSocket server;

  /**
   * Creates a new server object on the given TCP port.
   * If the port is occupied by another process a IOException (java.net.BindException) is thrown.
   *
   * @param port - TCP port number to listen on for requests
   */
  public PluggableHTTPServer(int port) throws IOException {
    this.port = port;
    this.handler = new Vector();
    cat.setPriority(Priority.ERROR);
    server = new ServerSocket(this.port);
  }

  /**
   * Creates a new server object on the default TCP port 80
   * If the port is occupied by another process a IOException (java.net.BindException) is thrown.
   */
  public PluggableHTTPServer() throws IOException {
    this(DEFAULT_PORT);
  }

  /**
   * Registers the given HTTPRequestHandler
   *
   * @param h - the HTTPRequestHandler to register
   */
  public void addRequestHandler(HTTPRequestHandler h) {
    handler.add(h);
  }

  /**
   * Unregisters the given HTTPRequestHandler
   *
   * @param h - the HTTPRequestHandler to unregister
   */
  public void removeRequestHandler(HTTPRequestHandler h) {
    handler.remove(h);
  }

  /**
   * Sends the HTTP message 404 - File Not Found
   * see RFC2616 for details
   *
   * @param out - Out stream for sending data to client browser
   */
  public static void replyNotFound(Writer out) {
    try {
      out.write("HTTP/1.0 404 Not Found\r\n");
      out.write("<HTML><HEAD><TITLE>Not Found</TITLE></HEAD>\r\n");
      out.write("<BODY><H1>Not Found</H1>\r\n");
      out.write("</BODY></HTML>\r\n");
      out.flush();
    }  // end try
    catch (IOException e) {
    }
  }

  /**
   * Sends the HTTP message 405 - Method Not Allowed
   * see RFC2616 for details
   *
   * @param out - Out stream for sending data to client browser
   */
  public static void replyMethodNotAllowed(Writer out) {
    try {
      out.write("HTTP/1.1 405 Method Not Allowed\r\n");
      out.write("Allow: GET, PUT\r\n");
      out.write("<HTML><HEAD><TITLE>Method Not Allowed</TITLE></HEAD>\r\n");
      out.write("<BODY><H1>Method Not Allowed</H1>\r\n");
      out.write("</BODY></HTML>\r\n");
      out.flush();
    }  // end try
    catch (IOException e) {
    }
  }

  /**
   * Creates the ReplyHTML data for the root page
   *
   * @param index - index of the RootRequestHandler
   */
  public void autoCreateRootPage(int index) {
    if (handler.get(index) instanceof RootRequestHandler) {
      RootRequestHandler r = (RootRequestHandler)handler.get(index);
      String html = "<HTML><HEAD><TITLE>"+r.getTitle()+"</TITLE></HEAD>\r\n";
      html = html + "<BODY><H1>"+r.getDescription()+"</H1>\r\n";
      for (int i = 0; i < handler.size(); i++) {
        html = html + "<a href=\"" + ((HTTPRequestHandler)handler.get(i)).getHandledPath();
        html = html + "\">" + ((HTTPRequestHandler)handler.get(i)).getDescription() + "</a><br>";
      }
      html = html + "</BODY></HTML>\r\n";
      r.setReplyHTML(html);
    }
  }

  /**
   * Main loop of the PluggableHTTPServer
   */
  public void run() {
    while (true) {
      try {
        Socket s = server.accept();
        Thread t = new ServerThread(s);
        t.start();
      }
      catch (IOException e) {
      }
    }
  }

  /**
   * This class handles the incomming connection for one request.
   */
  class ServerThread extends Thread {

    private Socket connection;

    ServerThread(Socket s) {
      this.connection = s;
    }

    /**
     * Serves the HTTP request.
     */
    public void run() {
      try {
        Writer out = new BufferedWriter(
                      new OutputStreamWriter(
                       connection.getOutputStream(), "ASCII"
                      )
                     );
        Reader in = new InputStreamReader(
                     new BufferedInputStream(
                      connection.getInputStream()
                     )
                    );

        // read the first line only; that's all we need
        StringBuffer req = new StringBuffer(80);
        while (true) {
          int c = in.read();
          if (c == '\r' || c == '\n' || c == -1) break;
          req.append((char) c);
        }
        String get = req.toString();
        cat.debug(get);
        StringTokenizer st = new StringTokenizer(get);
        String method = st.nextToken();
        String request = st.nextToken();
        String version = st.nextToken();

        if (method.equalsIgnoreCase("GET")) {
          boolean served = false;
          for (int i = 0; i < handler.size(); i++) {
            if (handler.get(i) instanceof HTTPRequestHandler) {
              if (((HTTPRequestHandler)handler.get(i)).handleRequest(request, out)) {
                served = true;
                break;
              }
            }
          }
          if (!served)
            PluggableHTTPServer.replyNotFound(out);
        }
        else {
          PluggableHTTPServer.replyMethodNotAllowed(out);
        }
      } // end try
      catch (IOException e) {
      }
      finally {
        try {
          if (connection != null) connection.close();
        }
        catch (IOException e) {}
      }
    }  // end run
  }  // end class ServerThread

  /**
   * Demo how to use the PluggableHTTPServer.
   */
  public static void main(String[] args) {

    int thePort;

    // create some logging stuff
    BasicConfigurator.configure();
    Category cat1 = Category.getInstance("cat1");
    cat1.addAppender(new org.apache.log4j.ConsoleAppender(new PatternLayout("%m%n")));
    Category cat2 = Category.getInstance("cat2");
    cat2.setPriority(Priority.INFO);
    cat2.addAppender(new org.apache.log4j.ConsoleAppender(new PatternLayout("%c - %m%n")));

    // set TCP port number
    try {
      thePort = Integer.parseInt(args[1]);
    }
    catch (Exception e) {
      thePort = PluggableHTTPServer.DEFAULT_PORT;
    }

    PluggableHTTPServer server = null;
    while (server == null) {
      try {
        server = new PluggableHTTPServer(thePort);
        server.addRequestHandler(new RootRequestHandler());
        server.addRequestHandler(new Log4jRequestHandler());
        server.addRequestHandler(new UserDialogRequestHandler());
        server.autoCreateRootPage(0);
        Thread t = new Thread(server);
        t.start();
      } catch (IOException e) {
        server = null;
        thePort++;
      }
    }

  }  // end main
}