Example usage for org.apache.commons.digester Digester parse

List of usage examples for org.apache.commons.digester Digester parse

Introduction

In this page you can find the example usage for org.apache.commons.digester Digester parse.

Prototype

public Object parse(URL url) throws IOException, SAXException 

Source Link

Document

Parse the content of the specified URL using this Digester.

Usage

From source file:at.tuwien.minimee.registry.MiniMeeRegistry.java

/**
 * Trashes current registry information and loads the information of the XML file, which is provided
 * by the input stream <param>config</config>.
 * //from   ww  w . j a  v a  2  s.  com
 *  @throws PlatoServiceException if the stream can't be parsed. 
 */
public void reloadFrom(String configFile) throws PlatoServiceException {
    Digester d = new Digester();
    d.setValidating(false);
    StrictErrorHandler errorHandler = new StrictErrorHandler();
    d.setErrorHandler(errorHandler);
    d.setClassLoader(PreservationActionServiceFactory.class.getClassLoader());

    services.clear();

    d.push(services);
    d.addFactoryCreate("*/preservationActionService", PreservationActionServiceFactory.class);
    d.addSetNext("*/preservationActionService", "add");
    d.addCallMethod("*/preservationActionService/name", "setName", 0);
    d.addCallMethod("*/preservationActionService/description", "setDescription", 0);
    d.addCallMethod("*/preservationActionService/descriptor", "setDescriptor", 0);

    d.addObjectCreate("*/preservationActionService/sourceFormats", ArrayList.class);
    d.addSetNext("*/preservationActionService/sourceFormats", "setSourceFormats");

    d.addObjectCreate("*/preservationActionService/sourceFormats/format", FormatInfo.class);
    d.addBeanPropertySetter("*/format/puid", "puid");
    d.addBeanPropertySetter("*/format/name", "name");
    d.addBeanPropertySetter("*/format/extension", "defaultExtension");
    d.addSetNext("*/preservationActionService/sourceFormats/format", "add");

    d.addObjectCreate("*/preservationActionService/targetFormat", FormatInfo.class);
    d.addBeanPropertySetter("*/targetFormat/puid", "puid");
    d.addBeanPropertySetter("*/targetFormat/name", "name");
    d.addBeanPropertySetter("*/targetFormat/extension", "defaultExtension");
    d.addSetNext("*/preservationActionService/targetFormat", "setTargetFormat");

    d.addCallMethod("*/preservationActionService/url", "setUrl", 0);

    d.addObjectCreate("*/preservationActionService/externalInfo", ArrayList.class);
    d.addSetNext("*/preservationActionService/externalInfo", "setExternalInfo");
    d.addCallMethod("*/preservationActionService/externalInfo/url", "add", 0);

    try {
        InputStream config = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFile);

        d.parse(config);
    } catch (IOException e) {
        throw new PlatoServiceException("Could not read registry data.", e);
    } catch (SAXException e) {
        throw new PlatoServiceException("Could not read registry data.", e);
    }
}

From source file:hr.fer.zemris.vhdllab.applets.editor.schema2.predefined.PredefinedComponentsParser.java

private PredefinedConf parseConfiguration() {
    Digester digester = new Digester();
    digester.setValidating(false);/*from ww  w . j av  a2  s  . c  om*/
    digester.addObjectCreate("componentList", PredefinedConf.class);
    digester.addObjectCreate("componentList/component", PredefinedComponent.class);
    digester.addBeanPropertySetter("componentList/component/componentName");
    digester.addBeanPropertySetter("componentList/component/codeFileName");
    digester.addBeanPropertySetter("componentList/component/drawerName");
    digester.addBeanPropertySetter("componentList/component/categoryName");
    digester.addBeanPropertySetter("componentList/component/preferredName");
    digester.addBeanPropertySetter("componentList/component/genericComponent");

    digester.addObjectCreate("componentList/component/parameterList/parameter", ParameterWrapper.class);
    digester.addBeanPropertySetter("componentList/component/parameterList/parameter/generic");
    digester.addBeanPropertySetter("componentList/component/parameterList/parameter/paramType");
    digester.addBeanPropertySetter("componentList/component/parameterList/parameter/name");
    digester.addBeanPropertySetter("componentList/component/parameterList/parameter/value");
    digester.addBeanPropertySetter("componentList/component/parameterList/parameter/allowedValues");
    digester.addBeanPropertySetter("componentList/component/parameterList/parameter/eventName");
    digester.addSetNext("componentList/component/parameterList/parameter", "addParameter");

    digester.addObjectCreate("componentList/component/portList/port", PortWrapper.class);
    digester.addBeanPropertySetter("componentList/component/portList/port/name");
    digester.addBeanPropertySetter("componentList/component/portList/port/orientation");
    digester.addBeanPropertySetter("componentList/component/portList/port/direction");
    digester.addBeanPropertySetter("componentList/component/portList/port/type");
    digester.addBeanPropertySetter("componentList/component/portList/port/vectorAscension");
    digester.addBeanPropertySetter("componentList/component/portList/port/lowerBound");
    digester.addBeanPropertySetter("componentList/component/portList/port/upperBound");
    digester.addSetNext("componentList/component/portList/port", "addPort");

    digester.addSetNext("componentList/component", "addPredefinedComponent");

    try {
        return (PredefinedConf) digester.parse(reader);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.sf.j2ep.ConfigParser.java

/**
 * Creates the rules.// w  ww. j a v  a2s  .  c  o m
 * 
 * @return The rules all put into a rule chain
 */
private LinkedList createServerList(File data) throws Exception {
    Digester digester = new Digester();
    digester.setUseContextClassLoader(true);

    // Construct server list
    digester.addObjectCreate("config", LinkedList.class);

    // Create servers
    digester.addObjectCreate("config/server", null, "className");
    digester.addSetProperties("config/server");
    // Create rule
    digester.addObjectCreate("config/server/rule", null, "className");
    digester.addSetProperties("config/server/rule");
    digester.addSetNext("config/server/rule", "setRule");
    // Create composite rule
    digester.addObjectCreate("config/server/composite-rule", null, "className");
    digester.addSetProperties("config/server/composite-rule");
    digester.addObjectCreate("config/server/composite-rule/rule", null, "className");
    digester.addSetProperties("config/server/composite-rule/rule");
    digester.addSetNext("config/server/composite-rule/rule", "addRule");
    digester.addSetNext("config/server/composite-rule", "setRule");
    // Add server to list
    digester.addSetNext("config/server", "add");

    // Create cluster servers
    digester.addObjectCreate("config/cluster-server", null, "className");
    digester.addSetProperties("config/cluster-server");
    // Create the servers in this cluster
    digester.addCallMethod("config/cluster-server/server", "addServer", 2);
    digester.addCallParam("config/cluster-server/server", 0, "domainName");
    digester.addCallParam("config/cluster-server/server", 1, "path");
    // Create rule
    digester.addObjectCreate("config/cluster-server/rule", null, "className");
    digester.addSetProperties("config/cluster-server/rule");
    digester.addSetNext("config/cluster-server/rule", "setRule");
    // Create composite rule
    digester.addObjectCreate("config/cluster-server/composite-rule", null, "className");
    digester.addSetProperties("config/cluster-server/composite-rule");
    digester.addObjectCreate("config/cluster-server/composite-rule/rule", null, "className");
    digester.addSetProperties("config/cluster-server/composite-rule/rule");
    digester.addSetNext("config/cluster-server/composite-rule/rule", "addRule");
    digester.addSetNext("config/cluster-server/composite-rule", "setRule");

    // Add server to list
    digester.addSetNext("config/cluster-server", "add");

    return (LinkedList) digester.parse(data);
}

From source file:net.sibcolombia.sibsp.model.factory.VocabularyFactory.java

/**
 * Builds a Vocabulary from the supplied input stream
 * /*  w  ww  . ja  va 2 s  .  c  o m*/
 * @param is For the XML
 * @return The extension
 */
public Vocabulary build(InputStream is) throws IOException, SAXException, ParserConfigurationException {
    Digester digester = new Digester(saxf.newSAXParser());
    digester.setNamespaceAware(true);
    digester.setXIncludeAware(false);
    digester.setRuleNamespaceURI(VOCABULARY_NAMESPACE);

    Vocabulary tv = new Vocabulary();
    digester.push(tv);

    // build the thesaurus
    digester.addCallMethod("*/thesaurus", "setTitle", 1);
    digester.addRule("*/thesaurus", new CallParamNoNSRule(0, "title"));

    digester.addCallMethod("*/thesaurus", "setDescription", 1);
    digester.addRule("*/thesaurus", new CallParamNoNSRule(0, "description"));

    digester.addCallMethod("*/thesaurus", "setLink", 1);
    digester.addRule("*/thesaurus", new CallParamNoNSRule(0, "relation"));

    digester.addCallMethod("*/thesaurus", "setUriString", 1);
    digester.addRule("*/thesaurus", new CallParamNoNSRule(0, "URI"));

    // build the concept
    digester.addObjectCreate("*/concept", VocabularyConcept.class);

    digester.addCallMethod("*/concept", "setLink", 1);
    digester.addRule("*/concept", new CallParamNoNSRule(0, "relation"));

    digester.addCallMethod("*/concept", "setDescription", 1);
    digester.addRule("*/concept", new CallParamNoNSRule(0, "description"));

    digester.addCallMethod("*/concept", "setUri", 1);
    digester.addRule("*/concept", new CallParamNoNSRule(0, "URI"));

    digester.addCallMethod("*/concept", "setIdentifier", 1);
    digester.addRule("*/concept", new CallParamNoNSRule(0, "identifier"));

    // build the terms
    digester.addObjectCreate("*/preferred/term", VocabularyTerm.class);

    digester.addCallMethod("*/preferred/term", "setLang", 1);
    digester.addRule("*/preferred/term", new CallParamNoNSRule(0, "lang"));

    digester.addCallMethod("*/preferred/term", "setTitle", 1);
    digester.addRule("*/preferred/term", new CallParamNoNSRule(0, "title"));

    digester.addSetNext("*/preferred/term", "addPreferredTerm");

    // build alternative terms
    digester.addObjectCreate("*/alternative/term", VocabularyTerm.class);

    digester.addCallMethod("*/alternative/term", "setLang", 1);
    digester.addRule("*/alternative/term", new CallParamNoNSRule(0, "lang"));

    digester.addCallMethod("*/alternative/term", "setTitle", 1);
    digester.addRule("*/alternative/term", new CallParamNoNSRule(0, "title"));

    digester.addSetNext("*/alternative/term", "addAlternativeTerm");

    // add concept
    digester.addSetNext("*/concept", "addConcept");

    digester.parse(is);
    return tv;
}

From source file:com.salesmanager.core.module.impl.integration.payment.AuthorizeNetTransactionImpl.java

public List<SalesManagerTransactionVO> retreiveTransactions(int merchantid, Order order) throws Exception {

    long orderid = order.getOrderId();
    TransactionHelper trxhelper = new TransactionHelper();
    List trxs = trxhelper.getSentData(merchantid, orderid);

    if (trxs == null) {
        return null;
    }//  w ww  . j  av a2s .  c  o m

    Iterator i = trxs.iterator();

    List returnlist = new ArrayList();

    while (i.hasNext()) {

        MerchantPaymentGatewayTrx trx = (MerchantPaymentGatewayTrx) i.next();

        AuthorizeNetParsedElements elems = new AuthorizeNetParsedElements();

        // $xmlresponse = '<?xml version="1.0"
        // encoding="UTF-8"?><transaction><responsecode>' . $response[0] .
        // '</responsecode><responsesubcode>' . $response[1] .
        // '</responsesubcode><reasoncode>' . $response[2] .
        // '</reasoncode><reasontext>' . $response[3] .
        // '</reasontext><approvalcode>' . $response[4] .
        // '</approvalcode><transactionid>' . $response[6] .
        // '</transactionid><transaction>';

        // we want to set
        // Response Sub Code
        // Approval Code

        Digester digester = new Digester();
        digester.push(elems);

        // <?xml version="1.0"
        // encoding="UTF-8"?><transaction><amount>58.00</amount><responsecode>1</responsecode><responsesubcode>1</responsesubcode><reasoncode>1</reasoncode><reasontext>(TESTMODE)
        // This transaction has been
        // approved.</reasontext><approvalcode>000000</approvalcode><transactionid>0</transactionid><originalresponse><![CDATA[1=1&2=1&3=1&4=%28TESTMODE%29+This+transaction+has+been+approved.&5=000000&6=P&7=0&8=43W2X558321209516732&9=Montreal+Canadian+T-Shirt%28qty%3A+1%29&10=58.00&11=CC&12=auth_only&13=43&14=dqwcqwdcqwdcqwc+AN+PA&15=dcqecwqedc&16=&17=368+Du+Languedoc&18=Boucherville&19=Quebec&20=j4b8j9&21=Canada&22=4445556666&23=&24=carl%40csticonsulting.com&25=dqwcqwdcqwdcqwc+AN+PA&26=dcqecwqedc&27=&28=368+Du+Languedoc&29=Boucherville&30=Quebec&31=j4b8j9&32=Canada&33=&34=&35=&36=&37=&38=44655B6E5FB3B458A37B93130899374E&39=&40=&41=&42=&43=&44=&45=&46=&47=&48=&49=&50=&51=&52=&53=&54=&55=&56=&57=&58=&59=&60=&61=&62=&63=&64=&65=&66=&67=&68=&69=April+29+2008+8%3A52+pm&70=127.0.0.1&71=cdd69664aea1f46998818d83f9b5a87a&]]></originalresponse></transaction>

        digester.addCallMethod("transaction/transactionid", "setTransactionId", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/responsecode", "setResponseCode", 0);
        digester.addCallMethod("transaction/amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/reasontext", "setReasontext", 0);

        Reader reader = new StringReader(trx.getMerchantPaymentGwReceived());

        digester.parse(reader);

        GatewayTransactionVO mtrx = new GatewayTransactionVO();

        mtrx.setOrderID(String.valueOf(orderid));
        mtrx.setInternalGatewayOrderId(elems.getApprovalCode());// returned
        // by
        // authorize
        // net
        mtrx.setTransactionID(elems.getTransactionId());// created by sales
        // manager
        mtrx.setTransactionDetails(trx);
        mtrx.setType(Integer.parseInt(trx.getMerchantPaymentGwAuthtype()));
        mtrx.setAmount(new BigDecimal(elems.getTransactionAmount()));
        returnlist.add(mtrx);

    }
    return returnlist;
}

From source file:net.sibcolombia.sibsp.model.factory.ExtensionFactory.java

/**
 * Builds an extension from the supplied input stream.
 * /*  w  w w .  j  a  v a 2  s.  com*/
 * @param is For the XML
 * @return The extension
 */
public Extension build(InputStream is) throws IOException, SAXException, ParserConfigurationException {

    // in order to deal with arbitrary namespace prefixes we need to parse namespace aware!
    Digester digester = new Digester(saxf.newSAXParser());
    digester.setRuleNamespaceURI(EXTENSION_NAMESPACE);

    Extension e = new Extension();
    digester.push(e);

    digester.addCallMethod("*/extension", "setTitle", 1);
    digester.addRule("*/extension", new CallParamNoNSRule(0, "title"));

    digester.addCallMethod("*/extension", "setName", 1);
    digester.addCallParam("*/extension", 0, "name");

    digester.addCallMethod("*/extension", "setNamespace", 1);
    digester.addCallParam("*/extension", 0, "namespace");

    digester.addCallMethod("*/extension", "setRowType", 1);
    digester.addCallParam("*/extension", 0, "rowType");

    digester.addCallMethod("*/extension", "setLink", 1);
    digester.addRule("*/extension", new CallParamNoNSRule(0, "relation"));

    digester.addCallMethod("*/extension", "setDescription", 1);
    digester.addRule("*/extension", new CallParamNoNSRule(0, "description"));

    digester.addCallMethod("*/extension", "setSubject", 1);
    digester.addRule("*/extension", new CallParamNoNSRule(0, "subject"));

    // build the properties
    digester.addObjectCreate("*/property", ExtensionProperty.class);

    digester.addCallMethod("*/property", "setQualname", 1);
    digester.addCallParam("*/property", 0, "qualName");

    digester.addCallMethod("*/property", "setName", 1);
    digester.addCallParam("*/property", 0, "name");

    digester.addCallMethod("*/property", "setNamespace", 1);
    digester.addCallParam("*/property", 0, "namespace");

    digester.addCallMethod("*/property", "setGroup", 1);
    digester.addCallParam("*/property", 0, "group");

    digester.addCallMethod("*/property", "setRequired", 1);
    digester.addCallParam("*/property", 0, "required");

    digester.addCallMethod("*/property", "setLink", 1);
    digester.addRule("*/property", new CallParamNoNSRule(0, "relation"));

    digester.addCallMethod("*/property", "setDescription", 1);
    digester.addRule("*/property", new CallParamNoNSRule(0, "description"));

    digester.addCallMethod("*/property", "setExamples", 1);
    digester.addCallParam("*/property", 0, "examples");

    digester.addCallMethod("*/property", "setType", 1);
    digester.addCallParam("*/property", 0, "type");

    // This is a special rule that will use the url2ThesaurusMap
    // to set the Vocabulary based on the attribute "thesaurus"
    digester.addRule("*/property", thesaurusRule);

    digester.addSetNext("*/property", "addProperty");

    digester.parse(is);

    return e;
}

From source file:at.tuwien.minimee.registry.ToolRegistry.java

private void load(InputStream config) throws IllegalArgumentException {
    Digester digester = new Digester();
    digester.setValidating(true);//from  w w w .j  ava  2 s. co  m
    digester.setErrorHandler(new StrictErrorHandler());

    digester.push(this);
    digester.addObjectCreate("*/tool", Tool.class);
    digester.addSetProperties("*/tool");

    digester.addObjectCreate("*/config", ToolConfig.class);
    digester.addSetProperties("*/config");
    digester.addBeanPropertySetter("*/config/name", "name");
    digester.addBeanPropertySetter("*/config/executablePath", "executablePath");
    digester.addBeanPropertySetter("*/config/engineName", "engine");
    digester.addBeanPropertySetter("*/config/params", "params");
    digester.addBeanPropertySetter("*/config/inEnding", "inEnding");
    digester.addBeanPropertySetter("*/config/outEnding", "outEnding");
    digester.addBeanPropertySetter("*/config/noOutFile", "noOutFile");
    digester.addBeanPropertySetter("*/config/initialisationDir", "initialisationDir");
    digester.addCallMethod("*/config/evaluators/evaluator", "addEvaluator", 0);

    digester.addSetNext("*/config", "addConfig");
    digester.addSetNext("*/tool", "addTool");

    digester.addFactoryCreate("*/evaluators/evaluator", EvaluatorFactory.class);
    digester.addSetProperties("*/evaluators/evaluator");
    digester.addSetNext("*/evaluators/evaluator", "addEvaluator");

    //Digester engineDigester = new Digester();
    //        engineDigester.setValidating(true);
    //        engineDigester.setErrorHandler(new StrictErrorHandler());
    //        engineDigester.push(this);
    digester.addFactoryCreate("*/engine", EngineFactory.class);
    digester.addSetProperties("*/engine");
    digester.addObjectCreate("*/measurableProperties/property", MeasurableProperty.class);
    digester.addSetProperties("*/measurableProperties/property");

    addCreateScale(digester, PositiveFloatScale.class);
    addCreateScale(digester, FreeStringScale.class);

    digester.addSetNext("*/measurableProperties/property", "addProperty");
    digester.addCallMethod("*/includedEngine", "addEngineName", 0);
    digester.addCallMethod("*/nextEngine", "setNextEngineName", 0);

    digester.addSetNext("*/engine", "addEngine");

    digester.addObjectCreate("*/machine", Machine.class);
    digester.addSetProperties("*/machine");
    digester.addSetNext("*/machine", "addMachine");
    try {

        digester.setUseContextClassLoader(true);
        digester.setValidating(false);
        digester.parse(config);

        //            config = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFile);
        //            engineDigester.setValidating(false);
        //            engineDigester.setUseContextClassLoader(true);            
        //            engineDigester.parse(config);

    } catch (Exception e) {
        log.error("Error in config file! ", e);
    }
}

From source file:eu.planets_project.pp.plato.services.characterisation.jhove.JHove.java

/**
 * Extract the JHoveFileProperty from the String and returns a
 * {@link JHoveFileProperty} class.//from w  ww .ja v  a  2  s.  c  o m
 * 
 * @param fileName
 * @return
 */
public JHoveFileProperty digestString(String stringToDigest) {
    Digester digester = null;
    try {

        digester = new Digester();
        digester.setValidating(false);

        StrictErrorHandler errorHandler = new StrictErrorHandler();
        digester.setErrorHandler(errorHandler);

        digester.setUseContextClassLoader(true);

        digester.addObjectCreate("jhove", JHoveFileProperty.class);
        // GENERAL INFOS
        digester.addBeanPropertySetter("jhove/date", "extractionDate");
        digester.addSetProperties("jhove/repInfo/uri", "fileURI", "uri");
        digester.addBeanPropertySetter("jhove/repInfo/size", "fileSize");
        digester.addBeanPropertySetter("jhove/repInfo/format", "format");
        digester.addBeanPropertySetter("jhove/repInfo/version", "version");
        digester.addBeanPropertySetter("jhove/repInfo/status", "status");
        digester.addBeanPropertySetter("jhove/repInfo/mimeType", "mimetype");
        digester.addBeanPropertySetter("jhove/repInfo/sigMatch/module", "jhoveModuleName");
        // OBJECT: MODULE - START
        digester.addObjectCreate("jhove/repInfo/reportingModule", Module.class);
        digester.addSetProperties("jhove/repInfo/reportingModule", "release", "release");
        digester.addSetProperties("jhove/repInfo/reportingModule", "date", "date");
        digester.addBeanPropertySetter("jhove/repInfo/reportingModule", "name");
        digester.addSetNext("jhove/repInfo/reportingModule", "setModule");
        // OBJECT: MODULE - END

        // OBJECT: PROFILES - START
        digester.addObjectCreate("jhove/repInfo/profiles", Vector.class);

        // OBJECT: PROFILE - START
        digester.addCallMethod("jhove/repInfo/profiles/profile", "add", 1);
        digester.addCallParam("jhove/repInfo/profiles/profile", 0);

        digester.addSetNext("jhove/repInfo/profiles", "setProfiles");
        // OBJECT: PROFILES- END

        // OBJECT: PROPERTIES - START
        digester.addObjectCreate("jhove/repInfo/properties", Vector.class);

        // OBJECT: PROPERTY - START
        digester.addObjectCreate("*/property/", Property.class);
        digester.addBeanPropertySetter("*/property/name", "name");
        digester.addSetProperties("*/property/values", "type", "type");

        digester.addObjectCreate("*/property/values", Vector.class);
        digester.addCallMethod("*/property/values/value", "add", 1);
        digester.addCallParam("*/property/values/value", 0);

        digester.addSetNext("*/property/values", "setValues");

        // OBJECT: PROPERTY - END
        digester.addSetNext("*/property/", "add");

        digester.addSetNext("jhove/repInfo/properties", "setProperties");

        Object jhoveFileProp = digester.parse(new StringReader(stringToDigest));

        if (jhoveFileProp instanceof JHoveFileProperty)
            return (JHoveFileProperty) jhoveFileProp;
        else
            return null;

    } catch (Exception exc) {
        log.error("error happened while digesting the following jhove string \n====================\n"
                + stringToDigest);
        log.error("could not digest jhove results. error: " + exc.getMessage(), exc);
        return null;
    } finally {
        digester.clear();
    }
}

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;/*ww  w  .  j  a va2 s  .c  o  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;
    }//  w  w  w  . j a  v a 2  s  . com

    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();
        }
    }
}