org.apache.http.protocol.HttpRequestHandler Java Examples

The following examples show how to use org.apache.http.protocol.HttpRequestHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpRequestSensorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    HttpRequestHandler handler = new TestHttpRequestHandler().header("Content-Type", "application/json").response("{\"myKey\":\"myValue\"}");
    recordingHandler = new RecordingHttpRequestHandler(handler);
    server = new TestHttpServer()
        .handler("/nonjson", new TestHttpRequestHandler().header("Content-Type", "text/plain").response("myresponse"))
        .handler("/jsonstring", new TestHttpRequestHandler().header("Content-Type", "application/json").response("\"myValue\""))
        .handler("/myKey/myValue", recordingHandler)
        .start();
    serverUrl = server.getUrl();

    app = TestApplication.Factory.newManagedInstanceForTests();
    entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
            .location(TestApplication.LOCALHOST_MACHINE_SPEC));
    app.start(ImmutableList.<Location>of());
}
 
Example #2
Source File: TestUtils.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
public static HttpRequestHandler makeHttpHandler(
        final int statusCode, final String body,
        final List<String> requestBodies) {
    return new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException,
                IOException {
            response.setStatusCode(statusCode);
            response.setEntity(new StringEntity(body));

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                requestBodies.add(EntityUtils.toString(entity));
            } else {
                requestBodies.add("");
            }
        }
    };
}
 
Example #3
Source File: TestInterruptibleHttpClient.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Starts the HTTP server.
 *
 * @return the listening port.
 */
static int start () throws IOException
{

   server = ServerBootstrap.bootstrap ().registerHandler ("*",
         new HttpRequestHandler ()
         {

            @Override
            public void handle (HttpRequest request, HttpResponse response,
                  HttpContext context)
                  throws HttpException, IOException
            {

               response.setStatusCode (HttpStatus.SC_OK);
               response.setEntity (new StringEntity ("0123456789"));
            }
         })
         .create ();
   server.start ();

   return server.getLocalPort ();
}
 
Example #4
Source File: InsecureHttpsServer.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the server.
 * @throws Exception in case of exception
 */
public void start() throws Exception {
    final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);

    if (html_ != null) {
        final HttpRequestHandler handler = new HttpRequestHandler() {
            @Override
            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
                response.setEntity(new StringEntity(html_, ContentType.TEXT_HTML));
            }
        };
        localServer_.register("*", handler);
    }
    localServer_.start();
}
 
Example #5
Source File: LongPollingChannelLifecycleTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new LocalTestServer(null, null);
    server.register(CHANNELPATH, new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException,
                                                                                            IOException {
            response.setStatusCode(createChannelResponseCode);
            response.setHeader("Location", bounceProxyUrl + "channels/" + channelId);
        }
    });
    server.start();
    serviceAddress = "http://" + server.getServiceAddress().getHostName() + ":"
            + server.getServiceAddress().getPort();
    bounceProxyUrl = serviceAddress + BOUNCEPROXYPATH;

    Properties properties = new Properties();
    properties.put(MessagingPropertyKeys.CHANNELID, channelId);
    properties.put(MessagingPropertyKeys.BOUNCE_PROXY_URL, bounceProxyUrl);

    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        public void configure() {
            bind(HttpRequestFactory.class).to(ApacheHttpRequestFactory.class);
            bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class).in(Singleton.class);
            bind(RequestConfig.class).toProvider(HttpDefaultRequestConfigProvider.class).in(Singleton.class);
            bind(MessagingSettings.class).to(ConfigurableMessagingSettings.class);
        }
    }, new JoynrPropertiesModule(properties), new JsonMessageSerializerModule(), new DummyDiscoveryModule());
    longpollingChannelLifecycle = injector.getInstance(LongPollingChannelLifecycle.class);
}
 
Example #6
Source File: ClusterServiceServletContainer.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ListenerThread(HttpRequestHandler requestHandler, int port) {
    _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));

    try {
        _serverSocket = new ServerSocket(port);
    } catch (IOException ioex) {
        s_logger.error("error initializing cluster service servlet container", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
        .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("/clusterservice", requestHandler);

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #7
Source File: HttpUploaderTest.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  super.setUp();
  this.serverBootstrap.registerHandler(
      "/*", (HttpRequestHandler) (request, response, context) -> {
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new StringEntity(EXPECTED_URI));
      });

  httpHost = start();

  final URI uri = new URIBuilder()
      .setScheme("http")
      .setHost(httpHost.getHostName())
      .setPort(httpHost.getPort())
      .setPath(EXPECTED_URI)
      .build();

  // Create the minimum config for tests
  config = Config.newBuilder()
      .put(Key.CLUSTER, "cluster")
      .put(Key.ROLE, "role")
      .put(Key.TOPOLOGY_NAME, "topology")
      .put(Key.TOPOLOGY_PACKAGE_TYPE, PackageType.TAR)
      .put(Key.TOPOLOGY_PACKAGE_FILE, tempFile.getCanonicalPath())
      .put(HttpUploaderContext.HERON_UPLOADER_HTTP_URI, uri.getPath())
      .build();
}
 
Example #8
Source File: ClusterServiceServletContainer.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public ListenerThread(final HttpRequestHandler requestHandler, final int port) {
    _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));

    try {
        _serverSocket = new ServerSocket(port);
    } catch (final IOException ioex) {
        s_logger.error("error initializing cluster service servlet container", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
           .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
    final BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

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

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #9
Source File: TestUtils.java    From phabricator-jenkins-plugin with MIT License 4 votes vote down vote up
public static HttpRequestHandler makeHttpHandler(final int statusCode, final String body) {
    ArrayList<String> requestBodies = new ArrayList<String>();
    return makeHttpHandler(statusCode, body, requestBodies);
}
 
Example #10
Source File: TestHttpServer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HandlerTuple(String path, HttpRequestHandler handler) {
    this.path = path;
    this.handler = handler;
}
 
Example #11
Source File: RecordingHttpRequestHandler.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public RecordingHttpRequestHandler(HttpRequestHandler delegate) {
    this.delegate = checkNotNull(delegate, "delegate");
}
 
Example #12
Source File: TinyHttpServer.java    From spydroid-ipcamera with GNU General Public License v3.0 4 votes vote down vote up
public synchronized void register(final String pattern, final HttpRequestHandler handler) {
	matcher.register(pattern, handler);
}
 
Example #13
Source File: TinyHttpServer.java    From spydroid-ipcamera with GNU General Public License v3.0 4 votes vote down vote up
public synchronized HttpRequestHandler lookup(final String requestURI) {
	// This is the only function that will often be called by threads of the HTTP server
	// and it seems like a rather small crtical section to me, so it should not slow things down much
	return (HttpRequestHandler) matcher.lookup(requestURI);
}
 
Example #14
Source File: ClusterServiceServletContainer.java    From cloudstack with Apache License 2.0 3 votes vote down vote up
public boolean start(HttpRequestHandler requestHandler, int port) {

        listenerThread = new ListenerThread(requestHandler, port);
        listenerThread.start();

        return true;
    }
 
Example #15
Source File: ClusterServiceServletContainer.java    From cosmic with Apache License 2.0 3 votes vote down vote up
public boolean start(final HttpRequestHandler requestHandler, final int port) {

        listenerThread = new ListenerThread(requestHandler, port);
        listenerThread.start();

        return true;
    }
 
Example #16
Source File: TinyHttpServer.java    From spydroid-ipcamera with GNU General Public License v3.0 2 votes vote down vote up
/** 
 * You may add some HttpRequestHandler to modify the default behavior of the server.
 * @param pattern Patterns may have three formats: * or *<uri> or <uri>*
 * @param handler A HttpRequestHandler
 */ 
protected void addRequestHandler(String pattern, HttpRequestHandler handler) {
	mRegistry.register(pattern, handler);
}
 
Example #17
Source File: LocalTestServer.java    From htmlunit with Apache License 2.0 2 votes vote down vote up
/**
 * Registers the given {@link HttpRequestHandler} as a handler for URIs matching the given pattern.
 * @param pattern the pattern
 * @param handler the handler
 */
public void register(final String pattern, final HttpRequestHandler handler) {
    serverBootstrap.registerHandler(pattern, handler);
}