Java Code Examples for org.apache.http.impl.client.HttpClientBuilder

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cubeai   Source File: NexusArtifactClient.java    License: Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example 2
Source Project: chaos-lemur   Source File: StandardDirectorUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
        new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .useTLS()
        .build();

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create()
        .disableRedirectHandling()
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLSocketFactory(connectionFactory)
        .build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}
 
Example 3
Source Project: mumu   Source File: HttpClientUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * httpClient post 获取资源
 * @param url
 * @param params
 * @return
 */
public static String post(String url, Map<String, Object> params) {
	log.info(url);
	try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				Object object = params.get(key);
				nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	} catch (Exception e) {
		log.error(e);
	}
	return null;
}
 
Example 4
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
Example 5
Source Project: teammates   Source File: HttpRequest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes a HTTP GET request and returns the response string.
 * @param uri The URI containing the request URL and request parameters.
 * @return the HTTP response string after executing the GET request
 */
public static String executeGetRequest(URI uri) throws IOException {
    HttpUriRequest request = new HttpGet(uri);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT_IN_MS).build();

    HttpResponse httpResponse = HttpClientBuilder.create()
                                                 .setDefaultRequestConfig(requestConfig)
                                                 .build()
                                                 .execute(request);
    HttpEntity entity = httpResponse.getEntity();
    String response = EntityUtils.toString(entity, "UTF-8");

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), response);
    }
}
 
Example 6
@Test
public void assertCustomConfig() throws Exception {
	HttpClient httpClient = HttpClientBuilder.create().build();
	HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(httpClient);
	hrf.setConnectTimeout(1234);
	hrf.setConnectionRequestTimeout(4321);
	hrf.setReadTimeout(4567);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsClientHttpRequest request = (HttpComponentsClientHttpRequest)
			hrf.createRequest(uri, HttpMethod.GET);

	Object config = request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull("Request config should be set", config);
	assertTrue("Wrong request config type" + config.getClass().getName(),
			RequestConfig.class.isInstance(config));
	RequestConfig requestConfig = (RequestConfig) config;
	assertEquals("Wrong custom connection timeout", 1234, requestConfig.getConnectTimeout());
	assertEquals("Wrong custom connection request timeout", 4321, requestConfig.getConnectionRequestTimeout());
	assertEquals("Wrong custom socket timeout", 4567, requestConfig.getSocketTimeout());
}
 
Example 7
Source Project: keycloak   Source File: LogoutTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void postLogoutWithExpiredIdToken() throws Exception {
    oauth.doLogin("[email protected]", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    oauth.clientSessionState("client-session");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String idTokenString = tokenResponse.getIdToken();

    // Logout should succeed with expired ID token, see KEYCLOAK-3399
    setTimeOffset(60 * 60 * 24);

    String logoutUrl = oauth.getLogoutUrl()
      .idTokenHint(idTokenString)
      .postLogoutRedirectUri(oauth.APP_AUTH_ROOT)
      .build();

    try (CloseableHttpClient c = HttpClientBuilder.create().disableRedirectHandling().build();
      CloseableHttpResponse response = c.execute(new HttpGet(logoutUrl))) {
        assertThat(response, Matchers.statusCodeIsHC(Status.FOUND));
        assertThat(response.getFirstHeader(HttpHeaders.LOCATION).getValue(), is(oauth.APP_AUTH_ROOT));
    }
}
 
Example 8
public CloseableHttpResponse post(String url, ContentType contentType, String data, String username, String password) {
    logger.debug("{}: Sending POST request url={} contentType={} data={}", applianceId, url, contentType, data);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    withUsernameAndPassword(httpClientBuilder, username, password);
    CloseableHttpClient client = httpClientBuilder.setDefaultRequestConfig(getRequestConfig()).build();
    try {
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(data, contentType));
        CloseableHttpResponse response = client.execute(request);
        return logResponse(response);
    }
    catch(IOException e) {
        logger.error("{}: Error executing POST", applianceId, e);
        return null;
    }
}
 
Example 9
Source Project: pnc   Source File: AbstractImportTest.java    License: Apache License 2.0 6 votes vote down vote up
protected String download(String url) throws Exception {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    String content = null;
    InputStream stream = null;
    try {
        client = HttpClientBuilder.create().build();
        response = client.execute(new HttpGet(url));
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        stream = response.getEntity().getContent();
        content = IOUtils.toString(stream, "UTF-8");
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }

    return content;
}
 
Example 10
Source Project: vespa   Source File: FlagsClient.java    License: Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
    DelayedConnectionLevelRetryHandler retryHandler = DelayedConnectionLevelRetryHandler.Builder
            .withExponentialBackoff(Duration.ofSeconds(1), Duration.ofSeconds(20), 5)
            .build();
    return HttpClientBuilder.create()
            .setUserAgent("controller-flags-v1-client")
            .setSSLContext(identityProvider.getIdentitySslContext())
            .setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
            .setDefaultRequestConfig(RequestConfig.custom()
                                             .setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
                                             .build())
            .setMaxConnPerRoute(2)
            .setMaxConnTotal(100)
            .setRetryHandler(retryHandler)
            .build();
}
 
Example 11
Source Project: amex-api-java-client-core   Source File: ApiClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = ExecutorException.class)
public void executeGet() throws Exception {

    ApiClient devPortalExecutor = new ApiClient.DevPortalExecutorBuilder()
            .setEndpoint(EndPoint.PRODUCTION)
            .setSigningInformation("RS256", "kid", "")
            .setTokenRequesterId("token")
            .createDevPortalExecutor();

    setTestOverride(devPortalExecutor, true);
    Field field = devPortalExecutor.getClass().getDeclaredField("httpClient");
    field.setAccessible(true);
    field.set(devPortalExecutor, HttpClientBuilder.create().build());
    AuthProvider authProvider = Mockito.mock(HmacAuthProvider.class);
    assertNotNull(devPortalExecutor.execute(
            new StatusRequest.StatusRequestBuilder().createStatusRequest(), authProvider));
}
 
Example 12
private String performPayPalApiCall(final String endpoint, final String callParams) throws IOException {

        if (LOG.isDebugEnabled()) {
            LOG.debug("PayPal NPV call:\n{}", callParams.replace('&', '\n'));
        }

        final StringBuilder respBuilder = new StringBuilder();

        final HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setEntity(new StringEntity(callParams));

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

        final HttpResponse response = client.execute(httpPost);
        final BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));

        String _line;
        while (((_line = rd.readLine()) != null)) {
            respBuilder.append(_line);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("PayPal NPV response:\n{}", respBuilder.toString().replace('&', '\n'));
        }
        return respBuilder.toString();
    }
 
Example 13
Source Project: pacbot   Source File: CommonUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String doHttpPost(String uri, String token, String accessToken) throws Exception {

		HttpPost httpPost = new HttpPost(uri);
		httpPost.addHeader("content-type", "application/json");
		httpPost.addHeader("cache-control", "no-cache");
		if (!Strings.isNullOrEmpty(token)) {
			httpPost.addHeader("Authorization", token + " " + accessToken);
		}
		HttpClient httpClient = HttpClientBuilder.create().build();
		if (httpClient != null) {
			HttpResponse httpResponse;
			try {
				httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					return EntityUtils.toString(httpResponse.getEntity());
				} else {
					throw new Exception("unable to execute post request caused by"
							+ EntityUtils.toString(httpResponse.getEntity()));
				}
			} catch (Exception e) {
				logger.error("Error getting the data ", e);
				throw e;
			}
		}
		return "{}";
	}
 
Example 14
Source Project: riptide   Source File: HttpClientFactory.java    License: MIT License 6 votes vote down vote up
private static HttpClientBuilder configureCaching(final Caching caching,
        @Nullable final Object cacheStorage) {
    final Heuristic heuristic = caching.getHeuristic();

    final CacheConfig.Builder config = CacheConfig.custom()
            .setSharedCache(caching.getShared())
            .setMaxObjectSize(caching.getMaxObjectSize())
            .setMaxCacheEntries(caching.getMaxCacheEntries());

    if (heuristic.getEnabled()) {
        config.setHeuristicCachingEnabled(true);
        config.setHeuristicCoefficient(heuristic.getCoefficient());
        config.setHeuristicDefaultLifetime(heuristic.getDefaultLifeTime().to(TimeUnit.SECONDS));
    }

    @Hack("return cast tricks classloader in case of missing httpclient-cache")
    CachingHttpClientBuilder builder = CachingHttpClients.custom()
                                                         .setCacheConfig(config.build())
                                                         .setHttpCacheStorage((HttpCacheStorage) cacheStorage)
                                                         .setCacheDir(Optional.ofNullable(caching.getDirectory())
                                                                              .map(Path::toFile)
                                                                              .orElse(null));
    return HttpClientBuilder.class.cast(builder);
}
 
Example 15
Source Project: sonar-quality-gates-plugin   Source File: SonarHttpRequester.java    License: MIT License 6 votes vote down vote up
private void loginApi(GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance) {

        httpClientContext = HttpClientContext.create();
        httpClient = HttpClientBuilder.create().build();

        if (StringUtils.isNotEmpty(globalConfigDataForSonarInstance.getToken())) {
            token = globalConfigDataForSonarInstance.getToken();
        } else {
            HttpPost loginHttpPost = new HttpPost(globalConfigDataForSonarInstance.getSonarUrl() + getSonarApiLogin());

            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("login", globalConfigDataForSonarInstance.getUsername()));
            nvps.add(new BasicNameValuePair("password", globalConfigDataForSonarInstance.getPass()));
            nvps.add(new BasicNameValuePair("remember_me", "1"));
            loginHttpPost.setEntity(createEntity(nvps));
            loginHttpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            executePostRequest(httpClient, loginHttpPost);
        }

        logged = true;
    }
 
Example 16
Source Project: jshERP   Source File: HttpClient.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 采用Post方式发送请求,获取响应数据
 *
 * @param url        url地址
 * @param param  参数值键值对的字符串
 * @return
 */
public static String httpPost(String url, String param) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpPost post = new HttpPost(url);
        EntityBuilder builder = EntityBuilder.create();
        builder.setContentType(ContentType.APPLICATION_JSON);
        builder.setText(param);
        post.setEntity(builder.build());

        CloseableHttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        logger.info("状态:"+statusCode+"数据:"+data);
        return data;
    } catch(Exception e){
        throw new RuntimeException(e.getMessage());
    } finally {
        try{
            client.close();
        }catch(Exception ex){ }
    }
}
 
Example 17
Source Project: pacbot   Source File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example 18
Source Project: phabricator-jenkins-plugin   Source File: ConduitAPIClient.java    License: MIT License 6 votes vote down vote up
/**
 * Call the conduit API of Phabricator
 *
 * @param action Name of the API call
 * @param params The data to send to Harbormaster
 * @return The result as a JSONObject
 * @throws IOException If there was a problem reading the response
 * @throws ConduitAPIException If there was an error calling conduit
 */
public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest request = createRequest(action, params);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConduitAPIException(e.getMessage());
    }

    InputStream responseBody = response.getEntity().getContent();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ConduitAPIException(IOUtils.toString(responseBody, Charset.defaultCharset()), response.getStatusLine().getStatusCode());
    }

    JsonSlurper jsonParser = new JsonSlurper();
    return (JSONObject) jsonParser.parse(responseBody);
}
 
Example 19
Source Project: couchbase-jvm-core   Source File: ClusterDependentTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper (hacked together) method to grab a config from a bucket without having to initialize the
 * client first - this helps with pre-bootstrap decisions like credentials for RBAC.
 */
public static int[] minClusterVersion() throws Exception {
    int port = 8091;
    if (useMock) {
        port = mock().getHttpPort();
    }
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost(seedNode).setPort(port).setPath("/pools/default/buckets/" + bucket)
        .setParameter("bucket", bucket);
    HttpGet request = new HttpGet(builder.build());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(seedNode, port), new UsernamePasswordCredentials(adminUser, adminPassword));
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
    HttpResponse response = client.execute(request);
    int status = response.getStatusLine().getStatusCode();
    if (status < 200 || status > 300) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
    String rawConfig = EntityUtils.toString(response.getEntity());
    return minNodeVersionFromConfig(rawConfig);
}
 
Example 20
Source Project: vespa   Source File: ConfigServerApiImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(200); // Increase max total connections to 200, which should be enough

    // Have experienced hang in socket read, which may have been because of
    // system defaults, therefore set explicit timeouts.
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
            .disableAutomaticRetries()
            .setUserAgent("node-admin")
            .setConnectionManager(cm)
            .build();
}
 
Example 21
Source Project: Openfire   Source File: FaviconServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    // Create a pool of HTTP connections to use to get the favicons
    client = HttpClientBuilder.create()
        .setConnectionManager(new PoolingHttpClientConnectionManager())
        .setRedirectStrategy(new LaxRedirectStrategy())
        .build();
    // Load the default favicon to use when no favicon was found of a remote host
    try {
       defaultBytes = Files.readAllBytes(Paths.get(JiveGlobals.getHomeDirectory(), "plugins/admin/webapp/images/server_16x16.gif"));
    }
    catch (final IOException e) {
        LOGGER.warn("Unable to retrieve default favicon", e);
    }
    // Initialize caches.
    missesCache = CacheFactory.createCache("Favicon Misses");
    hitsCache = CacheFactory.createCache("Favicon Hits");
}
 
Example 22
Source Project: signalfx-java   Source File: AWSInstanceInfo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to get the value for the AWSUniqueId dimension used in SignalFx AWS integrations.
 *
 * @param timeoutInMs
 *            how long to wait in milliseconds for AWS to respond
 * @return null if the value was not obtained for any reason
 */
public static String get(int timeoutInMs) {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .build();
    HttpGet request = new HttpGet(URL);

    try {
        HttpResponse response = client.execute(request);
        JsonNode object = MAPPER.readTree(response.getEntity().getContent());

        return object.get(INSTANCE_ID).asText() + "_" + object.get(REGION).asText() + "_"
                + object.get(ACCOUNT_ID).asText();

    } catch (Exception e) {
        log.trace("Exception trying to execute {}, Exception: {} ", request, e);
    }

    return null;
}
 
Example 23
Source Project: FishingBot   Source File: RealmsAPI.java    License: GNU General Public License v3.0 6 votes vote down vote up
public RealmsAPI(AuthData authData) {
    BasicCookieStore cookies = new BasicCookieStore();

    BasicClientCookie sidCookie = new BasicClientCookie("sid", String.join(":", "token", authData.getAccessToken(), authData.getProfile()));
    BasicClientCookie userCookie = new BasicClientCookie("user", authData.getUsername());
    BasicClientCookie versionCookie = new BasicClientCookie("version", ProtocolConstants.getVersionString(FishingBot.getInstance().getServerProtocol()));

    sidCookie.setDomain(".pc.realms.minecraft.net");
    userCookie.setDomain(".pc.realms.minecraft.net");
    versionCookie.setDomain(".pc.realms.minecraft.net");

    sidCookie.setPath("/");
    userCookie.setPath("/");
    versionCookie.setPath("/");

    cookies.addCookie(sidCookie);
    cookies.addCookie(userCookie);
    cookies.addCookie(versionCookie);

    client = HttpClientBuilder.create()
            .setDefaultCookieStore(cookies)
            .build();
}
 
Example 24
/** Gets the number of bytes the server has received. */
private long getReceivedByteCount(String uploadUrl) throws IOException {
  HttpPost httpPost = createAuthenticatedPostRequest(uploadUrl);
  httpPost.addHeader(UPLOAD_PROTOCOL_HEADER, UPLOAD_PROTOCOL_VALUE);
  httpPost.addHeader(UPLOAD_COMMAND_HEADER, UploadCommands.QUERY);

  CloseableHttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();
  HttpResponse response = httpClient.execute(httpPost);

  if (response.getFirstHeader(UPLOAD_GRANULARITY_HEADER) != null) {
    updateOptimalChunkSize(
        Integer.parseInt(response.getFirstHeader(UPLOAD_GRANULARITY_HEADER).getValue()));
  }

  switch (response.getFirstHeader(UPLOAD_STATUS_HEADER).getValue()) {
    case UploadStatuses.ACTIVE:
      return Long.parseLong(response.getFirstHeader(RECEIVED_BYTE_COUNT_HEADER).getValue());
    case UploadStatuses.FINAL:
      return request.getFileSize();
    default:
      throw new IllegalStateException(ExceptionStrings.INVALID_UPLOAD_STATUS);
  }
}
 
Example 25
Source Project: hadoop-ozone   Source File: LogSubcommand.java    License: Apache License 2.0 5 votes vote down vote up
private void streamLog(OzoneConfiguration conf, Component logComponent,
    List<LoggerSource> loggers, Predicate<String> filter) {
  HttpClient client = HttpClientBuilder.create().build();

  HttpGet get = new HttpGet(getHost(conf, logComponent) + "/logstream");
  try {
    HttpResponse execute = client.execute(get);
    try (BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(execute.getEntity().getContent(),
            StandardCharsets.UTF_8))) {
      bufferedReader.lines()
          .filter(line -> {
            for (LoggerSource logger : loggers) {
              if (line.contains(logger.getLoggerName()) && filter
                  .test(line)) {
                return true;
              }
            }
            return false;
          })
          .map(this::processLogLine)
          .map(l -> "[" + logComponent.prefix() + "] " + l)
          .forEach(System.out::println);
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 26
Source Project: tutorials   Source File: AppLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenBasicRoute_whenPut_thenCorrectOutput() throws Exception {
    final HttpUriRequest request = new HttpPut("http://localhost:9000/basic-route-example");
    try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
        .build()
        .execute(request);) {
        assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
    }
}
 
Example 27
Source Project: ephemerals   Source File: WireMockEphemeralTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test() throws IOException {
    URL url = wireMockResource.get();
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url.toString()+"/get/this");
    HttpResponse response = client.execute(request);
    Assert.assertEquals(200,response.getStatusLine().getStatusCode());
}
 
Example 28
Source Project: dependency-track   Source File: ManagedHttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void objectTest() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setConnectionManager(connectionManager);
    CloseableHttpClient client = clientBuilder.build();
    ManagedHttpClient managedHttpClient = new ManagedHttpClient(client, connectionManager);
    Assert.assertSame(client, managedHttpClient.getHttpClient());
    Assert.assertSame(connectionManager, managedHttpClient.getConnectionManager());
}
 
Example 29
Source Project: mycore   Source File: MCRHttpsClient.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static CloseableHttpClient getHttpsClient() {
    return HttpClientBuilder
        .create()
        .setConnectionTimeToLive(1, TimeUnit.MINUTES)
        .setSSLContext(SSLContexts.createSystemDefault())
        .build();
}
 
Example 30
Source Project: SolRDF   Source File: IntegrationTestSupertypeLayer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initilisation procedure for this test case.
 * 
 * @throws UnableToBuildSolRDFClientException in case the client cannot be built.
 * @throws Exception in case of Solr startup failure.
 */
@BeforeClass
public static void initITTest() {
	System.setProperty("tests.asserts", "false");	
	System.setProperty("jetty.port", "8080");
	System.setProperty("solr.core.name", "store");
	System.setProperty("solr.data.dir", initCoreDataDir.getAbsolutePath());
		
	try {
		SOLR = createJetty(
				"target/solrdf-integration-tests-1.1-dev/solrdf",
				JettyConfig.builder()
					.setPort(8080)
					.setContext("/solr")
					.stopAtShutdown(true)
					.build());		
		
		final HttpClient httpClient = HttpClientBuilder.create()
				.setRoutePlanner(
						new DefaultRoutePlanner(
								new SchemePortResolver() {
									@Override
									public int resolve(final HttpHost host) throws UnsupportedSchemeException {
										return SOLR.getLocalPort();
									}
								})).build();
		
		
		SOLRDF_CLIENT = SolRDF.newBuilder()
	              .withEndpoint("http://127.0.0.1:8080/solr/store")
	              .withGraphStoreProtocolEndpointPath("/rdf-graph-store")
	              .withHttpClient(httpClient)
	              .withSPARQLEndpointPath("/sparql")
	              .build();
		
		PLAIN_SOLR_CLIENT = new HttpSolrClient(SOLR_URI);
	} catch (final Exception exception) {
		throw new RuntimeException(exception);
	}
}