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.esupportail.filex.web.WebController.java

@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(50 * 1000)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
            .getRequestFactory();//from   www.j a va  2s  .c  o m
    factory.setHttpClient(httpClient);
}

From source file:com.norconex.jefmon.instances.InstancesManager.java

public static List<InstanceSummary> loadInstances() {

    List<InstanceSummary> freshInstances = new ArrayList<InstanceSummary>();
    freshInstances.add(createThisJefMonInstance());

    JEFMonConfig cfg = JEFMonApplication.get().getConfig();
    String[] remoteUrls = cfg.getRemoteInstanceUrls();
    if (remoteUrls == null) {
        return freshInstances;
    }/*from  w  w  w.jav  a 2 s  . c  o m*/

    HttpClient httpclient = HttpClientBuilder.create().build();

    for (String url : remoteUrls) {
        InstanceSummary instance = fetchJEFMonInstance(httpclient, url);
        if (instance != null) {
            freshInstances.add(instance);
        }
    }

    return freshInstances;
}

From source file:org.springframework.boot.cli.command.init.InitializrService.java

protected CloseableHttpClient getHttp() {
    if (this.http == null) {
        this.http = HttpClientBuilder.create().useSystemProperties().build();
    }//from   w  ww  .  j  a v  a 2  s  . c  o  m
    return this.http;
}

From source file:org.jboss.pnc.mavenrepositorymanager.UploadOneThenDownloadAndVerifyArtifactHasOriginUrlTest.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  .ja  v a  2  s.  co  m

    String baseUrl = rc.getConnectionInfo().getDeployUrl();
    String path = "org/commonjava/indy/indy-core/0.17.0/indy-core-0.17.0.pom";
    String content = "This is a test";

    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
    final String url = UrlUtils.buildUrl(baseUrl, path);

    assertThat("Failed to upload: " + url, ArtifactUploadUtils.put(client, url, content), equalTo(true));

    // download the two files via the repo session's dependency URL, which will proxy the test http server
    // using the expectations above
    assertThat(download(UrlUtils.buildUrl(baseUrl, path)), equalTo(content));

    ProjectVersionRef pvr = new SimpleProjectVersionRef("org.commonjava.indy", "indy-core", "0.17.0");
    String artifactRef = new SimpleArtifactRef(pvr, "pom", null).toString();

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

    // check that both files are present in extracted result
    List<Artifact> builtArtifacts = repositoryManagerResult.getBuiltArtifacts();
    log.info("Built artifacts: " + builtArtifacts.toString());

    assertThat(builtArtifacts, notNullValue());
    assertThat(builtArtifacts.size(), equalTo(1));

    Artifact builtArtifact = builtArtifacts.get(0);
    assertThat(builtArtifact + " doesn't match pom ref: " + artifactRef,
            artifactRef.equals(builtArtifact.getIdentifier()), equalTo(true));

    client.close();
}

From source file:cpcc.ros.sim.osm.TileCache.java

/**
 * @param url the URL of the desired file.
 * @param file the path where to store the retrieved data.
 * @throws IOException thrown in case of errors.
 *//*from  w  ww.j av a2  s.c  o m*/
public static void downloadFile(String url, File file) throws IOException {
    // TODO extract in a service.
    HttpResponse response = null;
    try {
        response = HttpClientBuilder.create().setUserAgent("TileCache/1.0").build().execute(new HttpGet(url));
    } catch (IOException e) {
        LOG.error("Can not load URL '" + url.toString() + "'", e);
        throw e;
    }

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        String msg = String.format("Can not load URL '%s' code=%d (%s)", url.toString(),
                response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        LOG.error(msg);
        throw new IOException(msg);
    }

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try (FileOutputStream outStream = new FileOutputStream(file)) {
            IOUtils.copy(entity.getContent(), outStream);
        }
    }
}

From source file:it.smartcommunitylab.aac.openid.service.JWKSetCacheService.java

public JWKSetCacheService() {
    this.validators = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch
            .maximumSize(100)//from  w  w  w .  j a va2  s .com
            .build(new JWKSetVerifierFetcher(HttpClientBuilder.create().useSystemProperties().build()));
    this.encrypters = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch
            .maximumSize(100)
            .build(new JWKSetEncryptorFetcher(HttpClientBuilder.create().useSystemProperties().build()));
}

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

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String hubotUrl = StringUtils.trimToNull(seyrenConfig.getHubotUrl());

    if (hubotUrl == null) {
        LOGGER.warn("Hubot URL needs to be set before sending notifications to Hubot");
        return;/*from  ww  w . j  a va2 s.com*/
    }

    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("rooms", subscription.getTarget().split(","));

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

    HttpPost post = new HttpPost(hubotUrl + "/seyren/alert");
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Hubot at " + hubotUrl + " failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.freaknet.gtrends.client.GoogleTrendsClientFactory.java

private static GoogleTrendsClient _parse(CmdLineParser cmdLine) throws GoogleTrendsClientRunException {
    setLogLevel(cmdLine);/*  w  ww.  j ava  2s.c  om*/
    try {
        // TODO - Move outside
        // Prints all available regions and exists
        if (cmdLine.getPrintRegionsOpt()) {
            RegionParser.getInstance().printAll();
            System.exit(0);
        }

        // HTTP Client setup
        int timeout = 5; // seconds
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
                .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
        _httpClient = HttpClientBuilder.create().setDefaultCookieStore(_cookieStore)
                .setDefaultRequestConfig(config)
                //.setRedirectStrategy(new LaxRedirectStrategy())
                .build();

        BasicClientCookie cookie = new BasicClientCookie("I4SUserLocale", "it");
        cookie.setVersion(0);
        cookie.setDomain("www.google.com");
        cookie.setPath("/trends");
        cookie.setSecure(false);
        _cookieStore.addCookie(cookie);

        cookie = new BasicClientCookie("PREF", "");
        cookie.setVersion(0);
        cookie.setDomain("www.google.com");
        cookie.setPath("/trends");
        cookie.setSecure(false);
        _cookieStore.addCookie(cookie);

        // TODO - fix proxy
        //      if (cmdLine.getProxyHostname() != null) {
        //        HttpHost proxyHost = new HttpHost(cmdLine.getProxyHostname(), cmdLine.getProxyPort(), cmdLine.getProxyProtocol());
        //        Credentials credentials = cmdLine.getProxyCredentials();
        //        if (credentials != null) {
        //          _httpClient.get
        //          _httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        //        }
        //        _httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        //      }
        // Setup Google Authenticator
        _authenticator = new GoogleAuthenticator(cmdLine.getUsername(), cmdLine.getPassword(), _httpClient);

    } catch (FileNotFoundException ex) {
        throw new GoogleTrendsClientRunException(ex);
    }

    return new GoogleTrendsClient(_authenticator, _httpClient);
}

From source file:application.Crawler.java

/**
 * call was from url /*  ww w  .j  a v a  2  s.  c o  m*/
 * @return json String
 * @throws CrawlerException 
 */
private String callWs() throws CrawlerException {

    String jsonResult = null;

    try {

        HttpGet getRequest = new HttpGet(URL);
        getRequest.addHeader("accept", "application/json");
        HttpClientBuilder create = HttpClientBuilder.create();
        CloseableHttpClient build = create.build();
        CloseableHttpResponse response = build.execute(getRequest);
        InputStream content = response.getEntity().getContent();
        jsonResult = IOUtils.toString(content);

    } catch (IOException ex) {
        LOG.error(ex.getMessage());
        throw new CrawlerException("no answer from server");

    }
    return jsonResult;
}

From source file:sample.jdbc.StagemonitorIntegrationTest.java

@Before
public void setUp() throws Exception {
    httpClient = HttpClientBuilder.create()
            .setDefaultHeaders(Arrays.asList(new BasicHeader("Accept", "text/html"))).build();
    this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}