Example usage for org.apache.http.client.protocol HttpClientContext create

List of usage examples for org.apache.http.client.protocol HttpClientContext create

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext create.

Prototype

public static HttpClientContext create() 

Source Link

Usage

From source file:org.alfresco.cacheserver.http.CacheHttpClient.java

public void getNodeById(String hostname, int port, String username, String password, String nodeId,
        String nodeVersion, HttpCallback callback) throws IOException {
    HttpHost target = new HttpHost(hostname, port, "http");

    // 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);/* w ww  .j  a v a  2  s  . c  om*/
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    CloseableHttpClient httpClient = getHttpClient(target, localContext, username, password);
    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000)
                .build();

        String uri = "http://" + hostname + ":" + port
                + "/alfresco/api/-default-/private/alfresco/versions/1/contentByNodeId/" + nodeId + "/"
                + nodeVersion;
        HttpGet httpGet = new HttpGet(uri);
        httpGet.setHeader("Content-Type", "text/plain");
        httpGet.setConfig(requestConfig);

        System.out.println("Executing request " + httpGet.getRequestLine());
        CloseableHttpResponse response = httpClient.execute(target, httpGet, localContext);
        try {
            callback.execute(response.getEntity().getContent());
            //                EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
}

From source file:edu.ucsb.nceas.ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls uning this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 * @throws EZIDException if authentication fails for any reason
 *//*from   w  w w .j  a v  a2  s  . c  o  m*/
public void login(String username, String password) throws EZIDException {
    try {
        URI serviceUri = new URI(loginServiceEndpoint);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        HttpClientContext localcontext = HttpClientContext.create();
        localcontext.setAuthCache(authCache);
        localcontext.setCredentialsProvider(credsProvider);

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(loginServiceEndpoint);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        String msg = parseIdentifierResponse(message);
    } catch (URISyntaxException e) {
        throw new EZIDException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new EZIDException(e.getMessage());
    } catch (IOException e) {
        throw new EZIDException(e.getMessage());
    }
}

From source file:org.callimachusproject.client.HttpClientRedirectTest.java

@Test
public void testHttpFragmentReset() throws Exception {
    register("*", new SimpleService());
    register("/~tim", new HttpRequestHandler() {
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_SEE_OTHER);
            response.setHeader("Location", "/People.htm#tim");
            final StringEntity entity = new StringEntity("Whatever");
            response.setEntity(entity);//from w  ww. j a v  a  2  s .  c om
        }
    });
    register("/People.htm", new HttpRequestHandler() {
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", "/people.html");
            final StringEntity entity = new StringEntity("Whatever");
            response.setEntity(entity);
        }
    });
    final HttpHost target = getServerHttp();

    final HttpClientContext context = HttpClientContext.create();

    this.httpclient.execute(target, new HttpGet("/~tim"), context);
    // this checks that the context was properly reset
    final HttpResponse response = this.httpclient.execute(target, new HttpGet("/People.htm"), context);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    final HttpRequest request = context.getRequest();
    Assert.assertEquals("/people.html", request.getRequestLine().getUri());

    final URI uri = new URIBuilder().setHost(target.getHostName()).setPort(target.getPort())
            .setScheme(target.getSchemeName()).setPath("/people.html").build();

    final URI location = getHttpLocation(new HttpGet("/People.htm"), context);
    Assert.assertEquals(uri, location);
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static int getNotificationCount(String serverId, String mirthVersion,
        Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols,
        String[] cipherSuites) {/*from   w w w .  ja  va 2  s.  c o m*/
    CloseableHttpClient client = null;
    HttpPost post = new HttpPost();
    CloseableHttpResponse response = null;

    int notificationCount = 0;

    try {
        ObjectMapper mapper = new ObjectMapper();
        String extensionVersionsJson = mapper.writeValueAsString(extensionVersions);
        NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET),
                new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion),
                new BasicNameValuePair("extensionVersions", extensionVersionsJson) };
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET));
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));

        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        client = getClient(protocols, cipherSuites);
        response = client.execute(post, postContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode == HttpStatus.SC_OK)) {
            HttpEntity responseEntity = response.getEntity();
            Charset responseCharset = null;
            try {
                responseCharset = ContentType.getOrDefault(responseEntity).getCharset();
            } catch (Exception e) {
                responseCharset = ContentType.TEXT_PLAIN.getCharset();
            }

            List<Integer> notificationIds = mapper.readValue(
                    IOUtils.toString(responseEntity.getContent(), responseCharset).trim(),
                    new TypeReference<List<Integer>>() {
                    });
            for (int id : notificationIds) {
                if (!archivedNotifications.contains(id)) {
                    notificationCount++;
                }
            }
        }
    } catch (Exception e) {
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
    return notificationCount;
}

From source file:com.cloud.utils.rest.RESTServiceConnectorTest.java

@Test
public void testExecuteCreateObjectWithParameters() 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);/*from w w  w  .  j  a  v  a 2s.  c o  m*/
    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", DEFAULT_TEST_PARAMETERS);

    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(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();
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * CloseableHttpResponse//  w w w  .j a  v a 2 s.co m
 * 
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public CloseableHttpResponse getCloseableResponse(String url, Series<Cookie> cookies)
        throws ClientProtocolException, IOException {

    HttpClientBuilder httpclientBuilder = HttpClients.custom();

    if (withproxy) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                ProxySettings.getProxyUser(), ProxySettings.getProxyPassword()));
        httpclientBuilder.setDefaultCredentialsProvider(credsProvider).build();
    }
    CloseableHttpClient httpclient = httpclientBuilder.build();

    HttpClientContext context = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();

    Iterator<Cookie> iter = cookies.iterator();

    while (iter.hasNext()) {
        Cookie restCookie = iter.next();
        BasicClientCookie cookie = new BasicClientCookie(restCookie.getName(), restCookie.getValue());
        // cookie.setDomain(restCookie.getDomain());
        cookie.setDomain(getDomainName(url));
        cookie.setPath(restCookie.getPath());
        cookie.setSecure(true);
        // cookie.setExpiryDate(restCookie);
        cookieStore.addCookie(cookie);
    }

    context.setCookieStore(cookieStore);

    HttpGet httpget = new HttpGet(url);

    Builder configBuilder = RequestConfig.custom();

    if (withproxy) {
        HttpHost proxy = new HttpHost(ProxySettings.getProxyHost(),
                Integer.parseInt(ProxySettings.getProxyPort()), "http");
        configBuilder.setProxy(proxy).build();
    }

    RequestConfig config = configBuilder.build();
    httpget.setConfig(config);

    return httpclient.execute(httpget, context);

}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

protected Callable<SyncLanClientQueryResult> createSyncLanClientQueryResultCallable(
        final SyncLanClient syncLanClient, SyncFile syncFile) {

    String url = _getUrl(syncLanClient, syncFile);

    final HttpHead httpHead = new HttpHead(url);

    return new Callable<SyncLanClientQueryResult>() {

        @Override//from   w ww . j  a  v a 2  s .c  o m
        public SyncLanClientQueryResult call() throws Exception {
            SyncLanClientQueryResult syncLanClientQueryResult = new SyncLanClientQueryResult();

            syncLanClientQueryResult.setSyncLanClient(syncLanClient);

            HttpResponse httpResponse = _queryHttpClient.execute(httpHead, HttpClientContext.create());

            Header connectionsCountHeader = httpResponse.getFirstHeader("connectionsCount");

            if (connectionsCountHeader == null) {
                return null;
            }

            syncLanClientQueryResult
                    .setConnectionsCount(GetterUtil.getInteger(connectionsCountHeader.getValue()));

            Header downloadRateHeader = httpResponse.getFirstHeader("downloadRate");

            if (downloadRateHeader == null) {
                return null;
            }

            syncLanClientQueryResult.setDownloadRate(GetterUtil.getInteger(downloadRateHeader.getValue()));

            Header encryptedTokenHeader = httpResponse.getFirstHeader("encryptedToken");

            if (encryptedTokenHeader == null) {
                return null;
            }

            syncLanClientQueryResult.setEncryptedToken(encryptedTokenHeader.getValue());

            Header maxConnectionsHeader = httpResponse.getFirstHeader("maxConnections");

            if (maxConnectionsHeader == null) {
                return null;
            }

            syncLanClientQueryResult.setMaxConnections(GetterUtil.getInteger(maxConnectionsHeader.getValue()));

            return syncLanClientQueryResult;
        }

    };
}

From source file:me.Aron.Heinecke.fbot.lib.Socket.java

/***
 * Performs the login into fronter based on the DB credentials
 * Requires the tokens form getReqID/*from  ww  w . j a va  2  s.  c o m*/
 * @return site content
 */
public synchronized String login() throws ClientProtocolException, IOException {
    String url = "https://fronter.com/giessen/index.phtml";
    //create client & post
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    post.setHeader("Accept-Encoding", "gzip, deflate");
    post.setHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
    post.setHeader("Connection", "keep-alive");
    post.setHeader("DNT", "1");
    post.setHeader("Host", "fronter.com");
    post.setHeader("Referer", "https://fronter.com/giessen/index.phtml");
    post.setHeader("User-Agent", UA);

    // set login parameters & fake normal login data
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("SSO_COMMAND", ""));
    urlParameters.add(new BasicNameValuePair("SSO_COMMAND_SECHASH", fbot.getDB().getSSOCOM()));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_HEIGH...", "1080"));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_WIDTH", "1920"));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_HEIGH...", "914"));
    urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_WIDTH", "1920"));
    urlParameters.add(new BasicNameValuePair("USER_SCREEN_SIZE", ""));
    urlParameters.add(new BasicNameValuePair("chp", ""));
    urlParameters.add(new BasicNameValuePair("fronter_request_token", fbot.getDB().getReqtoken()));
    urlParameters.add(new BasicNameValuePair("mainurl", "main.phtml"));
    urlParameters.add(new BasicNameValuePair("newlang", "de"));
    urlParameters.add(new BasicNameValuePair("password", fbot.getDB().getPass()));
    urlParameters.add(new BasicNameValuePair("saveid", "-1"));
    urlParameters.add(new BasicNameValuePair("username", fbot.getDB().getUser()));

    //create gzip encoder
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(urlParameters);
    urlEncodedFormEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF_8"));
    post.setEntity(urlEncodedFormEntity);

    //Create own context which stores the cookies
    HttpClientContext context = HttpClientContext.create();

    HttpResponse response = client.execute(post, context);

    if (fbot.isDebug()) {
        fbot.getLogger().debug("socket", "Sending POST request to URL: " + url);
        fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode());
        fbot.getLogger().log("debug", "socket", context.getCookieStore().getCookies());
    }

    // input-stream with gzip-accept
    InputStream input = response.getEntity().getContent();
    InputStreamReader isr = new InputStreamReader(input);
    BufferedReader rd = new BufferedReader(isr);

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    input.close();
    isr.close();
    rd.close();

    fbot.getDB().setCookieStore(context.getCookieStore());

    return result.toString();

}