Example usage for org.apache.http.client ClientProtocolException ClientProtocolException

List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException

Introduction

In this page you can find the example usage for org.apache.http.client ClientProtocolException ClientProtocolException.

Prototype

public ClientProtocolException(final Throwable cause) 

Source Link

Usage

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

public ESearchResult esearch(final String database, final String query, final int retstart, final int retmax)
        throws Exception {
    return httpClient.request(ESEARCH_BASE_URI).post()
            .bodyForm(esearchForm(database, query, retstart, retmax).build())
            .handleResponse(new ResponseHandler<ESearchResult>() {
                @Override/*from  ww w.  j av  a  2  s. c  om*/
                public ESearchResult handleResponse(final HttpResponse response) throws IOException {
                    final StatusLine statusLine = response.getStatusLine();
                    final HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    final ContentType contentType = getOrDefault(entity);
                    final String mimeType = contentType.getMimeType();
                    if (!mimeType.equals(APPLICATION_XML.getMimeType())
                            && !mimeType.equals(TEXT_XML.getMimeType())) {
                        throw new ClientProtocolException("Unexpected content type:" + contentType);
                    }
                    Charset charset = contentType.getCharset();
                    if (charset == null) {
                        charset = HTTP.DEF_CONTENT_CHARSET;
                    }
                    return ESEARCH_XMLB.typeFromInputStream(entity.getContent());
                }
            }, false);
}

From source file:com.thed.zapi.cloud.sample.FetchExecuteUpdate.java

public static String updateExecutions(String uriStr, ZFJCloudRestClient client, String accessKey,
        StringEntity executionJSON) throws URISyntaxException, JSONException, ParseException, IOException {

    URI uri = new URI(uriStr);
    int expirationInSec = 360;
    JwtGenerator jwtGenerator = client.getJwtGenerator();
    String jwt = jwtGenerator.generateJWT("PUT", uri, expirationInSec);
    // System.out.println(uri.toString());
    // System.out.println(jwt);

    HttpResponse response = null;/*from  w  w  w.  jav  a  2s.c  o  m*/
    HttpClient restClient = new DefaultHttpClient();

    HttpPut executeTest = new HttpPut(uri);
    executeTest.addHeader("Content-Type", "application/json");
    executeTest.addHeader("Authorization", jwt);
    executeTest.addHeader("zapiAccessKey", accessKey);
    executeTest.setEntity(executionJSON);

    try {
        response = restClient.execute(executeTest);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();
    // System.out.println(statusCode);
    String executionStatus = "No Test Executed";
    // System.out.println(response.toString());
    HttpEntity entity = response.getEntity();

    if (statusCode >= 200 && statusCode < 300) {
        String string = null;
        try {
            string = EntityUtils.toString(entity);
            JSONObject executionResponseObj = new JSONObject(string);
            JSONObject descriptionResponseObj = executionResponseObj.getJSONObject("execution");
            JSONObject statusResponseObj = descriptionResponseObj.getJSONObject("status");
            executionStatus = statusResponseObj.getString("description");
            System.out.println(executionResponseObj.get("issueKey") + "--" + executionStatus);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {

        try {
            String string = null;
            string = EntityUtils.toString(entity);
            JSONObject executionResponseObj = new JSONObject(string);
            cycleId = executionResponseObj.getString("clientMessage");
            // System.out.println(executionResponseObj.toString());
            throw new ClientProtocolException("Unexpected response status: " + statusCode);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }
    return executionStatus;
}

From source file:de.undercouch.gradle.tasks.download.DownloadAction.java

/**
 * Opens a connection to the given HTTP host and requests a file. Checks
 * the last-modified header on the server if the given timestamp is
 * greater than 0./*from   w  ww. j a va 2  s  .co m*/
 * @param httpHost the HTTP host to connect to
 * @param file the file to request
 * @param timestamp the timestamp of the destination file, in milliseconds
 * @param client the HTTP client to use to perform the request
 * @return the URLConnection
 * @throws IOException if the connection could not be opened
 */
private CloseableHttpResponse openConnection(HttpHost httpHost, String file, long timestamp,
        CloseableHttpClient client) throws IOException {
    //perform preemptive authentication
    HttpClientContext context = null;
    if ((username != null && password != null) || credentials != null) {
        context = HttpClientContext.create();
        AuthScheme as = authScheme;
        if (as == null) {
            as = new BasicScheme();
        }
        Credentials c;
        if (username != null && password != null) {
            if (!(as instanceof BasicScheme) && !(as instanceof DigestScheme)) {
                throw new IllegalArgumentException("If 'username' and "
                        + "'password' are set 'authScheme' must be either " + "'Basic' or 'Digest'.");
            }
            c = new UsernamePasswordCredentials(username, password);
        } else {
            c = credentials;
        }
        addAuthentication(httpHost, c, as, context);
    }

    //create request
    HttpGet get = new HttpGet(file);

    //configure timeouts
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeoutMs)
            .setConnectionRequestTimeout(timeoutMs).setSocketTimeout(timeoutMs).build();
    get.setConfig(config);

    //add authentication information for proxy
    String scheme = httpHost.getSchemeName();
    String proxyHost = System.getProperty(scheme + ".proxyHost");
    String proxyPort = System.getProperty(scheme + ".proxyPort");
    String proxyUser = System.getProperty(scheme + ".proxyUser");
    String proxyPassword = System.getProperty(scheme + ".proxyPassword");
    if (proxyHost != null && proxyPort != null && proxyUser != null && proxyPassword != null) {
        if (context == null) {
            context = HttpClientContext.create();
        }
        int nProxyPort = Integer.parseInt(proxyPort);
        HttpHost proxy = new HttpHost(proxyHost, nProxyPort, scheme);
        Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        addAuthentication(proxy, credentials, null, context);
    }

    //set If-Modified-Since header
    if (timestamp > 0) {
        get.setHeader("If-Modified-Since", DateUtils.formatDate(new Date(timestamp)));
    }

    //set headers
    if (headers != null) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            get.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }

    //enable compression
    if (compress) {
        get.setHeader("Accept-Encoding", "gzip");
    }

    //execute request
    CloseableHttpResponse response = client.execute(httpHost, get, context);

    //handle response
    int code = response.getStatusLine().getStatusCode();
    if ((code < 200 || code > 299) && code != HttpStatus.SC_NOT_MODIFIED) {
        throw new ClientProtocolException(response.getStatusLine().getReasonPhrase());
    }

    return response;
}

From source file:ss.udapi.sdk.services.HttpServices.java

private ResponseHandler<String> getResponseHandler(final int validStatus) {
    return new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int responseStatus = response.getStatusLine().getStatusCode();
            if (responseStatus == validStatus) {
                logger.debug("Http connection status " + responseStatus);
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(
                        "Unexpected http connection response status: " + responseStatus);
            }//ww w .ja v  a  2  s .  c om
        }
    };
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CachingHttpClient.java

/**
 * @param target/* ww  w  .j a  v  a2  s .  c om*/
 *            the target host for the request. Implementations may accept
 *            <code>null</code> if they can still determine a route, for
 *            example to a default target or by inspecting the request.
 * @param request
 *            the request to execute
 * @param context
 *            the context to use for the execution, or <code>null</code> to
 *            use the default context
 * @return the response
 * @throws IOException
 */
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {

    // default response context
    setResponseStatus(context, CacheResponseStatus.CACHE_MISS);

    String via = generateViaHeader(request);

    if (clientRequestsOurOptions(request)) {
        setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
        return new OptionsHttp11Response();
    }

    List<RequestProtocolError> fatalError = requestCompliance.requestIsFatallyNonCompliant(request);

    for (RequestProtocolError error : fatalError) {
        setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
        return requestCompliance.getErrorForRequest(error);
    }

    try {
        request = requestCompliance.makeRequestCompliant(request);
    } catch (ProtocolException e) {
        throw new ClientProtocolException(e);
    }
    request.addHeader("Via", via);

    try {
        responseCache.flushInvalidatedCacheEntriesFor(target, request);
    } catch (IOException ioe) {
        log.warn("Unable to flush invalidated entries from cache", ioe);
    }

    if (!cacheableRequestPolicy.isServableFromCache(request)) {
        return callBackend(target, request, context);
    }

    HttpCacheEntry entry = null;
    try {
        entry = responseCache.getCacheEntry(target, request);
    } catch (IOException ioe) {
        log.warn("Unable to retrieve entries from cache", ioe);
    }
    if (entry == null) {
        cacheMisses.getAndIncrement();
        if (log.isDebugEnabled()) {
            RequestLine rl = request.getRequestLine();
            log.debug("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]");
        }

        if (!mayCallBackend(request)) {
            return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
                    "Gateway Timeout");
        }

        try {
            responseCache.getVariantCacheEntries(target, request);
        } catch (IOException ioe) {
            log.warn("Unable to retrieve variant entries from cache", ioe);
        }

        return callBackend(target, request, context);
    }

    if (log.isDebugEnabled()) {
        RequestLine rl = request.getRequestLine();
        log.debug("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]");

    }
    cacheHits.getAndIncrement();

    Date now = getCurrentDate();
    if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
        final HttpResponse cachedResponse;
        if (request.containsHeader(HeaderConstants.IF_NONE_MATCH)
                || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) {
            cachedResponse = responseGenerator.generateNotModifiedResponse(entry);
        } else {
            cachedResponse = responseGenerator.generateResponse(entry);
        }
        setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
        if (validityPolicy.getStalenessSecs(entry, now) > 0L) {
            cachedResponse.addHeader("Warning", "110 localhost \"Response is stale\"");
        }
        return cachedResponse;
    }

    if (!mayCallBackend(request)) {
        return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout");
    }

    if (validityPolicy.isRevalidatable(entry)) {
        log.debug("Revalidating the cache entry");

        try {
            return revalidateCacheEntry(target, request, context, entry);
        } catch (IOException ioex) {
            if (validityPolicy.mustRevalidate(entry)
                    || (isSharedCache() && validityPolicy.proxyRevalidate(entry))
                    || explicitFreshnessRequest(request, entry, now)) {
                setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
                return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
                        "Gateway Timeout");
            } else {
                final HttpResponse cachedResponse = responseGenerator.generateResponse(entry);
                setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
                cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
                log.debug("111 revalidation failed due to exception: " + ioex);
                return cachedResponse;
            }
        } catch (ProtocolException e) {
            throw new ClientProtocolException(e);
        }
    }
    return callBackend(target, request, context);
}

From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java

public String jsonInvoke(String request) throws BtcException {
    LOG.info("request: " + request);
    String reply = "";
    if (url == null) {
        LOG.severe(BTC4J_DAEMON_DATA_NULL_URL);
        throw new BtcException(BtcException.BTC4J_ERROR_CODE,
                BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_NULL_URL);
    }//from   ww w .  java2 s .  c  o  m
    try (CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(requestConfig).disableAutomaticRetries().build();) {
        HttpPost post = new HttpPost(url.toString());
        post.addHeader(BTC4J_DAEMON_HTTP_HEADER, BTC4J_DAEMON_JSONRPC_CONTENT_TYPE);
        post.setEntity(new StringEntity(request,
                ContentType.create(BTC4J_DAEMON_JSON_CONTENT_TYPE, BTC4J_DAEMON_CHARSET)));
        ResponseHandler<String> handler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine status = response.getStatusLine();
                int code = status.getStatusCode();
                String phrase = status.getReasonPhrase();
                HttpEntity entity = response.getEntity();
                String results = (entity != null) ? EntityUtils.toString(entity) : "";
                if ((code != HttpStatus.SC_OK) && (code != HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
                    LOG.severe(code + " " + phrase);
                    throw new ClientProtocolException(code + " " + phrase);
                }
                return results;
            }
        };
        reply = client.execute(post, handler);
    } catch (IOException e) {
        LOG.severe(String.valueOf(e));
        throw new BtcException(BtcException.BTC4J_ERROR_CODE,
                BtcException.BTC4J_ERROR_MESSAGE + ": " + e.getMessage(), e);
    }
    LOG.info("response: " + reply);
    return reply;
}

From source file:com.salesmanager.core.business.modules.integration.shipping.impl.UPSShippingQuote.java

@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages,
        BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store,
        IntegrationConfiguration configuration, IntegrationModule module,
        ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {

    Validate.notNull(configuration, "IntegrationConfiguration must not be null for USPS shipping module");

    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }/* w w  w.  j  a  v  a 2 s  .c  om*/

    BigDecimal total = orderTotal;

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

    List<ShippingOption> options = null;

    // only applies to Canada and US
    Country country = delivery.getCountry();

    if (!(country.getIsoCode().equals("US") || country.getIsoCode().equals("CA"))) {
        return null;
        //throw new IntegrationException("UPS Not configured for shipping in country " + country.getIsoCode());
    }

    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
        language = Locale.ENGLISH.getLanguage();
    }

    String pack = configuration.getIntegrationOptions().get("packages").get(0);
    Map<String, String> keys = configuration.getIntegrationKeys();

    String accessKey = keys.get("accessKey");
    String userId = keys.get("userId");
    String password = keys.get("password");

    String host = null;
    String protocol = null;
    String port = null;
    String url = null;

    StringBuilder xmlbuffer = new StringBuilder();
    HttpPost httppost = null;
    BufferedReader reader = null;

    try {
        String env = configuration.getEnvironment();

        Set<String> regions = module.getRegionsSet();
        if (!regions.contains(store.getCountry().getIsoCode())) {
            throw new IntegrationException("Can't use the service for store country code ");
        }

        Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
        for (String key : moduleConfigsMap.keySet()) {

            ModuleConfig moduleConfig = (ModuleConfig) moduleConfigsMap.get(key);
            if (moduleConfig.getEnv().equals(env)) {
                host = moduleConfig.getHost();
                protocol = moduleConfig.getScheme();
                port = moduleConfig.getPort();
                url = moduleConfig.getUri();
            }
        }

        StringBuilder xmlreqbuffer = new StringBuilder();
        xmlreqbuffer.append("<?xml version=\"1.0\"?>");
        xmlreqbuffer.append("<AccessRequest>");
        xmlreqbuffer.append("<AccessLicenseNumber>");
        xmlreqbuffer.append(accessKey);
        xmlreqbuffer.append("</AccessLicenseNumber>");
        xmlreqbuffer.append("<UserId>");
        xmlreqbuffer.append(userId);
        xmlreqbuffer.append("</UserId>");
        xmlreqbuffer.append("<Password>");
        xmlreqbuffer.append(password);
        xmlreqbuffer.append("</Password>");
        xmlreqbuffer.append("</AccessRequest>");

        String xmlhead = xmlreqbuffer.toString();

        String weightCode = store.getWeightunitcode();
        String measureCode = store.getSeizeunitcode();

        if (weightCode.equals("KG")) {
            weightCode = "KGS";
        } else {
            weightCode = "LBS";
        }

        String xml = "<?xml version=\"1.0\"?><RatingServiceSelectionRequest><Request><TransactionReference><CustomerContext>Shopizer</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>Rate</RequestAction><RequestOption>Shop</RequestOption></Request>";
        StringBuffer xmldatabuffer = new StringBuffer();

        /**
         * <Shipment>
         * 
         * <Shipper> <Address> <City></City>
         * <StateProvinceCode>QC</StateProvinceCode>
         * <CountryCode>CA</CountryCode> <PostalCode></PostalCode>
         * </Address> </Shipper>
         * 
         * <ShipTo> <Address> <City>Redwood Shores</City>
         * <StateProvinceCode>CA</StateProvinceCode>
         * <CountryCode>US</CountryCode> <PostalCode></PostalCode>
         * <ResidentialAddressIndicator/> </Address> </ShipTo>
         * 
         * <Package> <PackagingType> <Code>21</Code> </PackagingType>
         * <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code>
         * </UnitOfMeasurement> <Weight>1.1</Weight> </PackageWeight>
         * <PackageServiceOptions> <InsuredValue>
         * <CurrencyCode>CAD</CurrencyCode>
         * <MonetaryValue>100</MonetaryValue> </InsuredValue>
         * </PackageServiceOptions> </Package>
         * 
         * 
         * </Shipment>
         * 
         * <CustomerClassification> <Code>03</Code>
         * </CustomerClassification> </RatingServiceSelectionRequest>
         * **/

        /**Map countriesMap = (Map) RefCache.getAllcountriesmap(LanguageUtil
              .getLanguageNumberCode(locale.getLanguage()));
        Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil
              .getLanguageNumberCode(locale.getLanguage()));
                
        Country storeCountry = (Country) countriesMap.get(store
              .getCountry());
                
        Country customerCountry = (Country) countriesMap.get(customer
              .getCustomerCountryId());
                
        int sZone = -1;
        try {
           sZone = Integer.parseInt(store.getZone());
        } catch (Exception e) {
           // TODO: handle exception
        }
                
        Zone storeZone = (Zone) zonesMap.get(sZone);
        Zone customerZone = (Zone) zonesMap.get(customer
              .getCustomerZoneId());**/

        xmldatabuffer.append("<PickupType><Code>03</Code></PickupType>");
        // xmldatabuffer.append("<Description>Daily Pickup</Description>");
        xmldatabuffer.append("<Shipment><Shipper>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(store.getStorecity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(store.getStorestateprovince())) {
        if (store.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            xmldatabuffer.append(store.getZone().getCode());// zone code
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(store.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
        xmldatabuffer.append("</PostalCode></Address></Shipper>");

        // ship to
        xmldatabuffer.append("<ShipTo>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(delivery.getCity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(customer.getCustomerState())) {
        if (delivery.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            xmldatabuffer.append(delivery.getZone().getCode());// zone code
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(delivery.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
        xmldatabuffer.append("</PostalCode></Address></ShipTo>");
        // xmldatabuffer.append("<Service><Code>11</Code></Service>");//TODO service codes (next day ...)

        for (PackageDetails packageDetail : packages) {

            xmldatabuffer.append("<Package>");
            xmldatabuffer.append("<PackagingType>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</PackagingType>");

            // weight
            xmldatabuffer.append("<PackageWeight>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(weightCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Weight>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingWeight()).setScale(1, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Weight>");
            xmldatabuffer.append("</PackageWeight>");

            // dimension
            xmldatabuffer.append("<Dimensions>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(measureCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Length>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Length>");
            xmldatabuffer.append("<Width>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Width>");
            xmldatabuffer.append("<Height>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingHeight()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Height>");
            xmldatabuffer.append("</Dimensions>");
            xmldatabuffer.append("</Package>");

        }

        xmldatabuffer.append("</Shipment>");
        xmldatabuffer.append("</RatingServiceSelectionRequest>");

        xmlbuffer.append(xmlhead).append(xml).append(xmldatabuffer.toString());

        LOGGER.debug("UPS QUOTE REQUEST " + xmlbuffer.toString());

        CloseableHttpClient httpclient = HttpClients.createDefault();
        //HttpClient client = new HttpClient();
        httppost = new HttpPost(protocol + "://" + host + ":" + port + url);

        StringEntity entity = new StringEntity(xmlbuffer.toString(), ContentType.APPLICATION_ATOM_XML);

        //RequestEntity entity = new StringRequestEntity(
        //      xmlbuffer.toString(), "text/plain", "UTF-8");
        httppost.setEntity(entity);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    LOGGER.error("Communication Error with ups quote " + status);
                    throw new ClientProtocolException("UPS quote communication error " + status);
                }
            }

        };

        String data = httpclient.execute(httppost, responseHandler);

        //int result = response.getStatusLine().getStatusCode();
        //int result = client.executeMethod(httppost);
        /*         if (result != 200) {
                    LOGGER.error("Communication Error with ups quote " + result + " "
          + protocol + "://" + host + ":" + port + url);
                    throw new Exception("UPS quote communication error " + result);
                 }*/

        LOGGER.debug("ups quote response " + data);

        UPSParsedElements parsed = new UPSParsedElements();

        Digester digester = new Digester();
        digester.push(parsed);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/Error", "setErrorCode", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/ErrorDescriprion", "setError", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusCode", "setStatusCode",
                0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusDescription",
                "setStatusMessage", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/Error/ErrorDescription", "setError", 0);

        digester.addObjectCreate("RatingServiceSelectionResponse/RatedShipment", ShippingOption.class);
        // digester.addSetProperties(
        // "RatingServiceSelectionResponse/RatedShipment", "sequence",
        // "optionId" );
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionId", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/MonetaryValue",
                "setOptionPriceText", 0);
        //digester
        //      .addCallMethod(
        //            "RatingServiceSelectionResponse/RatedShipment/TotalCharges/CurrencyCode",
        //            "setCurrency", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionCode", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/GuaranteedDaysToDelivery",
                "setEstimatedNumberOfDays", 0);
        digester.addSetNext("RatingServiceSelectionResponse/RatedShipment", "addOption");

        // <?xml
        // version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
        // Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
        // XML document is well formed but the document is not
        // valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>

        Reader xmlreader = new StringReader(data);

        digester.parse(xmlreader);

        if (!StringUtils.isBlank(parsed.getErrorCode())) {

            LOGGER.error(
                    "Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError());
            throw new IntegrationException(parsed.getError());
        }
        if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {

            throw new IntegrationException(parsed.getError());
        }

        if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {

            throw new IntegrationException("No shipping options available for the configuration");
        }

        /*String carrier = getShippingMethodDescription(locale);
        // cost is in CAD, need to do conversion
                
                
        boolean requiresCurrencyConversion = false; String storeCurrency
         = store.getCurrency();
        if(!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) {
         requiresCurrencyConversion = true; }
                 
                
        LabelUtil labelUtil = LabelUtil.getInstance();
        Map serviceMap = com.salesmanager.core.util.ShippingUtil
              .buildServiceMap("upsxml", locale);
                
        *//** Details on whit RT quote information to display **//*
                                                                  MerchantConfiguration rtdetails = config
                                                                  .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
                                                                  int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
                                                                          
                                                                          
                                                                  if (rtdetails != null) {
                                                                          
                                                                  if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
                                                                  // or
                                                                  // not
                                                                  // quotes
                                                                  try {
                                                                  displayQuoteDeliveryTime = Integer.parseInt(rtdetails
                                                                  .getConfigurationValue1());
                                                                          
                                                                  } catch (Exception e) {
                                                                  log.error("Display quote is not an integer value ["
                                                                  + rtdetails.getConfigurationValue1() + "]");
                                                                  }
                                                                  }
                                                                  }*/

        List<ShippingOption> shippingOptions = parsed.getOptions();

        if (shippingOptions != null) {

            Map<String, String> details = module.getDetails();

            for (ShippingOption option : shippingOptions) {

                String name = details.get(option.getOptionCode());
                option.setOptionName(name);
                if (option.getOptionPrice() == null) {
                    String priceText = option.getOptionPriceText();
                    if (StringUtils.isBlank(priceText)) {
                        throw new IntegrationException("Price text is null for option " + name);
                    }

                    try {
                        BigDecimal price = new BigDecimal(priceText);
                        option.setOptionPrice(price);
                    } catch (Exception e) {
                        throw new IntegrationException("Can't convert to numeric price " + priceText);
                    }

                }

            }

        }

        /*         if (options != null) {
                
                    Map selectedintlservices = (Map) config
          .getConfiguration("service-global-upsxml");
                
                    Iterator i = options.iterator();
                    while (i.hasNext()) {
                       ShippingOption option = (ShippingOption) i.next();
                       // option.setCurrency(store.getCurrency());
                       StringBuffer description = new StringBuffer();
                
                       String code = option.getOptionCode();
                       option.setOptionCode(code);
                       // get description
                       String label = (String) serviceMap.get(code);
                       if (label == null) {
          log
                .warn("UPSXML cannot find description for service code "
                      + code);
                       }
                
                       option.setOptionName(label);
                
                       description.append(option.getOptionName());
                       if (displayQuoteDeliveryTime == ShippingConstants.DISPLAY_RT_QUOTE_TIME) {
          if (!StringUtils.isBlank(option
                .getEstimatedNumberOfDays())) {
             description.append(" (").append(
                   option.getEstimatedNumberOfDays()).append(
                   " ").append(
                   labelUtil.getText(locale,
                         "label.generic.days.lowercase"))
                   .append(")");
          }
                       }
                       option.setDescription(description.toString());
                
                       // get currency
                       if (!option.getCurrency().equals(store.getCurrency())) {
          option.setOptionPrice(CurrencyUtil.convertToCurrency(
                option.getOptionPrice(), option.getCurrency(),
                store.getCurrency()));
                       }
                
                       if (!selectedintlservices.containsKey(option
             .getOptionCode())) {
          if (returnColl == null) {
             returnColl = new ArrayList();
          }
          returnColl.add(option);
          // options.remove(option);
                       }
                
                    }
                
                    if (options.size() == 0) {
                       LogMerchantUtil
             .log(
                   store.getMerchantId(),
                   " none of the service code returned by UPS ["
                         + selectedintlservices
                               .keySet()
                               .toArray(
                                     new String[selectedintlservices
                                           .size()])
                         + "] for this shipping is in your selection list");
                    }
                 }*/

        return shippingOptions;

    } catch (Exception e1) {
        LOGGER.error("UPS quote error", e1);
        throw new IntegrationException(e1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignore) {
            }
        }

        if (httppost != null) {
            httppost.releaseConnection();
        }
    }
}

From source file:org.vietspider.net.client.impl.AbstractHttpClient.java

public final HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {

    if (request == null) {
        throw new IllegalArgumentException("Request must not be null.");
    }//ww w.ja  v  a  2  s. co  m
    // a null target may be acceptable, this depends on the route planner
    // a null context is acceptable, default context created below

    HttpContext execContext = null;
    RequestDirector director = null;

    // Initialize the request execution context making copies of 
    // all shared objects that are potentially threading unsafe.
    synchronized (this) {

        HttpContext defaultContext = createHttpContext();
        if (context == null) {
            execContext = defaultContext;
        } else {
            execContext = new DefaultedHttpContext(context, defaultContext);
        }
        // Create a director for this request
        director = createClientRequestDirector(getRequestExecutor(), getConnectionManager(),
                getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(),
                getHttpProcessor().copy(), getHttpRequestRetryHandler(), getRedirectHandler(),
                getTargetAuthenticationHandler(), getProxyAuthenticationHandler(), getUserTokenHandler(),
                determineParams(request));
    }

    try {
        return director.execute(target, request, execContext);
    } catch (HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}

From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java

private Integer doRequest(final HttpRequestBase request)
        throws ClientProtocolException, IOException, InterruptedException {
    final CountDownLatch waitForCompletion = new CountDownLatch(1);

    final URI uri = request.getURI();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin"));
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);//from w ww  .  j ava  2s  . c o  m

    final CloseableHttpClient client = HttpClients.createDefault();

    final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() {
        @Override
        public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            try {
                final int status = response.getStatusLine().getStatusCode();
                // 400 because we return that if you try to delete something that is already deleted
                // 404 because it's OK if it's already not there
                if (status >= 200 && status < 300 || status == 400 || status == 404) {
                    EntityUtils.consume(response.getEntity());
                    return status;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            } finally {
                waitForCompletion.countDown();
            }
        }
    };

    final Integer status = client.execute(targetHost, request, responseHandler, context);

    waitForCompletion.await();
    client.close();
    return status;
}