Java Code Examples for org.apache.http.client.protocol.HttpClientContext

The following examples show how to use org.apache.http.client.protocol.HttpClientContext. 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 check out the related API usage on the sidebar.
Example 1
Source Project: cosmic   Source File: RESTServiceConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteDeleteObject() throws Exception {
    final HttpEntity entity = mock(HttpEntity.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(entity);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    connector.executeDeleteObject("/somepath");

    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("DELETE"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 2
Source Project: cloudstack   Source File: RESTServiceConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteCreateObject() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeCreateObject(newObject, "/somepath");

    assertThat(object, notNullValue());
    assertThat(object, equalTo(newObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 3
Source Project: flow   Source File: DefaultFileDownloader.java    License: Apache License 2.0 6 votes vote down vote up
private CloseableHttpResponse execute(URI requestUri) throws IOException {
    CloseableHttpResponse response;
    ProxyConfig.Proxy proxy = proxyConfig
            .getProxyForUrl(requestUri.toString());
    if (proxy != null) {
        getLogger().info("Downloading via proxy {}", proxy.toString());
        return executeViaProxy(proxy, requestUri);
    } else {
        getLogger().info("No proxy was configured, downloading directly");
        if (StringUtils.isNotEmpty(userName) && StringUtils
                .isNotEmpty(password)) {
            getLogger().info("Using credentials ({})", userName);
            // Auth target host
            URL aURL = requestUri.toURL();
            HttpClientContext localContext = makeLocalContext(aURL);
            CredentialsProvider credentialsProvider = makeCredentialsProvider(
                    aURL.getHost(), aURL.getPort(), userName, password);
            response = buildHttpClient(credentialsProvider)
                    .execute(new HttpGet(requestUri), localContext);
        } else {
            response = buildHttpClient(null)
                    .execute(new HttpGet(requestUri));
        }
    }
    return response;
}
 
Example 4
Source Project: vividus   Source File: JsonResponseValidationStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testFailedAssertionRecordingIfResponseDidNtContainJson() throws IOException, NoSuchFieldException,
        IllegalAccessException
{
    HttpRequestExecutor httpRequestExecutor = new HttpRequestExecutor(httpClient, httpTestContext, softAssert);
    Field executorField = jsonResponseValidationSteps.getClass().getDeclaredField(HTTP_REQUEST_EXECUTOR_FIELD);
    executorField.setAccessible(true);
    executorField.set(jsonResponseValidationSteps, httpRequestExecutor);
    HttpResponse response = mock(HttpResponse.class);
    when(httpClient.execute(argThat(base -> base instanceof HttpRequestBase),
            argThat(context -> context instanceof HttpClientContext))).thenReturn(response);
    when(httpTestContext.getResponse()).thenReturn(response);
    when(response.getResponseBodyAsString()).thenReturn(HTML);
    jsonResponseValidationSteps.waitForJsonFieldAppearance(STRING_PATH, URL, Duration.ofSeconds(1),
            DURATION_DIVIDER);
    verify(softAssert).recordFailedAssertion("HTTP response body is not present");
}
 
Example 5
Source Project: vividus   Source File: JsonResponseValidationStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testWaitForJsonFieldAppearsHandledException() throws IOException, IllegalAccessException, NoSuchFieldException
{
    when(httpClient.execute(argThat(base -> base instanceof HttpRequestBase
            && base.getMethod().equals(GET)
            && base.getURI().equals(URI.create(URL))),
            argThat(context -> context instanceof HttpClientContext)))
        .thenThrow(new ConnectionClosedException());
    HttpRequestExecutor httpRequestExecutor = new HttpRequestExecutor(httpClient, httpTestContext, softAssert);
    Field executorField = jsonResponseValidationSteps.getClass().getDeclaredField(HTTP_REQUEST_EXECUTOR_FIELD);
    executorField.setAccessible(true);
    executorField.set(jsonResponseValidationSteps, httpRequestExecutor);
    jsonResponseValidationSteps.waitForJsonFieldAppearance(STRING_PATH, URL, Duration.ofSeconds(1),
            DURATION_DIVIDER);
    verify(softAssert).recordFailedAssertion(
            (Exception) argThat(arg -> arg instanceof ConnectionClosedException
                    && "Connection is closed".equals(((Exception) arg).getMessage())));
}
 
Example 6
Source Project: tutorials   Source File: HttpClientConnectionManagementLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
// @Ignore
// 2.2 IN ARTICLE
public final void whenOpeningLowLevelConnectionWithSocketTimeout_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException {
    basicConnManager = new BasicHttpClientConnectionManager();
    context = HttpClientContext.create();
    final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null);
    conn = connRequest.get(1000, TimeUnit.SECONDS);
    if (!conn.isOpen()) {
        basicConnManager.connect(conn, route, 1000, context);
    }
    conn.setSocketTimeout(30000);

    assertTrue(conn.getSocketTimeout() == 30000);
    assertTrue(conn.isOpen());
}
 
Example 7
Source Project: seezoon-framework-all   Source File: UnionService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode?callback=checkSuccess&commonBean.phoneNo=13249073372&phoneVerifyCode=932453&timeStamp=0.3671002044464746
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void checkChargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("phoneVerifyCode", Lists.newArrayList("904114"));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 8
/**
 * Init method for this publisher.
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer,
		final HttpClient httpClient) {
	this.velocityRenderer = velocityRenderer;
	this.httpClient = httpClient;
	if (getHttpAuthentication() != null) {
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
				AuthScope.ANY_PORT), new UsernamePasswordCredentials(
				getHttpAuthentication().getUsername(),
				getHttpAuthentication().getPassword()));
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
	}
}
 
Example 9
Source Project: hop   Source File: HopServer.java    License: Apache License 2.0 6 votes vote down vote up
private void addProxy( HttpClientContext context ) {
  String proxyHost = environmentSubstitute( this.proxyHostname );
  String proxyPort = environmentSubstitute( this.proxyPort );
  String nonProxyHosts = environmentSubstitute( this.nonProxyHosts );

  String hostName = environmentSubstitute( this.hostname );
  if ( Utils.isEmpty( proxyHost ) || Utils.isEmpty( proxyPort ) ) {
    return;
  }
  // skip applying proxy if non-proxy host matches
  if ( !Utils.isEmpty( nonProxyHosts ) && hostName.matches( nonProxyHosts ) ) {
    return;
  }
  HttpHost httpHost = new HttpHost( proxyHost, Integer.valueOf( proxyPort ) );

  RequestConfig requestConfig = RequestConfig.custom()
    .setProxy( httpHost )
    .build();

  context.setRequestConfig( requestConfig );
}
 
Example 10
Source Project: timer   Source File: Session.java    License: Apache License 2.0 6 votes vote down vote up
public Session process() throws IOException {

        HttpRequest request = this.getRequest();
        Objects.requireNonNull(this.request);
        HttpClient httpClient = this.getHttpClient();
        HttpClientContext context = this.getContext();
        if (request instanceof HttpGet) {
            this.getContext().setCookieStore(cookies);
            HttpGet get = (HttpGet) request;
            this.httpResponse = httpClient.execute(get, context);
            this.httpCode = httpResponse.getStatusLine().getStatusCode();
            this.repUtils = new ResponseUtils(this.httpResponse);
        } else if (this.request instanceof HttpPost) {
            context.setCookieStore(cookies);
            HttpPost post = (HttpPost) request;
            post.setEntity(this.getProviderService().builder());
            this.httpResponse = this.httpClient.execute(post, this.context);
            this.httpCode = httpResponse.getStatusLine().getStatusCode();
            this.repUtils = new ResponseUtils(this.httpResponse);
        }
        return this;
    }
 
Example 11
Source Project: pentaho-kettle   Source File: HttpClientUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      new UsernamePasswordCredentials( user, 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( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example 12
Source Project: hop   Source File: WebService.java    License: Apache License 2.0 6 votes vote down vote up
private void initWsdlEnv() throws HopException {
  if ( meta.equals( cachedMeta ) ) {
    return;
  }
  cachedMeta = meta;

  try {
    cachedWsdl = new Wsdl( new java.net.URI( data.realUrl ), null, null, environmentSubstitute( meta.getHttpLogin() ),
      Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) ) );
  } catch ( Exception e ) {
    throw new HopTransformException( BaseMessages.getString( PKG, "WebServices.ERROR0013.ExceptionLoadingWSDL" ), e );
  }

  cachedURLService = cachedWsdl.getServiceEndpoint();
  cachedHostConfiguration = HttpClientContext.create();
  cachedHttpClient = getHttpClient( cachedHostConfiguration );
  // Generate the XML to send over, determine the correct name for the request...
  //
  cachedOperation = cachedWsdl.getOperation( meta.getOperationName() );
  if ( cachedOperation == null ) {
    throw new HopException( BaseMessages.getString( PKG, "WebServices.Exception.OperarationNotSupported", meta
      .getOperationName(), meta.getUrl() ) );
  }

}
 
Example 13
Source Project: arcusplatform   Source File: HttpService.java    License: Apache License 2.0 6 votes vote down vote up
public static CloseableHttpResponse execute(HttpUriRequest req, @Nullable Credentials auth) throws IOException {
   if (auth != null) {
      URI uri = req.getURI();
      AuthScope scope = new AuthScope(uri.getHost(), uri.getPort());

      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(scope, auth);

      HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(provider);

      return get().execute(req, context);
   }

   return execute(req);
}
 
Example 14
Source Project: openmeetings   Source File: AppointmentManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Function for create/updating multiple appointment on the server.
 * Performs modification alongside of creation new events on the server.
 *
 * @param client - {@link HttpClient} to discover calendar
 * @param context http context
 * @param appointment Appointment to create/update.
 * @return <code>true</code> in case item was updated
 */
public boolean updateItem(HttpClient client, HttpClientContext context, Appointment appointment) {
	cleanupIdleConnections();

	OmCalendar calendar = appointment.getCalendar();
	SyncType type = calendar.getSyncType();
	if (type != SyncType.NONE && type != SyncType.GOOGLE_CALENDAR) {
		CalendarHandler calendarHandler;
		String path = ensureTrailingSlash(calendar.getHref());

		switch (type) {
			case WEBDAV_SYNC:
			case CTAG:
			case ETAG:
				calendarHandler = new EtagsHandler(path, calendar, client, context, appointmentDao, utils);
				break;
			default:
				return false;
		}
		return calendarHandler.updateItem(appointment);
	}
	return false;
}
 
Example 15
@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 16
Source Project: openmeetings   Source File: CalendarDialog.java    License: Apache License 2.0 6 votes vote down vote up
private boolean setFormModelObject() {
	if (cals != null && !cals.isEmpty() && calIndex < cals.size()) {
		OmCalendar calendar = cals.get(calIndex++);
		HttpClient client = calendarPanel.getHttpClient();
		HttpClientContext context = calendarPanel.getHttpClientContext();
		if (!apptManager.testConnection(client, context, calendar)) {
			form.setModelObject(calendar);
			form.url.setModelObject(calendar.getHref());
			return true;
		} else {
			apptManager.syncItem(client, context, calendar);
			return setFormModelObject();
		}
	}

	cals = null;
	return false;
}
 
Example 17
Source Project: nexus-public   Source File: MavenITSupport.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected Maven2Client createMaven2Client(final URL repositoryUrl, final String username, final String password)
    throws Exception
{
  AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setExpectContinueEnabled(true);
  HttpClientContext httpClientContext = HttpClientContext.create();
  httpClientContext.setRequestConfig(requestConfigBuilder.build());
  return new Maven2Client(
      HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
      httpClientContext,
      repositoryUrl.toURI()
  );
}
 
Example 18
private HttpResponse makeHTTPConnection() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

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

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);

    BasicHttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(HttpClientContext.COOKIE_STORE, getWebDriverCookies(driver.manage().getCookies()));
    requestMethod.setHeader("User-Agent", getWebDriverUserAgent());

    if (null != urlParameters && (
            httpRequestMethod.equals(RequestType.PATCH) ||
                    httpRequestMethod.equals(RequestType.POST) ||
                    httpRequestMethod.equals(RequestType.PUT))
            ) {
        ((HttpEntityEnclosingRequestBase) requestMethod).setEntity(new UrlEncodedFormEntity(urlParameters));
    }

    return client.execute(requestMethod, localContext);
}
 
Example 19
Source Project: cosmic   Source File: RESTServiceConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteRetrieveObjectWithParameters() throws Exception {
    final TestPojo existingObject = new TestPojo();
    existingObject.setField("existingValue");
    final String newObjectJson = gson.toJson(existingObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeRetrieveObject(TestPojo.class, "/somepath", DEFAULT_TEST_PARAMETERS);

    assertThat(object, notNullValue());
    assertThat(object, equalTo(existingObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 20
@Test
public void defaultSettingsOfHttpAsyncClientLostOnExecutorCustomization() throws Exception {
	CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
			.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(1234).build())
			.build();
	HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(client);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);

	assertNull("No custom config should be set with a custom HttpClient",
			request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG));

	factory.setConnectionRequestTimeout(4567);
	HttpComponentsAsyncClientHttpRequest request2 = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);
	Object requestConfigAttribute = request2.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull(requestConfigAttribute);
	RequestConfig requestConfig = (RequestConfig) requestConfigAttribute;

	assertEquals(4567, requestConfig.getConnectionRequestTimeout());
	// No way to access the request config of the HTTP client so no way to "merge" our customizations
	assertEquals(-1, requestConfig.getConnectTimeout());
}
 
Example 21
Source Project: intellij-demandware   Source File: DWServerConnection.java    License: MIT License 6 votes vote down vote up
public DWServerConnection(DWSettingsProvider settingsProvider) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    this.settingsProvider = settingsProvider;

    // SSLContextFactory to allow all hosts. Without this an SSLException is thrown with self signed certs
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(200);
    connectionManager.setDefaultMaxPerRoute(20);

    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();

    context = new HttpClientContext();
    context.setCredentialsProvider(getCredientials());
}
 
Example 22
Source Project: geowave   Source File: GeoServerIT.java    License: Apache License 2.0 5 votes vote down vote up
public String lockPoint() throws Exception {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
    command.setEntity(
        EntityBuilder.create().setText(lock).setContentType(ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);

    final boolean result = r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
    if (result) {
      final String content = getContent(r);
      final String pattern = "lockId=\"([^\"]+)\"";

      // Create a Pattern object
      final Pattern compiledPattern = Pattern.compile(pattern);
      final Matcher matcher = compiledPattern.matcher(content);
      if (matcher.find()) {
        return matcher.group(1);
      }
      return content;
    }
    return null;
  } finally {
    httpclient.close();
  }
}
 
Example 23
@SuppressWarnings("unchecked")
@Test
public void retry_consumers_are_invoked() {
    RetryConsumer<IOException> retryConsumer = (RetryConsumer<IOException>) mock(RetryConsumer.class);
    RetryFailedConsumer<IOException> retryFailedConsumer = (RetryFailedConsumer<IOException>) mock(RetryFailedConsumer.class);

    Duration delay = Duration.ofSeconds(10);
    int maxRetries = 5;

    DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder
            .withFixedDelay(delay, maxRetries)
            .withSleeper(mock(Sleeper.class))
            .onRetry(retryConsumer)
            .onRetryFailed(retryFailedConsumer)
            .build();

    IOException exception = new IOException();
    HttpClientContext ctx = new HttpClientContext();
    int lastExecutionCount = maxRetries + 1;
    for (int i = 1; i <= lastExecutionCount; i++) {
        handler.retryRequest(exception, i, ctx);
    }

    verify(retryFailedConsumer).onRetryFailed(exception, lastExecutionCount, ctx);
    for (int i = 1; i < lastExecutionCount; i++) {
        verify(retryConsumer).onRetry(exception, delay, i, ctx);
    }
}
 
Example 24
Source Project: qpid-broker-j   Source File: JavaBrokerAdmin.java    License: Apache License 2.0 5 votes vote down vote up
private HttpClientContext getHttpClientContext(final HttpHost management)
{
    final BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(management, new BasicScheme());
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
 
Example 25
Source Project: vividus   Source File: PageStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testIAmOnTheMainApplicationPageIOExeption() throws IOException
{
    String exceptionMessage = "message";
    pageSteps.setKeepUserInfoForProtocolRedirects(true);
    URI mainPage = URI.create("http://xxx");
    when(webApplicationConfiguration.getMainApplicationPageUrl()).thenReturn(mainPage);
    when(webApplicationConfiguration.getAuthenticationMode()).thenReturn(AuthenticationMode.URL);
    IOException exception = new IOException(exceptionMessage);
    doThrow(exception).when(httpClient).doHttpHead(eq(mainPage), any(HttpClientContext.class));
    pageSteps.iAmOnTheMainApplicationPage();
    assertThat(logger.getLoggingEvents(),
            is(List.of(error("HTTP request for '{}' failed with the exception: {}", mainPage, exceptionMessage))));
}
 
Example 26
Source Project: keycloak   Source File: OAuthRedirectUriTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWithCustomScheme() throws IOException {
    oauth.clientId("custom-scheme");

    oauth.redirectUri("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login");
    oauth.openLoginForm();

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    String loginUrl = driver.getCurrentUrl();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

    try {
        String loginPage = SimpleHttp.doGet(loginUrl, client).asString();

        String formAction = loginPage.split("action=\"")[1].split("\"")[0].replaceAll("&amp;", "&");
        SimpleHttp.Response response = SimpleHttp.doPost(formAction, client).param("username", "[email protected]").param("password", "password").asResponse();

        response.getStatus();
        assertThat(response.getFirstHeader("Location"), Matchers.startsWith("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login"));
    } finally {
        client.close();
    }
}
 
Example 27
Source Project: openmeetings   Source File: CalendarDialog.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs syncing of the Calendar.
 *
 * @param c       Calendar to sync
 * @param handler Handler used to update the CalendarPanel
 */
private void syncCalendar(OmCalendar c, IPartialPageRequestHandler handler) {
	HttpClient client = calendarPanel.getHttpClient();
	HttpClientContext context = calendarPanel.getHttpClientContext();
	if (form.username.getModelObject() != null) {
		apptManager.provideCredentials(context, c, new UsernamePasswordCredentials(form.username.getModelObject(),
				form.pass.getModelObject()));
	}
	apptManager.syncItem(client, context, c);
	calendarPanel.refresh(handler);
	log.trace("Calendar {} Successfully synced.", c.getTitle());
}
 
Example 28
Source Project: metron   Source File: RestFunctionsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * The REST_GET function should handle IOExceptions and return null.
 * @throws IOException
 */
@Test
public void restGetShouldHandleIOException() throws IOException {
  RestFunctions.RestGet restGet = new RestFunctions.RestGet();
  CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
  ScheduledExecutorService executorService = mock(ScheduledExecutorService.class);

  RestFunctions.setCloseableHttpClient(httpClient);
  RestFunctions.setScheduledExecutorService(executorService);

  when(httpClient.execute(any(HttpRequestBase.class), any(HttpClientContext.class))).thenThrow(new IOException("io exception"));

  Object result = restGet.apply(Collections.singletonList("http://www.host.com:8080/some/uri"), context);
  assertNull(result);
}
 
Example 29
Source Project: lavaplayer   Source File: SettableHttpRequestFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onRequestResponse(HttpClientContext context, HttpUriRequest request, HttpResponse response) {
  HttpContextFilter current = filter;

  if (current != null) {
    return current.onRequestResponse(context, request, response);
  } else {
    return false;
  }
}
 
Example 30
Source Project: lucene-solr   Source File: BasicAuthPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean interceptInternodeRequest(HttpRequest httpRequest, HttpContext httpContext) {
  if (forwardCredentials) {
    if (httpContext instanceof HttpClientContext) {
      HttpClientContext httpClientContext = (HttpClientContext) httpContext;
      if (httpClientContext.getUserToken() instanceof BasicAuthUserPrincipal) {
        BasicAuthUserPrincipal principal = (BasicAuthUserPrincipal) httpClientContext.getUserToken();
        String userPassBase64 = Base64.encodeBase64String((principal.getName() + ":" + principal.getPassword()).getBytes(StandardCharsets.UTF_8));
        httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + userPassBase64);
        return true;
      }
    }
  }
  return false;
}