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

The following are top voted examples for showing how to use org.apache.http.client.protocol.HttpClientContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: datarouter   File: DatarouterHttpResponse.java   Source Code and License 11 votes vote down vote up
public DatarouterHttpResponse(HttpResponse response, HttpClientContext context,
		Consumer<HttpEntity> httpEntityConsumer){
	this.response = response;
	this.cookies = context.getCookieStore().getCookies();
	if(response != null){
		this.statusCode = response.getStatusLine().getStatusCode();
		this.entity = "";

		HttpEntity httpEntity = response.getEntity();
		if(httpEntity == null){
			return;
		}
		if(httpEntityConsumer != null){
			httpEntityConsumer.accept(httpEntity);
			return;
		}
		try{
			this.entity = EntityUtils.toString(httpEntity);
		}catch(IOException e){
			logger.error("Exception occurred while reading HTTP response entity", e);
		}finally{
			EntityUtils.consumeQuietly(httpEntity);
		}
	}
}
 
Example 2
Project: Reer   File: HttpClientConfigurer.java   Source Code and License 7 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
Example 3
Project: bubble2   File: ResponseWrap.java   Source Code and License 7 votes vote down vote up
public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context,
		ObjectMapper _mapper) {
	this.response = response;
	this.httpClient = httpClient;
	this.request = request;
	this.context = context;
	mapper = _mapper;

	try {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			this.entity = new BufferedHttpEntity(entity);
		} else {
			this.entity = new BasicHttpEntity();
		}

		EntityUtils.consumeQuietly(entity);
		this.response.close();
	} catch (IOException e) {
		logger.warn(e.getMessage());
	}
}
 
Example 4
Project: feedsucker   File: HttpUtils.java   Source Code and License 7 votes vote down vote up
/** Return final location from http redirects  */
public static String resolveHttpRedirects(String uri) 
        throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();
    HttpGet httpget = new HttpGet(uri);
    //httpget.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20121202 Firefox/17.0 Iceweasel/17.0.1");        
    CloseableHttpResponse response = httpclient.execute(httpget, context);          
    try {
        HttpHost target = context.getTargetHost();
        List<URI> redirectLocations = context.getRedirectLocations();
        URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
        return location.toString();
    } finally {
        response.close();           
    }                
}
 
Example 5
Project: devops-cstack   File: RestUtils.java   Source Code and License 6 votes vote down vote up
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {

        Map<String, String> response = new HashMap<String, String>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
        nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
        localContext = HttpClientContext.create();
        localContext.setCookieStore(new BasicCookieStore());
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
            ResponseHandler<String> handler = new CustomResponseErrorHandler();
            String body = handler.handleResponse(httpResponse);
            response.put(BODY, body);
            httpResponse.close();
        } catch (Exception e) {
            authentificationUtils.getMap().clear();
            throw new ManagerResponseException(e.getMessage(), e);
        }

        return response;
    }
 
Example 6
Project: datarouter   File: DatarouterHttpRetryHandler.java   Source Code and License 6 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context){
	if(logOnRetry){
		HttpClientContext clientContext = HttpClientContext.adapt(context);
		logger.warn("Request {} failure Nº {}", clientContext.getRequest().getRequestLine(), executionCount,
				exception);
	}
	Object retrySafe = context.getAttribute(RETRY_SAFE_ATTRIBUTE);
	if(retrySafe == null || !(retrySafe instanceof Boolean) || !(Boolean)retrySafe || executionCount > retryCount){
		return false;
	}
	return true;
}
 
Example 7
Project: cyberduck   File: CallbackProxyAuthenticationStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final Credentials credentials = clientContext.getAttribute(PROXY_CREDENTIALS_INPUT_ID, Credentials.class);
    if(null != credentials) {
        clientContext.removeAttribute(PROXY_CREDENTIALS_INPUT_ID);
        if(log.isInfoEnabled()) {
            log.info(String.format("Save passphrase for proxy %s", authhost));
        }
        keychain.addCredentials(authhost.getHostName(), credentials.getUsername(), credentials.getPassword());
    }
    super.authSucceeded(authhost, authScheme, context);
}
 
Example 8
Project: PicCrawler   File: RetryHandler.java   Source Code and License 6 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
Example 9
Project: bubble2   File: HttpUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 执行请求
 * 
 * @date 2015年7月17日
 * @return
 */
public ResponseWrap execute() {
	settingRequest();
	if (httpClient == null) {
		httpClient = clientBuilder.build();
	}

	try {
		HttpClientContext context = HttpClientContext.create();
		CloseableHttpResponse response = httpClient.execute(request, context);
		return new ResponseWrap(httpClient, request, response, context, mapper);
	} catch (IOException e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 10
Project: ProxyPool   File: RetryHandler.java   Source Code and License 6 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
Example 11
Project: aws-sdk-java-v2   File: ApacheUtils.java   Source Code and License 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.endpoint().getHost(), proxyConfiguration.endpoint().getPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
Example 12
Project: ibm-cos-sdk-java   File: ApacheUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a new HttpClientContext used for request execution.
 */
public static HttpClientContext newClientContext(HttpClientSettings settings,
                                                 Map<String, ? extends Object>
                                                         attributes) {
    final HttpClientContext clientContext = new HttpClientContext();

    if (attributes != null && !attributes.isEmpty()) {
        for (Map.Entry<String, ?> entry : attributes.entrySet()) {
            clientContext.setAttribute(entry.getKey(), entry.getValue());
        }
    }

    addPreemptiveAuthenticationProxy(clientContext, settings);
    return clientContext;

}
 
Example 13
Project: ibm-cos-sdk-java   File: ApacheUtils.java   Source Code and License 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
Example 14
Project: vscrawler   File: VSCrawlerRoutePlanner.java   Source Code and License 6 votes vote down vote up
@Override
protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
    HttpClientContext httpClientContext = HttpClientContext.adapt(context);
    Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession);

    if (proxy == null) {
        return null;
    }
    if (log.isDebugEnabled()) {
        log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort());
    }
    context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy);

    if (proxy.getAuthenticationHeaders() != null) {
        for (Header header : proxy.getAuthenticationHeaders()) {
            request.addHeader(header);
        }
    }

    if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) {
        BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider();
        httpClientContext.setCredentialsProvider(credsProvider1);
        credsProvider1.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
    }
    return new HttpHost(proxy.getIp(), proxy.getPort());
}
 
Example 15
Project: vscrawler   File: ProxyFeedBackClientExecChain.java   Source Code and License 6 votes vote down vote up
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext clientContext,
        HttpExecutionAware execAware) throws IOException, HttpException {
    Proxy proxy = (Proxy) clientContext.getAttribute(VSCrawlerConstant.VSCRAWLER_AVPROXY_KEY);
    if (proxy != null) {
        proxy.recordUsage();
    }
    try {
        return delegate.execute(route, request, clientContext, execAware);
    } catch (IOException ioe) {
        if (proxy != null) {
            proxy.recordFailed();
        }
        throw ioe;
    }
}
 
Example 16
Project: vscrawler   File: EverySessionPlanner.java   Source Code and License 6 votes vote down vote up
@Override
public Proxy determineProxy(HttpHost host, HttpRequest request, HttpContext context, IPPool ipPool,
        CrawlerSession crawlerSession) {
    HttpClientContext httpClientContext = HttpClientContext.adapt(context);

    Proxy proxy = (Proxy) crawlerSession.getExtInfo(VSCRAWLER_AVPROXY_KEY);
    if (proxy == null) {
        String accessUrl = null;
        if (request instanceof HttpRequestWrapper || request instanceof HttpGet) {
            accessUrl = HttpUriRequest.class.cast(request).getURI().toString();
        }
        if (!PoolUtil.isDungProxyEnabled(httpClientContext)) {
            log.info("{}不会被代理", accessUrl);
            return null;
        }
        proxy = ipPool.getIP(host.getHostName(), accessUrl);
        if (proxy == null) {
            return null;
        }
        crawlerSession.setExtInfo(VSCRAWLER_AVPROXY_KEY, proxy);
    }

    return proxy;
}
 
Example 17
Project: jeeves   File: WechatHttpServiceInternal.java   Source Code and License 6 votes vote down vote up
/**
 * Open the entry page.
 *
 * @param retryTimes retry times of qr scan
 */
void open(int retryTimes) {
    final String url = WECHAT_URL_ENTRY;
    HttpHeaders customHeader = new HttpHeaders();
    customHeader.setPragma("no-cache");
    customHeader.setCacheControl("no-cache");
    customHeader.set("Upgrade-Insecure-Requests", "1");
    customHeader.set(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
    HeaderUtils.assign(customHeader, getHeader);
    restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(customHeader), String.class);
    //manually insert two cookies into cookiestore, as they're supposed to be stored in browsers by javascript.
    CookieStore store = (CookieStore) ((StatefullRestTemplate) restTemplate).getHttpContext().getAttribute(HttpClientContext.COOKIE_STORE);
    Date maxDate = new Date(Long.MAX_VALUE);
    String domain = WECHAT_URL_ENTRY.replaceAll("https://", "").replaceAll("/", "");
    Map<String, String> cookies = new HashMap<>(3);
    cookies.put("MM_WX_NOTIFY_STATE", "1");
    cookies.put("MM_WX_SOUND_STATE", "1");
    if (retryTimes > 0) {
        cookies.put("refreshTimes", String.valueOf(retryTimes));
    }
    appendAdditionalCookies(store, cookies, domain, "/", maxDate);
    //It's now at entry page.
    this.originValue = WECHAT_URL_ENTRY;
    this.refererValue = WECHAT_URL_ENTRY.replaceAll("/$", "");
}
 
Example 18
Project: jeeves   File: WechatHttpServiceInternal.java   Source Code and License 6 votes vote down vote up
/**
 * Initialization
 *
 * @param hostUrl     hostUrl
 * @param baseRequest baseRequest
 * @return current user's information and contact information
 * @throws IOException if the http response body can't be convert to {@link InitResponse}
 */
InitResponse init(String hostUrl, BaseRequest baseRequest) throws IOException {
    String url = String.format(WECHAT_URL_INIT, hostUrl, RandomUtils.generateDateWithBitwiseNot());

    CookieStore store = (CookieStore) ((StatefullRestTemplate) restTemplate).getHttpContext().getAttribute(HttpClientContext.COOKIE_STORE);
    Date maxDate = new Date(Long.MAX_VALUE);
    String domain = hostUrl.replaceAll("https://", "").replaceAll("/", "");
    Map<String, String> cookies = new HashMap<>(3);
    cookies.put("MM_WX_NOTIFY_STATE", "1");
    cookies.put("MM_WX_SOUND_STATE", "1");
    appendAdditionalCookies(store, cookies, domain, "/", maxDate);
    InitRequest request = new InitRequest();
    request.setBaseRequest(baseRequest);
    HttpHeaders customHeader = new HttpHeaders();
    customHeader.set(HttpHeaders.REFERER, hostUrl + "/");
    customHeader.setOrigin(hostUrl);
    HeaderUtils.assign(customHeader, postHeader);
    ResponseEntity<String> responseEntity
            = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request, customHeader), String.class);
    return jsonMapper.readValue(WechatUtils.textDecode(responseEntity.getBody()), InitResponse.class);
}
 
Example 19
Project: geoportal-server-harvester   File: WafFile.java   Source Code and License 6 votes vote down vote up
/**
 * Reads content.
 * @param httpClient HTTP client
 * @param since since date
 * @return content reference
 * @throws IOException if reading content fails
 * @throws URISyntaxException if file url is an invalid URI
 */
public SimpleDataReference readContent(CloseableHttpClient httpClient, Date since) throws IOException, URISyntaxException {
  HttpGet method = new HttpGet(fileUrl.toExternalForm());
  method.setConfig(DEFAULT_REQUEST_CONFIG);
  method.setHeader("User-Agent", HttpConstants.getUserAgent());
  HttpClientContext context = creds!=null && !creds.isEmpty()? createHttpClientContext(fileUrl, creds): null;
  
  try (CloseableHttpResponse httpResponse = httpClient.execute(method,context); InputStream input = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    Date lastModifiedDate = readLastModifiedDate(httpResponse);
    MimeType contentType = readContentType(httpResponse);
    boolean readBody = since==null || lastModifiedDate==null || lastModifiedDate.getTime()>=since.getTime();
    SimpleDataReference ref = new SimpleDataReference(broker.getBrokerUri(), broker.getEntityDefinition().getLabel(), fileUrl.toExternalForm(), lastModifiedDate, fileUrl.toURI());
    ref.addContext(contentType, readBody? IOUtils.toByteArray(input): null);
    return ref;
  }
}
 
Example 20
Project: purecloud-iot   File: TestProtocolRequirements.java   Source Code and License 6 votes vote down vote up
@Test
public void testMustNotAddMultipartByteRangeContentTypeTo416Response() throws Exception {
    originResponse = Proxies.enhanceResponse(
            new BasicHttpResponse(HttpVersion.HTTP_1_1, 416, "Requested Range Not Satisfiable"));

    EasyMock.expect(
            mockBackend.execute(
                    EasyMock.isA(HttpRoute.class),
                    EasyMock.isA(HttpRequestWrapper.class),
                    EasyMock.isA(HttpClientContext.class),
                    EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse);

    replayMocks();
    final HttpResponse result = impl.execute(route, request, context, null);
    verifyMocks();

    if (result.getStatusLine().getStatusCode() == 416) {
        for (final Header h : result.getHeaders("Content-Type")) {
            for (final HeaderElement elt : h.getElements()) {
                Assert.assertFalse("multipart/byteranges".equalsIgnoreCase(elt.getName()));
            }
        }
    }
}
 
Example 21
Project: purecloud-iot   File: TestAuthenticationStrategy.java   Source Code and License 6 votes vote down vote up
@Test
public void testSelectNoCredentialsProvider() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
 
Example 22
Project: harvesters   File: HttpRequestBuilder.java   Source Code and License 6 votes vote down vote up
@Override
 public final HttpResponse execute() throws IOException {
     HttpResponse res = null;

     HttpClientContext clientContext = HttpClientContext.create();
     HttpClientBuilder clientBuilder = HttpClientBuilder.create();

     _prepareAuth(clientBuilder, clientContext);
     _prepareSSL(clientBuilder);

     try (CloseableHttpClient client = clientBuilder.build()) {
         @SuppressWarnings("unused")
org.apache.http.client.methods.HttpPost a;
         res = executeWithClient(client, clientContext);
     }

     return res;
 }
 
Example 23
Project: cloud-meter   File: HTTPHC4Impl.java   Source Code and License 6 votes vote down vote up
/**
 * Configure the UserToken so that the SSL context is reused
 * See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
 * @param localContext {@link HttpContext}
 */
private void setupClientContextBeforeSample(HttpContext localContext) {
    Object userToken = null;
    // During recording JMeterContextService.getContext().getVariables() is null
    JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
    if(jMeterVariables != null) {
        userToken = jMeterVariables.getObject(USER_TOKEN);            
    }
    if(userToken != null) {
        if(log.isDebugEnabled()) {
            log.debug("Found user token:"+userToken+" as JMeter variable:"+USER_TOKEN+", storing it in HttpContext");
        }
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
    } else {
        // It would be better to create a ClientSessionManager that would compute this value
        // for now it can be Thread.currentThread().getName() but must be changed when we would change 
        // the Thread per User model
        String userId = Thread.currentThread().getName();
        if(log.isDebugEnabled()) {
            log.debug("Storing in HttpContext the user token:"+userId);
        }
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userId);
    }
}
 
Example 24
Project: purecloud-iot   File: TestProtocolRequirements.java   Source Code and License 6 votes vote down vote up
@Test
public void test205ResponsesDoNotContainMessageBodies() throws Exception {
    originResponse = Proxies.enhanceResponse(
            new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_RESET_CONTENT, "Reset Content"));
    originResponse.setEntity(HttpTestUtils.makeBody(entityLength));

    EasyMock.expect(
            mockBackend.execute(
                    EasyMock.isA(HttpRoute.class),
                    EasyMock.isA(HttpRequestWrapper.class),
                    EasyMock.isA(HttpClientContext.class),
                    EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse);

    replayMocks();

    final HttpResponse result = impl.execute(route, request, context, null);

    verifyMocks();

    Assert.assertTrue(result.getEntity() == null || result.getEntity().getContentLength() == 0);
}
 
Example 25
Project: Brutusin-RPC   File: HttpEndpoint.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        HttpClientContextFactory ctxFact = new HttpClientContextFactory() {
            public HttpClientContext create() {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"),
                        new UsernamePasswordCredentials("user", "password"));
                HttpClientContext context = HttpClientContext.create();
                context.setCredentialsProvider(credsProvider);
                return context;
            }
        };

        HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact);

        HttpResponse resp = endpoint.exec("rpc.http.version", null, null);
        if (resp.isIsBinary()) {
            System.out.println("binary");
            System.out.println(resp.getInputStream().getName());
        } else {
            System.out.println(resp.getRpcResponse().getResult());
        }
    }
 
Example 26
Project: playground   File: SystemUserConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public BasicHttpContext createContext(final HttpHost targetHost) {

    BasicHttpContext context = CACHED_CONTEXTS.get(targetHost);

    if (context == null) {

        log.trace("creating and configuring new HttpContext for system user");
        context = basicAuthConfigurator.createContext(targetHost);

        final CookieStore cookieStore = new BasicCookieStore();
        context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

        log.trace("caching HttpContext for system user");
        CACHED_CONTEXTS.put(targetHost, context);
    }
    else {

        log.trace("using cached HttpContext for system user");
    }

    return context;
}
 
Example 27
Project: Peking-University-Open-Research-Data-Platform   File: DataCiteRESTfullClient.java   Source Code and License 6 votes vote down vote up
public DataCiteRESTfullClient(String url, String username, String password) {
    this.url = url;
    try {
        context = HttpClientContext.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        context.setCredentialsProvider(credsProvider);
        
        httpClient = HttpClients.createDefault();
    } catch (Exception ioe) {
        close();
        logger.log(Level.SEVERE,"Fail to init Client",ioe);
        throw new RuntimeException("Fail to init Client", ioe);
    }
}
 
Example 28
Project: purecloud-iot   File: TestClientAuthentication.java   Source Code and License 6 votes vote down vote up
@Test
public void testAuthenticationUserinfoInRedirectSuccess() throws Exception {
    this.serverBootstrap.registerHandler("*", new AuthHandler());
    this.serverBootstrap.registerHandler("/thatway", new RedirectHandler());

    final HttpHost target = start();

    final HttpGet httpget = new HttpGet("http://" +  target.toHostString() + "/thatway");
    final HttpClientContext context = HttpClientContext.create();

    final HttpResponse response = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
    EntityUtils.consume(entity);
}
 
Example 29
Project: purecloud-iot   File: TestProtocolRequirements.java   Source Code and License 6 votes vote down vote up
private void testDoesNotAddHeaderToRequestIfNotPresent(final String header) throws Exception {
    final BasicHttpEntityEnclosingRequest req =
        new BasicHttpEntityEnclosingRequest("POST","/",HttpVersion.HTTP_1_1);
    req.setEntity(HttpTestUtils.makeBody(128));
    req.setHeader("Content-Length","128");
    req.removeHeaders(header);

    final Capture<HttpRequestWrapper> cap = new Capture<HttpRequestWrapper>();

    EasyMock.expect(
            mockBackend.execute(
                    EasyMock.eq(route),
                    EasyMock.capture(cap),
                    EasyMock.isA(HttpClientContext.class),
                    EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse);

    replayMocks();
    impl.execute(route, HttpRequestWrapper.wrap(req), context, null);
    verifyMocks();

    final HttpRequest captured = cap.getValue();
    Assert.assertNull(captured.getFirstHeader(header));
}
 
Example 30
Project: purecloud-iot   File: TestClientAuthentication.java   Source Code and License 6 votes vote down vote up
@Test
public void testPreemptiveAuthentication() throws Exception {
    final CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.serverBootstrap.registerHandler("*", requestHandler);

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());
    context.setAuthCache(authCache);
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("test", "test"));
    context.setCredentialsProvider(credsProvider);

    final HttpGet httpget = new HttpGet("/");
    final HttpResponse response1 = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
}
 
Example 31
Project: purecloud-iot   File: TestClientAuthentication.java   Source Code and License 6 votes vote down vote up
@Test
public void testBasicAuthenticationFailure() throws Exception {
    this.serverBootstrap.registerHandler("*", new AuthHandler());

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
            new UsernamePasswordCredentials("test", "all-wrong"));
    context.setCredentialsProvider(credsProvider);
    final HttpGet httpget = new HttpGet("/");

    final HttpResponse response = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
    EntityUtils.consume(entity);
    final AuthScope authscope = credsProvider.getAuthScope();
    Assert.assertNotNull(authscope);
    Assert.assertEquals("test realm", authscope.getRealm());
}
 
Example 32
Project: cosmic   File: RESTServiceConnectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteUpdateObject() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    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.executeUpdateObject(newObject, "/somepath");

    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
}
 
Example 33
Project: cosmic   File: RESTServiceConnectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteUpdateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    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.executeUpdateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), 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));
}
 
Example 34
Project: purecloud-iot   File: TestMainClientExec.java   Source Code and License 6 votes vote down vote up
@Test(expected = HttpException.class)
public void testEstablishRouteViaProxyTunnelUnexpectedResponse() throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 101, "Lost");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenReturn(response);

    mainClientExec.establishRoute(authState, managedConn, route, request, context);
}
 
Example 35
Project: cosmic   File: RESTServiceConnectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteRetrieveObject() 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");

    assertThat(object, notNullValue());
    assertThat(object, equalTo(existingObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 36
Project: ibm-bpm-rest-client   File: KerberosBpmClient.java   Source Code and License 6 votes vote down vote up
private HttpClientContext getHttpContext() {
    HttpClientContext context = HttpClientContext.create();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    Credentials credentials = new Credentials() {

        public String getPassword() {
            return null;
        }

        public Principal getUserPrincipal() {
            return null;
        }
    };
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), credentials);
    context.setCredentialsProvider(credentialsProvider);
    return context;
}
 
Example 37
Project: releasetrain   File: HttpUtilImpl.java   Source Code and License 6 votes vote down vote up
/**
 * set user and password for basic authentication
 */
@Override
public String getPageAsString(String url) {
	try {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(url);
		httpget.setHeader("Cache-Control", "no-store");
		httpget.setHeader("Cache-Control", "no-cache");
		HttpClientContext context = initAuthIfNeeded(url);

		HttpResponse response = httpclient.execute(httpget, context);
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity);
	} catch (IOException e) {
		log.info(e.getMessage());
	}
	return "n/a";
}
 
Example 38
Project: purecloud-iot   File: TestProtocolRequirements.java   Source Code and License 6 votes vote down vote up
@Test
public void testResponsesToOPTIONSAreNotCacheable() throws Exception {
    emptyMockCacheExpectsNoPuts();
    request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "/", HttpVersion.HTTP_1_1));
    originResponse.addHeader("Cache-Control", "max-age=3600");

    EasyMock.expect(
            mockBackend.execute(
                    EasyMock.eq(route),
                    EasyMock.isA(HttpRequestWrapper.class),
                    EasyMock.isA(HttpClientContext.class),
                    EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse);

    replayMocks();

    impl.execute(route, request, context, null);

    verifyMocks();
}
 
Example 39
Project: Camel   File: PreemptiveAuthInterceptor.java   Source Code and License 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
        if (authScheme != null) {
            Credentials creds = credsProvider.getCredentials(AuthScope.ANY);
            if (creds == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }
            authState.update(authScheme, creds);
        }
    }

}
 
Example 40
Project: remote-files-sync   File: MainClientExec.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a tunnel to an intermediate proxy.
 * This method is <i>not</i> implemented in this class.
 * It just throws an exception here.
 */
private boolean createTunnelToProxy(
        final HttpRoute route,
        final int hop,
        final HttpClientContext context) throws HttpException {

    // Have a look at createTunnelToTarget and replicate the parts
    // you need in a custom derived class. If your proxies don't require
    // authentication, it is not too hard. But for the stock version of
    // HttpClient, we cannot make such simplifying assumptions and would
    // have to include proxy authentication code. The HttpComponents team
    // is currently not in a position to support rarely used code of this
    // complexity. Feel free to submit patches that refactor the code in
    // createTunnelToTarget to facilitate re-use for proxy tunnelling.

    throw new HttpException("Proxy chains are not supported.");
}