Example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity.

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:com.salesmanager.core.module.impl.integration.shipping.UPSQuotesImpl.java

public Collection<ShippingOption> getShippingQuote(ConfigurationResponse config, BigDecimal orderTotal,
        Collection<PackageDetail> packages, Customer customer, MerchantStore store, Locale locale) {

    CoreModuleService cis = null;//from  w w w . j  a va2  s  . co m

    StringBuffer xmlbuffer = new StringBuffer();
    BufferedReader reader = null;
    PostMethod httppost = null;

    try {

        CommonService cservice = (CommonService) ServiceFactory.getService(ServiceFactory.CommonService);

        String countrycode = CountryUtil.getCountryIsoCodeById(store.getCountry());
        cis = cservice.getModule(countrycode, "upsxml");

        if (cis == null) {
            log.error("Can't retreive an integration service [countryid " + store.getCountry()
                    + " ups subtype 1]");
            // throw new
            // Exception("UPS getQuote Can't retreive an integration service");
        }

        MerchantService service = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);

        ConfigurationRequest request_prefs = new ConfigurationRequest(store.getMerchantId(),
                ShippingConstants.MODULE_SHIPPING_RT_PKG_DOM_INT);
        ConfigurationResponse vo_prefs = service.getConfiguration(request_prefs);

        String pack = (String) vo_prefs.getConfiguration("package-upsxml");
        if (pack == null) {
            log.debug("Will assign packaging type 02 to UPS shipping for merchantid " + store.getMerchantId());
            pack = "02";
        }

        ConfigurationRequest request = new ConfigurationRequest(store.getMerchantId(),
                ShippingConstants.MODULE_SHIPPING_RT_CRED);
        ConfigurationResponse vo = service.getConfiguration(request);

        if (vo == null) {
            throw new Exception("ConfigurationVO is null upsxml");
        }

        String xmlhead = getHeader(store.getMerchantId(), vo);

        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>SalesManager Data</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 (storeZone != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            xmldatabuffer.append(storeZone.getZoneCode());// zone code
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(storeCountry.getCountryIsoCode2());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer
                .append(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode()));
        xmldatabuffer.append("</PostalCode></Address></Shipper>");

        // ship to
        xmldatabuffer.append("<ShipTo>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(customer.getCustomerCity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(customer.getCustomerState())) {
        if (customerZone != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            xmldatabuffer.append(customerZone.getZoneCode());// zone code
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(customerCountry.getCountryIsoCode2());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(
                com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode()));
        xmldatabuffer.append("</PostalCode></Address></ShipTo>");
        // xmldatabuffer.append("<Service><Code>11</Code></Service>");

        Iterator packagesIterator = packages.iterator();
        while (packagesIterator.hasNext()) {

            PackageDetail detail = (PackageDetail) packagesIterator.next();
            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(detail.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(detail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Length>");
            xmldatabuffer.append("<Width>");
            xmldatabuffer
                    .append(new BigDecimal(detail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Width>");
            xmldatabuffer.append("<Height>");
            xmldatabuffer
                    .append(new BigDecimal(detail.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());

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

        String data = "";

        IntegrationKeys keys = (IntegrationKeys) config.getConfiguration("upsxml-keys");

        IntegrationProperties props = (IntegrationProperties) config.getConfiguration("upsxml-properties");

        String host = cis.getCoreModuleServiceProdDomain();
        String protocol = cis.getCoreModuleServiceProdProtocol();
        String port = cis.getCoreModuleServiceProdPort();
        String uri = cis.getCoreModuleServiceProdEnv();

        if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) {
            host = cis.getCoreModuleServiceDevDomain();
            protocol = cis.getCoreModuleServiceDevProtocol();
            port = cis.getCoreModuleServiceDevPort();
            uri = cis.getCoreModuleServiceDevEnv();
        }

        HttpClient client = new HttpClient();
        httppost = new PostMethod(protocol + "://" + host + ":" + port + uri);
        RequestEntity entity = new StringRequestEntity(xmlbuffer.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        int result = client.executeMethod(httppost);
        if (result != 200) {
            log.error("Communication Error with ups quote " + result + " " + protocol + "://" + host + ":"
                    + port + uri);
            throw new Exception("UPS quote communication error " + result);
        }
        data = httppost.getResponseBodyAsString();
        log.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",
                com.salesmanager.core.entity.shipping.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())) {
            log.error(
                    "Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError());
            return null;
        }
        if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
            LogMerchantUtil.log(store.getMerchantId(), "Can't process UPS statusCode=" + parsed.getStatusCode()
                    + " message= " + parsed.getError());
            log.error("Can't process UPS statusCode=" + parsed.getStatusCode() + " message= "
                    + parsed.getError());
            return null;
        }

        if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
            log.warn("No options returned from UPS");
            return null;
        }

        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()
                            + "]");
                }
            }
        }
        /**/

        Collection returnColl = null;

        List options = parsed.getOptions();
        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 returnColl;

    } catch (Exception e1) {
        log.error(e1);
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignore) {
            }
        }

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

}

From source file:com.salesmanager.core.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 {

    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }/*from   w  w w  .ja  v a 2s . c o  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();
    PostMethod 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());

        String data = "";

        HttpClient client = new HttpClient();
        httppost = new PostMethod(protocol + "://" + host + ":" + port + url);
        RequestEntity entity = new StringRequestEntity(xmlbuffer.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        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);
        }
        data = httppost.getResponseBodyAsString();
        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:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public EntriesQueryResult listEntries(ListEntriesRequest request) {
    String uri = baseUrl + ENTRIES;
    PutMethod method = new PutMethod(uri);
    try {/*ww  w. j a v  a2  s.  co m*/
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, EntriesQueryResult.class);

        } else {
            throw new RuntimeException("Failed to list transactions, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException("Failed listing entries via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request// w  w  w. ja  va  2  s  .  c om
 ***************************************************************************/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    boolean checkedContent = false;
    boolean legend = false;
    String strErrorMessage = "";
    String serverUrl = request.getParameter("url");
    log.info("POST param serverUrl: " + serverUrl);
    if (serverUrl.startsWith("legend")) {
        serverUrl = serverUrl.replace("legend", "");
        serverUrl = serverUrl.replace("?", "&");
        serverUrl = serverUrl.replaceFirst("&", "?");
        legend = true;
    }
    serverUrl = checkTypeRequest(serverUrl);
    // log.info("serverUrl ckecked: " + serverUrl);
    if (!serverUrl.equals("ERROR")) {
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = null;
            try {
                if (log.isDebugEnabled()) {
                    Enumeration<?> e = request.getHeaderNames();
                    while (e.hasMoreElements()) {
                        String name = (String) e.nextElement();
                        String value = request.getHeader(name);
                        log.debug("request header:" + name + ":" + value);
                    }
                }
                HttpClient client = new HttpClient();
                httppost = new PostMethod(serverUrl);
                // PATH
                httppost.setDoAuthentication(false);
                httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(3, false));
                // FIN_PATH
                // PATH_MAPEAEDITA_SECURITY - AP
                // PATCH_TICKET_MJM-20112405-POST
                String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210
                if (authorizationValue == null) {
                    // The 'Authorization' header must be in this form ->
                    // Authorization: Basic <encodedLogin>
                    // 'encodedLogin' is a string in the form 'user:pass'
                    // that has been encoded by way of the Base64 algorithm.
                    // More info on this can be found at
                    // http://en.wikipedia.org/wiki/Basic_access_authentication
                    String user = (String) request.getSession().getAttribute("user");
                    String pass = (String) request.getSession().getAttribute("pass");
                    if (user != null && pass != null) {
                        String userAndPass = user + ":" + pass;
                        String encodedLogin = new String(
                                org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes()));
                        httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                    } else { // MJM - 20110520
                        String ticketParameter = request.getParameter("ticket");
                        if (ticketParameter != null) {
                            ticketParameter = ticketParameter.trim();
                            if (!ticketParameter.isEmpty()) {
                                Ticket ticket = TicketFactory.createInstance();
                                try {
                                    Map<String, String> props = ticket.getProperties(ticketParameter);
                                    user = props.get("user");
                                    pass = props.get("pass");
                                    String userAndPass = user + ":" + pass;
                                    String encodedLogin = new String(org.apache.commons.codec.binary.Base64
                                            .encodeBase64(userAndPass.getBytes()));
                                    httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                                } catch (Exception e) {
                                    log.info("-------------------------------------------");
                                    log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS");
                                    log.info("METHOD: doPost");
                                    log.info("TICKET VALUE: " + ticketParameter);
                                    log.info("-------------------------------------------");
                                }
                            }
                        }
                    }
                } else {
                    httppost.addRequestHeader(AUTHORIZATION, authorizationValue);
                }
                // FIN_PATH_TICKET_MJM-20112405-POST
                // FIN_PATH_MAPEAEDITA_SECURITY - AP
                String body = inputStreamAsString(request.getInputStream());
                StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null);
                if (0 == httppost.getParameters().length) {
                    log.debug("No Name/Value pairs found ... pushing as received"); // PATCH
                    httppost.setRequestEntity(bodyEntity); // PATCH
                }
                if (log.isDebugEnabled()) {
                    log.debug("Body = " + body);
                    NameValuePair[] nameValuePairs = httppost.getParameters();
                    log.debug("NameValuePairs found: " + nameValuePairs.length);
                    for (int i = 0; i < nameValuePairs.length; ++i) {
                        log.debug("parameters:" + nameValuePairs[i].toString());
                    }
                }
                if (!legend)
                    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
                if (soap) {
                    httppost.addRequestHeader("SOAPAction", serverUrl);
                }
                client.executeMethod(httppost);
                // PATH_FOLLOW_REDIRECT_POST
                int j = 0;
                String redirectLocation;
                Header locationHeader = httppost.getResponseHeader("location");
                while (locationHeader != null && j < numMaxRedirects) {
                    redirectLocation = locationHeader.getValue();
                    // AGG 20111304 Aadimos el cuerpo de la peticin POST a
                    // la nueva peticin redirigida
                    // String bodyPost = httppost.getResponseBodyAsString();
                    StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null);
                    httppost.releaseConnection();
                    httppost = new PostMethod(redirectLocation);
                    // AGG 20110912 Aadidas cabeceras peticin SOAP
                    if (redirectLocation.toLowerCase().contains("wsdl")) {
                        redirectLocation = serverUrl.replace("?wsdl", "");
                        httppost.addRequestHeader("SOAPAction", redirectLocation);
                        httppost.addRequestHeader("Content-type", "text/xml");
                    }
                    httppost.setRequestEntity(bodyEntityPost);
                    client.executeMethod(httppost);
                    locationHeader = httppost.getResponseHeader("location");
                    j++;
                }
                log.info("Number of followed redirections: " + j);
                if (locationHeader != null && j == numMaxRedirects) {
                    log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed.");
                }
                // FIN_PATH_FOLLOW_REDIRECT_POST
                if (log.isDebugEnabled()) {
                    Header[] responseHeaders = httppost.getResponseHeaders();
                    for (int i = 0; i < responseHeaders.length; ++i) {
                        String headerName = responseHeaders[i].getName();
                        String headerValue = responseHeaders[i].getValue();
                        log.debug("responseHeaders:" + headerName + "=" + headerValue);
                    }
                }
                // dump response to out
                if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                    // PATH_SECURITY_PROXY - AG
                    Header[] respHeaders = httppost.getResponseHeaders();
                    int compSize = httppost.getResponseBody().length;
                    ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders));
                    String headersString = headerList.toString();
                    checkedContent = checkContent(headersString, compSize, serverUrl);
                    // FIN_PATH_SECURITY_PROXY - AG
                    if (checkedContent == true) {
                        /*
                         * checks if it has requested an getfeatureinfo to modify the response content
                         * type.
                         */
                        String requesteredUrl = request.getParameter("url");
                        if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/plain");
                        } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("application/gml+xml");
                        } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/html");
                        } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch")
                                || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) {
                            response.setContentType("application/json");
                        } else {
                            response.setContentType("text/xml");
                        }
                        if (legend) {
                            String responseBody = httppost.getResponseBodyAsString();
                            if (responseBody.contains("ServiceExceptionReport")
                                    && serverUrl.contains("LegendGraphic")) {
                                response.sendRedirect("Componente/img/blank.gif");
                            } else {
                                response.setContentLength(responseBody.length());
                                PrintWriter out = response.getWriter();
                                out.print(responseBody);
                                response.flushBuffer();
                            }
                        } else {
                            // Patch_AGG 20112505 Prevents IE cache
                            if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
                                response.setHeader("Pragma", "no-cache");
                            } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
                                response.setHeader("Cache-Control", "no-cache");
                            }
                            response.setDateHeader("Expires", -1);
                            // END patch
                            // Copy request to response
                            InputStream st = httppost.getResponseBodyAsStream();
                            final ServletOutputStream sos = response.getOutputStream();
                            IOUtils.copy(st, sos);
                        }
                    } else {
                        strErrorMessage += errorType;
                        log.error(strErrorMessage);
                    }
                } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    response.addHeader(WWW_AUTHENTICATE,
                            httppost.getResponseHeader(WWW_AUTHENTICATE).getValue());
                } else {
                    strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString())
                            .concat(" ").concat(httppost.getResponseBodyAsString());
                    log.error("Unexpected failure: " + httppost.getStatusLine().toString());
                }
                httppost.releaseConnection();
                // AGG 20110927 Avoid Throwable (change it with exceptions)
            } catch (Exception e) {
                log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e);
            } finally {
                if (httppost != null) {
                    httppost.releaseConnection();
                }
            }
        } else {
            strErrorMessage += "Only HTTP(S) protocol supported";
            log.error("Only HTTP(S) protocol supported");
            // throw new
            // ServletException("only HTTP(S) protocol supported");
        }
    }
    // There are errors.
    if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) {
        if (strErrorMessage.equals("") == true) {
            strErrorMessage = "Error en el parametro url de entrada";
        }
        // String errorXML = strErrorMessage;
        String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage
                + "</descripcion></error>";
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            out.print(errorXML);
            response.flushBuffer();
        } catch (Exception e) {
            log.error(e);
        }
    }
    log.info("-------- End POST method --------");
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

private <T> T executeCreateObject(T newObject, Type returnObjectType, String uri,
        Map<String, String> parameters) throws NiciraNvpApiException {
    String url;/*from  w w w  .  j ava  2 s.c om*/
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    Gson gson = new Gson();

    PostMethod pm = new PostMethod(url);
    pm.setRequestHeader("Content-Type", "application/json");
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), "application/json", null));
    } catch (UnsupportedEncodingException e) {
        throw new NiciraNvpApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
        String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to create object : " + errorMessage);
        throw new NiciraNvpApiException("Failed to create object : " + errorMessage);
    }

    T result;
    try {
        result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
    } catch (IOException e) {
        throw new NiciraNvpApiException("Failed to decode json response body", e);
    } finally {
        pm.releaseConnection();
    }

    return result;
}

From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java

public int addRoleToUserPostMethod(String userOid, String roleOid) throws Exception {
    String returnString = "";
    int result = 0;
    // Get target URL
    String strURLBase = "http://localhost:8080/midpoint/ws/rest/users/";
    String strURL = strURLBase + userOid;

    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    //AUTHENTICATION BY GURER
    //String username = "administrator";
    //String password = "5ecr3t";
    String userPass = this.getUsername() + ":" + this.getPassword();
    String basicAuth = "Basic "
            + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
    post.addRequestHeader("Authorization", basicAuth);

    //construct searching string. place "name" attribute into <values> tags.
    String sendingXml = XML_TEMPLATE_ADD_ROLE_TO_USER;

    sendingXml = sendingXml.replace("<oid></oid>", "<oid>" + userOid + "</oid>");
    sendingXml = sendingXml.replace("oid=\"\"", "oid=\"" + roleOid + "\"");

    RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8");
    post.setRequestEntity(userSearchEntity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {// w  w w.j  ava2s.c om
        result = httpclient.executeMethod(post);
        // Display status code
        //System.out.println("Response status code: " + result);
        // Display response
        //System.out.println("Response body: ");
        // System.out.println(post.getResponseBodyAsString());
        //String sbf = new String(post.getResponseBodyAsString());
        //System.out.println(sbf);

    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }

    return result;
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String registerNewClientWithPredefinedClientId(String clientName, String scope, String redirectUri,
        String clientId, String clientSecret) {
    PostMethod post = new PostMethod(baseOAuth20Uri + APPLICATION_ENDPOINT);
    String response = null;/*from  w  w w.  ja  v a  2  s .  c  o m*/
    try {
        JSONObject json = new JSONObject();
        json.put("name", clientName);
        json.put("description", DEFAULT_DESCRIPTION);
        json.put("scope", scope);
        json.put("redirect_uri", redirectUri);
        json.put("client_id", clientId);
        json.put("client_secret", clientSecret);

        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        post.setRequestEntity(requestEntity);
        response = readResponse(post);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot register new client app", e);
    } catch (JSONException e) {
        log.error("cannot register new client app", e);
    }
    post.releaseConnection();
    return response;
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same content POST
 * data (JSON, XML, etc.) as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a standard POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *///from  ww w. j av a2 s  .c om
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null)
            break;
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    if (contentType.startsWith("text/x-gwt-rpc")) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "")
                + httpServletRequest.getServletPath();
        //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")");
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent);
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

protected String doCreate(String xml, HttpClient httpClient, PostMethod post) throws IOException {
    try {//www .j  a v  a 2  s  .  c o m
        // Prepare HTTP post
        // Request content will be retrieved directly
        // from the input stream
        RequestEntity entity = new StringRequestEntity(xml, "text/xml", "UTF-8");
        post.setRequestEntity(entity);

        logMessage("Issuing POST to " + post.getURI());

        // Execute request
        httpClient.getState().setCredentials(new AuthScope(host, port, null),
                new UsernamePasswordCredentials(username, password));
        setRequestHeaderInfo(post);

        setProxyParameters(httpClient);

        int result = httpClient.executeMethod(post);
        logMessage("POST response code was: " + result);

        // check status
        if (result != HttpStatus.SC_OK) {
            throw new IOException("HTTP POST Failed" + post.getStatusLine());
        }

        String response = inputStreamToString(post.getResponseBodyAsStream());

        if (!isValidResponse(response)) {
            throw new IOException("Create failed with errors: " + getErrors(response));
        }

        return response;
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public void setUserAvatarId(Long userId, String avatarId) {
    String resource = String.format(baseUrl + USER_AVATARID, userId);
    PutMethod method = new PutMethod(resource);
    try {//from   w ww  .j  a v  a2  s.  c o m
        ChangeUserAvatarIdRequest request = new ChangeUserAvatarIdRequest();
        request.setUserAvatarId(avatarId);
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}