Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder build.

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:com.mediaworx.intellij.opencmsplugin.connector.OpenCmsPluginConnector.java

/**
 * Creates a new Plugin Connector/*from ww w.ja  v  a2  s  .  c o m*/
 * @param connectorUrl          the Url under which the connector JSP cam be called
 * @param user                  OpenCms user to be used for communication with the connector
 * @param password              The OpenCms user's password
 * @param useMetaDateVariables  <code>true</code> if date variables should be used in meta data, <code>false</code>
 *                              otherwise
 * @param useMetaIdVariables    <code>true</code> if UUID variables should be used in meta data, <code>false</code>
 *                              otherwise
 */
public OpenCmsPluginConnector(String connectorUrl, String user, String password, boolean useMetaDateVariables,
        boolean useMetaIdVariables) {
    this.connectorUrl = connectorUrl;
    this.user = user;
    this.password = password;
    this.useMetaDateVariables = useMetaDateVariables;
    this.useMetaIdVariables = useMetaIdVariables;
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setUserAgent("IntelliJ OpenCms plugin connector");
    httpClient = clientBuilder.build();

    jsonParser = new JSONParser();
}

From source file:com.sumologic.log4j.http.SumoHttpSender.java

public void init() {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();

    HttpClientBuilder builder = HttpClients.custom()
            .setConnectionManager(new PoolingHttpClientConnectionManager())
            .setDefaultRequestConfig(requestConfig);

    HttpProxySettingsCreator creator = new HttpProxySettingsCreator(proxySettings);
    creator.configureProxySettings(builder);

    httpClient = builder.build();
}

From source file:net.officefloor.plugin.web.http.security.integrate.AbstractHttpSecurityIntegrateTestCase.java

/**
 * Use credentials.//from  w ww.j  a v  a2 s.c o m
 * 
 * @param realm
 *            Security realm.
 * @param scheme
 *            Security scheme.
 * @param username
 *            User name.
 * @param password
 *            Password.
 * @return {@link CredentialsProvider}.
 * @throws IOException
 *             If fails to use credentials.
 */
protected CredentialsProvider useCredentials(String realm, String scheme, String username, String password)
        throws IOException {

    // Close the existing client
    this.client.close();

    // Use client with credentials
    HttpClientBuilder builder = HttpClientBuilder.create();
    CredentialsProvider provider = HttpTestUtil.configureCredentials(builder, realm, scheme, username,
            password);
    this.client = builder.build();

    // Reset the client context
    this.context = new HttpClientContext();

    // FIXME: determine if HttpClient cookie authentication fix
    if ("Digest".equalsIgnoreCase(scheme)) {
        isDigestHttpClientCookieBug = true;
    }

    // Return the credentials provider
    return provider;
}

From source file:net.officefloor.plugin.web.http.continuation.HttpUrlContinuationSectionSourceTest.java

/**
 * Undertakes the service URL continuation test.
 *//*from ww w . ja v  a2s  .c  o m*/
public void doServiceTest(boolean isSecure) throws Exception {

    // Create and configure application
    AutoWireApplication source = new AutoWireOfficeFloorSource();

    // Add the servicer
    AutoWireSection section = source.addSection("SECTION", ClassSectionSource.class.getName(),
            MockSectionRunClass.class.getName());

    // Provide remaining configuration
    HttpServerSocketManagedObjectSource.autoWire(source, 7878, "ROUTE", HttpRouteWorkSource.TASK_NAME);
    HttpsServerSocketManagedObjectSource.autoWire(source, 7979, HttpTestUtil.getSslEngineSourceClass(), "ROUTE",
            HttpRouteWorkSource.TASK_NAME);
    AutoWireSection route = source.addSection("ROUTE", WorkSectionSource.class.getName(),
            HttpRouteWorkSource.class.getName());
    source.link(route, "NOT_HANDLED", section, "notHandled");
    source.addManagedObject(HttpApplicationLocationManagedObjectSource.class.getName(), null,
            new AutoWire(HttpApplicationLocation.class));
    source.addManagedObject(HttpRequestStateManagedObjectSource.class.getName(), null,
            new AutoWire(HttpRequestState.class));
    source.addManagedObject(HttpSessionManagedObjectSource.class.getName(), null,
            new AutoWire(HttpSession.class)).setTimeout(1000);

    // Add the transformer
    HttpUrlContinuationSectionSource transformer = new HttpUrlContinuationSectionSource();
    source.addSectionTransformer(transformer);

    // Map in the URI
    HttpUriLink link = transformer.linkUri("uri", section, "service");
    if (isSecure) {
        // Flag to be secure (default is non-secure)
        link.setUriSecure(isSecure);
    }
    assertEquals("Incorrect URI", "uri", link.getApplicationUriPath());
    assertSame("Incorrect Section", section, link.getAutoWireSection());
    assertEquals("Incorrect Section Input", "service", link.getAutoWireSectionInputName());

    // Ensure return listing of all registered URI paths
    HttpUriLink[] registeredUriLinks = transformer.getRegisteredHttpUriLinks();
    assertEquals("Incorrect number of registered URI links", 1, registeredUriLinks.length);
    assertSame("Incorrect URI link", link, registeredUriLinks[0]);

    // Create the client (without redirect)
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpTestUtil.configureHttps(builder);
    HttpTestUtil.configureNoRedirects(builder);
    CloseableHttpClient client = builder.build();

    // Obtain the host name
    String hostName = HttpApplicationLocationManagedObjectSource.getDefaultHostName();

    // Obtain the URLs
    final String SECURE_URL = "https://" + hostName + ":7979/uri";
    final String NON_SECURE_URL = "http://" + hostName + ":7878/uri";
    String urlInitial;
    String urlRedirect;
    if (isSecure) {
        urlInitial = NON_SECURE_URL;
        urlRedirect = SECURE_URL + HttpRouteTask.REDIRECT_URI_SUFFIX;
    } else {
        urlInitial = SECURE_URL;
        urlRedirect = NON_SECURE_URL + HttpRouteTask.REDIRECT_URI_SUFFIX;
    }

    // Start application
    AutoWireOfficeFloor officeFloor = source.openOfficeFloor();
    try {

        // Ensure redirect if not appropriately secure
        HttpResponse response = client.execute(new HttpGet(urlInitial));
        assertEquals("Should be redirect", 303, response.getStatusLine().getStatusCode());
        assertEquals("Incorrect redirect location", urlRedirect,
                response.getFirstHeader("Location").getValue());
        response.getEntity().getContent().close();

        // Ensure servicing request
        response = client.execute(new HttpGet(urlRedirect));
        assertEquals("Should be successful", 200, response.getStatusLine().getStatusCode());
        assertEquals("Incorrect response", "SERVICED", HttpTestUtil.getEntityBody(response));

    } finally {
        try {
            // Ensure stop client
            client.close();
        } finally {
            // Ensure stop application
            officeFloor.closeOfficeFloor();
        }
    }
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Builds and executes HttpGet Request by appending the urlQuery parameter to the 
 * serverHost:serverPort variables.  Returns the data payload response as a JSONObject. 
 * // w ww .ja  va 2s  .  co m
 * @param urlQuery
 * @return org.json.simple.JSONObject
 * @throws Exception
 */
public JSONObject getAPI(String urlQuery) throws Exception {
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    JSONObject data;
    try {
        HttpGet httpGet = new HttpGet(ePoint + urlQuery);
        m_log.info("Executing request: " + httpGet.getRequestLine());
        CloseableHttpResponse resp = httpClient.execute(httpGet);
        try {
            m_log.info("Respone: " + resp.getStatusLine());
            String jsonResponse = EntityUtils.toString(resp.getEntity()); // json response
            JSONParser jp = new JSONParser();
            JSONObject jObj = (JSONObject) jp.parse(jsonResponse);
            data = (JSONObject) jObj.get("data");
            m_log.debug(data);
        } finally {
            resp.close();
        }
    } finally {
        httpClient.close();
    }
    return data;
}

From source file:co.tuzza.swipehq.transport.ManagedHttpTransport.java

private HttpClient getHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setUserAgent("SwipeHQClient " + SwipeHQClient.VERSION);
    httpClientBuilder.setConnectionManager(clientConnectionManager);
    httpClientBuilder.setDefaultRequestConfig(getRequestConfig());
    httpClientBuilder.setSSLContext(sslContext);

    return httpClientBuilder.build();

}

From source file:test.integ.be.e_contract.cdi.crossconversation.CrossConversationScopedTest.java

@Test
public void testAndroidSessionSeparation() throws Exception {
    String webBrowserTestLocation = this.baseURL + "browser";
    String webBrowserValueLocation = this.baseURL + "value";
    LOGGER.debug("location: {}", webBrowserTestLocation);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    HttpClient webBrowserHttpClient1 = httpClientBuilder.build();

    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    HttpClient webBrowserHttpClient2 = httpClientBuilder.build();

    HttpContext webBrowserHttpContext1 = new BasicHttpContext();
    String webBrowserCode1 = doGet(webBrowserHttpClient1, webBrowserHttpContext1, webBrowserTestLocation);
    String webBrowserValue1 = doGet(webBrowserHttpClient1, webBrowserHttpContext1, webBrowserValueLocation);

    HttpContext webBrowserHttpContext2 = new BasicHttpContext();
    String webBrowserCode2 = doGet(webBrowserHttpClient2, webBrowserHttpContext2, webBrowserTestLocation);
    String webBrowserValue2 = doGet(webBrowserHttpClient2, webBrowserHttpContext2, webBrowserValueLocation);

    assertNotEquals(webBrowserCode1, webBrowserCode2);
    assertNotEquals(webBrowserValue1, webBrowserValue2);

    String androidLocation1 = this.baseURL + "android?androidCode=" + webBrowserCode1;
    String androidValueLocation1 = webBrowserValueLocation + "?androidCode=" + webBrowserCode1;

    HttpClient androidHttpClient = httpClientBuilder.build();

    HttpContext androidHttpContext1 = new BasicHttpContext();
    String androidCode1 = doGet(androidHttpClient, androidHttpContext1, androidLocation1);
    String androidValue1 = doGet(androidHttpClient, androidHttpContext1, androidValueLocation1);

    assertEquals(webBrowserCode1, androidCode1);
    assertEquals(webBrowserValue1, androidValue1);

    String androidLocation2 = this.baseURL + "android?androidCode=" + webBrowserCode2;
    String androidValueLocation2 = webBrowserValueLocation + "?androidCode=" + webBrowserCode2;

    HttpContext androidHttpContext2 = new BasicHttpContext();
    String androidCode2 = doGet(androidHttpClient, androidHttpContext2, androidLocation2);
    String androidValue2 = doGet(androidHttpClient, androidHttpContext2, androidValueLocation2);

    assertEquals(webBrowserCode2, androidCode2);
    assertEquals(webBrowserValue2, androidValue2);
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Builds and executes an HttpPost Request by appending the urlQuery parameter to the 
 * serverHost:serverPort variables and inserting the contents of the payload parameter.
 * Returns the data payload response as a JSONObject. 
 * /*from www  .j  a  va 2 s.c o  m*/
 * @param urlQuery
 * @param payload
 * @return org.json.simple.JSONObject
 * @throws Exception
 */
public JSONObject postAPI(String urlQuery, String payload) throws Exception {
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    JSONObject data;
    StringEntity payloadEntity = new StringEntity(payload, ContentType.APPLICATION_JSON);
    try {
        HttpPost httpPost = new HttpPost(ePoint + urlQuery);
        m_log.info("Executing request : " + httpPost.getRequestLine());
        m_log.debug("Payload : " + payload);
        httpPost.setEntity(payloadEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            String jsonResponse = EntityUtils.toString(resp.getEntity());
            JSONParser jp = new JSONParser();
            JSONObject jObj = (JSONObject) jp.parse(jsonResponse);
            data = (JSONObject) jObj.get("data");
            m_log.debug(data);

        } finally {
            resp.close();
        }
    } finally {
        httpClient.close();
    }
    return data;
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid
 * If the file is succesfully uploaded the response code of 204 is returned.
 * /*  ww w  .j a v a2  s .c om*/
 * @param planUid 
 * @param sessionId
 * @param file
 * @return HTTP Response code as int
 * @throws Exception
 */

public int postFileAPI(String planUid, String sessionId, File file) throws Exception {

    int respCode;
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN);
    StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN);

    try {
        HttpPost httpPost = new HttpPost(ePoint + "/api/File");
        FileBody fb = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId)
                .addPart("sessionId", sId).build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            m_log.info("executing " + httpPost.getRequestLine());
            m_log.info(resp.getStatusLine());
            respCode = resp.getStatusLine().getStatusCode();
        } finally {
            resp.close();
        }

    } finally {
        httpClient.close();
    }

    return respCode;
}