Example usage for org.apache.http.impl NoConnectionReuseStrategy NoConnectionReuseStrategy

List of usage examples for org.apache.http.impl NoConnectionReuseStrategy NoConnectionReuseStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl NoConnectionReuseStrategy NoConnectionReuseStrategy.

Prototype

NoConnectionReuseStrategy

Source Link

Usage

From source file:org.sonatype.nexus.internal.httpclient.HttpClientFactoryImpl.java

@Override
public HttpClient create() {
    RemoteStorageContext context = globalRemoteStorageContextProvider.get();
    Builder builder = prepare(new RemoteStorageContextCustomizer(context));

    // FIXME: Why is this here and not general?
    boolean reuseConnections = reuseConnectionsNeeded(context);
    if (!reuseConnections) {
        builder.getHttpClientBuilder().setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }/*from w  w  w. ja  va 2 s .c  om*/

    return builder.build();
}

From source file:org.forgerock.openig.http.HttpClient.java

/**
 * Disables connection caching./*  w w w .j  a  va 2s. co  m*/
 *
 * @return this HTTP client.
 */
public HttpClient disableConnectionReuse() {
    httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
    return this;
}

From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java

@Override
protected void preStart() {
    final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER);
    final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR);
    final Integer groupId = getConfig(GROUP_ID);
    final Integer templateId = getConfig(TEMPLATE_ID);
    final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS);

    log.info("starting zabbix feed for {}", entity);

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    // TODO for https should we really trust all?
    final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll()
            .clientConnectionManager(new ThreadSafeClientConnManager())
            .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build();

    // Registration job, calls Zabbix host.create API
    final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() {
        @Override//from   w w  w . j ava  2s.c o m
        public HttpToolResponse call() throws Exception {
            if (!registered.get()) {
                // Find the first machine, if available
                Optional<Location> location = Iterables.tryFind(entity.getLocations(),
                        Predicates.instanceOf(MachineLocation.class));
                if (!location.isPresent()) {
                    return null; // Do nothing until location is present
                }
                MachineLocation machine = (MachineLocation) location.get();

                String host = uniqueHostnameGenerator.apply(entity);

                // Select address and port using port-forwarding if available
                String address = entity.getAttribute(Attributes.ADDRESS);
                Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT);
                if (machine instanceof SupportsPortForwarding) {
                    Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR);
                    HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management,
                            port);
                    address = forwarded.getHostText();
                    port = forwarded.getPort();
                }

                // Fill in the JSON template and POST it
                byte[] body = JSON_HOST_CREATE
                        .replace("{{token}}",
                                entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                        .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                        .replace("{{host}}", host).replace("{{ip}}", address)
                        .replace("{{port}}", Integer.toString(port))
                        .replace("{{groupId}}", Integer.toString(groupId))
                        .replace("{{templateId}}", Integer.toString(templateId))
                        .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                        ImmutableMap.of("Content-Type", "application/json"), body);
            }
            return null;
        }
    };

    // The handler for the registration job
    PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() {
        @Override
        public void onSuccess(HttpToolResponse val) {
            if (registered.get() || val == null) {
                return; // Skip if we are registered already or no data from job
            }
            JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject();
            if (response.has("error")) {
                // Parse the JSON error object and log the message
                JsonObject error = response.get("error").getAsJsonObject();
                String message = error.get("message").getAsString();
                String data = error.get("data").getAsString();
                log.warn("zabbix failed registering host - {}: {}", message, data);
            } else if (response.has("result")) {
                // Parse the JSON result object and save the hostId
                JsonObject result = response.get("result").getAsJsonObject();
                String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString();
                // Update the registered status if not set
                if (registered.compareAndSet(false, true)) {
                    entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId);
                    log.info("zabbix registered host as id {}", hostId);
                }
            } else {
                throw new IllegalStateException(String
                        .format("zabbix host registration returned invalid result: %s", response.toString()));
            }
        }

        @Override
        public boolean checkSuccess(HttpToolResponse val) {
            return (val.getResponseCode() == 200);
        }

        @Override
        public void onFailure(HttpToolResponse val) {
            log.warn("zabbix sever returned failure code: {}", val.getResponseCode());
        }

        @Override
        public void onException(Exception exception) {
            log.warn("zabbix exception registering host", exception);
        }

        @Override
        public String toString() {
            return super.toString() + "[" + getDescription() + "]";
        }

        @Override
        public String getDescription() {
            return "Zabbix rest poll";
        }
    };

    // Schedule registration attempt once per second
    getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable

    // Create a polling job for each Zabbix metric
    for (final ZabbixPollConfig<?> config : polls) {
        Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() {
            @Override
            public HttpToolResponse call() throws Exception {
                if (registered.get()) {
                    if (log.isTraceEnabled())
                        log.trace("zabbix polling {} for {}", entity, config);
                    byte[] body = JSON_ITEM_GET
                            .replace("{{token}}",
                                    entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                            .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                            .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID))
                            .replace("{{itemKey}}", config.getItemKey())
                            .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                    return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                            ImmutableMap.of("Content-Type", "application/json"), body);
                } else {
                    throw new IllegalStateException("zabbix agent not yet registered");
                }
            }
        };

        // Schedule the Zabbix polling job
        AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>(
                config, entity, this);
        long minPeriod = Integer.MAX_VALUE; // TODO make configurable
        if (config.getPeriod() > 0)
            minPeriod = Math.min(minPeriod, config.getPeriod());
        getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod);
    }

}

From source file:org.apache.brooklyn.entity.monitoring.zabbix.ZabbixFeed.java

@Override
protected void preStart() {
    final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER);
    final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR);
    final Integer groupId = getConfig(GROUP_ID);
    final Integer templateId = getConfig(TEMPLATE_ID);
    final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS);

    log.info("starting zabbix feed for {}", entity);

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    // TODO for https should we really trust all?
    final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll()
            .clientConnectionManager(new ThreadSafeClientConnManager())
            .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build();

    // Registration job, calls Zabbix host.create API
    final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() {
        @Override/*  ww w  .j av a  2s  .c o m*/
        public HttpToolResponse call() throws Exception {
            if (!registered.get()) {
                // Find the first machine, if available
                Optional<Location> location = Iterables.tryFind(entity.getLocations(),
                        Predicates.instanceOf(MachineLocation.class));
                if (!location.isPresent()) {
                    return null; // Do nothing until location is present
                }
                MachineLocation machine = (MachineLocation) location.get();

                String host = uniqueHostnameGenerator.apply(entity);

                // Select address and port using port-forwarding if available
                String address = entity.getAttribute(Attributes.ADDRESS);
                Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT);
                if (machine instanceof SupportsPortForwarding) {
                    Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR);
                    HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management,
                            port);
                    address = forwarded.getHostText();
                    port = forwarded.getPort();
                }

                // Fill in the JSON template and POST it
                byte[] body = JSON_HOST_CREATE
                        .replace("{{token}}",
                                entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                        .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                        .replace("{{host}}", host).replace("{{ip}}", address)
                        .replace("{{port}}", Integer.toString(port))
                        .replace("{{groupId}}", Integer.toString(groupId))
                        .replace("{{templateId}}", Integer.toString(templateId))
                        .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                        ImmutableMap.of("Content-Type", "application/json"), body);
            }
            return null;
        }
    };

    // The handler for the registration job
    PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() {
        @Override
        public void onSuccess(HttpToolResponse val) {
            if (registered.get() || val == null) {
                return; // Skip if we are registered already or no data from job
            }
            JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject();
            if (response.has("error")) {
                // Parse the JSON error object and log the message
                JsonObject error = response.get("error").getAsJsonObject();
                String message = error.get("message").getAsString();
                String data = error.get("data").getAsString();
                log.warn("zabbix failed registering host - {}: {}", message, data);
            } else if (response.has("result")) {
                // Parse the JSON result object and save the hostId
                JsonObject result = response.get("result").getAsJsonObject();
                String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString();
                // Update the registered status if not set
                if (registered.compareAndSet(false, true)) {
                    entity.sensors().set(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId);
                    log.info("zabbix registered host as id {}", hostId);
                }
            } else {
                throw new IllegalStateException(String
                        .format("zabbix host registration returned invalid result: %s", response.toString()));
            }
        }

        @Override
        public boolean checkSuccess(HttpToolResponse val) {
            return (val.getResponseCode() == 200);
        }

        @Override
        public void onFailure(HttpToolResponse val) {
            log.warn("zabbix sever returned failure code: {}", val.getResponseCode());
        }

        @Override
        public void onException(Exception exception) {
            log.warn("zabbix exception registering host", exception);
        }

        @Override
        public String toString() {
            return super.toString() + "[" + getDescription() + "]";
        }

        @Override
        public String getDescription() {
            return "Zabbix rest poll";
        }
    };

    // Schedule registration attempt once per second
    getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable

    // Create a polling job for each Zabbix metric
    for (final ZabbixPollConfig<?> config : polls) {
        Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() {
            @Override
            public HttpToolResponse call() throws Exception {
                if (registered.get()) {
                    if (log.isTraceEnabled())
                        log.trace("zabbix polling {} for {}", entity, config);
                    byte[] body = JSON_ITEM_GET
                            .replace("{{token}}",
                                    entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                            .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                            .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID))
                            .replace("{{itemKey}}", config.getItemKey())
                            .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                    return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                            ImmutableMap.of("Content-Type", "application/json"), body);
                } else {
                    throw new IllegalStateException("zabbix agent not yet registered");
                }
            }
        };

        // Schedule the Zabbix polling job
        AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>(
                config, entity, this);
        long minPeriod = Integer.MAX_VALUE; // TODO make configurable
        if (config.getPeriod() > 0)
            minPeriod = Math.min(minPeriod, config.getPeriod());
        getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod);
    }

}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }//from ww  w.j  a v a 2 s  .  c  om
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:org.opennms.core.web.HttpClientWrapper.java

public CloseableHttpClient getClient() {
    if (m_httpClient == null) {
        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

        if (!m_reuseConnections) {
            httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
        }//from w w w.  ja v a  2  s . com
        if (m_usePreemptiveAuth) {
            enablePreemptiveAuth(httpClientBuilder);
        }
        if (m_useSystemProxySettings) {
            httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        }
        if (!isEmpty(m_cookieSpec)) {
            requestConfigBuilder.setCookieSpec(m_cookieSpec);
        }
        if (m_cookieStore != null) {
            httpClientBuilder.setDefaultCookieStore(m_cookieStore);
        }
        if (m_username != null) {
            setCredentials(httpClientBuilder, m_username, m_password);
        }
        if (m_socketTimeout != null) {
            requestConfigBuilder.setSocketTimeout(m_socketTimeout);
        }
        if (m_connectionTimeout != null) {
            requestConfigBuilder.setConnectTimeout(m_connectionTimeout);
        }
        if (m_retries != null) {
            httpClientBuilder.setRetryHandler(new HttpRequestRetryOnExceptionHandler(m_retries, false));
        }
        if (m_sslContext.size() != 0) {
            configureSSLContext(httpClientBuilder);
        }
        for (final HttpRequestInterceptor interceptor : m_requestInterceptors) {
            httpClientBuilder.addInterceptorLast(interceptor);
        }
        for (final HttpResponseInterceptor interceptor : m_responseInterceptors) {
            httpClientBuilder.addInterceptorLast(interceptor);
        }
        if (m_useLaxRedirect) {
            httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
        }
        httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
        m_httpClient = httpClientBuilder.build();
    }
    return m_httpClient;
}

From source file:org.rapidoid.http.HttpClient.java

private static CloseableHttpAsyncClient asyncClient(boolean enableCookies, boolean enableRedirects) {
    ConnectionReuseStrategy reuseStrategy = new NoConnectionReuseStrategy();

    HttpAsyncClientBuilder builder = HttpAsyncClients.custom()
            .setThreadFactory(new RapidoidThreadFactory("http-client"));

    if (!enableCookies) {
        builder = builder.disableCookieManagement().disableConnectionState().disableAuthCaching()
                .setConnectionReuseStrategy(reuseStrategy);
    }/*  ww w .j  a va 2s  .  c  o m*/

    if (!enableRedirects) {
        builder = builder.setRedirectStrategy(NO_REDIRECTS);
    }

    return builder.build();
}