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:net.java.dev.weblets.impl.WebletContainerImpl.java

/**
 * registers the configuration file//from ww  w .  j  a  v  a2  s.  c  o  m
 * in its internal data structure
 *
 * @param webletsConfig the weblets config to be registered
 */
public void registerConfig(URL webletsConfig) {
    try {
        InputStream in = webletsConfig.openStream();
        try {
            Digester digester = new Digester();
            digester.setClassLoader(getLoader());
            digester.setValidating(false);
            digester.setClassLoader(getLoader());

            digester.setEntityResolver(DisconnectedEntityResolver.sharedInstance());
            digester.push(this);
            digester.addFactoryCreate(Const.WEBLETS_CONFIG + Const.PAR_WEBLET, WEBLET_CONFIG_FACTORY);
            digester.addSetNext(Const.WEBLETS_CONFIG + Const.PAR_WEBLET, "addWeblet",
                    WebletConfigImpl.class.getName());
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_WEBLET_NAME,
                    "setWebletName", Const.FIRST_PARAM);
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_WEBLET_CLASS,
                    "setWebletClass", Const.FIRST_PARAM);
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_WEBLET_VERSION,
                    "setWebletVersion", Const.FIRST_PARAM);
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_INIT_PARAM,
                    "addInitParam", Const.TWO_PARAMS);
            digester.addCallParam(
                    Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_INIT_PARAM + Const.PAR_PARAM_NAME,
                    Const.FIRST_PARAM);
            digester.addCallParam(
                    Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_INIT_PARAM + Const.PAR_PARAM_VALUE,
                    Const.SECOND_PARAM);
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_MIME_MAPPING,
                    "addMimeMapping", Const.TWO_PARAMS);
            digester.addCallParam(
                    Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_MIME_MAPPING + Const.PAR_EXTENSION,
                    Const.FIRST_PARAM);
            digester.addCallParam(
                    Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_MIME_MAPPING + Const.PAR_MIME_TYPE,
                    Const.SECOND_PARAM);
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET_MAPPING, "setWebletMapping",
                    Const.TWO_PARAMS);
            digester.addCallParam(Const.WEBLETS_CONFIG + Const.PAR_WEBLET_MAPPING + Const.PAR_WEBLET_NAME,
                    Const.FIRST_PARAM);
            digester.addCallParam(Const.WEBLETS_CONFIG + Const.PAR_WEBLET_MAPPING + Const.PAR_URL_PATTERN,
                    Const.SECOND_PARAM);
            digester.addCallMethod(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_SUBBUNDLE,
                    Const.FUNC_ADD_SUBBUNDLE, Const.TWO_PARAMS);
            digester.addCallParam(Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_SUBBUNDLE + Const.PAR_ID,
                    Const.FIRST_PARAM);
            digester.addCallParam(
                    Const.WEBLETS_CONFIG + Const.PAR_WEBLET + Const.PAR_SUBBUNDLE + Const.PAR_RESOURCES,
                    Const.SECOND_PARAM);
            digester.parse(in);
        } finally {
            in.close();
        }
    } catch (IOException e) {
        throw new WebletException(e);
    } catch (SAXException e) {
        throw new WebletException(e);
    }
}

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

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

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

    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }/*from w ww .j a  v a 2s. 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();
    HttpPost httppost = null;
    BufferedReader reader = null;

    try {
        String env = configuration.getEnvironment();

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

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

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

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

        String xmlhead = xmlreqbuffer.toString();

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

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

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

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

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

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

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

        for (PackageDetails packageDetail : packages) {

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

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

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

        }

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

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

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

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

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

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

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

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

        };

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

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

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

        UPSParsedElements parsed = new UPSParsedElements();

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

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

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

        Reader xmlreader = new StringReader(data);

        digester.parse(xmlreader);

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

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

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

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

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

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

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

        if (shippingOptions != null) {

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

            for (ShippingOption option : shippingOptions) {

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

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

                }

            }

        }

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

        return shippingOptions;

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

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

From source file:de.micromata.genome.gwiki.page.gspt.taglibs.TagLibraryInfoImpl.java

protected void loadTagLibary(String uri) {
    Digester dig = new Digester();
    dig.setClassLoader(Thread.currentThread().getContextClassLoader());
    dig.setValidating(false);//w ww.j  a  va  2  s  .c o m
    final EntityResolver parentResolver = dig.getEntityResolver();
    dig.setEntityResolver(new EntityResolver() {

        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            InputStream is = null;
            if (StringUtils.equals(systemId, "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd") == true
                    || StringUtils.equals(publicId,
                            "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN") == true) {
                is = loadLocalDtd("web-jsptaglibrary_1_1.dtd");

            } else if (StringUtils.equals(systemId, "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd") == true
                    || StringUtils.equals(publicId,
                            "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN") == true) {
                is = loadLocalDtd("web-jsptaglibrary_1_2.dtd");
            }
            if (is == null) {
                if (parentResolver == null) {
                    GWikiLog.error("Cannot resolve entity: " + systemId);
                    return null;
                }
                return parentResolver.resolveEntity(publicId, systemId);
            }
            InputSource source = new InputSource(is);
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            return source;
        }
    });
    dig.addCallMethod("taglib/tlib-version", "setTlibversion", 0);
    dig.addCallMethod("taglib/tlibversion", "setTlibversion", 0);
    dig.addCallMethod("taglib/jsp-version", "setJspversion", 0);
    dig.addCallMethod("taglib/jspversion", "setJspversion", 0);
    dig.addCallMethod("taglib/short-name", "setShortname", 0);
    dig.addCallMethod("taglib/shortname", "setShortname", 0);
    dig.addObjectCreate("taglib/tag", TagTmpInfo.class);
    dig.addCallMethod("taglib/tag/name", "setTagName", 0);
    dig.addCallMethod("taglib/tag/description", "setInfoString", 0);
    dig.addCallMethod("taglib/tag/tag-class", "setTagClassName", 0);
    dig.addCallMethod("taglib/tag/tagclass", "setTagClassName", 0);

    dig.addCallMethod("taglib/tag/body-content", "setBodycontent", 0);
    dig.addCallMethod("taglib/tag/bodycontent", "setBodycontent", 0);

    dig.addObjectCreate("taglib/tag/attribute", TagTmpAttributeInfo.class);
    dig.addCallMethod("taglib/tag/attribute/name", "setName", 0);
    dig.addCallMethod("taglib/tag/attribute/required", "setRequired", 0);
    dig.addCallMethod("taglib/tag/attribute/rtexprvalue", "setRtexprvalue", 0);
    dig.addSetNext("taglib/tag/attribute", "addAttributeInfo");
    dig.addSetNext("taglib/tag", "addTag");

    dig.push(this);
    try {
        InputStream is = loadImpl(uri);
        if (is == null) {
            throw new RuntimeException("could not load tld '" + uri + "'");
        }
        /*
         * ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); String text =
         * Converter.stringFromBytes(baos.toByteArray()); dig.parse(new StringReader(text));
         */
        dig.parse(is);
        rework();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

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

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

    CoreModuleService cis = null;/*  w  w w . j  a  v a 2 s.c  o m*/

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

    GetMethod httpget = null;

    try {

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

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

        if (cis == null) {
            log.error("Can't retreive an integration service [countryid " + store.getCountry()
                    + " usps subtype 1]");
        }

        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-usps");
        if (pack == null) {
            log.debug("Will assign packaging type 02 to USPS shipping for merchantid " + store.getMerchantId());
            pack = "PARCEL";
        }

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

        // if not shipping to USA
        boolean domestic = true;
        int shippingCountryId = customer.getCustomerCountryId();
        if (shippingCountryId != Constants.US_COUNTRY_ID) {
            domestic = false;
        }

        IntegrationKeys keys = (IntegrationKeys) vo.getConfiguration("usps-keys");

        if (keys == null) {
            throw new Exception("Integration keys are null from configuration request usps");
        }

        String xmlheader = "<RateV3Request USERID=\"" + keys.getUserid() + "\">";
        if (!domestic) {
            xmlheader = "<IntlRateRequest USERID=\"" + keys.getUserid() + "\">";
        }

        StringBuffer xmldatabuffer = new StringBuffer();

        Map countriesMap = (Map) RefCache
                .getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
        Country customerCountry = (Country) countriesMap.get(customer.getCustomerCountryId());

        Iterator packagesIterator = packages.iterator();

        double totalW = 0;
        double totalH = 0;
        double totalL = 0;
        double totalG = 0;
        double totalP = 0;

        while (packagesIterator.hasNext()) {

            PackageDetail detail = (PackageDetail) packagesIterator.next();

            // need size in inch
            double w = CurrencyUtil.getMeasure(detail.getShippingWidth(), store, Constants.INCH_SIZE_UNIT);
            double h = CurrencyUtil.getMeasure(detail.getShippingHeight(), store, Constants.INCH_SIZE_UNIT);
            double l = CurrencyUtil.getMeasure(detail.getShippingLength(), store, Constants.INCH_SIZE_UNIT);

            totalW = totalW + w;
            totalH = totalH + h;
            totalL = totalL + l;

            // Girth = Length + (Width x 2) + (Height x 2)
            double girth = l + (w * 2) + (h * 2);

            totalG = totalG + girth;

            // need weight in pounds
            double p = CurrencyUtil.getWeight(detail.getShippingWeight(), store, Constants.LB_WEIGHT_UNIT);

            totalP = totalP + p;

        }

        BigDecimal convertedOrderTotal = CurrencyUtil.convertToCurrency(orderTotal, store.getCurrency(),
                Constants.CURRENCY_CODE_USD);

        // calculate total shipping volume

        // ship date is 3 days from here
        Date newDate = DateUtil.addDaysToCurrentDate(3);
        String shipDate = DateUtil.formatDateMonthString(newDate);

        int i = 1;

        // need pounds and ounces
        int pounds = (int) totalP;
        String ouncesString = String.valueOf(totalP - pounds);
        int ouncesIndex = ouncesString.indexOf(".");
        String ounces = "00";
        if (ouncesIndex > -1) {
            ounces = ouncesString.substring(ouncesIndex + 1);
        }

        String size = "REGULAR";

        if (totalL + totalG <= 64) {
            size = "REGULAR";
        } else if (totalL + totalG <= 108) {
            size = "LARGE";
        } else {
            size = "OVERSIZE";
        }

        /**
         * Domestic <Package ID="1ST"> <Service>ALL</Service>
         * <ZipOrigination>90210</ZipOrigination>
         * <ZipDestination>96698</ZipDestination> <Pounds>8</Pounds>
         * <Ounces>32</Ounces> <Container/> <Size>REGULAR</Size>
         * <Machinable>true</Machinable> </Package>
         * 
         * //MAXWEIGHT=70 lbs
         * 
         * 
         * //domestic container default=VARIABLE whiteSpace=collapse
         * enumeration=VARIABLE enumeration=FLAT RATE BOX enumeration=FLAT
         * RATE ENVELOPE enumeration=LG FLAT RATE BOX
         * enumeration=RECTANGULAR enumeration=NONRECTANGULAR
         * 
         * //INTL enumeration=Package enumeration=Postcards or aerogrammes
         * enumeration=Matter for the blind enumeration=Envelope
         * 
         * Size May be left blank in situations that do not Size. Defined as
         * follows: REGULAR: package plus girth is 84 inches or less; LARGE:
         * package length plus girth measure more than 84 inches not more
         * than 108 inches; OVERSIZE: package length plus girth is more than
         * 108 but not 130 inches. For example: <Size>REGULAR</Size>
         * 
         * International <Package ID="1ST"> <Machinable>true</Machinable>
         * <MailType>Envelope</MailType> <Country>Canada</Country>
         * <Length>0</Length> <Width>0</Width> <Height>0</Height>
         * <ValueOfContents>250</ValueOfContents> </Package>
         * 
         * <Package ID="2ND"> <Pounds>4</Pounds> <Ounces>3</Ounces>
         * <MailType>Package</MailType> <GXG> <Length>46</Length>
         * <Width>14</Width> <Height>15</Height> <POBoxFlag>N</POBoxFlag>
         * <GiftFlag>N</GiftFlag> </GXG>
         * <ValueOfContents>250</ValueOfContents> <Country>Japan</Country>
         * </Package>
         */

        xmldatabuffer.append("<Package ID=\"").append(i).append("\">");
        // if domestic

        // user selected services
        // Map selectedintlservices =
        // (Map)config.getConfiguration("service-global-usps");

        // now get corresponding code
        // Map allservices =
        // com.salesmanager.core.util.ShippingUtil.buildServiceMapLabelByCode("usps",locale);
        // TreeBidiMap bidiMap = new TreeBidiMap(allservices);
        // Map invertedservicesmap = (Map)bidiMap.inverseBidiMap();

        // Iterator selServices = selectedintlservices.keySet().iterator();
        // while(selServices.hasNext()) {

        // String serviceId = (String)selServices.next();

        // String svc = (String)invertedservicesmap.get(serviceId);

        if (domestic) {

            xmldatabuffer.append("<Service>");
            xmldatabuffer.append("ALL");
            xmldatabuffer.append("</Service>");
            xmldatabuffer.append("<ZipOrigination>");
            xmldatabuffer
                    .append(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode()));
            xmldatabuffer.append("</ZipOrigination>");
            xmldatabuffer.append("<ZipDestination>");
            xmldatabuffer.append(
                    com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode()));
            xmldatabuffer.append("</ZipDestination>");
            xmldatabuffer.append("<Pounds>");
            xmldatabuffer.append(pounds);
            xmldatabuffer.append("</Pounds>");
            xmldatabuffer.append("<Ounces>");
            xmldatabuffer.append(ounces);
            xmldatabuffer.append("</Ounces>");
            xmldatabuffer.append("<Container>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</Container>");
            xmldatabuffer.append("<Size>");
            xmldatabuffer.append(size);
            xmldatabuffer.append("</Size>");
            xmldatabuffer.append("<ShipDate>");
            xmldatabuffer.append(shipDate);
            xmldatabuffer.append("</ShipDate>");
        } else {
            // if international
            xmldatabuffer.append("<Pounds>");
            xmldatabuffer.append(pounds);
            xmldatabuffer.append("</Pounds>");
            xmldatabuffer.append("<Ounces>");
            xmldatabuffer.append(ounces);
            xmldatabuffer.append("</Ounces>");
            xmldatabuffer.append("<MailType>");
            xmldatabuffer.append("Package");
            xmldatabuffer.append("</MailType>");
            xmldatabuffer.append("<ValueOfContents>");
            xmldatabuffer.append(convertedOrderTotal);
            xmldatabuffer.append("</ValueOfContents>");
            xmldatabuffer.append("<Country>");
            xmldatabuffer.append(customerCountry.getCountryName());
            xmldatabuffer.append("</Country>");
        }

        // }

        // if international & CXG
        /*
         * xmldatabuffer.append("<CXG>"); xmldatabuffer.append("<Length>");
         * xmldatabuffer.append(""); xmldatabuffer.append("</Length>");
         * xmldatabuffer.append("<Width>"); xmldatabuffer.append("");
         * xmldatabuffer.append("</Width>");
         * xmldatabuffer.append("<Height>"); xmldatabuffer.append("");
         * xmldatabuffer.append("</Height>");
         * xmldatabuffer.append("<POBoxFlag>"); xmldatabuffer.append("");
         * xmldatabuffer.append("</POBoxFlag>");
         * xmldatabuffer.append("<GiftFlag>"); xmldatabuffer.append("");
         * xmldatabuffer.append("</GiftFlag>");
         * xmldatabuffer.append("</CXG>");
         */

        /*
         * xmldatabuffer.append("<Width>"); xmldatabuffer.append(totalW);
         * xmldatabuffer.append("</Width>");
         * xmldatabuffer.append("<Length>"); xmldatabuffer.append(totalL);
         * xmldatabuffer.append("</Length>");
         * xmldatabuffer.append("<Height>"); xmldatabuffer.append(totalH);
         * xmldatabuffer.append("</Height>");
         * xmldatabuffer.append("<Girth>"); xmldatabuffer.append(totalG);
         * xmldatabuffer.append("</Girth>");
         */

        xmldatabuffer.append("</Package>");

        String xmlfooter = "</RateRequest>";
        if (!domestic) {
            xmlfooter = "</IntlRateRequest>";
        }

        xmlbuffer.append(xmlheader.toString()).append(xmldatabuffer.toString()).append(xmlfooter.toString());

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

        String data = "";

        IntegrationProperties props = (IntegrationProperties) config.getConfiguration("usps-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();

        String encoded = java.net.URLEncoder.encode(xmlbuffer.toString());

        String completeUri = uri + "?API=RateV3&XML=" + encoded;
        if (!domestic) {
            completeUri = uri + "?API=IntlRate&XML=" + encoded;
        }

        // ?API=RateV3

        httpget = new GetMethod(protocol + "://" + host + ":" + port + completeUri);
        // RequestEntity entity = new
        // StringRequestEntity(xmlbuffer.toString(),"text/plain","UTF-8");
        // httpget.setRequestEntity(entity);

        int result = client.executeMethod(httpget);
        if (result != 200) {
            log.error("Communication Error with usps quote " + result + " " + protocol + "://" + host + ":"
                    + port + uri);
            throw new Exception("USPS quote communication error " + result);
        }
        data = httpget.getResponseBodyAsString();
        log.debug("usps quote response " + data);

        UPSParsedElements parsed = new UPSParsedElements();

        /**
         * <RateV3Response> <Package ID="1ST">
         * <ZipOrigination>44106</ZipOrigination>
         * <ZipDestination>20770</ZipDestination>
         */

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

        if (domestic) {

            digester.addCallMethod("RateV3Response/Package/Error", "setError", 0);
            digester.addObjectCreate("RateV3Response/Package/Postage",
                    com.salesmanager.core.entity.shipping.ShippingOption.class);
            digester.addSetProperties("RateV3Response/Package/Postage", "CLASSID", "optionId");
            digester.addCallMethod("RateV3Response/Package/Postage/MailService", "optionName", 0);
            digester.addCallMethod("RateV3Response/Package/Postage/MailService", "optionCode", 0);
            digester.addCallMethod("RateV3Response/Package/Postage/Rate", "optionPrice", 0);
            digester.addCallMethod("RateV3Response/Package/Postage/Commitment/CommitmentDate",
                    "estimatedNumberOfDays", 0);
            digester.addSetNext("RateV3Response/Package/Postage", "addOption");

        } else {

            digester.addCallMethod("IntlRateResponse/Package/Error", "setError", 0);
            digester.addObjectCreate("IntlRateResponse/Package/Service",
                    com.salesmanager.core.entity.shipping.ShippingOption.class);
            digester.addSetProperties("IntlRateResponse/Package/Service", "ID", "optionId");
            digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionName", 0);
            digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionCode", 0);
            digester.addCallMethod("IntlRateResponse/Package/Service/Postage", "setOptionPriceText", 0);
            digester.addCallMethod("IntlRateResponse/Package/Service/SvcCommitments",
                    "setEstimatedNumberOfDays", 0);
            digester.addSetNext("IntlRateResponse/Package/Service", "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 USD, need to do conversion

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

        LabelUtil labelUtil = LabelUtil.getInstance();
        // Map serviceMap =
        // com.salesmanager.core.util.ShippingUtil.buildServiceMap("usps",locale);

        List options = parsed.getOptions();

        Collection returnColl = null;

        if (options != null && options.size() > 0) {

            returnColl = new ArrayList();
            // Map selectedintlservices =
            // (Map)config.getConfiguration("service-global-usps");
            // need to create a Map of LABEL - LABLEL
            // Iterator servicesIterator =
            // selectedintlservices.keySet().iterator();
            // Map services = new HashMap();

            // ResourceBundle bundle = ResourceBundle.getBundle("usps",
            // locale);

            // while(servicesIterator.hasNext()) {
            // String key = (String)servicesIterator.next();
            // String value =
            // bundle.getString("shipping.quote.services.label." + key);
            // services.put(value, key);
            // }

            Iterator it = options.iterator();
            while (it.hasNext()) {
                ShippingOption option = (ShippingOption) it.next();
                option.setCurrency(Constants.CURRENCY_CODE_USD);

                StringBuffer description = new StringBuffer();
                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(!services.containsKey(option.getOptionCode())) {
                // if(returnColl==null) {
                // returnColl = new ArrayList();
                // }
                // returnColl.add(option);
                // }
                returnColl.add(option);
            }

            // if(options.size()==0) {
            // CommonService.logServiceMessage(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 (httpget != null) {
            httpget.releaseConnection();
        }
    }

}

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

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

    BigDecimal total = orderTotal;

    if (packages == null) {
        return null;
    }//from www . ja  v  a 2s  .c  o  m

    // only applies to Canada and US
    if (customer.getCustomerCountryId() != 38 && customer.getCustomerCountryId() != 223) {
        return null;
    }

    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Constants.FRENCH_CODE) && !language.equals(Constants.ENGLISH_CODE)) {
        language = Constants.ENGLISH_CODE;
    }

    // get canadapost credentials
    if (config == null) {
        log.error("CanadaPostQuotesImp.getShippingQuote requires ConfigurationVO for key SHP_RT_CRED");
        return null;
    }

    // if store is not CAD
    if (!store.getCurrency().equals(Constants.CURRENCY_CODE_CAD)) {
        total = CurrencyUtil.convertToCurrency(total, store.getCurrency(), Constants.CURRENCY_CODE_CAD);
    }

    PostMethod httppost = null;

    CanadaPostParsedElements canadaPost = null;

    try {

        int icountry = store.getCountry();
        String country = CountryUtil.getCountryIsoCodeById(icountry);

        ShippingService sservice = (ShippingService) ServiceFactory.getService(ServiceFactory.ShippingService);
        CoreModuleService cms = sservice.getRealTimeQuoteShippingService(country, "canadapost");

        IntegrationKeys keys = (IntegrationKeys) config.getConfiguration("canadapost-keys");
        IntegrationProperties props = (IntegrationProperties) config.getConfiguration("canadapost-properties");

        if (cms == null) {
            // throw new
            // Exception("Central integration services not configured for "
            // + PaymentConstants.PAYMENT_PSIGATENAME + " and country id " +
            // origincountryid);
            log.error("CoreModuleService not configured for  canadapost and country id " + icountry);
            return null;
        }

        String host = cms.getCoreModuleServiceProdDomain();
        String protocol = cms.getCoreModuleServiceProdProtocol();
        String port = cms.getCoreModuleServiceProdPort();
        String url = cms.getCoreModuleServiceProdEnv();
        if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) {
            host = cms.getCoreModuleServiceDevDomain();
            protocol = cms.getCoreModuleServiceDevProtocol();
            port = cms.getCoreModuleServiceDevPort();
            url = cms.getCoreModuleServiceDevEnv();
        }

        // accept KG and CM

        StringBuffer request = new StringBuffer();

        request.append("<?xml version=\"1.0\" ?>");
        request.append("<eparcel>");
        request.append("<language>").append(language).append("</language>");

        request.append("<ratesAndServicesRequest>");
        request.append("<merchantCPCID>").append(keys.getUserid()).append("</merchantCPCID>");
        request.append("<fromPostalCode>")
                .append(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode()))
                .append("</fromPostalCode>");
        request.append("<turnAroundTime>").append("24").append("</turnAroundTime>");
        request.append("<itemsPrice>").append(CurrencyUtil.displayFormatedAmountNoCurrency(total, "CAD"))
                .append("</itemsPrice>");
        request.append("<lineItems>");

        Iterator packageIterator = packages.iterator();
        while (packageIterator.hasNext()) {
            PackageDetail pack = (PackageDetail) packageIterator.next();
            request.append("<item>");
            request.append("<quantity>").append(pack.getShippingQuantity()).append("</quantity>");
            request.append("<weight>")
                    .append(String.valueOf(
                            CurrencyUtil.getWeight(pack.getShippingWeight(), store, Constants.KG_WEIGHT_UNIT)))
                    .append("</weight>");
            request.append("<length>")
                    .append(String.valueOf(
                            CurrencyUtil.getMeasure(pack.getShippingLength(), store, Constants.CM_SIZE_UNIT)))
                    .append("</length>");
            request.append("<width>")
                    .append(String.valueOf(
                            CurrencyUtil.getMeasure(pack.getShippingWidth(), store, Constants.CM_SIZE_UNIT)))
                    .append("</width>");
            request.append("<height>")
                    .append(String.valueOf(
                            CurrencyUtil.getMeasure(pack.getShippingHeight(), store, Constants.CM_SIZE_UNIT)))
                    .append("</height>");
            request.append("<description>").append(pack.getProductName()).append("</description>");
            request.append("<readyToShip/>");
            request.append("</item>");
        }

        Country c = null;
        Map countries = (Map) RefCache
                .getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
        c = (Country) countries.get(store.getCountry());

        request.append("</lineItems>");
        request.append("<city>").append(customer.getCustomerCity()).append("</city>");

        request.append("<provOrState>").append(customer.getShippingSate()).append("</provOrState>");
        Map cs = (Map) RefCache.getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
        Country customerCountry = (Country) cs.get(customer.getCustomerCountryId());
        request.append("<country>").append(customerCountry.getCountryName()).append("</country>");
        request.append("<postalCode>").append(
                com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode()))
                .append("</postalCode>");
        request.append("</ratesAndServicesRequest>");
        request.append("</eparcel>");

        /**
         * <?xml version="1.0" ?> <eparcel>
         * <!--********************************--> <!-- Prefered language
         * for the --> <!-- response (FR/EN) (optional) -->
         * <!--********************************--> <language>en</language>
         * 
         * <ratesAndServicesRequest>
         * <!--**********************************--> <!-- Merchant
         * Identification assigned --> <!-- by Canada Post --> <!-- --> <!--
         * Note: Use 'CPC_DEMO_HTML' or ask --> <!-- our Help Desk to change
         * your --> <!-- profile if you want HTML to be --> <!-- returned to
         * you --> <!--**********************************--> <merchantCPCID>
         * CPC_DEMO_XML </merchantCPCID>
         * 
         * <!--*********************************--> <!--Origin Postal Code
         * --> <!--This parameter is optional -->
         * <!--*********************************-->
         * <fromPostalCode>m1p1c0</fromPostalCode>
         * 
         * <!--**********************************--> <!-- Turn Around Time
         * (hours) --> <!-- This parameter is optional -->
         * <!--**********************************--> <turnAroundTime> 24
         * </turnAroundTime>
         * 
         * <!--**********************************--> <!-- Total amount in $
         * of the items --> <!-- for insurance calculation --> <!-- This
         * parameter is optional -->
         * <!--**********************************-->
         * <itemsPrice>0.00</itemsPrice>
         * 
         * <!--**********************************--> <!-- List of items in
         * the shopping --> <!-- cart --> <!-- Each item is defined by : -->
         * <!-- - quantity (mandatory) --> <!-- - size (mandatory) --> <!--
         * - weight (mandatory) --> <!-- - description (mandatory) --> <!--
         * - ready to ship (optional) -->
         * <!--**********************************--> <lineItems> <item>
         * <quantity> 1 </quantity> <weight> 1.491 </weight> <length> 1
         * </length> <width> 1 </width> <height> 1 </height> <description>
         * KAO Diskettes </description> </item>
         * 
         * <item> <quantity> 1 </quantity> <weight> 1.5 </weight> <length>
         * 20 </length> <width> 30 </width> <height> 20 </height>
         * <description> My Ready To Ship Item</description>
         * <!--**********************************************--> <!-- By
         * adding the 'readyToShip' tag, Sell Online --> <!-- will not pack
         * this item in the boxes --> <!-- defined in the merchant profile.
         * --> <!-- Instead, this item will be shipped in its --> <!--
         * original box: 1.5 kg and 20x30x20 cm -->
         * <!--**********************************************-->
         * <readyToShip/> </item> </lineItems>
         * 
         * <!--********************************--> <!-- City where the
         * parcel will be --> <!-- shipped to -->
         * <!--********************************--> <city> </city>
         * 
         * <!--********************************--> <!-- Province (Canada) or
         * State (US)--> <!-- where the parcel will be --> <!-- shipped to
         * --> <!--********************************--> <provOrState>
         * Wisconsin </provOrState>
         * 
         * <!--********************************--> <!-- Country or ISO
         * Country code --> <!-- where the parcel will be --> <!-- shipped
         * to --> <!--********************************--> <country> CANADA
         * </country>
         * 
         * <!--********************************--> <!-- Postal Code (or ZIP)
         * where the --> <!-- parcel will be shipped to -->
         * <!--********************************--> <postalCode>
         * H3K1E5</postalCode> </ratesAndServicesRequest> </eparcel>
         **/

        log.debug("canadapost request " + request.toString());

        HttpClient client = new HttpClient();

        StringBuilder u = new StringBuilder().append(protocol).append("://").append(host).append(":")
                .append(port);
        if (!StringUtils.isBlank(url)) {
            u.append(url);
        }

        log.debug("Canadapost URL " + u.toString());

        httppost = new PostMethod(u.toString());
        RequestEntity entity = new StringRequestEntity(request.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        int result = client.executeMethod(httppost);

        if (result != 200) {
            log.error("Communication Error with canadapost " + protocol + "://" + host + ":" + port + url);
            throw new Exception(
                    "Communication Error with canadapost " + protocol + "://" + host + ":" + port + url);
        }
        String stringresult = httppost.getResponseBodyAsString();
        log.debug("canadapost response " + stringresult);

        canadaPost = new CanadaPostParsedElements();
        Digester digester = new Digester();
        digester.push(canadaPost);

        digester.addCallMethod("eparcel/ratesAndServicesResponse/statusCode", "setStatusCode", 0);
        digester.addCallMethod("eparcel/ratesAndServicesResponse/statusMessage", "setStatusMessage", 0);
        digester.addObjectCreate("eparcel/ratesAndServicesResponse/product",
                com.salesmanager.core.entity.shipping.ShippingOption.class);
        digester.addSetProperties("eparcel/ratesAndServicesResponse/product", "sequence", "optionId");
        digester.addCallMethod("eparcel/ratesAndServicesResponse/product/shippingDate", "setShippingDate", 0);
        digester.addCallMethod("eparcel/ratesAndServicesResponse/product/deliveryDate", "setDeliveryDate", 0);
        digester.addCallMethod("eparcel/ratesAndServicesResponse/product/name", "setOptionName", 0);
        digester.addCallMethod("eparcel/ratesAndServicesResponse/product/rate", "setOptionPriceText", 0);
        digester.addSetNext("eparcel/ratesAndServicesResponse/product", "addOption");

        /**
         * response
         * 
         * <?xml version="1.0" ?> <!DOCTYPE eparcel (View Source for full
         * doctype...)> - <eparcel> - <ratesAndServicesResponse>
         * <statusCode>1</statusCode> <statusMessage>OK</statusMessage>
         * <requestID>1769506</requestID> <handling>0.0</handling>
         * <language>0</language> - <product id="1040" sequence="1">
         * <name>Priority Courier</name> <rate>38.44</rate>
         * <shippingDate>2008-12-22</shippingDate>
         * <deliveryDate>2008-12-23</deliveryDate>
         * <deliveryDayOfWeek>3</deliveryDayOfWeek>
         * <nextDayAM>true</nextDayAM> <packingID>P_0</packingID> </product>
         * - <product id="1020" sequence="2"> <name>Expedited</name>
         * <rate>16.08</rate> <shippingDate>2008-12-22</shippingDate>
         * <deliveryDate>2008-12-23</deliveryDate>
         * <deliveryDayOfWeek>3</deliveryDayOfWeek>
         * <nextDayAM>false</nextDayAM> <packingID>P_0</packingID>
         * </product> - <product id="1010" sequence="3">
         * <name>Regular</name> <rate>16.08</rate>
         * <shippingDate>2008-12-22</shippingDate>
         * <deliveryDate>2008-12-29</deliveryDate>
         * <deliveryDayOfWeek>2</deliveryDayOfWeek>
         * <nextDayAM>false</nextDayAM> <packingID>P_0</packingID>
         * </product> - <packing> <packingID>P_0</packingID> - <box>
         * <name>Small Box</name> <weight>1.691</weight>
         * <expediterWeight>1.691</expediterWeight> <length>25.0</length>
         * <width>17.0</width> <height>16.0</height> - <packedItem>
         * <quantity>1</quantity> <description>KAO Diskettes</description>
         * </packedItem> </box> - <box> <name>My Ready To Ship Item</name>
         * <weight>2.0</weight> <expediterWeight>1.5</expediterWeight>
         * <length>30.0</length> <width>20.0</width> <height>20.0</height> -
         * <packedItem> <quantity>1</quantity> <description>My Ready To Ship
         * Item</description> </packedItem> </box> </packing> -
         * <shippingOptions> <insurance>No</insurance>
         * <deliveryConfirmation>Yes</deliveryConfirmation>
         * <signature>No</signature> </shippingOptions> <comment />
         * </ratesAndServicesResponse> </eparcel> - <!-- END_OF_EPARCEL -->
         */

        Reader reader = new StringReader(stringresult);

        digester.parse(reader);

    } catch (Exception e) {
        log.error(e);
    } finally {
        if (httppost != null) {
            httppost.releaseConnection();
        }
    }

    if (canadaPost == null || canadaPost.getStatusCode() == null) {
        return null;
    }

    if (canadaPost.getStatusCode().equals("-6") || canadaPost.getStatusCode().equals("-7")) {
        LogMerchantUtil.log(store.getMerchantId(), "Can't process CanadaPost statusCode="
                + canadaPost.getStatusCode() + " message= " + canadaPost.getStatusMessage());
    }

    if (!canadaPost.getStatusCode().equals("1")) {
        log.error("An error occured with canadapost request (code-> " + canadaPost.getStatusCode()
                + " message-> " + canadaPost.getStatusMessage() + ")");
        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;
    }

    /** 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 options = canadaPost.getOptions();
    if (options != null) {
        Iterator i = options.iterator();
        while (i.hasNext()) {
            ShippingOption option = (ShippingOption) i.next();
            option.setCurrency(store.getCurrency());
            StringBuffer description = new StringBuffer();
            description.append(option.getOptionName());
            if (displayQuoteDeliveryTime == ShippingConstants.DISPLAY_RT_QUOTE_TIME) {
                description.append(" (").append(option.getDeliveryDate()).append(")");
            }
            option.setDescription(description.toString());
            if (requiresCurrencyConversion) {
                option.setOptionPrice(CurrencyUtil.convertToCurrency(option.getOptionPrice(),
                        Constants.CURRENCY_CODE_CAD, store.getCurrency()));
            }
            // System.out.println(option.getOptionPrice().toString());

        }
    }

    return options;
}

From source file:be.ff.gui.web.struts.action.ActionPlugInPlugIn.java

/**
 * Loads and verifies (using a DTD) the action plug-in configuration file. Afterwards this
 * method initializes the <code>ActionPlugInChain</code>.
 *
 * @param config ApplicationConfig for the sub-application with which this plug in is associated
 * @exception ServletException if this <code>PlugIn</code> cannot be successfully initialized
 *//*from   ww w.  jav  a 2  s . co m*/
public void init(ActionServlet config, ModuleConfig module) throws ServletException {
    if (ActionPlugInChain.foiInicializado()) {
        if (log.isDebugEnabled()) {
            log.debug("O ActionPlugInPlugIn j foi inicializado anteriormente. Ignorando.");
        }
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Entrada no mtodo");
    }

    // this value object will hold the values specified in the action plug-in config file
    ActionPlugInChainDefinition chainDefintion = new ActionPlugInChainDefinition();

    // create a digester to scan through the action plug-in config file
    Digester digester = new Digester();
    digester.push(chainDefintion);

    // try to find a local DTD to validate the configuration file
    ServletContext context = config.getServletContext();
    if (getConfigDTD() == null) {
        String msg = "[ActionPlugInPlugIn::init] Please specify a valid context relative location of "
                + "the DTD for the action plug-in configuration file. Do this in the Struts configuration "
                + "file at the plug-in tag that initializes the Action Plug-in Extension.";
        log.warn(msg);
        digester.setValidating(false);
        // Although set to false the SAX based parser STILL wants to load the publicly
        // available DTD that is specified in the XML file!! This causes an error on
        // times when the DTD at the specified location is not available.
        // Why doesn't this statement turn this of????
    } else {
        URL dtdURL = null;
        try {
            dtdURL = context.getResource(getConfigDTD());
            if (dtdURL == null) {
                String msg = "[ActionPlugInPlugIn::init] The action plug-in configuration DTD was not found at the "
                        + "context relative location '" + getConfigDTD()
                        + "'. Please make sure that this DTD is available at "
                        + "a context relative location, because the system identifier that is specified in the "
                        + "configuration file might not be accessible.";
                log.warn(msg);
                digester.setValidating(false);
                // Although set to false the SAX based parser STILL wants to load the publicly
                // available DTD that is specified in the XML file!! This causes an error on
                // times when the DTD at the specified location is not available.
                // Why doesn't this statement turn this of????
            } else {
                digester.register(DOCTYPE_PUBLIC_ID, dtdURL.toString());
                digester.setValidating(true);
            }
        } catch (MalformedURLException e) {
            String msg = "[ActionPlugInPlugIn::init] The location of the DTD for the action plug-in configuration file was "
                    + "invalid:'" + getConfigDTD()
                    + "'. Please specify a valid context relative location for the DTD.";
            log.warn(msg);
            digester.setValidating(false);
            // Although set to false the SAX based parser STILL wants to load the publicly
            // available DTD that is specified in the XML file!! This causes an error on
            // times when the DTD at the specified location is not available.
            // Why doesn't this statement turn this of????
        }
    }

    // add rules
    digester.addObjectCreate("action-plug-in-config/action-plug-in", ActionPlugInDefinition.class);
    digester.addSetNext("action-plug-in-config/action-plug-in", "addActionPlugInDefintion",
            ActionPlugInDefinition.class.getName());
    digester.addCallMethod("action-plug-in-config/action-plug-in/class", "setClassName", 0);
    digester.addCallMethod("action-plug-in-config/action-plug-in/init-params/param", "addInitParam", 2);
    digester.addCallParam("action-plug-in-config/action-plug-in/init-params/param/name", 0);
    digester.addCallParam("action-plug-in-config/action-plug-in/init-params/param/value", 1);
    digester.addCallMethod("action-plug-in-config/action-plug-in/disabled-for/action-path",
            "addDisabledActionPath", 0);
    digester.addCallMethod("action-plug-in-config/action-plug-in/enabled-for/action-path",
            "addEnabledActionPath", 0);

    // point to the XML file
    InputStream input = context.getResourceAsStream(getConfigFile());
    if (input == null) {
        String msg = "[ActionPlugInPlugIn::init] The action plug-in configuration file was not found "
                + "at location '" + getConfigFile() + "'. Please make sure that you have specified "
                + "the correct value for the 'configFile' property of the action plug-in Struts "
                + "plug-in that is defined in struts-config.xml. Please note that this path is Web "
                + "application context relative.";
        throw new ServletException(msg);
    }

    // run the digester
    try {
        digester.parse(new BufferedInputStream(input));
    } catch (Exception e) {
        String msg = "[ActionPlugInPlugIn::init] An exception was thrown during the parsing of the "
                + "action plug-in configuration file (" + getConfigFile() + "). Make sure that "
                + "the configuration file refers to a DTD and that its content is valid according to "
                + "that DTD.";
        throw new ServletException(msg, e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                log.error(
                        "[ActionPlugInPlugIn::init] An IOException was thrown while trying to close the input stream of the action plug-in configuration file.",
                        e);
            }
        }
    }

    // ask the action plug-in chain to initialize itself
    ActionPlugInChain.init(chainDefintion, context);
}

From source file:com.google.gsa.valve.configuration.ValveConfigurationDigester.java

/**
 * Executes the parameter reading process to get all the configuration
 * attributes present in the security framework.
 * /*from   w w  w . j  av a2  s  .co m*/
 * @param configurationFile configuration file path
 * @return the valve configuration
 */
public ValveConfiguration run(String configurationFile) {

    //Valve Config definition
    ValveConfiguration valveConfig = null;

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

        //Load individual parameters
        digester.addObjectCreate("GSAValveConfiguration", ValveConfiguration.class);
        digester.addBeanPropertySetter("GSAValveConfiguration/authCookieDomain", "authCookieDomain");
        digester.addBeanPropertySetter("GSAValveConfiguration/authenticationProcessImpl",
                "authenticationProcessImpl");
        digester.addBeanPropertySetter("GSAValveConfiguration/authenticationProcessImpl",
                "authenticationProcessImpl");
        digester.addBeanPropertySetter("GSAValveConfiguration/authorizationProcessImpl",
                "authorizationProcessImpl");
        digester.addBeanPropertySetter("GSAValveConfiguration/authenticateServletPath",
                "authenticateServletPath");
        digester.addBeanPropertySetter("GSAValveConfiguration/authCookiePath", "authCookiePath");
        digester.addBeanPropertySetter("GSAValveConfiguration/authMaxAge", "authMaxAge");
        digester.addBeanPropertySetter("GSAValveConfiguration/authCookieName", "authCookieName");
        digester.addBeanPropertySetter("GSAValveConfiguration/refererCookieName", "refererCookieName");
        digester.addBeanPropertySetter("GSAValveConfiguration/loginUrl", "loginUrl");
        digester.addBeanPropertySetter("GSAValveConfiguration/maxConnectionsPerHost", "maxConnectionsPerHost");
        digester.addBeanPropertySetter("GSAValveConfiguration/maxTotalConnections", "maxTotalConnections");
        digester.addBeanPropertySetter("GSAValveConfiguration/testFormsCrawlUrl", "testFormsCrawlUrl");
        digester.addBeanPropertySetter("GSAValveConfiguration/errorLocation", "errorLocation");

        //Call Method addSearchHost that takes a single parameter
        digester.addCallMethod("GSAValveConfiguration/searchHost", "addSearchHost", 1);

        //Set value of the parameter for the addSearchHost method
        digester.addCallParam("GSAValveConfiguration/searchHost", 0);

        //Krb, Sessions and SAML
        digester.addObjectCreate("GSAValveConfiguration/kerberos", ValveKerberosConfiguration.class);
        digester.addSetProperties("GSAValveConfiguration/kerberos", "isKerberos", "isKerberos");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "isNegotiate", "isNegotiate");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "krbini", "krbini");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "krbconfig", "krbconfig");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "KrbAdditionalAuthN", "KrbAdditionalAuthN");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "KrbLoginUrl", "KrbLoginUrl");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "KrbUsrPwdCrawler", "KrbUsrPwdCrawler");
        digester.addSetProperties("GSAValveConfiguration/kerberos", "KrbUsrPwdCrawlerUrl",
                "KrbUsrPwdCrawlerUrl");
        digester.addSetNext("GSAValveConfiguration/kerberos", "setKrbConfig");

        digester.addObjectCreate("GSAValveConfiguration/sessions", ValveSessionConfiguration.class);
        digester.addSetProperties("GSAValveConfiguration/sessions", "isSessionEnabled", "isSessionEnabled");
        digester.addSetProperties("GSAValveConfiguration/sessions", "sessionTimeout", "sessionTimeout");
        digester.addSetProperties("GSAValveConfiguration/sessions", "sessionCleanup", "sessionCleanup");
        digester.addSetProperties("GSAValveConfiguration/sessions", "sendCookies", "sendCookies");

        digester.addSetNext("GSAValveConfiguration/sessions", "setSessionConfig");

        digester.addObjectCreate("GSAValveConfiguration/saml", ValveSAMLConfiguration.class);
        digester.addSetProperties("GSAValveConfiguration/saml", "isSAML", "isSAML");
        digester.addSetProperties("GSAValveConfiguration/saml", "maxArtifactAge", "maxArtifactAge");
        digester.addSetProperties("GSAValveConfiguration/saml", "samlTimeout", "samlTimeout");
        digester.addSetNext("GSAValveConfiguration/saml", "setSAMLConfig");

        digester.addObjectCreate("GSAValveConfiguration/repository", ValveRepositoryConfiguration.class);
        digester.addSetProperties("GSAValveConfiguration/repository", "id", "id");
        digester.addSetProperties("GSAValveConfiguration/repository", "pattern", "pattern");
        digester.addSetProperties("GSAValveConfiguration/repository", "authN", "authN");
        digester.addSetProperties("GSAValveConfiguration/repository", "authZ", "authZ");
        digester.addSetProperties("GSAValveConfiguration/repository", "failureAllow", "failureAllow");
        digester.addSetProperties("GSAValveConfiguration/repository", "checkAuthN", "checkAuthN");

        digester.addObjectCreate("GSAValveConfiguration/repository/P", ValveRepositoryParameter.class);
        digester.addSetProperties("GSAValveConfiguration/repository/P", "N", "name");
        digester.addSetProperties("GSAValveConfiguration/repository/P", "V", "value");
        digester.addSetNext("GSAValveConfiguration/repository/P", "addParameter");

        digester.addSetNext("GSAValveConfiguration/repository", "addRepository");

        //Read and parse the file
        File inputFile = new File(configurationFile);
        valveConfig = (ValveConfiguration) digester.parse(inputFile);

    } catch (IOException ioexp) {
        logger.error("Failed to read from configuration file: " + configurationFile, ioexp);

    } catch (SAXException e) {
        logger.error("SAX Exception when reading configuration file: " + e.getMessage(), e);
        e.printStackTrace();
    }

    return valveConfig;

}

From source file:com.change_vision.astah.extension.plugin.cplusreverse.reverser.DoxygenXmlParser.java

/**
 * //  w  w w . j a  v  a 2s .com
 * @param file
 *            : target file
 * @return the Compounddef
 * @throws IOException
 * @throws SAXException
 */
public static CompoundDef parserCompounddefXML(File file) throws IOException, SAXException {
    // init digester for parser class.xml or interface.xml...
    Digester digester = new DoxygenDigester();
    digester.setValidating(false);
    // create the Compounddef
    digester.addRule("doxygen/compounddef", new ObjectCreateAfterLanguageRule(CompoundDef.class));
    digester.addSetProperties("doxygen/compounddef", "id", "compounddefId");
    digester.addSetProperties("doxygen/compounddef", "prot", "compounddefVisible");
    digester.addSetProperties("doxygen/compounddef", "kind", "compounddefKind");
    digester.addBeanPropertySetter("doxygen/compounddef/compoundname", "compoundName");

    // crreate the TempleParam
    digester.addRule("doxygen/compounddef/templateparamlist/param",
            new ObjectCreateAfterLanguageRule(TempleParam.class));
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/type", "type");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/declname", "declname");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/defname", "defname");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/defval", "defval");
    digester.addRule("doxygen/compounddef/templateparamlist/param/defval/ref",
            new ObjectCreateAfterLanguageRule(Ref.class));
    digester.addSetProperties("doxygen/compounddef/templateparamlist/param/defval/ref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/templateparamlist/param/defval/ref", "refid", "kindref");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/defval/ref", "value");
    digester.addSetNext("doxygen/compounddef/templateparamlist/param/defval/ref", "setDefaultValue");

    digester.addSetNext("doxygen/compounddef/templateparamlist/param", "addTemplateParam");

    // create the BaseCompounddefref
    digester.addRule("doxygen/compounddef/basecompoundref",
            new ObjectCreateAfterLanguageRule(BaseCompoundDefRef.class));
    digester.addSetProperties("doxygen/compounddef/basecompoundref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/basecompoundref", "prot", "prot");
    digester.addSetProperties("doxygen/compounddef/basecompoundref", "virt", "virt");
    digester.addBeanPropertySetter("doxygen/compounddef/basecompoundref", "value");
    digester.addSetNext("doxygen/compounddef/basecompoundref", "addBasecompoundList");

    // create the Derivedcompoundref
    digester.addRule("doxygen/compounddef/derivedcompoundref",
            new ObjectCreateAfterLanguageRule(DerivedCompoundRef.class));
    digester.addSetProperties("doxygen/compounddef/derivedcompoundref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/derivedcompoundref", "prot", "prot");
    digester.addSetProperties("doxygen/compounddef/derivedcompoundref", "virt", "virt");
    digester.addBeanPropertySetter("doxygen/compounddef/derivedcompoundref", "value");
    digester.addSetNext("doxygen/compounddef/derivedcompoundref", "addDerivedcompoundList");

    // create the InnerClass
    digester.addRule("doxygen/compounddef/innerclass", new ObjectCreateAfterLanguageRule(InnerClass.class));
    digester.addSetProperties("doxygen/compounddef/innerclass", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/innerclass", "prot", "prot");
    digester.addSetNext("doxygen/compounddef/innerclass", "addInnerclass");

    // create the Innernamespace
    digester.addRule("doxygen/compounddef/innernamespace",
            new ObjectCreateAfterLanguageRule(InnerNameSpace.class));
    digester.addSetProperties("doxygen/compounddef/innernamespace", "refid", "refid");
    digester.addSetNext("doxygen/compounddef/innernamespace", "addInnernamespace");

    digester.addSetProperties("doxygen/compounddef/location", "file", "locationFile");
    digester.addSetProperties("doxygen/compounddef/location", "line", "locationLine");
    digester.addSetProperties("doxygen/compounddef/location", "bodyfile", "locationBodyFile");
    digester.addSetProperties("doxygen/compounddef/location", "bodystart", "locationBodyStart");
    digester.addSetProperties("doxygen/compounddef/location", "bodyend", "locationBodyEnd");
    //
    digester.addBeanPropertySetter("doxygen/compounddef/briefdescription/para", "briefdescriptionPara");
    digester.addBeanPropertySetter("doxygen/compounddef/detaileddescription/para", "detaileddescriptionPara");

    // create the Section
    digester.addRule("doxygen/compounddef/sectiondef", new ObjectCreateAfterLanguageRule(Section.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef", "kind", "kind");
    digester.addSetNext("doxygen/compounddef/sectiondef", "addSection");

    // create the Member
    digester.addRule("doxygen/compounddef/sectiondef/memberdef",
            new ObjectCreateAfterLanguageRule(Member.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "kind", "kind");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "id", "id");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "prot", "prot");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "const", "constBoolean");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "static", "staticBoolean");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "gettable", "gettable");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "settable", "settable");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "virt", "virt");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "explicit", "explicit");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "inline", "inline");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "mutable", "mutable");

    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/type", "type");
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/type/ref",
            new ObjectCreateAfterLanguageRule(Ref.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/type/ref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/type/ref", "refid", "kindref");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/type/ref", "value");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/type/ref", "addTypeRef");

    // resolve special initializer
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/initializer", new InitBeanPropertySetterRule());

    digester.addRule("doxygen/compounddef/sectiondef/memberdef/enumvalue",
            new ObjectCreateAfterLanguageRule(EnumValue.class));
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/name", "name");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/initializer",
            "initializer");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/briefdescription",
            "briefdescription");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/detaileddescription",
            "detaileddescription");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/enumvalue", "addEnum");

    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/name", "name");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/argsstring", "argsstring");

    // create the Param
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/param",
            new ObjectCreateAfterLanguageRule(Param.class));
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/type", "type");
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/param/type/ref",
            new ObjectCreateAfterLanguageRule(Ref.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "refid", "kindref");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "value");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "addTypeRef");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/declname", "declname");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/defname", "defname");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/array", "array");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/param", "addMemberParam");

    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/briefdescription/para",
            "briefdescriptionPara");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/detaileddescription/para",
            "detaileddescriptionPara");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef", "addMember");
    logger.debug("file:{}", file);
    return (CompoundDef) digester.parse(file);
}

From source file:com.change_vision.astah.extension.plugin.csharpreverse.reverser.DoxygenXmlParser.java

/**
 * /*from  w  ww. jav  a  2  s  .  c  o  m*/
 * @param file
 *            : target file
 * @return the Compounddef
 * @throws IOException
 * @throws SAXException
 */
public static CompoundDef parserCompounddefXML(File file) throws IOException, SAXException {
    // init digester for parser class.xml or interface.xml...
    Digester digester = new DoxygenDigester();
    digester.setValidating(false);
    // create the Compounddef
    digester.addRule("doxygen/compounddef", new ObjectCreateAfterLanguageRule(CompoundDef.class));
    digester.addSetProperties("doxygen/compounddef", "id", "compounddefId");
    digester.addSetProperties("doxygen/compounddef", "prot", "compounddefVisible");
    digester.addSetProperties("doxygen/compounddef", "kind", "compounddefKind");
    digester.addBeanPropertySetter("doxygen/compounddef/compoundname", "compoundName");
    digester.addBeanPropertySetter("doxygen/compounddef/briefdescription/para", "briefdescriptionPara");
    digester.addBeanPropertySetter("doxygen/compounddef/detaileddescription/para", "detaileddescriptionPara");

    // crreate the TempleParam
    digester.addRule("doxygen/compounddef/templateparamlist/param",
            new ObjectCreateAfterLanguageRule(TemplateParam.class));
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/type", "type");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/declname", "declname");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/defname", "defname");
    digester.addBeanPropertySetter("doxygen/compounddef/templateparamlist/param/defval", "defval");
    digester.addSetNext("doxygen/compounddef/templateparamlist/param", "addTemplateParam");

    // create the BaseCompounddefref
    digester.addRule("doxygen/compounddef/basecompoundref",
            new ObjectCreateAfterLanguageRule(BaseCompoundDefRef.class));
    digester.addSetProperties("doxygen/compounddef/basecompoundref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/basecompoundref", "prot", "prot");
    digester.addSetProperties("doxygen/compounddef/basecompoundref", "virt", "virt");
    digester.addBeanPropertySetter("doxygen/compounddef/basecompoundref", "value");
    digester.addSetNext("doxygen/compounddef/basecompoundref", "addBasecompoundList");

    // create the Derivedcompoundref
    digester.addRule("doxygen/compounddef/derivedcompoundref",
            new ObjectCreateAfterLanguageRule(DerivedCompoundRef.class));
    digester.addSetProperties("doxygen/compounddef/derivedcompoundref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/derivedcompoundref", "prot", "prot");
    digester.addSetProperties("doxygen/compounddef/derivedcompoundref", "virt", "virt");
    digester.addBeanPropertySetter("doxygen/compounddef/derivedcompoundref", "value");
    digester.addSetNext("doxygen/compounddef/derivedcompoundref", "addDerivedcompoundList");

    // create the InnerClass
    digester.addRule("doxygen/compounddef/innerclass", new ObjectCreateAfterLanguageRule(InnerClass.class));
    digester.addSetProperties("doxygen/compounddef/innerclass", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/innerclass", "prot", "prot");
    digester.addSetNext("doxygen/compounddef/innerclass", "addInnerclass");

    // create the Innernamespace
    digester.addRule("doxygen/compounddef/innernamespace",
            new ObjectCreateAfterLanguageRule(InnerNameSpace.class));
    digester.addSetProperties("doxygen/compounddef/innernamespace", "refid", "refid");
    digester.addSetNext("doxygen/compounddef/innernamespace", "addInnernamespace");

    digester.addSetProperties("doxygen/compounddef/location", "file", "locationFile");
    digester.addSetProperties("doxygen/compounddef/location", "line", "locationLine");
    digester.addSetProperties("doxygen/compounddef/location", "bodyfile", "locationBodyFile");
    digester.addSetProperties("doxygen/compounddef/location", "bodystart", "locationBodyStart");
    digester.addSetProperties("doxygen/compounddef/location", "bodyend", "locationBodyEnd");
    //
    digester.addBeanPropertySetter("doxygen/compounddef/detaileddescription/para", "detaileddescriptionPara");

    // create the Section
    digester.addRule("doxygen/compounddef/sectiondef", new ObjectCreateAfterLanguageRule(Section.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef", "kind", "kind");
    digester.addSetNext("doxygen/compounddef/sectiondef", "addSection");

    // create the Member
    digester.addRule("doxygen/compounddef/sectiondef/memberdef",
            new ObjectCreateAfterLanguageRule(Member.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "kind", "kind");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "id", "id");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "prot", "prot");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "const", "constBoolean");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "static", "staticBoolean");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "gettable", "gettable");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "settable", "settable");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef", "virt", "virt");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/briefdescription/para",
            "briefdescriptionPara");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/detaileddescription/para",
            "detaileddescriptionPara");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/detaileddescription/para/"
            + "parameterlist/parameteritem/parameternamelist/parametername", "parametername");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/detaileddescription/para/"
            + "parameterlist/parameteritem/parameterdescription/para", "parameterdescriptionPara");
    digester.addBeanPropertySetter(
            "doxygen/compounddef/sectiondef/memberdef/detaileddescription/para/simplesect/para",
            "simplesectPara");

    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/type", "type");
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/type/ref",
            new ObjectCreateAfterLanguageRule(Ref.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/type/ref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/type/ref", "refid", "kindref");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/type/ref", "value");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/type/ref", "addTypeRef");

    // resolve special initializer
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/initializer", new InitBeanPropertySetterRule());

    digester.addRule("doxygen/compounddef/sectiondef/memberdef/enumvalue",
            new ObjectCreateAfterLanguageRule(EnumValue.class));
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/name", "name");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/initializer",
            "initializer");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/briefdescription",
            "briefdescription");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/enumvalue/detaileddescription",
            "detaileddescription");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/enumvalue", "addEnum");

    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/name", "name");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/argsstring", "argsstring");

    // create the Param
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/param",
            new ObjectCreateAfterLanguageRule(Param.class));
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/type", "type");
    digester.addRule("doxygen/compounddef/sectiondef/memberdef/param/type/ref",
            new ObjectCreateAfterLanguageRule(Ref.class));
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "refid", "refid");
    digester.addSetProperties("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "refid", "kindref");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "value");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/param/type/ref", "addTypeRef");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/declname", "declname");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/defname", "defname");
    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/param/array", "array");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef/param", "addMemberParam");

    digester.addBeanPropertySetter("doxygen/compounddef/sectiondef/memberdef/detaileddescription/para",
            "detaileddescriptionPara");
    digester.addSetNext("doxygen/compounddef/sectiondef/memberdef", "addMember");

    logger.trace(String.format("%s", file));
    return (CompoundDef) digester.parse(file);
}

From source file:eu.planets_project.pp.plato.xml.ProjectImporter.java

/**
 * Imports the XML representation of plans from the given inputstream.
 * /*  w ww.j a v a  2 s.c o  m*/
 * @return list of read plans
 */
public List<Plan> importProjects(InputStream in) throws IOException, SAXException {
    String tempPath = OS.getTmpPath() + "import_xml" + System.currentTimeMillis() + "/";
    File tempDir = new File(tempPath);
    tempDir.mkdirs();
    try {
        String currentVersionFile = getCurrentVersionData(in, tempPath);

        if (currentVersionFile == null) {
            log.error("Failed to migrate plans.");
            return this.plans;
        }

        Digester digester = new Digester();
        //            digester.setValidating(true);
        StrictErrorHandler errorHandler = new StrictErrorHandler();
        digester.setErrorHandler(errorHandler);
        digester.setNamespaceAware(true);
        //            digester.setSchemaLanguage("http://www.w3.org/2001/XMLSchema");
        //            digester.setSchema("http://localhost:8080/plato/schema/plato-2.1.xsd");

        /*
         * It is NOT sufficient to use setValidating(true) and digester.setSchema("data/schemas/plato.xsd")!
         * the following parameters have to be set and a special error handler is necessary
         */
        try {
            digester.setFeature("http://xml.org/sax/features/validation", true);
            digester.setFeature("http://apache.org/xml/features/validation/schema", true);
            //    
            digester.setFeature("http://xml.org/sax/features/namespaces", true);
            //                digester.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            /*
             * And provide the relative path to the xsd-schema:
             */
            digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            URL platoSchema = Thread.currentThread().getContextClassLoader()
                    .getResource("data/schemas/plato-3.0.xsd");
            URL wdtSchema = Thread.currentThread().getContextClassLoader()
                    .getResource("data/schemas/planets_wdt-1.0.xsd");
            digester.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                    "http://www.planets-project.eu/plato " + platoSchema + " http://www.planets-project.eu/wdt "
                            + wdtSchema);
            //http://localhost:8080/plato/schema/planets_wdt-1.0.xsd
        } catch (ParserConfigurationException e) {
            log.debug("Cannot import XML file: Configuration of parser failed.", e);
            throw new SAXException("Cannot import XML file: Configuration of parser failed.");
        }

        digester.push(this);
        // start with a new file
        digester.addObjectCreate("*/plan", Plan.class);
        digester.addSetProperties("*/plan");
        digester.addSetRoot("*/plan", "setProject");

        digester.addFactoryCreate("*/changelog", ChangeLogFactory.class);
        digester.addSetNext("*/changelog", "setChangeLog");

        digester.addObjectCreate("*/plan/state", PlanState.class);
        digester.addSetProperties("*/plan/state");
        digester.addSetNext("*/plan/state", "setState");

        digester.addObjectCreate("*/plan/properties", PlanProperties.class);
        digester.addSetProperties("*/plan/properties");
        digester.addSetNext("*/plan/properties", "setPlanProperties");
        digester.addCallMethod("*/plan/properties/description", "setDescription", 0);
        digester.addCallMethod("*/plan/properties/owner", "setOwner", 0);

        addCreateUpload(digester, "*/plan/properties/report", "setReportUpload", DigitalObject.class);

        digester.addObjectCreate("*/plan/basis", ProjectBasis.class);
        digester.addSetProperties("*/plan/basis");
        digester.addSetNext("*/plan/basis", "setProjectBasis");
        digester.addCallMethod("*/plan/basis/applyingPolicies", "setApplyingPolicies", 0);
        digester.addCallMethod("*/plan/basis/designatedCommunity", "setDesignatedCommunity", 0);
        digester.addCallMethod("*/plan/basis/mandate", "setMandate", 0);

        digester.addCallMethod("*/plan/basis/documentTypes", "setDocumentTypes", 0);
        digester.addCallMethod("*/plan/basis/identificationCode", "setIdentificationCode", 0);
        digester.addCallMethod("*/plan/basis/organisationalProcedures", "setOrganisationalProcedures", 0);
        digester.addCallMethod("*/plan/basis/planningPurpose", "setPlanningPurpose", 0);
        digester.addCallMethod("*/plan/basis/planRelations", "setPlanRelations", 0);
        digester.addCallMethod("*/plan/basis/preservationRights", "setPreservationRights", 0);
        digester.addCallMethod("*/plan/basis/referenceToAgreements", "setReferenceToAgreements", 0);

        // define common rule for triggers, for all */triggers/...!
        // also used for PlanDefinition
        digester.addObjectCreate("*/triggers", TriggerDefinition.class);
        digester.addSetNext("*/triggers", "setTriggers");
        // every time a */triggers/trigger is encountered:
        digester.addFactoryCreate("*/triggers/trigger", TriggerFactory.class);
        digester.addSetNext("*/triggers/trigger", "setTrigger");

        //
        // Policy Tree
        //
        digester.addObjectCreate("*/plan/basis/policyTree", PolicyTree.class);
        digester.addSetProperties("*/plan/basis/policyTree");
        digester.addSetNext("*/plan/basis/policyTree", "setPolicyTree");

        digester.addObjectCreate("*/plan/basis/policyTree/policyNode", PolicyNode.class);
        digester.addSetProperties("*/plan/basis/policyTree/policyNode");
        digester.addSetNext("*/plan/basis/policyTree/policyNode", "setRoot");

        digester.addObjectCreate("*/policyNode/policyNode", PolicyNode.class);
        digester.addSetProperties("*/policyNode/policyNode");
        digester.addSetNext("*/policyNode/policyNode", "addChild");

        digester.addObjectCreate("*/policyNode/policy", Policy.class);
        digester.addSetProperties("*/policyNode/policy");
        digester.addSetNext("*/policyNode/policy", "addChild");

        //
        // Sample Records
        //

        digester.addObjectCreate("*/plan/sampleRecords", SampleRecordsDefinition.class);
        digester.addSetProperties("*/plan/sampleRecords");
        digester.addSetNext("*/plan/sampleRecords", "setSampleRecordsDefinition");

        digester.addCallMethod("*/plan/sampleRecords/samplesDescription", "setSamplesDescription", 0);

        // - records
        digester.addObjectCreate("*/record", SampleObject.class);
        digester.addSetProperties("*/record");
        digester.addSetNext("*/record", "addRecord");

        digester.addCallMethod("*/record/description", "setDescription", 0);
        digester.addCallMethod("*/record/originalTechnicalEnvironment", "setOriginalTechnicalEnvironment", 0);

        digester.addObjectCreate("*/record/data", BinaryDataWrapper.class);
        digester.addSetTop("*/record/data", "setData");
        digester.addCallMethod("*/record/data", "setFromBase64Encoded", 0);

        // set up an general rule for all jhove strings!
        digester.addObjectCreate("*/jhoveXML", BinaryDataWrapper.class);
        digester.addSetTop("*/jhoveXML", "setString");
        digester.addCallMethod("*/jhoveXML", "setFromBase64Encoded", 0);
        digester.addCallMethod("*/jhoveXML", "setMethodName", 1, new String[] { "java.lang.String" });
        digester.addObjectParam("*/jhoveXML", 0, "setJhoveXMLString");

        // set up general rule for all fitsXMLs
        digester.addObjectCreate("*/fitsXML", BinaryDataWrapper.class);
        digester.addSetTop("*/fitsXML", "setString");
        digester.addCallMethod("*/fitsXML", "setFromBase64Encoded", 0);
        digester.addCallMethod("*/fitsXML", "setMethodName", 1, new String[] { "java.lang.String" });
        digester.addObjectParam("*/fitsXML", 0, "setFitsXMLString");

        digester.addObjectCreate("*/record/formatInfo", FormatInfo.class);
        digester.addSetProperties("*/record/formatInfo");
        digester.addSetNext("*/record/formatInfo", "setFormatInfo");

        addCreateUpload(digester, "*/record/xcdlDescription", "setXcdlDescription", XcdlDescription.class);

        // - collection profile
        digester.addObjectCreate("*/plan/sampleRecords/collectionProfile", CollectionProfile.class);
        digester.addSetProperties("*/plan/sampleRecords/collectionProfile");
        digester.addSetNext("*/plan/sampleRecords/collectionProfile", "setCollectionProfile");

        digester.addCallMethod("*/plan/sampleRecords/collectionProfile/collectionID", "setCollectionID", 0);
        digester.addCallMethod("*/plan/sampleRecords/collectionProfile/description", "setDescription", 0);
        digester.addCallMethod("*/plan/sampleRecords/collectionProfile/numberOfObjects", "setNumberOfObjects",
                0);
        digester.addCallMethod("*/plan/sampleRecords/collectionProfile/typeOfObjects", "setTypeOfObjects", 0);
        digester.addCallMethod("*/plan/sampleRecords/collectionProfile/expectedGrowthRate",
                "setExpectedGrowthRate", 0);
        digester.addCallMethod("*/plan/sampleRecords/collectionProfile/retentionPeriod", "setRetentionPeriod",
                0);

        // requirements definition
        digester.addObjectCreate("*/plan/requirementsDefinition", RequirementsDefinition.class);
        digester.addSetProperties("*/plan/requirementsDefinition");
        digester.addSetNext("*/plan/requirementsDefinition", "setRequirementsDefinition");

        digester.addCallMethod("*/plan/requirementsDefinition/description", "setDescription", 0);

        // - uploads
        digester.addObjectCreate("*/plan/requirementsDefinition/uploads", ArrayList.class);
        digester.addSetNext("*/plan/requirementsDefinition/uploads", "setUploads");
        addCreateUpload(digester, "*/plan/requirementsDefinition/uploads/upload", "add", DigitalObject.class);

        // alternatives
        digester.addObjectCreate("*/plan/alternatives", AlternativesDefinition.class);
        digester.addSetProperties("*/plan/alternatives");
        digester.addCallMethod("*/plan/alternatives/description", "setDescription", 0);
        digester.addSetNext("*/plan/alternatives", "setAlternativesDefinition");

        digester.addObjectCreate("*/plan/alternatives/alternative", Alternative.class);
        digester.addSetProperties("*/plan/alternatives/alternative");
        digester.addSetNext("*/plan/alternatives/alternative", "addAlternative");
        // - action
        digester.addObjectCreate("*/plan/alternatives/alternative/action", PreservationActionDefinition.class);
        digester.addSetProperties("*/plan/alternatives/alternative/action");
        digester.addBeanPropertySetter("*/plan/alternatives/alternative/action/descriptor");
        digester.addBeanPropertySetter("*/plan/alternatives/alternative/action/parameterInfo");

        digester.addSetNext("*/plan/alternatives/alternative/action", "setAction");

        digester.addCallMethod("*/plan/alternatives/alternative/description", "setDescription", 0);

        // - - params
        digester.addObjectCreate("*/plan/alternatives/alternative/action/params", LinkedList.class);
        digester.addSetNext("*/plan/alternatives/alternative/action/params", "setParams");

        digester.addObjectCreate("*/plan/alternatives/alternative/action/params/param", Parameter.class);
        digester.addSetProperties("*/plan/alternatives/alternative/action/params/param");
        digester.addSetNext("*/plan/alternatives/alternative/action/params/param", "add");
        // - resource description
        digester.addObjectCreate("*/resourceDescription", ResourceDescription.class);
        digester.addSetProperties("*/resourceDescription");
        digester.addSetNext("*/resourceDescription", "setResourceDescription");

        digester.addCallMethod("*/resourceDescription/configSettings", "setConfigSettings", 0);
        digester.addCallMethod("*/resourceDescription/necessaryResources", "setNecessaryResources", 0);
        digester.addCallMethod("*/resourceDescription/reasonForConsidering", "setReasonForConsidering", 0);

        // - experiment
        digester.addObjectCreate("*/experiment", ExperimentWrapper.class);
        digester.addSetProperties("*/experiment");
        digester.addSetNext("*/experiment", "setExperiment");
        digester.addCallMethod("*/experiment/description", "setDescription", 0);
        digester.addCallMethod("*/experiment/settings", "setSettings", 0);

        addCreateUpload(digester, "*/experiment/results/result", null, DigitalObject.class);
        addCreateUpload(digester, "*/result/xcdlDescription", "setXcdlDescription", XcdlDescription.class);

        // call function addUpload of ExperimentWrapper
        CallMethodRule r = new CallMethodRule(1, "addResult", 2); //method with two params
        // every time  */experiment/uploads/upload  is encountered
        digester.addRule("*/experiment/results/result", r);
        // use attribute "key" as first param
        digester.addCallParam("*/experiment/results/result", 0, "key");
        // and the object on stack (DigitalObject) as the second
        digester.addCallParam("*/experiment/results/result", 1, true);

        //        addCreateUpload(digester, "*/experiment/xcdlDescriptions/xcdlDescription", null, XcdlDescription.class);
        //        // call function addXcdlDescription of ExperimentWrapper
        //        r = new CallMethodRule(1, "addXcdlDescription", 2);  //method with two params
        //        // every time  */experiment/xcdlDescriptions/xcdlDescription  is encountered
        //        digester.addRule("*/experiment/xcdlDescriptions/xcdlDescription", r);
        //        // use attribute "key" as first param
        //        digester.addCallParam("*/experiment/xcdlDescriptions/xcdlDescription", 0 , "key");
        //        // and the object on stack (DigitalObject) as the second
        //        digester.addCallParam("*/experiment/xcdlDescriptions/xcdlDescription",1,true);

        digester.addObjectCreate("*/experiment/detailedInfos/detailedInfo", DetailedExperimentInfo.class);
        digester.addSetProperties("*/experiment/detailedInfos/detailedInfo");
        digester.addBeanPropertySetter("*/experiment/detailedInfos/detailedInfo/programOutput");
        digester.addBeanPropertySetter("*/experiment/detailedInfos/detailedInfo/cpr");

        // call function "addDetailedInfo" of ExperimentWrapper
        r = new CallMethodRule(1, "addDetailedInfo", 2); //method with two params
        // every time  */experiment/detailedInfos/detailedInfo is encountered
        digester.addRule("*/experiment/detailedInfos/detailedInfo", r);
        // use attribute "key" as first param
        digester.addCallParam("*/experiment/detailedInfos/detailedInfo", 0, "key");
        // and the object on stack as second parameter
        digester.addCallParam("*/experiment/detailedInfos/detailedInfo", 1, true);

        // read contained measurements:
        digester.addObjectCreate("*/detailedInfo/measurements/measurement", Measurement.class);
        digester.addSetNext("*/detailedInfo/measurements/measurement", "put");
        // values are defined with wild-cards, and therefore set automatically        
        digester.addObjectCreate("*/measurement/property", MeasurableProperty.class);
        digester.addSetProperties("*/measurement/property");
        digester.addSetNext("*/measurement/property", "setProperty");
        // scales are defined with wild-cards, and therefore set automatically 

        /*
         * for each value type a set of rules
         * because of FreeStringValue we need to store the value as XML-element
         * instead of an attribute
         * naming them "ResultValues" wasn't nice too
         */
        addCreateValue(digester, BooleanValue.class, "setValue");
        addCreateValue(digester, FloatRangeValue.class, "setValue");
        addCreateValue(digester, IntegerValue.class, "setValue");
        addCreateValue(digester, IntRangeValue.class, "setValue");
        addCreateValue(digester, OrdinalValue.class, "setValue");
        addCreateValue(digester, PositiveFloatValue.class, "setValue");
        addCreateValue(digester, PositiveIntegerValue.class, "setValue");
        addCreateValue(digester, YanValue.class, "setValue");
        addCreateValue(digester, FreeStringValue.class, "setValue");

        // go no go decision
        digester.addObjectCreate("*/plan/decision", Decision.class);
        digester.addSetProperties("*/plan/decision");
        digester.addSetNext("*/plan/decision", "setDecision");

        digester.addCallMethod("*/plan/decision/actionNeeded", "setActionNeeded", 0);
        digester.addCallMethod("*/plan/decision/reason", "setReason", 0);

        digester.addFactoryCreate("*/plan/decision/goDecision", GoDecisionFactory.class);
        digester.addSetNext("*/plan/decision/goDecision", "setDecision");

        // evaluation
        digester.addObjectCreate("*/plan/evaluation", Evaluation.class);
        digester.addSetProperties("*/plan/evaluation");
        digester.addSetNext("*/plan/evaluation", "setEvaluation");

        digester.addCallMethod("*/plan/evaluation/comment", "setComment", 0);

        // importance weighting
        digester.addObjectCreate("*/plan/importanceWeighting", ImportanceWeighting.class);
        digester.addSetProperties("*/plan/importanceWeighting");
        digester.addSetNext("*/plan/importanceWeighting", "setImportanceWeighting");

        digester.addCallMethod("*/plan/importanceWeighting/comment", "setComment", 0);

        // recommendation
        digester.addObjectCreate("*/plan/recommendation", RecommendationWrapper.class);
        digester.addSetProperties("*/plan/recommendation");
        digester.addSetNext("*/plan/recommendation", "setRecommendation");

        digester.addCallMethod("*/plan/recommendation/reasoning", "setReasoning", 0);
        digester.addCallMethod("*/plan/recommendation/effects", "setEffects", 0);

        // transformation
        digester.addObjectCreate("*/plan/transformation", Transformation.class);
        digester.addSetProperties("*/plan/transformation");
        digester.addSetNext("*/plan/transformation", "setTransformation");

        digester.addCallMethod("*/plan/transformation/comment", "setComment", 0);

        // Tree
        /* Some rules for tree parsing are necessary for importing templates too,
         * that's why they are added by this static method. */
        ProjectImporter.addTreeParsingRulesToDigester(digester);

        digester.addObjectCreate("*/leaf/evaluation", HashMap.class);
        digester.addSetNext("*/leaf/evaluation", "setValueMap");
        /*
         *  The valueMap has an entry for each (considered) alternative ...
         *  and for each alternative there is a list of values, one per SampleObject.
         *  Note: The digester uses a stack, therefore the rule to put the list of values to the valueMap
         *  must be added after the rule for adding the values to the list.
         */

        /*
         * 2. and for each alternative there is a list of values, one per SampleObject
         */
        digester.addObjectCreate("*/leaf/evaluation/alternative", Values.class);
        digester.addCallMethod("*/leaf/evaluation/alternative/comment", "setComment", 0);

        /*
         *  for each result-type a set of rules
         *  they are added to the valueMap by the rules above
         */
        addCreateResultValue(digester, BooleanValue.class);
        addCreateResultValue(digester, FloatValue.class);
        addCreateResultValue(digester, FloatRangeValue.class);
        addCreateResultValue(digester, IntegerValue.class);
        addCreateResultValue(digester, IntRangeValue.class);
        addCreateResultValue(digester, OrdinalValue.class);
        addCreateResultValue(digester, PositiveFloatValue.class);
        addCreateResultValue(digester, PositiveIntegerValue.class);
        addCreateResultValue(digester, YanValue.class);
        addCreateResultValue(digester, FreeStringValue.class);

        /*
         * 1. The valueMap has an entry for each (considered) alternative ...
         */
        // call put of the ValueMap (HashMap)
        r = new CallMethodRule(1, "put", 2);
        digester.addRule("*/leaf/evaluation/alternative", r);
        digester.addCallParam("*/leaf/evaluation/alternative", 0, "key");
        digester.addCallParam("*/leaf/evaluation/alternative", 1, true);

        //        digester.addObjectCreate("*/plan/executablePlan/planWorkflow", ExecutablePlanContentWrapper.class);
        //        digester.addSetProperties("*/plan/executablePlan/planWorkflow");
        //        digester.addSetNext("*/plan/executablePlan/planWorkflow", "setRecommendation");

        // Executable plan definition
        digester.addObjectCreate("*/plan/executablePlan", ExecutablePlanDefinition.class);
        digester.addSetProperties("*/plan/executablePlan");
        digester.addSetNext("*/plan/executablePlan", "setExecutablePlanDefinition");

        //
        // Import Planets executable plan if present
        //
        try {
            // object-create rules are called at the beginning element-tags, in the same order as defined 
            // first create the wrapper
            digester.addObjectCreate("*/plan/executablePlan/planWorkflow", NodeContentWrapper.class);
            // then an element for workflowConf
            digester.addRule("*/plan/executablePlan/planWorkflow/workflowConf", new NodeCreateRule());

            // CallMethod and SetNext rules are called at closing element-tags, (last in - first out!)

            CallMethodRule rr = new CallMethodRule(1, "setNodeContent", 2);
            digester.addRule("*/plan/executablePlan/planWorkflow/workflowConf", rr);
            // right below the wrapper is an instance of ExecutablePlanDefinition  
            digester.addCallParam("*/plan/executablePlan/planWorkflow/workflowConf", 0, 1);
            // provide the name of the setter method
            digester.addObjectParam("*/plan/executablePlan/planWorkflow/workflowConf", 1, "setExecutablePlan");

            // the generated node is not accessible as CallParam (why?!?), but available for addSetNext
            digester.addSetNext("*/plan/executablePlan/planWorkflow/workflowConf", "setNode");

        } catch (ParserConfigurationException e) {
            PlatoLogger.getLogger(this.getClass()).error(e.getMessage(), e);
        }

        //
        // Import EPrints executable plan if present
        //
        try {

            digester.addObjectCreate("*/plan/executablePlan/eprintsPlan", NodeContentWrapper.class);
            // then an element for workflowConf
            digester.addRule("*/plan/executablePlan/eprintsPlan", new NodeCreateRule());

            CallMethodRule rr2 = new CallMethodRule(1, "setNodeContentEPrintsPlan", 2);
            digester.addRule("*/plan/executablePlan/eprintsPlan", rr2);
            // right below the wrapper is an instance of ExecutablePlanDefinition  
            digester.addCallParam("*/plan/executablePlan/eprintsPlan", 0, 1);
            // provide the name of the setter method
            digester.addObjectParam("*/plan/executablePlan/eprintsPlan", 1, "setEprintsExecutablePlan");

            digester.addSetNext("*/plan/executablePlan/eprintsPlan", "setNode");

        } catch (ParserConfigurationException e) {
            PlatoLogger.getLogger(this.getClass()).error(e.getMessage(), e);
        }

        digester.addCallMethod("*/plan/executablePlan/objectPath", "setObjectPath", 0);
        digester.addCallMethod("*/plan/executablePlan/toolParameters", "setToolParameters", 0);
        digester.addCallMethod("*/plan/executablePlan/triggersConditions", "setTriggersConditions", 0);
        digester.addCallMethod("*/plan/executablePlan/validateQA", "setValidateQA", 0);

        // Plan definition        
        digester.addObjectCreate("*/plan/planDefinition", PlanDefinition.class);
        digester.addSetProperties("*/plan/planDefinition");
        digester.addSetNext("*/plan/planDefinition", "setPlanDefinition");

        digester.addCallMethod("*/plan/planDefinition/costsIG", "setCostsIG", 0);
        digester.addCallMethod("*/plan/planDefinition/costsPA", "setCostsPA", 0);
        digester.addCallMethod("*/plan/planDefinition/costsPE", "setCostsPE", 0);
        digester.addCallMethod("*/plan/planDefinition/costsQA", "setCostsQA", 0);
        digester.addCallMethod("*/plan/planDefinition/costsREI", "setCostsREI", 0);
        digester.addCallMethod("*/plan/planDefinition/costsRemarks", "setCostsRemarks", 0);
        digester.addCallMethod("*/plan/planDefinition/costsRM", "setCostsRM", 0);
        digester.addCallMethod("*/plan/planDefinition/costsTCO", "setCostsTCO", 0);
        digester.addCallMethod("*/plan/planDefinition/responsibleExecution", "setResponsibleExecution", 0);
        digester.addCallMethod("*/plan/planDefinition/responsibleMonitoring", "setResponsibleMonitoring", 0);

        digester.addObjectCreate("*/plan/planDefinition/triggers", TriggerDefinition.class);
        digester.addSetNext("*/plan/planDefinition/triggers", "setTriggers");
        // every time a */plan/basis/triggers/trigger is encountered:
        digester.addFactoryCreate("*/plan/planDefinition/triggers/trigger", TriggerFactory.class);
        digester.addSetNext("*/plan/planDefinition/triggers/trigger", "setTrigger");

        digester.setUseContextClassLoader(true);
        this.plans = new ArrayList<Plan>();

        // finally parse the XML representation with all created rules
        digester.parse(new FileInputStream(currentVersionFile));

        for (Plan plan : plans) {
            String projectName = plan.getPlanProperties().getName();
            if ((projectName != null) && (!"".equals(projectName))) {
                /*
                 * establish links from values to scales
                 */
                plan.getTree().initValues(plan.getAlternativesDefinition().getConsideredAlternatives(),
                        plan.getSampleRecordsDefinition().getRecords().size(), true);
                /*
                 * establish references of Experiment.uploads
                 */
                HashMap<String, SampleObject> records = new HashMap<String, SampleObject>();
                for (SampleObject record : plan.getSampleRecordsDefinition().getRecords()) {
                    records.put(record.getShortName(), record);
                }
                for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) {
                    if ((alt.getExperiment() != null) && (alt.getExperiment() instanceof ExperimentWrapper)) {
                        alt.setExperiment(((ExperimentWrapper) alt.getExperiment()).getExperiment(records));
                    }
                }

                // DESCRIBE all DigitalObjects with Jhove.
                for (SampleObject record : plan.getSampleRecordsDefinition().getRecords()) {
                    if (record.isDataExistent()) {
                        // characterise

                        try {
                            record.setJhoveXMLString(new JHoveAdaptor().describe(record));
                        } catch (Throwable e) {
                            log.error("Error running Jhove for record " + record.getShortName() + ". "
                                    + e.getMessage(), e);
                        }
                        for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) {
                            DigitalObject result = alt.getExperiment().getResults().get(record);
                            if (result != null && result.isDataExistent()) {
                                try {
                                    result.setJhoveXMLString(new JHoveAdaptor().describe(result));
                                } catch (Throwable e) {
                                    log.error(
                                            "Error running Jhove for record " + record.getShortName()
                                                    + ", alternative " + alt.getName() + ". " + e.getMessage(),
                                            e);
                                }

                            }
                        }
                    }
                }

                // CHECK NUMERIC TRANSFORMER THRESHOLDS
                for (Leaf l : plan.getTree().getRoot().getAllLeaves()) {
                    eu.planets_project.pp.plato.model.transform.Transformer t = l.getTransformer();
                    if (t != null && t instanceof NumericTransformer) {
                        NumericTransformer nt = (NumericTransformer) t;
                        if (!nt.checkOrder()) {
                            StringBuffer sb = new StringBuffer("NUMERICTRANSFORMER THRESHOLD ERROR ");
                            sb.append(l.getName()).append("::NUMERICTRANSFORMER:: ");
                            sb.append(nt.getThreshold1()).append(" ").append(nt.getThreshold2()).append(" ")
                                    .append(nt.getThreshold3()).append(" ").append(nt.getThreshold4())
                                    .append(" ").append(nt.getThreshold5());
                            log.error(sb.toString());
                        }
                    }
                }

                /*
                 * establish references to selected alternative
                 */
                HashMap<String, Alternative> alternatives = new HashMap<String, Alternative>();
                for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) {
                    alternatives.put(alt.getName(), alt);
                }
                if ((plan.getRecommendation() != null)
                        && (plan.getRecommendation() instanceof RecommendationWrapper)) {
                    plan.setRecommendation(
                            ((RecommendationWrapper) plan.getRecommendation()).getRecommendation(alternatives));
                }
                if ((plan.getState().getValue() == PlanState.ANALYSED) && ((plan.getRecommendation() == null)
                        || (plan.getRecommendation().getAlternative() == null))) {
                    /*
                     * This project is NOT completely analysed
                     */
                    plan.getState().setValue(PlanState.ANALYSED - 1);
                }
            } else {
                throw new SAXException("Could not find any project data.");
            }
        }
    } finally {
        OS.deleteDirectory(tempDir);
        /*
         * Importing big plans results in an increasing memory consumption
         * strange: The rise of memory consumption occurs when persisting the loaded project
         * NOT during parsing with the digester
         */
        System.gc();
    }

    return this.plans;
}