1 package org.openslx.imagemaster.thrift.server;
3 import java.io.IOException;
4 import java.util.Arrays;
5 import java.util.concurrent.TimeUnit;
7 import org.apache.logging.log4j.LogManager;
8 import org.apache.logging.log4j.Logger;
9 import org.apache.thrift.protocol.TJSONProtocol;
10 import org.apache.thrift.protocol.TProtocol;
11 import org.apache.thrift.transport.TMemoryBuffer;
12 import org.
openslx.bwlp.thrift.iface.MasterServer;
13 import org.
openslx.util.CascadedThreadPoolExecutor;
16 import fi.iki.elonen.NanoHTTPD;
26 public HttpListener( String hostname,
int port )
throws IOException
28 super( hostname, port,
new CascadedThreadPoolExecutor( 4, 32, 1, TimeUnit.MINUTES, 2,
"HTTP" ) );
29 this.maxRequestSize = 1_000_000;
33 public Response
serve( IHTTPSession session )
35 Method method = session.getMethod();
36 if ( Method.OPTIONS.equals( method ) ) {
37 Response response =
new Response( Response.Status.NO_CONTENT,
"application/json",
"" );
41 if ( !Method.PUT.equals( method ) && !Method.POST.equals( method ) )
42 return new Response( Response.Status.BAD_REQUEST,
"text/plain; charset=UTF-8",
"Method not supported" );
46 String str = session.getHeaders().get(
"content-length" );
49 len =
Util.parseInt( str, 0 );
52 len = session.getInputStream().available();
55 return new Response( Response.Status.BAD_REQUEST,
"text/plain; charset=UTF-8",
"No Content-Length provided" );
57 byte[] buffer = session.getInputStream().readNBytes( len );
58 TMemoryBuffer inbuffer =
new TMemoryBuffer( buffer.length );
59 inbuffer.write( buffer );
60 TProtocol inprotocol =
new TJSONProtocol( inbuffer );
63 TMemoryBuffer outbuffer =
new TMemoryBuffer( 900 );
64 TProtocol outprotocol =
new TJSONProtocol( outbuffer );
66 processor.process( inprotocol, outprotocol );
68 buffer = Arrays.copyOf( outbuffer.getArray(), outbuffer.length() );
70 Response response =
new Response( Response.Status.OK,
"application/json", buffer );
73 }
catch ( Throwable t ) {
74 if ( !t.getMessage().contains(
"Remote side has closed" ) ) {
75 LOGGER.warn(
"Error handling HTTP thrift", t );
77 return new Response( Response.Status.INTERNAL_ERROR,
"text/plain; charset=UTF-8", t.getMessage() );
90 response.addHeader(
"Allow",
"OPTIONS, GET, HEAD, POST, PUT" );
91 response.addHeader(
"Access-Control-Allow-Methods",
"*" );
92 response.addHeader(
"Access-Control-Allow-Origin",
"*" );
93 response.addHeader(
"Access-Control-Allow-Headers",
"*, Content-Type" );
94 response.addHeader(
"Access-Control-Max-Age",
"86400" );
final MasterServer.Processor< MasterServerHandler > processor
static final Logger LOGGER
HttpListener(String hostname, int port)
Some utilities to make our lives easier.
Response serve(IHTTPSession session)
static void addCorsHeaders(Response response)