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

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

Introduction

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

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:org.restcomm.connect.java.sdk.http.HttpClient.java

public void authenticate() {
    this.credentials = Base64.encodeBase64(
            (Restcomm.getAuthID() + ":" + Restcomm.getPassword()).getBytes(StandardCharsets.UTF_8));
    this.httpclient = HttpClientBuilder.create().build();
}

From source file:com.seyren.core.service.notification.HttpNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String httpUrl = StringUtils.trimToNull(subscription.getTarget());

    if (httpUrl == null) {
        LOGGER.warn("URL needs to be set before sending notifications to HTTP");
        return;/*from  w  w  w  .  j  a v a 2 s. co m*/
    }
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("preview", getPreviewImage(check));

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost post;

    if (StringUtils.isNotBlank(seyrenConfig.getHttpNotificationUrl())) {
        post = new HttpPost(seyrenConfig.getHttpNotificationUrl());
    } else {
        post = new HttpPost(subscription.getTarget());
    }

    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to HTTP", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:teletype.model.vk.Auth.java

public void authorize() throws VKAuthException, IOException {

    // Phase 1. Send authorization request.
    // Opening OAuth Authorization Dialog
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("https").setHost("oauth.vk.com").setPath("/authorize").setParameter("client_id", appID)
            .setParameter("scope", "messages,friends,status")
            .setParameter("redirect_uri", "https://oauth.vk.com/blank.html").setParameter("display", "wap")
            .setParameter("v", "5.28").setParameter("response_type", "token");

    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    URI uri = getUri(uriBuilder);
    HttpPost request = new HttpPost(uri);
    HttpResponse response = httpClient.execute(request);
    request.abort();/*w  w  w . j a  v a2  s  .co m*/

    // Get ip_h and to_h parameters for next request 
    StringBuilder contentText = getContentText(response);

    String ip_h = parseResponse(contentText, "ip_h", 18);
    //System.out.println("ip_h : " + ip_h);

    String to_h = parseResponse(contentText, "=\"to\"", 212);
    //System.out.println("to_h : " + to_h);

    uriBuilder = new URIBuilder();
    uriBuilder.setScheme("https").setHost("login.vk.com").setPath("/").setParameter("act", "login")
            .setParameter("soft", "1").setParameter("q", "1").setParameter("ip_h", ip_h)
            .setParameter("from_host", "oauth.vk.com").setParameter("to", to_h).setParameter("expire", "0")
            .setParameter("email", login).setParameter("pass", password);

    request = new HttpPost(getUri(uriBuilder));
    response = httpClient.execute(request);
    request.abort();

    //System.out.println("Incorrect login url: " + uriBuilder.toString());

    // Phase 2. Providing Access Permissions
    // TODO: if got access request then call externall web browser. possible do it ourselves.

    // Phase 3. Open url with webengine and receiving "access_token".
    // It does not work with httpClient
    LoginControllerHelper.callHiddenWebBrowser(uriBuilder.toString());

    //if (true) return;

    /*
    printHeader(response);
            
    // Phase 2. Got redirect to authorization page.
    // Filling the form and sending it.
    //String HeaderLocation = response.getFirstHeader("location").getValue();
    request = new HttpPost(HeaderLocation);
    response = httpClient.execute(request);
    //System.out.println("==================>");
    request.abort();
    //String url = response.getFirstHeader("location").getValue();
            
    // Phase 3. Got permissions request.
    // Open web browser and sending link there.
    //System.out.println("URL is: " + url);
    // Calling externall web browser.
    ControllerHelper.callHiddenWebBrowser(url);
    //ControllerHelper.callWebBrowser(url);
            
    /*
     * It works by calling external web-browser.
     * All redirects ok and gives the token.
     * But doesn't work using HttpClient.
     * Server redirects me to error page.
     *
            
    request = new HttpPost(url);
    response = httpClient.execute(request);
    System.out.println("Sending last ==================>\n");
            
    HeaderLocation = response.getFirstHeader("location").getValue();
            
    //String access_token = HeaderLocation.split("#")[1].split("&")[0].split("=")[1];
    System.out.println("Header is: " + HeaderLocation);
    */
}

From source file:org.hawkular.client.RestFactory.java

public T createAPI(URI uri, String userName, String password) {
    HttpClient httpclient = null;//from   ww  w . ja v  a2s. com
    if (uri.toString().startsWith("https")) {
        httpclient = getHttpClient();
    } else {
        httpclient = HttpClientBuilder.create().build();
    }
    ResteasyClient client = null;
    if (userName != null) {
        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    } else {
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient());
        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }

    client.register(JacksonJaxbJsonProvider.class);
    client.register(JacksonObjectMapperProvider.class);
    client.register(RestRequestFilter.class);
    client.register(RestResponseFilter.class);
    client.register(HCJacksonJson2Provider.class);
    ProxyBuilder<T> proxyBuilder = client.target(uri).proxyBuilder(apiClassType);
    if (classLoader != null) {
        proxyBuilder = proxyBuilder.classloader(classLoader);
    }
    return proxyBuilder.build();
}

From source file:io.rainfall.web.operation.HttpOperation.java

@Override
public void exec(final StatisticsHolder statisticsHolder,
        final Map<Class<? extends Configuration>, Configuration> configurations,
        final List<AssertionEvaluator> assertions) throws TestException {
    String url = null;//from ww w  .  j ava2 s  . co m
    HttpConfig httpConfig = (HttpConfig) configurations.get(HttpConfig.class);
    if (httpConfig != null) {
        url = httpConfig.getUrl();
    }
    if (url == null) {
        throw new TestException("baseURL of io.rainfall.web.HttpConfig is missing");
    }
    final HttpClient client = HttpClientBuilder.create().build();

    if (path != null) {
        url += path;
    }

    statisticsHolder.measure("http", function.execute(client, httpRequest(url)));

    //TODO : evaluate assertions
}

From source file:org.fcrepo.integration.connector.file.FileConnectorIT.java

private static CloseableHttpClient createClient() {
    return HttpClientBuilder.create().setMaxConnPerRoute(MAX_VALUE).setMaxConnTotal(MAX_VALUE).build();
}

From source file:org.jboss.pnc.mavenrepositorymanager.UploadTwoThenVerifyExtractedArtifactsContainThemTest.java

@Test
public void extractBuildArtifacts_ContainsTwoUploads() throws Exception {
    // create a dummy non-chained build execution and repo session based on it
    BuildExecution execution = new TestBuildExecution();
    RepositorySession rc = driver.createBuildRepository(execution, accessToken);

    assertThat(rc, notNullValue());//w ww  .j  a v  a 2  s  .  com

    String baseUrl = rc.getConnectionInfo().getDeployUrl();
    String pomPath = "org/commonjava/indy/indy-core/0.17.0/indy-core-0.17.0.pom";
    String jarPath = "org/commonjava/indy/indy-core/0.17.0/indy-core-0.17.0.jar";

    CloseableHttpClient client = HttpClientBuilder.create().build();

    // upload a couple files related to a single GAV using the repo session deployment url
    // this simulates a build deploying one jar and its associated POM
    for (String path : new String[] { pomPath, jarPath }) {
        final String url = UrlUtils.buildUrl(baseUrl, path);

        assertThat("Failed to upload: " + url, ArtifactUploadUtils.put(client, url, "This is a test"),
                equalTo(true));
    }

    // extract the "built" artifacts we uploaded above.
    RepositoryManagerResult repositoryManagerResult = rc.extractBuildArtifacts();

    // check that both files are present in extracted result
    List<Artifact> artifacts = repositoryManagerResult.getBuiltArtifacts();
    System.out.println(artifacts);

    assertThat(artifacts, notNullValue());
    assertThat(artifacts.size(), equalTo(2));

    ProjectVersionRef pvr = new SimpleProjectVersionRef("org.commonjava.indy", "indy-core", "0.17.0");
    Set<String> refs = new HashSet<>();
    refs.add(new SimpleArtifactRef(pvr, "pom", null).toString());
    refs.add(new SimpleArtifactRef(pvr, "jar", null).toString());

    // check that the artifact getIdentifier() stores GAVT[C] information in the standard Maven rendering
    for (Artifact artifact : artifacts) {
        assertThat(artifact + " is not in the expected list of built artifacts: " + refs,
                refs.contains(artifact.getIdentifier()), equalTo(true));
    }

    Indy indy = driver.getIndy(accessToken);

    // check that we can download the two files from the build repository
    for (String path : new String[] { pomPath, jarPath }) {
        final String url = indy.content().contentUrl(StoreType.hosted, rc.getBuildRepositoryId(), path);
        boolean downloaded = client.execute(new HttpGet(url), response -> {
            try {
                return response.getStatusLine().getStatusCode() == 200;
            } finally {
                if (response instanceof CloseableHttpResponse) {
                    IOUtils.closeQuietly((CloseableHttpResponse) response);
                }
            }
        });

        assertThat("Failed to download: " + url, downloaded, equalTo(true));
    }

    client.close();

}

From source file:org.obm.satellite.client.SatelliteClientModule.java

@Provides
private HttpClient provideHttpClient() {
    try {//from  w w  w.j a  v a2s . co m
        SSLContext sslContext = buildSSLContext(TRUST_ALL_KEY_MANAGERS);
        return HttpClientBuilder.create().setSslcontext(sslContext)
                .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .useSystemProperties().build();
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException("Could not initialize a ssl context", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Could not initialize a ssl context", e);
    }
}

From source file:com.messagemedia.restapi.client.v1.internal.RestClient.java

public RestClient(String endpoint, String key, String secret, Integer maxConnections, Integer connectTimeout,
        Integer socketTimeout, AuthorizationScheme authorizationScheme) {
    this.endpoint = endpoint;
    int maxConnectionsValue = maxConnections != null ? maxConnections : MAX_CONNECTIONS_DEFAULT;
    int connectTimeoutValue = connectTimeout != null ? connectTimeout : CONNECT_TIMEOUT_DEFAULT;
    int socketTimeoutValue = socketTimeout != null ? socketTimeout : SOCKET_TIMEOUT_DEFAULT;

    RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutValue)
            .setSocketTimeout(socketTimeoutValue).build();

    httpClient = HttpClientBuilder.create().addInterceptorFirst(new ContentTypeInterceptor())
            .addInterceptorFirst(new RequestDateInterceptor())
            .addInterceptorFirst(toRequestInterceptor(authorizationScheme, key, secret))
            .setMaxConnPerRoute(maxConnectionsValue).setMaxConnTotal(maxConnectionsValue)
            .disableCookieManagement().setUserAgent(USER_AGENT).setDefaultRequestConfig(config).build();
}

From source file:com.seyren.core.service.notification.PushoverNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String pushoverAppApiToken = StringUtils.trimToNull(seyrenConfig.getPushoverAppApiToken());
    String pushoverUserKey = StringUtils.trimToNull(subscription.getTarget());
    String pushoverMsgTitle = formatMsgTitle(check);
    String pushoverMsgBody = "Check details : " + seyrenConfig.getBaseUrl() + "/#/checks/" + check.getId();
    String pushoverMsgPriority = getMsgPriority(check);

    if (pushoverAppApiToken == null) {
        LOGGER.warn("Pushover App API Token must be provided");
        return;/*  w w w.ja  v a2  s  .  com*/
    }

    if (pushoverUserKey == null || pushoverUserKey.length() != 30) {
        LOGGER.warn("Invalid or missing Pushover user key");
        return;
    }

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost post = new HttpPost("https://api.pushover.net/1/messages.json");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("token", pushoverAppApiToken));
        nameValuePairs.add(new BasicNameValuePair("user", pushoverUserKey));
        nameValuePairs.add(new BasicNameValuePair("title", pushoverMsgTitle));
        nameValuePairs.add(new BasicNameValuePair("message", pushoverMsgBody));
        nameValuePairs.add(new BasicNameValuePair("priority", pushoverMsgPriority));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Pushover failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}