Debian Codegraph @

src/java/org/astrogrid/samp/xmlrpc/internal/InternalServer.java

raw
1 package org.astrogrid.samp.xmlrpc.internal;
2
3 import java.io.BufferedOutputStream;
4 import java.io.ByteArrayInputStream;
5 import java.io.ByteArrayOutputStream;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.io.UnsupportedEncodingException;
9 import java.net.ServerSocket;
10 import java.net.URL;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.LinkedHashMap;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.logging.Level;
18 import java.util.logging.Logger;
19 import org.astrogrid.samp.SampUtils;
20 import org.astrogrid.samp.httpd.HttpServer;
21 import org.astrogrid.samp.httpd.UtilServer;
22 import org.astrogrid.samp.xmlrpc.SampXmlRpcHandler;
23 import org.astrogrid.samp.xmlrpc.SampXmlRpcServer;
24 import org.w3c.dom.Document;
25
26 /**
27 * SampXmlRpcServer implementation without external dependencies.
28 * The <code>reqInfo</code> argument passed to the
29 * {@link SampXmlRpcHandler#handleCall handleCall} method of registered
30 * <code>SampXmlRpcHandler</code>s is the associated
31 * {@link org.astrogrid.samp.httpd.HttpServer.Request}.
32 *
33 * @author Mark Taylor
34 * @since 27 Aug 2008
35 */
36 public class InternalServer implements SampXmlRpcServer {
37
38 private final HttpServer server_;
39 private final URL endpoint_;
40 private final List handlerList_;
41 private final HttpServer.Handler serverHandler_;
42 private static final HttpServer.Response GET_RESPONSE =
43 createInfoResponse( true );
44 private static final HttpServer.Response HEAD_RESPONSE =
45 createInfoResponse( false );
46
47 private static final Logger logger_ =
48 Logger.getLogger( InternalServer.class.getName() );
49
50 /**
51 * Constructor based on a given HTTP server.
52 * It is the caller's responsibility to configure and start the HttpServer.
53 *
54 * @param httpServer server for processing HTTP requests
55 * @param path path part of server endpoint (starts with "/");
56 */
57 public InternalServer( HttpServer httpServer, final String path )
58 throws IOException {
59 server_ = httpServer;
60 endpoint_ = new URL( server_.getBaseUrl(), path );
61 handlerList_ = Collections.synchronizedList( new ArrayList() );
62 serverHandler_ = new HttpServer.Handler() {
63 public HttpServer.Response serveRequest( HttpServer.Request req ) {
64 if ( req.getUrl().equals( path ) ) {
65 String method = req.getMethod();
66 if ( "POST".equals( method ) ) {
67 return getXmlRpcResponse( req );
68 }
69 else if ( "GET".equals( method ) ) {
70 return GET_RESPONSE;
71 }
72 else if ( "HEAD".equals( method ) ) {
73 return HEAD_RESPONSE;
74 }
75 else {
76 return HttpServer
77 .create405Response( new String[] { "POST", "GET",
78 "HEAD", } );
79 }
80 }
81 else {
82 return null;
83 }
84 }
85 };
86 }
87
88 /**
89 * Constructs a server running with default characteristics.
90 * Currently, the default server
91 * {@link org.astrogrid.samp.httpd.UtilServer#getInstance} is used.
92 */
93 public InternalServer() throws IOException {
94 this( UtilServer.getInstance().getServer(),
95 UtilServer.getInstance().getBasePath( "/xmlrpc" ) );
96 }
97
98 public URL getEndpoint() {
99 return endpoint_;
100 }
101
102 /**
103 * Returns the HTTP server hosting this XML-RPC server.
104 *
105 * @return http server
106 */
107 public HttpServer getHttpServer() {
108 return server_;
109 }
110
111 public void addHandler( SampXmlRpcHandler handler ) {
112 synchronized ( handlerList_ ) {
113 if ( handlerList_.isEmpty() ) {
114 server_.addHandler( serverHandler_ );
115 }
116 handlerList_.add( handler );
117 }
118 }
119
120 public void removeHandler( SampXmlRpcHandler handler ) {
121 synchronized ( handlerList_ ) {
122 handlerList_.remove( handler );
123 if ( handlerList_.isEmpty() ) {
124 server_.removeHandler( serverHandler_ );
125 }
126 }
127 }
128
129 /**
130 * Returns the HTTP response object given an incoming XML-RPC POST request.
131 * Any error should be handled by returning a fault-type methodResponse
132 * element rather than by throwing an exception.
133 *
134 * @param request POSTed HTTP request
135 * @return XML-RPC response (possibly fault)
136 */
137 protected HttpServer.Response
138 getXmlRpcResponse( HttpServer.Request request ) {
139 byte[] rbuf;
140 try {
141 rbuf = getResultBytes( getXmlRpcResult( request ) );
142 }
143 catch ( Throwable e ) {
144 boolean isSerious = e instanceof Error;
145 logger_.log( isSerious ? Level.WARNING : Level.INFO,
146 "XML-RPC fault return", e );
147 try {
148 rbuf = getFaultBytes( e );
149 }
150 catch ( IOException e2 ) {
151 return HttpServer.createErrorResponse( 500, "Server error",
152 e2 );
153 }
154 }
155 final byte[] replyBuf = rbuf;
156 Map hdrMap = new LinkedHashMap();
157 hdrMap.put( "Content-Length", Integer.toString( replyBuf.length ) );
158 hdrMap.put( "Content-Type", "text/xml" );
159 return new HttpServer.Response( 200, "OK", hdrMap ) {
160 public void writeBody( OutputStream out ) throws IOException {
161 out.write( replyBuf );
162 }
163 };
164 }
165
166 /**
167 * Returns the SAMP-friendly (string, list and map only) object representing
168 * the reply to an XML-RPC request given by a request.
169 *
170 * @param request POSTed HTTP request
171 * @return SAMP-friendly object
172 * @throws Exception in case of error (will become XML-RPC fault)
173 */
174 private Object getXmlRpcResult( HttpServer.Request request )
175 throws Exception {
176 byte[] body = request.getBody();
177
178 // Parse body as XML document.
179 if ( body == null || body.length == 0 ) {
180 throw new XmlRpcFormatException( "No body in POSTed request" );
181 }
182 Document doc = XmlUtils.createDocumentBuilder()
183 .parse( new ByteArrayInputStream( body ) );
184
185 // Extract XML-RPC information from DOM.
186 XmlRpcCall call = XmlRpcCall.createCall( doc );
187 String methodName = call.getMethodName();
188 List paramList = call.getParams();
189
190 // Find one of the registered handlers to handle this request.
191 SampXmlRpcHandler handler = null;
192 SampXmlRpcHandler[] handlers =
193 (SampXmlRpcHandler[])
194 handlerList_.toArray( new SampXmlRpcHandler[ 0 ] );
195 for ( int ih = 0; ih < handlers.length && handler == null; ih++ ) {
196 SampXmlRpcHandler h = handlers[ ih ];
197 if ( h.canHandleCall( methodName ) ) {
198 handler = h;
199 }
200 }
201 if ( handler == null ) {
202 throw new XmlRpcFormatException( "Unknown XML-RPC method "
203 + methodName );
204 }
205
206 // Pass the call to the handler and return the result.
207 return handleCall( handler, methodName, paramList, request );
208 }
209
210 /**
211 * Actually passes the XML-RPC method name and parameter list to one
212 * of the registered servers for processing.
213 *
214 * @param handler handler which has declared it can handle the
215 * named method
216 * @param methodName XML-RPC method name
217 * @param paramList list of parameters to XML-RPC call
218 * @param request HTTP request from which this call originated
219 */
220 protected Object handleCall( SampXmlRpcHandler handler, String methodName,
221 List paramList, HttpServer.Request request )
222 throws Exception {
223 return handler.handleCall( methodName, paramList, request );
224 }
225
226 /**
227 * Turns a SAMP-friendly (string, list, map only) object into an array
228 * of bytes giving an XML-RPC methodResponse document.
229 *
230 * @param result SAMP-friendly object
231 * @return XML methodResponse document as byte array
232 */
233 public static byte[] getResultBytes( Object result ) throws IOException {
234 ByteArrayOutputStream out = new ByteArrayOutputStream();
235 BufferedOutputStream bout = new BufferedOutputStream( out );
236 XmlWriter xout = new XmlWriter( bout, 2 );
237 xout.start( "methodResponse" );
238 xout.start( "params" );
239 xout.start( "param" );
240 xout.sampValue( result );
241 xout.end( "param" );
242 xout.end( "params" );
243 xout.end( "methodResponse" );
244 xout.close();
245 return out.toByteArray();
246 }
247
248 /**
249 * Turns an exception into an array of bytes giving an XML-RPC
250 * methodResponse (fault) document.
251 *
252 * @param error throwable
253 * @return XML methodResponse document as byte array
254 */
255 public static byte[] getFaultBytes( Throwable error ) throws IOException {
256 int faultCode = 1;
257 String faultString = error.toString();
258
259 // Write the method response element. We can't use the XmlWriter
260 // sampValue method to do the grunt-work here since the faultCode
261 // contains an <int>, which is not a known SAMP type.
262 ByteArrayOutputStream out = new ByteArrayOutputStream();
263 BufferedOutputStream bout = new BufferedOutputStream( out );
264 XmlWriter xout = new XmlWriter( bout, 2 );
265 xout.start( "methodResponse" );
266 xout.start( "fault" );
267 xout.start( "value" );
268 xout.start( "struct" );
269 xout.start( "member" );
270 xout.inline( "name", "faultCode" );
271 xout.start( "value" );
272 xout.inline( "int", Integer.toString( faultCode ) );
273 xout.end( "value" );
274 xout.end( "member" );
275 xout.start( "member" );
276 xout.inline( "name", "faultString" );
277 xout.inline( "value", faultString );
278 xout.end( "member" );
279 xout.end( "struct" );
280 xout.end( "value" );
281 xout.end( "fault" );
282 xout.end( "methodResponse" );
283 xout.close();
284 return out.toByteArray();
285 }
286
287 /**
288 * Returns a simple response suitable for GET/HEAD at the XML-RPC
289 * server's endpoint.
290 *
291 * @param withData true for text (GET), false for no text (HEAD)
292 * @return HTTP response
293 */
294 private static HttpServer.Response createInfoResponse( final boolean
295 withData ) {
296 String text = new StringBuffer()
297 .append( "<html>\n" )
298 .append( "<head><title>XML-RPC</title></head>\n" )
299 .append( "<body>\n" )
300 .append( "<h1>XML-RPC Server</h1>\n" )
301 .append( "<p>This is an " )
302 .append( "<a href='http://www.xmlrpc.com/'>XML-RPC</a> server.\n" )
303 .append( "</p>\n" )
304 .append( "<p>Try POSTing.</p>\n" )
305 .append( "</body>\n" )
306 .append( "</html>\n" )
307 .toString();
308 byte[] buf1;
309 try {
310 buf1 = text.getBytes( "utf-8" );
311 }
312 catch ( UnsupportedEncodingException e ) {
313 assert false : "no UTF-8??";
314 buf1 = new byte[ 0 ];
315 }
316 final byte[] buf = buf1;
317 Map hdrMap = new LinkedHashMap();
318 hdrMap.put( "Content-Type", "text/html" );
319 hdrMap.put( "Content-Length", Integer.toString( buf.length ) );
320 return new HttpServer.Response( 200, "OK", hdrMap ) {
321 public void writeBody( OutputStream out ) throws IOException {
322 if ( withData ) {
323 out.write( buf );
324 }
325 }
326 };
327 }
328 }