예제 #1
0
    public ListenerThread(ApiServer requestHandler, int port) {
      try {
        _serverSocket = new ServerSocket(port);
      } catch (IOException ioex) {
        s_logger.error("error initializing api server", ioex);
        return;
      }

      _params = new BasicHttpParams();
      _params
          .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
          .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
          .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
          .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
          .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

      // Set up the HTTP protocol processor
      BasicHttpProcessor httpproc = new BasicHttpProcessor();
      httpproc.addInterceptor(new ResponseDate());
      httpproc.addInterceptor(new ResponseServer());
      httpproc.addInterceptor(new ResponseContent());
      httpproc.addInterceptor(new ResponseConnControl());

      // Set up request handlers
      HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
      reqistry.register("*", requestHandler);

      // Set up the HTTP service
      _httpService =
          new HttpService(
              httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
      _httpService.setParams(_params);
      _httpService.setHandlerResolver(reqistry);
    }
  /**
   * Obtains an HTTP protocol processor with default interceptors.
   *
   * @return a protocol processor for server-side use
   */
  protected BasicHttpProcessor newProcessor() {

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    return httpproc;
  }
  @Test
  public void testBasicAuthenticationSuccessOnNonRepeatablePutExpectContinue() throws Exception {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());
    httpproc.addInterceptor(new RequestBasicAuth());
    httpproc.addInterceptor(new ResponseBasicUnauthorized());
    this.localServer =
        new LocalTestServer(httpproc, null, null, new AuthExpectationVerifier(), null, null);
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    TestCredentialsProvider credsProvider =
        new TestCredentialsProvider(new UsernamePasswordCredentials("test", "test"));

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpPut httpput = new HttpPut("/");
    httpput.setEntity(
        new InputStreamEntity(
            new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), -1));
    httpput.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    HttpResponse response = this.httpclient.execute(getServerHttp(), httpput);
    HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
  }
예제 #4
0
	protected NHttpServiceHandler createHttpServiceHandler(
			 HttpRequestHandler requestHandler,
			 HttpExpectationVerifier expectationVerifier,
			 EventListener eventListener) {

		BasicHttpProcessor httpproc = new BasicHttpProcessor();
		httpproc.addInterceptor(new ResponseDate());
		httpproc.addInterceptor(new ResponseServer());
		httpproc.addInterceptor(new ResponseContent());
		httpproc.addInterceptor(new ResponseConnControl());

		BufferingHttpServiceHandler serviceHandler = new BufferingHttpServiceHandler(
				httpproc, new DefaultHttpResponseFactory(),
				new DefaultConnectionReuseStrategy(), this.serverParams);

		serviceHandler.setHandlerResolver(new SimpleHttpRequestHandlerResolver(
				requestHandler));
		serviceHandler.setExpectationVerifier(expectationVerifier);
		serviceHandler.setEventListener(eventListener);

		return serviceHandler;
	}
  @Before
  public void setUp() throws Exception {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());
    httpproc.addInterceptor(new RequestBasicAuth());
    httpproc.addInterceptor(new ResponseBasicUnauthorized());

    this.localServer = new LocalTestServer(httpproc, null);
    this.httpclient = new DefaultHttpClient();
  }
예제 #6
0
  public void execute(EventListener listener) throws IOException {
    BasicHttpProcessor processor = new BasicHttpProcessor();
    processor.addInterceptor(new ResponseDate());
    processor.addInterceptor(new ResponseServer());
    processor.addInterceptor(new ResponseContent());
    processor.addInterceptor(new ResponseConnControl());

    AsyncNHttpServiceHandler serviceHandler =
        new AsyncNHttpServiceHandler(
            processor,
            new DefaultHttpResponseFactory(),
            new DefaultConnectionReuseStrategy(),
            params);

    serviceHandler.setEventListener(listener);

    serviceHandler.setHandlerResolver(this.registry);

    reactor =
        new DefaultDispatchedIOReactor(
            params, NIODispatcher.instance().getScheduledExecutorService());
    IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(serviceHandler, params);
    reactor.execute(ioEventDispatch);
  }
 @Override
 protected BasicHttpProcessor createHttpProcessor() {
   BasicHttpProcessor httpproc = new BasicHttpProcessor();
   httpproc.addInterceptor(new RequestDefaultHeaders());
   // Required protocol interceptors
   httpproc.addInterceptor(new RequestContent());
   httpproc.addInterceptor(new RequestTargetHost());
   // Recommended protocol interceptors
   httpproc.addInterceptor(new RequestClientConnControl());
   httpproc.addInterceptor(new RequestUserAgent());
   httpproc.addInterceptor(new RequestExpectContinue());
   // HTTP state management interceptors
   httpproc.addInterceptor(new RequestAddCookies());
   httpproc.addInterceptor(new ResponseProcessCookies());
   // HTTP authentication interceptors
   httpproc.addInterceptor(new RequestAuthCache());
   httpproc.addInterceptor(new ResponseAuthCache());
   httpproc.addInterceptor(new RequestTargetAuthentication());
   httpproc.addInterceptor(new RequestProxyAuthentication());
   return httpproc;
 }
예제 #8
0
  public void run() {
    try {
      this.serverSocket = new ServerSocket(Settings.getPropertyInteger("server_port"));
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_open_port_", Settings.getLocale())
              + Settings.getPropertyInteger("server_port"));
      if (FancyFileServer.getGUI() != null) {
        FancyFileServer.getGUI().updateServerStatus();
      }
      return;
    }

    running = true;

    this.parameters = new BasicHttpParams();
    this.parameters.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000);
    this.parameters.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    this.parameters.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    this.parameters.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true);
    this.parameters.setParameter(
        HttpProtocolParams.ORIGIN_SERVER,
        FancyFileServer.NAME.replaceAll("\\s", "-") + "/" + FancyFileServer.VERSION);

    Logger.log(Level.INFO, Messages.getString("server_started", Settings.getLocale()));

    try {
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) interfaces.nextElement();
        if (i.isLoopback() || i.isVirtual()) {
          continue;
        }
        Enumeration<InetAddress> addresses = i.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress a = (InetAddress) addresses.nextElement();
          if (a instanceof Inet4Address) {
            Logger.log(
                Level.INFO,
                Messages.getString("server_address_", Settings.getLocale())
                    + "http://"
                    + a.getHostAddress()
                    + ":"
                    + serverSocket.getLocalPort()
                    + "/");
          }
        }
      }
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_get_server_address_", Settings.getLocale()) + e.getMessage());
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }

    while (running) {
      try {
        /** Set up HTTP connection */
        Socket socket = this.serverSocket.accept();
        DefaultHttpServerConnection connection = new DefaultHttpServerConnection();
        Logger.log(
            Level.DEBUG,
            Messages.getString("incoming_connection_from_", Settings.getLocale())
                + socket.getInetAddress().getHostAddress());
        connection.bind(socket, this.parameters);

        /** Set up HTTP protocol processor */
        BasicHttpProcessor processor = new BasicHttpProcessor();
        processor.addInterceptor(new ResponseDate());
        processor.addInterceptor(new ResponseServer());
        processor.addInterceptor(new ResponseContent());
        processor.addInterceptor(new ResponseConnControl());

        /** Set up HTTP request handlers */
        HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
        registry.register("*", new FileHandler());

        /** Set up HTTP service */
        HttpService service =
            new HttpService(
                processor,
                new DefaultConnectionReuseStrategy(),
                new DefaultHttpResponseFactory(),
                registry,
                this.parameters);

        /** Start worker thread */
        WorkerThread t = new WorkerThread(this, service, connection);
        t.setDaemon(true);
        t.start();
      } catch (IOException e) {
        if (running) {
          running = false;
          Logger.log(
              Level.SEVERE,
              Messages.getString("i_o_error_", Settings.getLocale()) + e.getMessage());
          break;
        }
      }
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }
    Logger.log(Level.INFO, Messages.getString("server_stopped", Settings.getLocale()));
  }
  public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params
        .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
        .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
        .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
        .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
        .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
        .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // Set up protocol handler
    BufferingHttpClientHandler protocolHandler =
        new BufferingHttpClientHandler(
            httpproc,
            new MyHttpRequestExecutionHandler(),
            new DefaultConnectionReuseStrategy(),
            params);
    protocolHandler.setEventListener(new EventLogger());

    // Limit the total maximum of concurrent connections to 5
    int maxTotalConnections = 5;

    // Use the connection manager to maintain a pool of connections to localhost:8080
    final AsyncConnectionManager connMgr =
        new AsyncConnectionManager(
            new HttpHost("localhost", 8080), maxTotalConnections, protocolHandler, params);

    // Start the I/O reactor in a separate thread
    Thread t =
        new Thread(
            new Runnable() {

              public void run() {
                try {
                  connMgr.execute(); // The connection manager wraps the I/O reactor.
                } catch (InterruptedIOException ex) {
                  System.err.println("Interrupted");
                } catch (IOException e) {
                  System.err.println("I/O error: " + e.getMessage());
                }
                System.out.println("I/O reactor terminated");
              }
            });
    t.start();

    // Submit 50 requests using maximum 5 concurrent connections
    Queue<RequestHandle> queue = new LinkedList<RequestHandle>();
    for (int i = 0; i < 50; i++) {
      AsyncConnectionRequest connRequest =
          connMgr.requestConnection(); // Get a working connection from the connection manager.
      connRequest
          .waitFor(); // Wait for the connection request to be completed to the target authority.
      NHttpClientConnection conn =
          connRequest.getConnection(); // Get the real connection from the connection request.
      if (conn == null) {
        System.err.println("Failed to obtain connection");
        break;
      }

      HttpContext context = conn.getContext();
      BasicHttpRequest httpget = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
      RequestHandle handle = new RequestHandle(connMgr, conn);

      context.setAttribute("request", httpget);
      context.setAttribute("request-handle", handle);

      queue.add(handle);
      conn.requestOutput();
    }

    // Wait until all requests have been completed
    while (!queue.isEmpty()) {
      RequestHandle handle = queue.remove();
      handle.waitFor();
    }

    // Give the I/O reactor 10 sec to shut down
    connMgr.shutdown(10000);
    System.out.println("Done");
  }
예제 #10
0
  public void run() {
    logger.info("Starting server.");

    int localPort = MaryProperties.needInteger("socket.port");

    HttpParams params = new BasicHttpParams();
    params
        .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0)
        // 0 means no timeout, any positive value means time out in miliseconds (i.e. 50000 for 50
        // seconds)
        .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
        .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
        .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
        .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    BufferingHttpServiceHandler handler =
        new BufferingHttpServiceHandler(
            httpproc,
            new DefaultHttpResponseFactory(),
            new DefaultConnectionReuseStrategy(),
            params);

    // Set up request handlers
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("/process", new SynthesisRequestHandler());
    InfoRequestHandler infoRH = new InfoRequestHandler();
    registry.register("/version", infoRH);
    registry.register("/datatypes", infoRH);
    registry.register("/locales", infoRH);
    registry.register("/voices", infoRH);
    registry.register("/audioformats", infoRH);
    registry.register("/exampletext", infoRH);
    registry.register("/audioeffects", infoRH);
    registry.register("/audioeffect-default-param", infoRH);
    registry.register("/audioeffect-full", infoRH);
    registry.register("/audioeffect-help", infoRH);
    registry.register("/audioeffect-is-hmm-effect", infoRH);
    registry.register("/features", infoRH);
    registry.register("/features-discrete", infoRH);
    registry.register("/vocalizations", infoRH);
    registry.register("/styles", infoRH);
    registry.register("*", new FileRequestHandler());

    handler.setHandlerResolver(registry);

    // Provide an event logger
    handler.setEventListener(new EventLogger());

    IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);

    int numParallelThreads = MaryProperties.getInteger("server.http.parallelthreads", 5);

    logger.info("Waiting for client to connect on port " + localPort);

    try {
      ListeningIOReactor ioReactor = new DefaultListeningIOReactor(numParallelThreads, params);
      ioReactor.listen(new InetSocketAddress(localPort));
      isReady = true;
      ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
      logger.info("Interrupted", ex);
    } catch (IOException e) {
      logger.info("Problem with HTTP connection", e);
    }
    logger.debug("Shutdown");
  }