Java 类org.apache.http.protocol.HttpRequestHandler 实例源码

项目:dhus-core    文件:TestInterruptibleHttpClient.java   
/**
 * 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 ();
}
项目:Camel    文件:HttpProducerContentTypeTest.java   
@Before
@Override
public void setUp() throws Exception {
    localServer = ServerBootstrap.bootstrap().
            setHttpProcessor(getBasicHttpProcessor()).
            setConnectionReuseStrategy(getConnectionReuseStrategy()).
            setResponseFactory(getHttpResponseFactory()).
            setExpectationVerifier(getHttpExpectationVerifier()).
            setSslContext(getSSLContext()).
            registerHandler("/content", new HttpRequestHandler() {
                @Override
                public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
                    String contentType = request.getFirstHeader(Exchange.CONTENT_TYPE).getValue();

                    assertEquals(CONTENT_TYPE, contentType);

                    response.setEntity(new StringEntity(contentType, "ASCII"));
                    response.setStatusCode(HttpStatus.SC_OK);
                }
            }).create();
    localServer.start();

    super.setUp();
}
项目:Camel    文件:HttpConcurrentTest.java   
@Before
@Override
public void setUp() throws Exception {
    localServer = ServerBootstrap.bootstrap().
            setHttpProcessor(getBasicHttpProcessor()).
            setConnectionReuseStrategy(getConnectionReuseStrategy()).
            setResponseFactory(getHttpResponseFactory()).
            setExpectationVerifier(getHttpExpectationVerifier()).
            setSslContext(getSSLContext()).
            registerHandler("/", new HttpRequestHandler() {
                public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                    response.setStatusCode(HttpStatus.SC_OK);
                    response.setEntity(new StringEntity("" + counter.incrementAndGet()));
                }
            }).create();
    localServer.start();

    super.setUp();
}
项目:Camel    文件:HttpProducerTwoParametersWithSameKeyTest.java   
@Before
@Override
public void setUp() throws Exception {
    localServer = ServerBootstrap.bootstrap().
            setHttpProcessor(getBasicHttpProcessor()).
            setConnectionReuseStrategy(getConnectionReuseStrategy()).
            setResponseFactory(getHttpResponseFactory()).
            setExpectationVerifier(getHttpExpectationVerifier()).
            setSslContext(getSSLContext()).
            registerHandler("/myapp", new HttpRequestHandler() {
                @Override
                public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
                    String uri = request.getRequestLine().getUri();
                    assertEquals("/myapp?from=me&to=foo&to=bar", uri);

                    response.setHeader("bar", "yes");
                    response.addHeader("foo", "123");
                    response.addHeader("foo", "456");
                    response.setEntity(new StringEntity("OK", "ASCII"));
                    response.setStatusCode(HttpStatus.SC_OK);
                }
            }).create();
    localServer.start();

    super.setUp();
}
项目:purecloud-iot    文件:TestWindowsNegotiateScheme.java   
@Before @Override
public void setUp() throws Exception {
    super.setUp();
    this.serverBootstrap.registerHandler("/", new HttpRequestHandler() {

        @Override
        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
            response.addHeader(AUTH.WWW_AUTH, AuthSchemes.SPNEGO);
            response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }

    });
}
项目:DataHubSystem    文件:TestInterruptibleHttpClient.java   
/**
 * 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 ();
}
项目:phabricator-jenkins-plugin    文件:TestUtils.java   
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("");
            }
        }
    };
}
项目:gondola    文件:LocalTestServer.java   
public LocalTestServer(HttpRequestHandler handler) {
    try {
        setUp();
        HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new ResponseDate())
            .add(new ResponseServer(LocalServerTestBase.ORIGIN))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .add(new RequestBasicAuth())
            .add(new ResponseBasicUnauthorized()).build();
        this.serverBootstrap.setHttpProcessor(httpproc);
        this.serverBootstrap.registerHandler("*", handler);
        host = start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:gluten    文件:HttpClientTest.java   
@Before
public void setUp() throws Exception {
    BasicConfigurator.configure();

    server = new LocalTestServer(null, null);

    server.register("/hitme/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest req, HttpResponse resp, HttpContext ctx)
                throws HttpException, IOException 
        {
            resp.setStatusCode(200);
            resp.setEntity(new StringEntity("Hello World"));
        }
    });

    server.start();

    client = new HttpClient();
}
项目:mashery-sdk    文件:MasheryClientTest.java   
@Override
@Before
public void setUp() throws Exception {
    OAuthTokenService.INSTANCE.clearToken();

    HttpRequestHandler tokenHandler = new TokenHandler();
    HttpRequestHandler resourceHandler = new ResourceHandler();

    testServer = new LocalTestServer(null, null);
    testServer.register("/v3/rest/*", resourceHandler);
    testServer.register("/v3/token", tokenHandler);
    testServer.start();

    port = testServer.getServicePort();
    host = testServer.getServiceHostName();

    // System.out.println("LocalTestServer available via http://" + host + ":" + port);

    params = new HashMap<String, String>();
    params.put("username", userName);
    params.put("password", password);
    params.put("scope", scope);
    params.put("grant_type", grantType);

    client = MasheryClientBuilder.masheryClient().withHost(host).withProtocol("http").withPort(port).withApiKey(apiKey).withApiSecret(apiSecret).withTokenRequestParams(params).build();
}
项目:sosumi-java    文件:SosumiTest.java   
@Before
public void setUp() throws Exception {

    handler = mock(HttpRequestHandler.class);

    server = new LocalTestServer(null, null);
    server.register("/*", handler);
    server.start();

    // report how to access the server
    System.out.println("LocalTestServer available at " + server.getServiceAddress());
    primaryServiceAddress = server.getServiceAddress().getHostName() + ":" + server.getServiceAddress().getPort();
    secondaryServiceAddress = server.getServiceAddress().getAddress().getHostAddress() + ":" + server.getServiceAddress().getPort();

    impl = new Sosumi("http://" + primaryServiceAddress, "user", "pass");

}
项目:belladati-sdk-java    文件:RequestTrackingServer.java   
public void register(String pattern, final HttpRequestHandler handler) {
    if (server != null) {
        throw new RuntimeException("Cannot register hander when server is running");
    }
    serverBootstrap.registerHandler(pattern, new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
            throws HttpException, IOException {
            // wrap the original handler to track the request
            String uri = request.getRequestLine().getUri();
            requestUris.add(uri.contains("?") ? uri.substring(0, uri.indexOf("?")) : uri);
            // never cache during tests
            response.addHeader("Cache-Control", "no-cache");
            handler.handle(request, response, context);
        }
    });
}
项目:sling-org-apache-sling-testing-clients    文件:SlingClientWaitExistsTest.java   
@Override
protected void registerHandlers() throws IOException {
    serverBootstrap.registerHandler(GET_WAIT_PATH + ".json", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            callCount++;
            if (callCount == waitCount) {
                response.setEntity(new StringEntity(OK_RESPONSE));
            } else {
                response.setEntity(new StringEntity(NOK_RESPONSE));
                response.setStatusCode(404);
            }
        }
    });
}
项目:r2cloud    文件:CelestrakClientTest.java   
@Test
public void testSuccess() {
    StringBuilder expectedStr = new StringBuilder();
    Map<String, TLE> expected;
    try (BufferedReader r = new BufferedReader(new InputStreamReader(CelestrakClientTest.class.getClassLoader().getResourceAsStream("sample-tle.txt")))) {
        String curLine = null;
        List<String> lines = new ArrayList<>();
        while( (curLine = r.readLine()) != null ) {
            lines.add(curLine);
            expectedStr.append(curLine).append("\n");
        }
        expected = convert(lines);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    server.register("/*", new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            response.setEntity(new StringEntity(expectedStr.toString(), StandardCharsets.UTF_8));
        }
    });
    // one slash is important here
    CelestrakClient client = new CelestrakClient("http:/" + server.getServiceAddress());
    Map<String, TLE> actual = client.getWeatherTLE();
    assertEquals(expected.size(), actual.size());
    assertTrue(expected.equals(actual));
}
项目:outcomes    文件:TestHttpCore.java   
@Test
public void test() throws ExecutionException, InterruptedException {


    HttpHost target = new HttpHost("localhost");
    BasicConnPool connpool = new BasicConnPool();
    connpool.setMaxTotal(200);
    connpool.setDefaultMaxPerRoute(10);
    connpool.setMaxPerRoute(target, 20);
    Future<BasicPoolEntry> future = connpool.lease(target, null);
    BasicPoolEntry poolEntry = future.get();
    HttpClientConnection conn = poolEntry.getConnection();

    HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new ResponseDate())
            .add(new ResponseServer("MyServer-HTTP/1.1"))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .build();

    HttpRequestHandler myRequestHandler = new HttpRequestHandler() {

        public void handle(
                HttpRequest request,
                HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(
                    new StringEntity("some important message",
                            ContentType.TEXT_PLAIN));
        }

    };

    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    handlerMapper.register("/service/*", myRequestHandler);
    HttpService httpService = new HttpService(httpproc, handlerMapper);
}
项目:cosmic    文件:ClusterServiceServletContainer.java   
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);
}
项目:Camel    文件:Http4MaxConnectionPerHostTest.java   
@BeforeClass
public static void setUp() throws Exception {
    localServer = new HttpTestServer(null, null);
    localServer.register("/", new HttpRequestHandler() {
        public void handle(HttpRequest request, HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("OK", Consts.ISO_8859_1));
        }
    });
    localServer.start();
}
项目:Camel    文件:Http4EndpointTest.java   
@BeforeClass
public static void setUp() throws Exception {
    localServer = new HttpTestServer(null, null);
    localServer.register("/", new HttpRequestHandler() {
        public void handle(HttpRequest request, HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("OK", Consts.ISO_8859_1));
        }
    });
    localServer.start();
}
项目:Camel    文件:HttpNoCamelHeaderTest.java   
@Before
@Override
public void setUp() throws Exception {
    localServer = ServerBootstrap.bootstrap().
            setHttpProcessor(getBasicHttpProcessor()).
            setConnectionReuseStrategy(getConnectionReuseStrategy()).
            setResponseFactory(getHttpResponseFactory()).
            setExpectationVerifier(getHttpExpectationVerifier()).
            setSslContext(getSSLContext()).
            registerHandler("/hello", new HttpRequestHandler() {
                @Override
                public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
                    response.setStatusCode(HttpStatus.SC_OK);
                    Object header = request.getFirstHeader(Exchange.FILE_NAME);
                    assertNull("There should be no Camel header", header);

                    for (Header h : request.getAllHeaders()) {
                        if (h.getName().startsWith("Camel") || h.getName().startsWith("org.apache.camel")) {
                            assertNull("There should be no Camel header", h);
                        }
                    }

                    // set ar regular and Camel header
                    response.setHeader("MyApp", "dude");
                    response.setHeader(Exchange.TO_ENDPOINT, "foo");
                }
            }).create();
    localServer.start();

    super.setUp();
}
项目:purecloud-iot    文件:TestFutureRequestExecutionService.java   
@Before
public void before() throws Exception {
        this.localServer = ServerBootstrap.bootstrap()
                .registerHandler("/wait", new HttpRequestHandler() {

            @Override
            public void handle(
                    final HttpRequest request, final HttpResponse response,
                    final HttpContext context) throws HttpException, IOException {
                try {
                    while(blocked.get()) {
                        Thread.sleep(10);
                    }
                } catch (final InterruptedException e) {
                    throw new IllegalStateException(e);
                }
                response.setStatusCode(200);
            }
        }).create();

        this.localServer.start();
        uri = "http://localhost:" + this.localServer.getLocalPort() + "/wait";
        final HttpClient httpClient = HttpClientBuilder.create()
                .setMaxConnPerRoute(5)
                .build();
        final ExecutorService executorService = Executors.newFixedThreadPool(5);
        httpAsyncClientWithFuture = new FutureRequestExecutionService(httpClient, executorService);
}
项目:sumologic-jenkins-plugin    文件:SumoBuildNotifierTest.java   
@Before
public void setUp() throws Exception {
  handler = Mockito.mock(HttpRequestHandler.class);
  server = new LocalTestServer(null, null);
  server.register("/jenkinstest/*", handler);
  server.start();

  serverUrl = "http://" + server.getServiceHostName() + ":"
      + server.getServicePort() + "/jenkinstest/123";

  // report how to access the server
  System.out.println("LocalTestServer available at " + serverUrl);
  j.get(PluginDescriptorImpl.class).setUrl(serverUrl);

}
项目:shariff-backend-java    文件:TestServer.java   
public void setUp(HttpRequestHandler handler) throws Exception {
  server = new LocalTestServer(null, null);
  server.register("/*", handler);
  server.start();

  // report how to access the server
  address = "http://" + server.getServiceAddress().getHostName() + ":"
      + server.getServiceAddress().getPort();
  System.out.println("LocalTestServer available at " + address);

}
项目:shogun2    文件:HttpUtilTest.java   
/**
 *
 * @throws IOException
 * @throws URISyntaxException
 */
@BeforeClass
public static void setUp() throws IOException, URISyntaxException {

    // simple implementation of the HttpRequestHandler
    class TestRequestHandler implements HttpRequestHandler {
        @Override
        public void handle(HttpRequest request, HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setEntity(new StringEntity("SHOGun2 rocks!", "UTF-8"));
        }
    };

    TestRequestHandler handler = new TestRequestHandler();

    HttpUtilTest.server = ServerBootstrap.bootstrap()
            .setLocalAddress(InetAddress.getByName(TEST_SERVER_HOST))
            .setListenerPort(TEST_SERVER_PORT)
            .setServerInfo(TEST_SERVER_INFO)
            .registerHandler("/", handler)
            .create();

    HttpUtilTest.server.start();

    URIBuilder builder = new URIBuilder();
    builder.setScheme(TEST_SERVER_SCHEME);
    builder.setHost(TEST_SERVER_HOST);
    builder.setPort(TEST_SERVER_PORT);

    HttpUtilTest.URI = builder.build();
    HttpUtilTest.URL = HttpUtilTest.URI.toString();
}
项目:MiniWeb    文件:UriRequestHandlerResolver.java   
public Endpoint(String pattern, HttpRequestHandler handler) {
    pattern = pattern.trim();
    pattern = pattern.replaceAll("\\*", "[^/]*");
    pattern = pattern.startsWith("^") ? pattern : "^"+pattern;
    mPattern = Pattern.compile(pattern);
    mHandler = handler;
}
项目:MiniWeb    文件:UriRequestHandlerResolver.java   
@Override
public HttpRequestHandler lookup(String requestURI) {
    String path = UriQueryParser.getUrlPath(requestURI);

    for(Endpoint ep : mEndpoints){
        if(ep.matches(path)){
            return ep.mHandler;
        }
    }

    return null;
}
项目:cloudstack    文件:ClusterServiceServletContainer.java   
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);
}
项目:opentravelmate    文件:HttpServer.java   
/**
 * Create a server socket on an available port and process the requests.
 */
public void start() throws IOException {
    // Prepare the HTTP server
    this.serverSocket = new ServerSocket(0);

    HttpParams httpParams = new BasicHttpParams()
        .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");

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

    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    for (Map.Entry<String, HttpRequestHandler> entry : requestHandlerByPattern.entrySet()) {
        registry.register(entry.getKey(), entry.getValue());
    }

    HttpService httpService = new HttpService(httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    httpService.setParams(httpParams);
    httpService.setHandlerResolver(registry);

    // Handle incoming connections
    executorService.execute(new RequestListener(this.serverSocket, httpParams, httpService, executorService, exceptionListener));
    }
项目:belladati-sdk-java    文件:RequestTrackingServer.java   
public RequestTrackingServer() throws Exception {
    super();
    setUp();
    register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
            throws HttpException, IOException {
            System.err.println(request.getRequestLine());
            // do nothing, this is just a dummy to track the URI
        }
    });
}
项目:belladati-sdk-java    文件:RequestTrackingServer.java   
public void register(String pattern, final String responseContent) {
    register(pattern, new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
            throws HttpException, IOException {
            response.setEntity(new StringEntity(responseContent));
        }
    });
}
项目:belladati-sdk-android    文件:RequestTrackingServer.java   
public RequestTrackingServer() {
    super(null);
    register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            // do nothing, this is just a dummy to track the URI
        }
    });
}
项目:belladati-sdk-android    文件:RequestTrackingServer.java   
@Override
public void register(String pattern, final HttpRequestHandler handler) {
    super.register(pattern, new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            // wrap the original handler to track the request
            String uri = request.getRequestLine().getUri();
            requestUris.add(uri.contains("?") ? uri.substring(0, uri.indexOf("?")) : uri);
            // never cache during tests
            response.addHeader("Cache-Control", "no-cache");
            handler.handle(request, response, context);
        }
    });
}
项目:belladati-sdk-android    文件:RequestTrackingServer.java   
public void register(String pattern, final String responseContent) {
    register(pattern, new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            response.setEntity(new StringEntity(responseContent));
        }
    });
}
项目:joynr    文件:LongPollingChannelLifecycleTest.java   
@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);
}
项目:Android_CCTV    文件:TinyHttpServer.java   
public synchronized void register(final String pattern, final HttpRequestHandler handler) {
    matcher.register(pattern, handler);
}
项目:Android_CCTV    文件:TinyHttpServer.java   
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);
}
项目:purecloud-iot    文件:TestContentCodings.java   
/**
 * Creates a new {@link HttpRequestHandler} that will attempt to provide a deflate stream
 * Content-Coding.
 *
 * @param entityText
 *            the non-null String entity text to be returned by the server
 * @param rfc1951
 *            if true, then the stream returned will be a raw RFC1951 deflate stream, which
 *            some servers return as a result of misinterpreting the HTTP 1.1 RFC. If false,
 *            then it will return an RFC2616 compliant deflate encoded zlib stream.
 * @return a non-null {@link HttpRequestHandler}
 */
private HttpRequestHandler createDeflateEncodingRequestHandler(
        final String entityText, final boolean rfc1951) {
    return new HttpRequestHandler() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
            response.setEntity(new StringEntity(entityText));
            response.addHeader("Content-Type", "text/plain");
            final Header[] acceptEncodings = request.getHeaders("Accept-Encoding");

            for (final Header header : acceptEncodings) {
                for (final HeaderElement element : header.getElements()) {
                    if ("deflate".equalsIgnoreCase(element.getName())) {
                        response.addHeader("Content-Encoding", "deflate");

                        /* Gack. DeflaterInputStream is Java 6. */
                        // response.setEntity(new InputStreamEntity(new DeflaterInputStream(new
                        // ByteArrayInputStream(
                        // entityText.getBytes("utf-8"))), -1));
                        final byte[] uncompressed = entityText.getBytes(Consts.UTF_8);
                        final Deflater compressor = new Deflater(Deflater.DEFAULT_COMPRESSION, rfc1951);
                        compressor.setInput(uncompressed);
                        compressor.finish();
                        final byte[] output = new byte[100];
                        final int compressedLength = compressor.deflate(output);
                        final byte[] compressed = new byte[compressedLength];
                        System.arraycopy(output, 0, compressed, 0, compressedLength);
                        response.setEntity(new InputStreamEntity(
                                new ByteArrayInputStream(compressed), compressedLength));
                        return;
                    }
                }
            }
        }
    };
}
项目:purecloud-iot    文件:TestContentCodings.java   
/**
 * Returns an {@link HttpRequestHandler} implementation that will attempt to provide a gzip
 * Content-Encoding.
 *
 * @param entityText
 *            the non-null String entity to be returned by the server
 * @return a non-null {@link HttpRequestHandler}
 */
private HttpRequestHandler createGzipEncodingRequestHandler(final String entityText) {
    return new HttpRequestHandler() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
            response.setEntity(new StringEntity(entityText));
            response.addHeader("Content-Type", "text/plain");
            final Header[] acceptEncodings = request.getHeaders("Accept-Encoding");

            for (final Header header : acceptEncodings) {
                for (final HeaderElement element : header.getElements()) {
                    if ("gzip".equalsIgnoreCase(element.getName())) {
                        response.addHeader("Content-Encoding", "gzip");

                        /*
                         * We have to do a bit more work with gzip versus deflate, since
                         * Gzip doesn't appear to have an equivalent to DeflaterInputStream in
                         * the JDK.
                         *
                         * UPDATE: DeflaterInputStream is Java 6 anyway, so we have to do a bit
                         * of work there too!
                         */
                        final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        final OutputStream out = new GZIPOutputStream(bytes);

                        final ByteArrayInputStream uncompressed = new ByteArrayInputStream(
                                entityText.getBytes(Consts.UTF_8));

                        final byte[] buf = new byte[60];

                        int n;
                        while ((n = uncompressed.read(buf)) != -1) {
                            out.write(buf, 0, n);
                        }

                        out.close();

                        final byte[] arr = bytes.toByteArray();
                        response.setEntity(new InputStreamEntity(new ByteArrayInputStream(arr),
                                arr.length));

                        return;
                    }
                }
            }
        }
    };
}
项目:phabricator-jenkins-plugin    文件:TestUtils.java   
public static HttpRequestHandler makeHttpHandler(final int statusCode, final String body) {
    ArrayList<String> requestBodies = new ArrayList<String>();
    return makeHttpHandler(statusCode, body, requestBodies);
}
项目:dlna-for-android    文件:HttpServerServiceImpl.java   
@Override
public void addHandler(String pattern, HttpRequestHandler handler) {
    httpServer.getHandlerRegistry().register(pattern, handler);
}
项目:catwatcher    文件:TomcatManagerServiceTest.java   
@Before
public void setUp () throws Exception
{
    LocalTestServer server = new LocalTestServer(null, null);
    server.register("/manager/text/*", new HttpRequestHandler()
    {

        @Override
        public void handle ( HttpRequest request, HttpResponse response, HttpContext content )
                throws HttpException, IOException
        {
            final String uri = request.getRequestLine().getUri();

            if (uri.contains("list"))
            {
                response.setEntity(new StringEntity("OK - Listed applications for virtual host localhost\n"
                        + "/:running:0:ROOT\n"
                        + "/host-manager:running:0:/usr/share/tomcat7-admin/host-manager\n"
                        + "/manager:running:3:/usr/share/tomcat7-admin/manager\n"
                        + "/good-app:running:4:/var/lib/tomcat7/webapps/good-app\n"
                        + "/bad-app:stopped:0:/var/lib/tomcat7/webapps/bad-app\n"));
                response.setStatusCode(200);
            }
            else if (uri.contains("start") || uri.contains("stop") || uri.contains("undeploy"))
            {
                response.setEntity(new StringEntity("OK - Operation executed"));
                response.setStatusCode(200);
            }
            else
            {
                response.setStatusCode(400);
            }
        }
    });
    server.start();
    hostName = server.getServiceAddress().getHostName();
    port = server.getServiceAddress().getPort();

    tomcatManagerService = new TomcatManagerServiceImpl("http://" + hostName + ":" + port + "/manager/text", null,
            null);
}