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.lokra.seaweedfs.core.Connection.java

/**
 * Fetch http API input stream cache./* w ww .j a va 2s .  c o m*/
 *
 * @param request Http request.
 * @return Stream fetch by http response.
 * @throws IOException Http connection is fail or server response within some error message.
 */
StreamResponse fetchStreamCacheByRequest(HttpRequestBase request) throws IOException {
    CloseableHttpResponse response = null;
    request.setHeader("Connection", "close");
    StreamResponse cache;

    try {
        response = httpClient.execute(request, HttpClientContext.create());
        HttpEntity entity = response.getEntity();
        cache = new StreamResponse(entity.getContent(), response.getStatusLine().getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ignored) {
            }
        }
        request.releaseConnection();
    }
    return cache;
}

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

/**
 * //w ww. jav a2s  . c o m
 * @return all the crowd groups
 * @throws RemoteException
 */
public Set<Role> getAllGroups() throws RemoteException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getAllGroups()");
    }

    HttpClientContext hc = HttpClientContext.create();
    int maxResults = 1000;
    int startIndex = 0;
    Set<Role> results = new HashSet<>();
    StringBuilder request = new StringBuilder("search?entity-type=group&expand=group&restriction=active%3dtrue")
            .append("&max-results=").append(maxResults).append("&start-index=");

    Set<String> roleIds = getGroupsFromCrowdLoop(hc, request, startIndex, maxResults);
    for (String roleId : roleIds) {
        results.add(new Role(roleId, roleId, "", "", true, null, null));
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("returning %d groups as Nexus Role objects", results.size()));
    }

    return results;
}

From source file:org.pentaho.di.trans.steps.couchdbinput.CouchDbInput.java

@VisibleForTesting
HttpClientContext getHttpClientContext(String hostname, int port) {
    HttpClientContext context;/* w  ww .  j  a v a 2 s.com*/
    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);

    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setAuthCache(authCache);
    return context;
}

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

@Test(expected = JsonParseException.class)
public void testCustomDeserializerTypeMismatch() throws Exception {
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    when(response.getEntity()).thenReturn(new StringEntity("[{somethig_not_type : \"WrongType\"}]"));
    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.  co m*/
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient)
            .classToDeserializerEntry(TestPojo.class, new TestPojoDeserializer()).build();

    connector.executeRetrieveObject(TestPojo.class, "/somepath");
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;//from ww w.j  a va2  s  .c o  m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Make the DOI obsolete by setting the EZID metadata field "_status" to
 * "unavailable".// w w w . j a v  a 2  s . c  o  m
 * 
 * @param doi The DOI to obsolete
 * @throws EzidException
 */
public void obsoleteDoi(String doi) throws EzidException {

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // 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(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    String url = this.getEzidUrl("/id/" + doi);

    StringBuffer metadata = new StringBuffer("");
    metadata.append("_status: unavailable | withdrawn by author\n");

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Content-type", "text/plain");
    HttpEntity stringEntity = null;
    Integer statusCode = null;
    String entityString = null;

    try {
        stringEntity = new StringEntity(metadata.toString());
        httpPost.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpHost, httpPost, context);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        entityString = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    logger.info("obsoleteDoi: " + entityString);

    if (statusCode != HttpStatus.SC_OK) {
        String gripe = "DOI obsoletion failed for: " + doi;
        throw new EzidException(gripe);
    }

}

From source file:org.apache.openmeetings.web.user.calendar.CalendarPanel.java

public HttpClientContext getHttpClientContext() {
    if (context == null) {
        context = HttpClientContext.create();
        context.setCredentialsProvider(new BasicCredentialsProvider());
    }//  w  ww. jav  a  2s . co  m

    return context;
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
    HttpClientContext context = null;/*ww  w. j  ava  2s  . co  m*/
    HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
    if (username != null && password != null) {

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, password));

        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, new BasicScheme());

        // Add AuthCache to the execution context
        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } else {
        context = null;
    }
    return context;
}

From source file:org.lokra.seaweedfs.core.Connection.java

/**
 * Fetch http API hearers with status code(in array).
 *
 * @param request Only http method head.
 * @return Header fetch by http response.
 * @throws IOException Http connection is fail or server response within some error message.
 *//*w  w  w.  ja v a  2 s  . c  o  m*/
HeaderResponse fetchHeaderByRequest(HttpHead request) throws IOException {
    CloseableHttpResponse response = null;
    request.setHeader("Connection", "close");
    HeaderResponse headerResponse;

    try {
        response = httpClient.execute(request, HttpClientContext.create());
        headerResponse = new HeaderResponse(response.getAllHeaders(), response.getStatusLine().getStatusCode());
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ignored) {
            }
        }
        request.releaseConnection();
    }
    return headerResponse;
}