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

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

Introduction

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

Prototype

ResponseHandler

Source Link

Usage

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

@Test
public void testAuthentication() throws Exception {
    HttpGet get = new HttpGet("http://example.com/protected");
    HttpContext localContext = new BasicHttpContext();
    List<String> authpref = Collections.singletonList(AuthPolicy.BASIC);
    AuthScope scope = new AuthScope("example.com", -1);
    UsernamePasswordCredentials cred = new UsernamePasswordCredentials("Aladdin", "open sesame");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(scope, cred);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    get.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    BasicHttpResponse unauth = new BasicHttpResponse(_401);
    unauth.setHeader("WWW-Authenticate", "Basic realm=\"insert realm\"");
    responses.add(unauth);/*from  ww  w . ja  v  a 2  s .c o  m*/
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            assertContains("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", asString(response.getEntity()));
            return null;
        }
    }, localContext);
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public IHttpResponse post(String url, ContentType contentType, Map<String, String> params, Header[] headers,
        final String defaultResponseCharset) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {//ww  w .  jav  a 2  s.c  o  m
        RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create()
                .setContentType(contentType)
                .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET
                        : contentType.getCharset().name())
                .setParameters(__doBuildNameValuePairs(params)).build());
        if (headers != null && headers.length > 0) {
            for (Header _header : headers) {
                _reqBuilder.addHeader(_header);
            }
        }
        return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() {

            public IHttpResponse handleResponse(HttpResponse response) throws IOException {
                if (StringUtils.isNotBlank(defaultResponseCharset)) {
                    return new IHttpResponse.NEW(response, defaultResponseCharset);
                }
                return new IHttpResponse.NEW(response);
            }

        });
    } finally {
        _httpClient.close();
    }
}

From source file:com.momock.http.HttpSession.java

public void start(boolean sync) {
    if (state != STATE_WAITING && state != STATE_FINISHED) {
        Logger.warn(url + " is executing.");
        return;// w  w w.  j a va2  s  .co  m
    }
    error = null;
    downloadedLength = 0;
    contentLength = -1;
    if (downloadMode) {
        try {
            request = new HttpGet(url);
        } catch (Exception e) {
            error = e;
            setState(STATE_ERROR);
            setState(STATE_FINISHED);
            return;
        }
        if (file.exists())
            file.delete();
        if (fileData.exists() && fileInfo.exists()) {
            request.setHeader("Range", "bytes=" + fileData.length() + "-");
            downloadedLength = fileData.length();
            readHeaders();
            resetFromHeaders();
        } else {
            try {
                if (fileData.exists())
                    fileData.delete();
                fileData.createNewFile();
                if (fileInfo.exists())
                    fileInfo.delete();
                fileInfo.createNewFile();
            } catch (IOException e) {
                Logger.error(e);
            }
        }
        if (acceptGzip)
            request.setHeader("Accept-Encoding", "gzip");
    }
    if (DEBUG)
        Logger.debug("Request headers of " + url + " : ");
    if (request != null) {
        for (Header header : request.getAllHeaders()) {
            if (DEBUG)
                Logger.debug(header.getName() + " = " + header.getValue());
        }
    }
    setState(STATE_STARTED);
    Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                httpClient.execute(request, new ResponseHandler<Object>() {

                    @Override
                    public Object handleResponse(HttpResponse response) {
                        statusCode = response.getStatusLine().getStatusCode();
                        if (DEBUG)
                            Logger.debug("Response headers of " + url + "[" + statusCode + "] : ");
                        for (Header header : response.getAllHeaders()) {
                            if (DEBUG)
                                Logger.debug(header.getName() + " = " + header.getValue());
                        }

                        headers = new TreeMap<String, List<String>>();
                        for (Header h : response.getAllHeaders()) {
                            String key = h.getName();
                            List<String> vals = null;
                            if (headers.containsKey(key))
                                vals = headers.get(key);
                            else {
                                vals = new ArrayList<String>();
                                headers.put(key, vals);
                            }
                            vals.add(h.getValue());
                        }
                        if (downloadMode) {
                            writeHeaders();
                        }
                        resetFromHeaders();
                        setState(STATE_HEADER_RECEIVED);
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            try {
                                InputStream instream = entity.getContent();
                                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                                if (contentEncoding != null
                                        && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                                    instream = new GZIPInputStream(instream);
                                }
                                InputStream input = new BufferedInputStream(instream);
                                OutputStream output = downloadMode
                                        ? new FileOutputStream(fileData, fileData.exists())
                                        : new ByteArrayOutputStream();

                                byte data[] = new byte[1024 * 10];
                                int count;
                                int percent = -1;
                                while ((count = input.read(data)) != -1) {
                                    downloadedLength += count;
                                    if (contentLength > 0
                                            && downloadedLength * 100 / contentLength != percent) {
                                        percent = (int) (downloadedLength * 100 / contentLength);
                                        setState(STATE_CONTENT_RECEIVING);
                                    }
                                    output.write(data, 0, count);
                                }

                                output.flush();
                                if (!downloadMode)
                                    result = ((ByteArrayOutputStream) output).toByteArray();
                                output.close();
                                instream.close();

                                if (downloadMode) {
                                    if (isDownloaded() || isChunked()) {
                                        if (file.exists())
                                            file.delete();
                                        if (!fileData.renameTo(file))
                                            fileData.delete();
                                        fileInfo.delete();
                                        setState(STATE_CONTENT_RECEIVED);
                                    }
                                } else {
                                    setState(STATE_CONTENT_RECEIVED);
                                }
                            } catch (Exception e) {
                                error = e;
                                Logger.error(e);
                                setState(STATE_ERROR);
                            } finally {
                                setState(STATE_FINISHED);
                            }
                        }
                        return null;
                    }
                });
            } catch (Exception e) {
                error = e;
                Logger.error(e);
                setState(STATE_ERROR);
                setState(STATE_FINISHED);
            }
        };
    };
    if (!sync && asyncTaskService != null)
        asyncTaskService.run(task);
    else
        task.run();
}

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);
    }/*  w  w  w  .  ja  va  2s . 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:jp.mau.twappremover.MainActivity.java

private void getApps() {
    _apps.clear();/*from w w  w  .  j av  a2  s.  c  om*/

    HttpGet request = new HttpGet(APP_PAGE);
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Cookie", "_twitter_sess=" + _session_id + "; auth_token=" + _cookie_auth);

    try {
        String result = _client.execute(request, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    return EntityUtils.toString(response.getEntity(), "UTF-8");
                case HttpStatus.SC_NOT_FOUND:
                    throw new RuntimeException("not found");
                default:
                    throw new RuntimeException("error");
                }
            }
        });

        Document doc = null;
        doc = Jsoup.parse(result);

        // parse top page and get authenticity token
        Elements forms = doc.getElementsByTag("form");
        for (Element e : forms) {
            Elements auths = e.getElementsByAttributeValue("name", "authenticity_token");
            if (auths.size() > 0) {
                _auth_token = auths.get(0).attr("value");
                break;
            }
        }

        Elements apps = doc.getElementsByClass("app");
        for (Element e : apps) {
            LinkedApp app = new LinkedApp();
            if (e.getElementsByTag("strong").size() > 0)
                app.name = e.getElementsByTag("strong").get(0).text();
            if (e.getElementsByClass("creator").size() > 0)
                app.creator = e.getElementsByClass("creator").get(0).text();
            if (e.getElementsByClass("description").size() > 0)
                app.desc = e.getElementsByClass("description").get(0).text();
            if (e.getElementsByClass("app-img").size() > 0)
                app.imgUrl = e.getElementsByClass("app-img").get(0).attr("src");
            if (e.getElementsByClass("revoke").size() > 0) {
                String tmp = e.getElementsByClass("revoke").get(0).attr("id");
                app.revokeId = tmp.replaceAll(KEY_HEADER_REVOKE, "");
            } else {
                // revoke id ????(facebook????????)
                continue;
            }
            _apps.add(app);
        }
        _handler.post(new Runnable() {
            @Override
            public void run() {
                _appadapter.notifyDataSetChanged();
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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 ava 2 s  .co  m*/

    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:ca.sqlpower.matchmaker.enterprise.MatchMakerClientSideSession.java

private DataSourceCollection<JDBCDataSource> getDataSourcesFromServer() {
    ResponseHandler<DataSourceCollection<JDBCDataSource>> plIniHandler = new ResponseHandler<DataSourceCollection<JDBCDataSource>>() {
        public DataSourceCollection<JDBCDataSource> handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {

            if (response.getStatusLine().getStatusCode() == 401) {
                throw new AccessDeniedException("Access Denied");
            }/*from  w  w w.j a  v a2 s  .  c  o m*/

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("Server error while reading data sources: " + response.getStatusLine());
            }

            PlDotIni plIni;
            try {
                plIni = new PlDotIni(ClientSideSessionUtils.getServerURI(projectLocation.getServiceInfo(),
                        "/" + ClientSideSessionUtils.REST_TAG + "/jdbc/")) {

                    @Override
                    public List<UserDefinedSQLType> getSQLTypes() {
                        List<UserDefinedSQLType> types = new ArrayList<UserDefinedSQLType>();
                        types.addAll(delegateSession.getSQLTypes());
                        return types;
                    }

                    public SPDataSource getDataSource(String name) {
                        SPDataSource ds = super.getDataSource(name);
                        if (ds == null) {
                            mergeNewDataSources();
                            return super.getDataSource(name);
                        } else {
                            return ds;
                        }
                    }

                    public <C extends SPDataSource> C getDataSource(String name, java.lang.Class<C> classType) {
                        C ds = super.getDataSource(name, classType);
                        if (ds == null) {
                            mergeNewDataSources();
                            return super.getDataSource(name, classType);
                        } else {
                            return ds;
                        }
                    }

                    private void mergeNewDataSources() {
                        DataSourceCollection<JDBCDataSource> dsc = getDataSourcesFromServer();
                        for (SPDataSource merge : dsc.getConnections()) {
                            mergeDataSource(merge);
                        }
                    }
                };
                plIni.read(response.getEntity().getContent());
                logger.debug("Data source collection has URI " + plIni.getServerBaseURI());
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }

            return new SpecificDataSourceCollection<JDBCDataSource>(plIni, JDBCDataSource.class);
        }
    };

    DataSourceCollection<JDBCDataSource> dsc;
    try {
        dsc = ClientSideSessionUtils.executeServerRequest(outboundHttpClient, projectLocation.getServiceInfo(),
                "/" + ClientSideSessionUtils.REST_TAG + "/data-sources/", plIniHandler);
    } catch (AccessDeniedException e) {
        throw e;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    return dsc;
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public IHttpResponse upload(String url, String fieldName, ContentBody uploadFile, Header[] headers,
        final String defaultResponseCharset) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {/* w  w w  . j a v a 2 s .com*/
        RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url)
                .setEntity(MultipartEntityBuilder.create().addPart(fieldName, uploadFile).build());
        if (headers != null && headers.length > 0) {
            for (Header _header : headers) {
                _reqBuilder.addHeader(_header);
            }
        }
        return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() {

            public IHttpResponse handleResponse(HttpResponse response) throws IOException {
                if (StringUtils.isNotBlank(defaultResponseCharset)) {
                    return new IHttpResponse.NEW(response, defaultResponseCharset);
                }
                return new IHttpResponse.NEW(response);
            }

        });
    } finally {
        _httpClient.close();
    }
}

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

/**
 * Send an HTTP request to the EZID service with a request body (for POST and PUT requests).
 * @param requestType the type of the service as an integer
 * @param uri endpoint to be accessed in the request
 * @param requestBody the String body to be encoded into the body of the request
 * @return byte[] containing the response body
 *///from www  . j a va  2s .c om
private byte[] sendRequest(int requestType, String uri, String requestBody) throws EZIDException {
    HttpUriRequest request = null;
    log.debug("Trying uri: " + uri);
    switch (requestType) {
    case GET:
        request = new HttpGet(uri);
        break;
    case PUT:
        request = new HttpPut(uri);
        if (requestBody != null && requestBody.length() > 0) {
            StringEntity myEntity = new StringEntity(requestBody, "UTF-8");
            ((HttpPut) request).setEntity(myEntity);
        }
        break;
    case POST:
        request = new HttpPost(uri);
        if (requestBody != null && requestBody.length() > 0) {
            StringEntity myEntity = new StringEntity(requestBody, "UTF-8");
            ((HttpPost) request).setEntity(myEntity);
        }
        break;
    case DELETE:
        request = new HttpDelete(uri);
        break;
    default:
        throw new EZIDException("Unrecognized HTTP method requested.");
    }
    request.addHeader("Accept", "text/plain");

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

    try {
        body = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
        throw new EZIDException(e.getMessage());
    } catch (IOException e) {
        throw new EZIDException(e.getMessage());
    }
    return body;
}

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 w  w  .  j  av  a2  s . 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;
}