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

The following examples show how to use org.apache.http.client.protocol.HttpClientContext. 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 File: DWServerConnection.java    From intellij-demandware with 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 #2
Source File: RESTServiceConnectorTest.java    From cloudstack with 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 File: RESTServiceConnectorTest.java    From cosmic with 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 #4
Source File: DefaultFileDownloader.java    From flow with 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 #5
Source File: JsonResponseValidationStepsTests.java    From vividus with 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 #6
Source File: JsonResponseValidationStepsTests.java    From vividus with 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 #7
Source File: HttpClientConnectionManagementLiveTest.java    From tutorials with 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 #8
Source File: UnionService.java    From seezoon-framework-all with 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 #9
Source File: HttpPublisher.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #10
Source File: HopServer.java    From hop with 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 #11
Source File: Session.java    From timer with 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 #12
Source File: HttpService.java    From arcusplatform with 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 #13
Source File: WebService.java    From hop with 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 #14
Source File: HttpComponentsAsyncClientHttpRequestFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: RESTServiceConnectorTest.java    From cosmic with 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 #16
Source File: FileDownloader.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
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 #17
Source File: MavenITSupport.java    From nexus-public with 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
Source File: CalendarDialog.java    From openmeetings with 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 #19
Source File: HttpComponentsClientHttpRequestFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #20
Source File: AppointmentManager.java    From openmeetings with 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 #21
Source File: HttpClientUtil.java    From pentaho-kettle with 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 #22
Source File: PageStepsTests.java    From vividus with 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 #23
Source File: HttpComponentsAsyncClientHttpRequestFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void customHttpAsyncClientUsesItsDefault() throws Exception {
	HttpComponentsAsyncClientHttpRequestFactory factory =
			new HttpComponentsAsyncClientHttpRequestFactory();

	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 HttpAsyncClient",
			request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG));
}
 
Example #24
Source File: HttpComponentsAsyncClientHttpRequestFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
	HttpAsyncClient client = startAsyncClient();

	HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
	postProcessHttpRequest(httpRequest);
	HttpContext context = createHttpContext(httpMethod, uri);
	if (context == null) {
		context = HttpClientContext.create();
	}

	// Request configuration not set in the context
	if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
		// Use request configuration given by the user, when available
		RequestConfig config = null;
		if (httpRequest instanceof Configurable) {
			config = ((Configurable) httpRequest).getConfig();
		}
		if (config == null) {
			config = createRequestConfig(client);
		}
		if (config != null) {
			context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
		}
	}

	return new HttpComponentsAsyncClientHttpRequest(client, httpRequest, context);
}
 
Example #25
Source File: SyntheticMonitorService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private HttpClientContext getHttpClientContext() throws Exception {
    HttpProxyConfig httpProxyConfig = configRepository.getHttpProxyConfig();
    if (httpProxyConfig.host().isEmpty() || httpProxyConfig.username().isEmpty()) {
        return HttpClientContext.create();
    }

    // perform preemptive proxy authentication

    int proxyPort = MoreObjects.firstNonNull(httpProxyConfig.port(), 80);
    HttpHost proxyHost = new HttpHost(httpProxyConfig.host(), proxyPort);

    BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm="));
    BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(proxyHost, basicScheme);

    String password = httpProxyConfig.encryptedPassword();
    if (!password.isEmpty()) {
        password = Encryption.decrypt(password, configRepository.getLazySecretKey());
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxyHost),
            new UsernamePasswordCredentials(httpProxyConfig.username(), password));
    HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);
    context.setCredentialsProvider(credentialsProvider);
    return context;
}
 
Example #26
Source File: SessionConfigurator.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private HttpContext getContext( URI uri ) {
  HttpClientContext httpClientContext = HttpClientContext.create();
  //used by httpclient version >= 4.3
  httpClientContext
    .setAttribute( HttpClientContext.HTTP_ROUTE, new HttpRoute( new HttpHost( uri.getHost(), uri.getPort() ) ) );
  //used by httpclient version 4.2
  httpClientContext
    .setAttribute( HttpClientContext.HTTP_TARGET_HOST, new HttpHost( uri.getHost(), uri.getPort() ) );
  return httpClientContext;
}
 
Example #27
Source File: QpidRestAPIQueueCreator.java    From qpid-broker-j with 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 #28
Source File: HttpTest.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
@Test
public void  test03() throws IOException, SchedulisSchedulerException {
    Cookie cookie = test01();
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("ajax","fetchProjectPage"));
    params.add(new BasicNameValuePair("start","0"));
    params.add(new BasicNameValuePair("length","10"));
    params.add(new BasicNameValuePair("projectsType","personal"));
    params.add(new BasicNameValuePair("pageNum","1"));
    params.add(new BasicNameValuePair("order","orderProjectName"));
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = null;
    try {
        String finalUrl = "http://127.0.0.1:8088/index" + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params));
        HttpGet httpGet = new HttpGet(finalUrl);
        httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        response = httpClient.execute(httpGet, context);
        /*Header[] allHeaders = context.getRequest().getAllHeaders();
        Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getAppJointName())).findFirst();
        header.ifPresent(AzkabanUtils.handlingConsumerWrapper(this::parseCookie));*/
    } catch (Exception e) {
        throw new SchedulisSchedulerException(90004, e.getMessage());
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
}
 
Example #29
Source File: OAuthRedirectUriTest.java    From keycloak with 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", "test-user@localhost").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 #30
Source File: YoutubeHttpContextFilter.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequest(HttpClientContext context, HttpUriRequest request, boolean isRepetition) {
  request.setHeader("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
      "Chrome/76.0.3809.100 Safari/537.36");
  request.setHeader("x-youtube-client-name", "1");
  request.setHeader("x-youtube-client-version", "2.20191008.04.01");
  request.setHeader("x-youtube-page-cl", "276511266");
  request.setHeader("x-youtube-page-label", "youtube.ytfe.desktop_20191024_3_RC0");
  request.setHeader("x-youtube-utc-offset", "0");
  request.setHeader("x-youtube-variants-checksum", "7a1198276cf2b23fc8321fac72aa876b");
  request.setHeader("accept-language", "en");
}