Java Code Examples for org.eclipse.jetty.client.HttpClient#start()

The following examples show how to use org.eclipse.jetty.client.HttpClient#start() . 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: DynRealmITCase.java    From syncope with Apache License 2.0 6 votes vote down vote up
private static ArrayNode fetchDynRealmsFromElasticsearch(final String userKey) throws Exception {
    String body =
        '{'
            + "    \"query\": {"
            + "        \"match\": {\"_id\": \"" + userKey + "\"}"
            + "    }"
            + '}';

    HttpClient httpClient = new HttpClient();
    httpClient.start();
    ContentResponse response = httpClient.newRequest("http://localhost:9200/master_user/_search").
            method(HttpMethod.GET).
            header(HttpHeader.CONTENT_TYPE, MediaType.APPLICATION_JSON).
            content(new InputStreamContentProvider(IOUtils.toInputStream(body))).
            send();
    assertEquals(HttpStatus.OK_200, response.getStatus());

    return (ArrayNode) OBJECT_MAPPER.readTree(response.getContent()).
            get("hits").get("hits").get(0).get("_source").get("dynRealms");
}
 
Example 2
Source File: ChaosHttpProxyTest.java    From chaos-http-proxy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    Properties properties = new Properties();
    properties.setProperty(Failure.CHAOS_CONFIG_PREFIX + "success", "5");
    config = new ChaosConfig(properties);
    proxy = new ChaosHttpProxy(proxyEndpoint, config);
    proxy.start();

    // reset endpoint to handle zero port
    proxyEndpoint = new URI(proxyEndpoint.getScheme(),
            proxyEndpoint.getUserInfo(), proxyEndpoint.getHost(),
            proxy.getPort(), proxyEndpoint.getPath(),
            proxyEndpoint.getQuery(), proxyEndpoint.getFragment());
    logger.debug("ChaosHttpProxy listening on {}", proxyEndpoint);

    setupHttpBin(new HttpBin(httpBinEndpoint));

    client = new HttpClient();
    ProxyConfiguration proxyConfig = client.getProxyConfiguration();
    proxyConfig.getProxies().add(new HttpProxy(proxyEndpoint.getHost(),
            proxyEndpoint.getPort()));
    client.start();
}
 
Example 3
Source File: InjectionModule.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
private HttpClient createHttpClient() {
    //Allow ssl by default
    SslContextFactory sslContextFactory = new SslContextFactory();
    //Don't exclude RSA because Sixt needs them, dammit!
    sslContextFactory.setExcludeCipherSuites("");
    HttpClient client = new HttpClient(sslContextFactory);
    client.setFollowRedirects(false);
    client.setMaxConnectionsPerDestination(16);
    client.setRequestBufferSize(65536);
    client.setConnectTimeout(FeatureFlags.getHttpConnectTimeout(serviceProperties));
    client.setAddressResolutionTimeout(FeatureFlags.getHttpAddressResolutionTimeout(serviceProperties));
    //You can set more restrictive timeouts per request, but not less, so
    //  we set the maximum timeout of 1 hour here.
    client.setIdleTimeout(60 * 60 * 1000);
    try {
        client.start();
    } catch (Exception e) {
        logger.error("Error building http client", e);
    }
    return client;
}
 
Example 4
Source File: ServiceImpersonatorLoadBalancer.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
private HttpClient createHttpClient() {
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setExcludeCipherSuites("");
    HttpClient client = new HttpClient(sslContextFactory);
    client.setFollowRedirects(false);
    client.setMaxConnectionsPerDestination(2);
    //You can set more restrictive timeouts per request, but not less, so
    //  we set the maximum timeout of 1 hour here.
    client.setIdleTimeout(60 * 60 * 1000);
    try {
        client.start();
    } catch (Exception e) {
        logger.error("Error building http client", e);
    }
    return client;
}
 
Example 5
Source File: FSInternetRadioHandlerJavaTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    ServletHolder holder = new ServletHolder(radioServiceDummy);
    server = new TestServer(DEFAULT_CONFIG_PROPERTY_IP, DEFAULT_CONFIG_PROPERTY_PORT, TIMEOUT, holder);
    setTheChannelsMap();
    server.startServer();
    httpClient = new HttpClient();
    httpClient.start();
}
 
Example 6
Source File: AbstractAudioServeltTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected void startHttpClient(HttpClient client) {
    if (!client.isStarted()) {
        try {
            client.start();
        } catch (Exception e) {
            fail("An exception " + e + " was thrown, while starting the HTTP client");
        }
    }
}
 
Example 7
Source File: AsyncRestServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig servletConfig) throws ServletException {
  super.init(servletConfig);
  SslContextFactory sslContextFactory = new SslContextFactory();
  client = new HttpClient(sslContextFactory);

  try {
    client.start();
  } catch (Exception e) {
    throw new ServletException(e);
  }
}
 
Example 8
Source File: JettyClientFactory.java    From moon-api-gateway with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(jettyClientConfig.getThreadCount());
    httpClient = new HttpClient();
    try {
        httpClient.setMaxConnectionsPerDestination(jettyClientConfig.getMaxConnection());
        httpClient.setConnectTimeout(jettyClientConfig.getTimeout());
        httpClient.setExecutor(executor);
        httpClient.start();
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: AbstractAudioServletTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void startHttpClient(HttpClient client) {
    if (!client.isStarted()) {
        try {
            client.start();
        } catch (Exception e) {
            fail("An exception " + e + " was thrown, while starting the HTTP client");
        }
    }
}
 
Example 10
Source File: HttpClientModule.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public HttpClient provideHttpClient(ExecutorService executorService,
                                    @Named("httpClient.maxConnectionsQueued") Integer maxConnectionsQueued,
                                    @Named("httpClient.maxConnectionPerRoute") Integer maxConnectionPerRoute,
                                    @Named("httpClient.requestBufferSize") Integer requestBufferSize,
                                    @Named("httpClient.responseBufferSize") Integer responseBufferSize,
                                    @Named("httpClient.maxRedirects") Integer maxRedirects,
                                    @Named("httpClient.trustAllCertificates") Boolean trustAllCertificates) {

    try {
        SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
        sslContextFactory.setTrustAll(trustAllCertificates);
        HttpClient httpClient = new HttpClient(sslContextFactory);
        httpClient.setExecutor(executorService);
        httpClient.setMaxConnectionsPerDestination(maxConnectionsQueued);
        httpClient.setMaxRequestsQueuedPerDestination(maxConnectionPerRoute);
        httpClient.setRequestBufferSize(requestBufferSize);
        httpClient.setResponseBufferSize(responseBufferSize);
        httpClient.setMaxRedirects(maxRedirects);
        httpClient.start();

        registerHttpClientShutdownHook(httpClient);

        return httpClient;
    } catch (Exception e) {
        System.out.println(Arrays.toString(e.getStackTrace()));
        throw new RuntimeException(e.getLocalizedMessage(), e);
    }
}
 
Example 11
Source File: WebServerTest.java    From app-runner with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    client = new HttpClient();
    client.setFollowRedirects(false);
    client.start();
    AppEstate estate = new AppEstate(proxyMap, fileSandbox(),
        new AppRunnerFactoryProvider(new ArrayList<>()));
    int port = WebServer.getAFreePort();
    webServerUrl = "http://localhost:" + port;
    SystemInfo systemInfo = SystemInfo.create();
    webServer = new WebServer(port, -1, null, null, -1, proxyMap, "test-app",
        new SystemResource(systemInfo, new AtomicBoolean(true), new ArrayList<>(), null), new AppResource(estate, systemInfo, fileSandbox()), PROXY_TIMEOUT, PROXY_TIMEOUT, "apprunner", 500 * 1024 * 1024);
    webServer.start();
    appServer = new TestServer();
}
 
Example 12
Source File: HttpRpcEndpoint.java    From nutzcloud with Apache License 2.0 5 votes vote down vote up
public void init() throws Exception {
    client = new HttpClient(new SslContextFactory(true));
    client.setFollowRedirects(false);
    client.setCookieStore(new HttpCookieStore.Empty());

    executor = new QueuedThreadPool(conf.getInt(PRE + ".maxThreads", 256));
    client.setExecutor(executor);
    client.setMaxConnectionsPerDestination(conf.getInt(PRE + ".maxConnections", 256));
    client.setIdleTimeout(conf.getLong(PRE + ".idleTimeout", 30000));

    client.setConnectTimeout(conf.getLong(PRE + ".connectTime", 1000));

    if (conf.has(PRE + "requestBufferSize"))
        client.setRequestBufferSize(conf.getInt(PRE + "requestBufferSize"));

    if (conf.has(PRE + "responseBufferSize"))
        client.setResponseBufferSize(conf.getInt(PRE + "responseBufferSize"));

    client.start();

    // Content must not be decoded, otherwise the client gets confused.
    client.getContentDecoderFactories().clear();

    // Pass traffic to the client, only intercept what's necessary.
    ProtocolHandlers protocolHandlers = client.getProtocolHandlers();
    protocolHandlers.clear();
}
 
Example 13
Source File: AuthIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    httpClient = new HttpClient();
    httpClient.start();
}
 
Example 14
Source File: HTTPAction.java    From nadia with Apache License 2.0 5 votes vote down vote up
private void init(){
	SslContextFactory sslContextFactory = new SslContextFactory();
   	client = new HttpClient(sslContextFactory);
   	try {
		client.start();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: StreamClientImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    log.info("Starting Jetty HttpClient...");
    client = new HttpClient();

    // Jetty client needs threads for its internal expiration routines, which we don't need but
    // can't disable, so let's abuse the request executor service for this
    client.setThreadPool(
        new ExecutorThreadPool(getConfiguration().getRequestExecutorService()) {
            @Override
            protected void doStop() throws Exception {
                // Do nothing, don't shut down the Cling ExecutorService when Jetty stops!
            }
        }
    );

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    client.setTimeout((configuration.getTimeoutSeconds()+5) * 1000);
    client.setConnectTimeout((configuration.getTimeoutSeconds()+5) * 1000);

    client.setMaxRetries(configuration.getRequestRetryCount());

    try {
        client.start();
    } catch (Exception ex) {
        throw new InitializationException(
            "Could not start Jetty HTTP client: " + ex, ex
        );
    }
}
 
Example 16
Source File: EventRecordCreator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void init() throws StageException {
  super.init();

  try {
    httpClient = new HttpClient(ForceUtils.makeSslContextFactory(conf));
    if (conf.useProxy) {
      ForceUtils.setProxy(httpClient, conf);
    }
    httpClient.start();
  } catch (Exception e) {
    throw new StageException(Errors.FORCE_34, e);
  }
}
 
Example 17
Source File: CloudStore.java    From athenz with Apache License 2.0 5 votes vote down vote up
void setupHttpClient(HttpClient client) {

        client.setFollowRedirects(false);
        client.setStopTimeout(1000);
        try {
            client.start();
        } catch (Exception ex) {
            LOGGER.error("CloudStore: unable to start http client", ex);
            throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR,
                    "Http client not available");
        }
    }
 
Example 18
Source File: StreamClientImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    log.info("Starting Jetty HttpClient...");
    client = new HttpClient();

    // Jetty client needs threads for its internal expiration routines, which we don't need but
    // can't disable, so let's abuse the request executor service for this
    client.setThreadPool(
        new ExecutorThreadPool(getConfiguration().getRequestExecutorService()) {
            @Override
            protected void doStop() throws Exception {
                // Do nothing, don't shut down the Cling ExecutorService when Jetty stops!
            }
        }
    );

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    client.setTimeout((configuration.getTimeoutSeconds()+5) * 1000);
    client.setConnectTimeout((configuration.getTimeoutSeconds()+5) * 1000);

    client.setMaxRetries(configuration.getRequestRetryCount());

    try {
        client.start();
    } catch (Exception ex) {
        throw new InitializationException(
            "Could not start Jetty HTTP client: " + ex, ex
        );
    }
}
 
Example 19
Source File: JerseyUnixSocketConnector.java    From tessera with Apache License 2.0 5 votes vote down vote up
public JerseyUnixSocketConnector(URI unixfile) {
    this.unixfile = unixfile;
    String unixFilePath = Paths.get(unixfile).toFile().getAbsolutePath();

    httpClient = new HttpClient(new HttpClientTransportOverUnixSockets(unixFilePath), null);
    try{
        httpClient.start();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 20
Source File: ProxyIsAHttpProxyTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Test
public void testStreaming() throws Exception {
    LinkedBlockingQueue<String> dataQueue = new LinkedBlockingQueue<>();
    Server streamingServer = new Server(0);
    streamingServer.setHandler(newStreamingHandler(dataQueue));
    streamingServer.start();

    Properties props = new Properties();
    props.setProperty("httpOutputBufferSize", "1");
    props.setProperty("httpReverseProxy.foobar.path", "/stream");
    props.setProperty("httpReverseProxy.foobar.proxyTo", streamingServer.getURI().toString());
    props.setProperty("servicePort", "0");
    props.setProperty("webServicePort", "0");

    ProxyConfiguration proxyConfig = PulsarConfigurationLoader.create(props, ProxyConfiguration.class);
    AuthenticationService authService = new AuthenticationService(
            PulsarConfigurationLoader.convertFrom(proxyConfig));

    WebServer webServer = new WebServer(proxyConfig, authService);
    ProxyServiceStarter.addWebServerHandlers(webServer, proxyConfig, null,
                                             new BrokerDiscoveryProvider(proxyConfig, mockZooKeeperClientFactory));
    webServer.start();

    HttpClient httpClient = new HttpClient();
    httpClient.start();
    try {
        LinkedBlockingQueue<Byte> responses = new LinkedBlockingQueue<>();
        CompletableFuture<Result> promise = new CompletableFuture<>();
        httpClient.newRequest(webServer.getServiceUri()).path("/stream")
            .onResponseContent((response, content) -> {
                    while (content.hasRemaining()) {
                        try {
                            responses.put(content.get());
                        } catch (Exception e) {
                            log.error("Error reading response", e);
                            promise.completeExceptionally(e);
                        }
                    }
                })
            .send((result) -> {
                    log.info("Response complete");
                    promise.complete(result);
                });

        dataQueue.put("Some data");
        assertEventuallyTrue(() -> responses.size() == "Some data".length());
        Assert.assertEquals("Some data", drainToString(responses));
        Assert.assertFalse(promise.isDone());

        dataQueue.put("More data");
        assertEventuallyTrue(() -> responses.size() == "More data".length());
        Assert.assertEquals("More data", drainToString(responses));
        Assert.assertFalse(promise.isDone());

        dataQueue.put("DONE");
        assertEventuallyTrue(() -> promise.isDone());
        Assert.assertTrue(promise.get().isSucceeded());
    } finally {
        webServer.stop();
        httpClient.stop();
        streamingServer.stop();
    }
}