Example usage for java.util Locale getLanguage

List of usage examples for java.util Locale getLanguage

Introduction

In this page you can find the example usage for java.util Locale getLanguage.

Prototype

public String getLanguage() 

Source Link

Document

Returns the language code of this Locale.

Usage

From source file:om.edu.squ.squportal.portlet.dps.study.extension.db.ExtensionDbImpl.java

/**
 * /*from   w  w w . j  a v  a  2s  .c  o m*/
 * method name  : getExtensionReasons
 * @param locale
 * @return
 * ExtensionDbImpl
 * return type  : List<ExtensionReason>
 * 
 * purpose      : Get list of extensions
 *
 * Date          :   Jan 16, 2017 4:52:14 PM
 */
public List<ExtensionReason> getExtensionReasons(Locale locale) {
    String SQL_EXTENSION_REASONS = queryExtensionProps.getProperty(Constants.CONST_SQL_EXTENSION_REASONS);
    RowMapper<ExtensionReason> mapper = new RowMapper<ExtensionReason>() {

        public ExtensionReason mapRow(ResultSet rs, int rowNum) throws SQLException {
            ExtensionReason reason = new ExtensionReason();
            reason.setSiscodecd(rs.getString(Constants.CONST_COLMN_SISCODECD));
            reason.setReasonName(rs.getString(Constants.CONST_COLMN_EXTENSION_REASON_NAME));
            return reason;
        }
    };

    Map<String, String> namedParameterMap = new HashMap<String, String>();
    namedParameterMap.put("paramLocale", locale.getLanguage());

    return nPJdbcTemplDpsExtension.query(SQL_EXTENSION_REASONS, namedParameterMap, mapper);

}

From source file:de.iteratec.turm.servlets.TurmServlet.java

/**
 * Determines the current Locale, stores it in the session and returns it.
 * //from  w  w  w . j a  v  a2 s.com
 * It first checks, if a request parameter contains the current locale. This
 * means the user has selected a different locale. Otherwise, it tries to
 * retrieve the locale from the session. If that doesn't exist, the current
 * locale is taken from the request itself.
 * 
 * @param request The current Serlvet Request
 * @return The current Locale as set by the user, or as stored in the session.
 */
private Locale setAndStoreCurrentLocale(HttpServletRequest request) {
    HttpSession session = request.getSession();
    Locale currentLocaleToSet;
    if (request.getParameter(CURRENT_LOCALE_KEY) != null) {
        String parameterLocale = request.getParameter(CURRENT_LOCALE_KEY);
        if (parameterLocale.equals("de")) {
            currentLocaleToSet = Locale.GERMAN;
        } else {
            currentLocaleToSet = Locale.ENGLISH;
        }
        LOGGER.debug("Locale created from HTTP parameter: " + currentLocaleToSet);
    } else if (session.getAttribute(CURRENT_LOCALE_KEY) != null) {
        currentLocaleToSet = (Locale) session.getAttribute(CURRENT_LOCALE_KEY);
        LOGGER.debug("Locale loaded from session: " + currentLocaleToSet);
    } else {
        currentLocaleToSet = request.getLocale();
        if (currentLocaleToSet.getLanguage().toUpperCase().matches(".*DE.*")) {
            currentLocaleToSet = Locale.GERMAN;
        } else {
            currentLocaleToSet = Locale.ENGLISH;
        }
        LOGGER.debug(
                "Locale loaded from HTTP request header. Language is: " + currentLocaleToSet.getLanguage());
    }
    this.currentLocale = currentLocaleToSet;
    session.setAttribute(CURRENT_LOCALE_KEY, currentLocale);
    return currentLocale;
}

From source file:com.salesmanager.core.service.merchant.MerchantService.java

/**
 * Creates a basic merchant id//from  w  ww.j  a v a2  s . c  o m
 * first name
 * last name
 * email
 * admin name
 * password
 * Sends an email
 * @param merchantId
 * @param merchantUserInformation
 * @param locale
 */
@Transactional
public void createMerchantUserInformation(int merchantId, MerchantUserInformation merchantUserInformation,
        Collection<MerchantUserRole> roles, Locale locale) throws Exception {

    if (merchantUserInformation == null) {
        merchantUserInformation = new MerchantUserInformation();
    }
    merchantUserInformation.setMerchantId(merchantId);
    merchantUserInformation.setLastModified(new Date());
    merchantUserInformation.setUserlang(locale.getLanguage());

    PasswordGeneratorModule passwordGenerator = (PasswordGeneratorModule) SpringUtil
            .getBean("passwordgenerator");
    String key = EncryptionUtil.generatekey(String.valueOf(SecurityConstants.idConstant));
    String encrypted;
    String password = "";
    try {
        password = passwordGenerator.generatePassword();
        encrypted = EncryptionUtil.encrypt(key, password);
    } catch (Exception e) {
        log.error(e);
        throw new ServiceException(e);

    }
    merchantUserInformation.setAdminPass(encrypted);

    MerchantStore store = this.getMerchantStore(merchantId);

    merchantUserInformation.setUseraddress(store.getStoreaddress());
    merchantUserInformation.setUsercity(store.getStorecity());
    merchantUserInformation.setUsercountrycode(store.getCountry());
    merchantUserInformation.setUserphone(store.getStorephone());
    merchantUserInformation.setUserpostalcode(store.getStorepostalcode());
    merchantUserInformation.setUserstate(store.getZone());

    this.saveOrUpdateMerchantUserInformation(merchantUserInformation);

    // send an introduction email
    LabelUtil lhelper = LabelUtil.getInstance();
    String title = lhelper.getText(merchantUserInformation.getUserlang(),
            "label.profile.newmerchantemailtitle");
    String adminInfo = lhelper.getText(merchantUserInformation.getUserlang(), "label.profile.userinformation");
    String username = lhelper.getText(merchantUserInformation.getUserlang(), "username");
    String pwd = lhelper.getText(merchantUserInformation.getUserlang(), "password");
    String url = lhelper.getText(merchantUserInformation.getUserlang(), "label.profile.adminurl");
    String mailTitle = lhelper.getText(merchantUserInformation.getUserlang(), "label.profile.newusertitle");

    Map context = new HashMap();
    context.put("EMAIL_NEW_USER_TEXT", title);
    context.put("EMAIL_STORE_NAME", store.getStorename());
    context.put("EMAIL_ADMIN_LABEL", adminInfo);
    context.put("EMAIL_CUSTOMER_FIRSTNAME", merchantUserInformation.getUserfname());
    context.put("EMAIL_CUSTOMER_LAST", merchantUserInformation.getUserlname());
    context.put("EMAIL_ADMIN_NAME", merchantUserInformation.getAdminName());
    context.put("EMAIL_ADMIN_PASSWORD", password);
    context.put("EMAIL_ADMIN_USERNAME_LABEL", username);
    context.put("EMAIL_ADMIN_PASSWORD_LABEL", pwd);
    context.put("EMAIL_ADMIN_URL_LABEL", url);
    context.put("EMAIL_ADMIN_URL", ReferenceUtil.buildCentralUri(store));

    this.saveOrUpdateRoles(roles);

    String email = merchantUserInformation.getAdminEmail();

    CommonService cservice = new CommonService();
    cservice.sendHtmlEmail(email, mailTitle, store, context, "email_template_new_user.ftl",
            merchantUserInformation.getUserlang());

}

From source file:it.uniud.ailab.dcore.annotation.annotators.RegexNGramGeneratorAnnotator.java

private void loadDatabase(Locale lang) throws IOException, ParseException {
    // Get the POS pattern file and parse it.

    InputStreamReader is = FileSystem.getInputStreamReaderFromPath(posDatabasePaths.get(lang));

    BufferedReader reader = new BufferedReader(is);
    Object obj = (new JSONParser()).parse(reader);
    JSONObject fileblock = (JSONObject) obj;
    JSONArray pagesBlock = (JSONArray) fileblock.get("languages");

    // Find the required language in the specified file
    Iterator<JSONObject> iterator = pagesBlock.iterator();
    JSONObject languageBlock = null;//from ww  w  .j  a v  a  2s  . c  om
    while (iterator.hasNext()) {
        languageBlock = (iterator.next());
        String currLanguage = (String) languageBlock.get("language");
        if (currLanguage.equals(lang.getLanguage())) {
            break;
        }
    }

    // If the language is not supported by the database, stop the execution.
    if (languageBlock == null) {
        throw new NullPointerException(
                "Language " + lang.getLanguage() + " not found in file " + posDatabasePaths.get(lang));
    }

    JSONArray patternBlock = (JSONArray) languageBlock.get("patterns");

    Iterator<JSONObject> patternIterator = patternBlock.iterator();

    // put the patterns in the hashmap
    while (patternIterator.hasNext()) {
        JSONObject pattern = (patternIterator.next());
        String POSpattern = (String) pattern.get("pattern");
        validPosPatterns.add(POSpattern);
    }
}

From source file:it.uniud.ailab.dcore.annotation.annotators.SimpleNGramGeneratorAnnotator.java

/**
 * Loads the nGram database according to the path and language specified in
 * the constructor.//www .j a va 2s .co  m
 *
 * @param lang the language to search in the database
 * @throws IOException if the database file is nonexistent or non accessible
 * @throws ParseException if the database file is malformed
 * @throws NullPointerException if the language requested is not in the
 * database
 */
private void loadDatabase(Locale lang) throws IOException, ParseException {
    // Get the POS pattern file and parse it.

    InputStreamReader is = FileSystem.getInputStreamReaderFromPath(posDatabasePaths.get(lang));

    BufferedReader reader = new BufferedReader(is);
    Object obj = (new JSONParser()).parse(reader);
    JSONObject fileblock = (JSONObject) obj;
    JSONArray pagesBlock = (JSONArray) fileblock.get("languages");

    // Find the required language in the specified file
    Iterator<JSONObject> iterator = pagesBlock.iterator();
    JSONObject languageBlock = null;
    while (iterator.hasNext()) {
        languageBlock = (iterator.next());
        String currLanguage = (String) languageBlock.get("language");
        if (currLanguage.equals(lang.getLanguage())) {
            break;
        }
    }

    // If the language is not supported by the database, stop the execution.
    if (languageBlock == null) {
        throw new NullPointerException(
                "Language " + lang.getLanguage() + " not found in file " + posDatabasePaths.get(lang));
    }

    JSONArray patternBlock = (JSONArray) languageBlock.get("patterns");

    try {
        maxGramSize = Integer.parseInt(languageBlock.get("maxGramSize").toString());
    } catch (Exception e) {
        // the field is badly formatted or non-existent: set to default
        maxGramSize = DEFAULT_MAX_NGRAM_SIZE;
        ;
    }

    Iterator<JSONObject> patternIterator = patternBlock.iterator();

    // put the patterns in the hashmap
    while (patternIterator.hasNext()) {
        JSONObject pattern = (patternIterator.next());
        String POSpattern = (String) pattern.get("pattern");
        Long nounCount = (Long) pattern.get("nounCount");
        validPOSPatterns.put(POSpattern, nounCount.intValue());
    }
}

From source file:com.salesmanager.core.util.LocaleUtil.java

public static void setLocaleForRequest(HttpServletRequest request, HttpServletResponse response,
        ActionContext ctx, MerchantStore store) throws Exception {

    /**//from  ww w.j a v a  2 s.com
     * LOCALE
     */

    Map sessions = ctx.getSession();

    if (ctx == null) {
        throw new Exception("This request was not made inside Struts request, ActionContext is null");
    }

    Locale locale = null;

    // check in http request
    String req_locale = (String) request.getParameter("request_locale");
    if (!StringUtils.isBlank(req_locale)) {

        String l = null;
        String c = null;

        if (req_locale.length() == 2) {//assume it is the language
            l = req_locale;
            c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        }

        if (req_locale.length() == 5) {

            try {
                l = req_locale.substring(0, 2);
                c = req_locale.substring(3);
            } catch (Exception e) {
                log.warn("Invalid locale format " + req_locale);
                l = null;
                c = null;
            }

        }

        if (l != null && c != null) {

            String storeLang = null;
            Map languages = store.getGetSupportedLanguages();
            if (languages != null && languages.size() > 0) {
                Iterator i = languages.keySet().iterator();
                while (i.hasNext()) {
                    Integer langKey = (Integer) i.next();
                    Language lang = (Language) languages.get(langKey);
                    if (lang.getCode().equals(l)) {
                        storeLang = l;
                        break;
                    }
                }
            }

            if (storeLang == null) {
                l = store.getDefaultLang();
                if (StringUtils.isBlank(l)) {
                    l = LanguageUtil.getDefaultLanguage();
                }
            }

            locale = new Locale(l, c);
            if (StringUtils.isBlank(locale.getLanguage()) || StringUtils.isBlank(locale.getCountry())) {
                log.error("Language or Country is not set in the new locale " + req_locale);
                return;
            }
            sessions.put("WW_TRANS_I18N_LOCALE", locale);

        }
    }

    locale = (Locale) sessions.get("WW_TRANS_I18N_LOCALE");
    request.getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);

    if (locale == null) {

        String c = CountryUtil.getCountryIsoCodeById(store.getCountry());
        String lang = store.getDefaultLang();
        if (!StringUtils.isBlank(c) && !StringUtils.isBlank(lang)) {
            locale = new Locale(lang, c);
        } else {
            locale = LocaleUtil.getDefaultLocale();
            String langs = store.getSupportedlanguages();
            if (!StringUtils.isBlank(langs)) {
                Map languages = store.getGetSupportedLanguages();
                String defaultLang = locale.getLanguage();
                if (languages != null && languages.size() > 0) {
                    Iterator i = languages.keySet().iterator();
                    String storeLang = "";
                    while (i.hasNext()) {
                        Integer langKey = (Integer) i.next();
                        Language l = (Language) languages.get(langKey);
                        if (l.getCode().equals(defaultLang)) {
                            storeLang = defaultLang;
                            break;
                        }
                    }
                    if (!storeLang.equals(defaultLang)) {
                        defaultLang = storeLang;
                    }
                }

                if (!StringUtils.isBlank(defaultLang) && !StringUtils.isBlank(c)) {
                    locale = new Locale(defaultLang, c);
                }

            }
        }

        sessions.put("WW_TRANS_I18N_LOCALE", locale);
    }

    if (locale != null) {
        LabelUtil label = LabelUtil.getInstance();
        label.setLocale(locale);
        String lang = label.getText("label.language." + locale.getLanguage());
        request.setAttribute("LANGUAGE", lang);
    }

    if (store.getLanguages() == null || store.getLanguages().size() == 0) {

        // languages
        if (!StringUtils.isBlank(store.getSupportedlanguages())) {
            List languages = new ArrayList();
            List langs = LanguageUtil.parseLanguages(store.getSupportedlanguages());
            for (Object o : langs) {
                String lang = (String) o;
                Language l = LanguageUtil.getLanguageByCode(lang);
                if (l != null) {
                    l.setLocale(locale, store.getCurrency());
                    languages.add(l);
                }
            }
            store.setLanguages(languages);
        }
    }

    request.setAttribute("LOCALE", locale);
    Cookie c = new Cookie("LOCALE", locale.getLanguage() + "_" + locale.getCountry());
    c.setPath("/");
    c.setMaxAge(2 * 24 * 24);
    response.addCookie(c);

}

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;
    }// ww w  . ja v a 2 s .  co 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:com.hiperium.bo.manager.exception.ExceptionManager.java

/**
 * {@inheritDoc}/*from   w w w  . ja  v a 2s  . c  o  m*/
 */
public InformationException createMessageException(@NotNull Exception ex, @NotNull Locale locale)
        throws InformationException {
    this.log.debug("createMessageException - START");
    if (ex instanceof InformationException || ex.getCause() instanceof InformationException) {
        return (InformationException) ex;
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    InformationException informacionExcepcion = null;
    try {
        informacionExcepcion = this.findErrorCode(ex, locale);
        if (informacionExcepcion == null) {
            return InformationException.generate(EnumI18N.COMMON, EnumInformationException.SYSTEM_EXCEPTION,
                    locale);
        } else if (informacionExcepcion.getErrorCode() == null) {
            return informacionExcepcion;
        }
        ErrorLanguagePK languagePK = new ErrorLanguagePK(informacionExcepcion.getErrorCode().toString(),
                locale.getLanguage());
        ErrorLanguage errorLenguaje = this.errorLanguageDAO.findById(languagePK, false, true);
        if (errorLenguaje == null) {
            throw new NoResultException(informacionExcepcion.getMessage());
        } else {
            informacionExcepcion = new InformationException(errorLenguaje.getText());
        }
        informacionExcepcion = this.createMessageParameters(informacionExcepcion, locale);
    } catch (NoResultException e) {
        this.log.error("ERROR - MESSAGE NOT FOUND IN DATA BASE: " + e.getMessage());
    }
    this.log.debug("createMessageException - END");
    return informacionExcepcion;
}

From source file:com.salesmanager.catalog.common.AjaxCatalogUtil.java

public String setPrice(ProductAttribute[] attributes, String productId) {

    if (StringUtils.isBlank(productId)) {
        return "";
    }/*www .j a  v  a2  s .co  m*/

    HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();

    HttpSession session = req.getSession();

    MerchantStore store = (MerchantStore) session.getAttribute("STORE");

    Locale locale = (Locale) session.getAttribute("WW_TRANS_I18N_LOCALE");

    String price = "";

    // get original product price
    try {

        CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
        Product p = cservice.getProduct(Long.valueOf(productId));
        if (p == null) {
            return "";
        }

        if (attributes != null && attributes.length > 0) {
            List ids = new ArrayList();
            for (int i = 0; i < attributes.length; i++) {
                if (!attributes[i].isStringValue()) {
                    ids.add(new Long(attributes[i].getValue()));
                }
            }
            Collection attrs = cservice.getProductAttributes(ids, locale.getLanguage());

            if (attrs != null && attrs.size() > 0) {
                price = ProductUtil.formatHTMLProductPriceWithAttributes(locale, store.getCurrency(), p, attrs,
                        false);
            }
        }

    } catch (Exception e) {
        logger.error(e);
    }

    return price;

}

From source file:com.seajas.search.attender.service.feed.FeedService.java

/**
 * Create a feed from the given profile and base URL.
 * /*from   w ww .  j  a  v a 2 s  .  c om*/
 * @param profile
 * @param notificationType
 * @param totalResults
 * @param baseUrl
 * @param locale
 * @return SyndFeed
 */
public SyndFeed createFeed(final Profile profile, final NotificationType notificationType,
        final Integer totalResults, final String baseUrl, final Locale locale) {
    // Round up the search parameters and taxonomies into a concise parameter list

    Map<String, String> searchParameters = InterfaceQueryUtils.combineParametersAndTaxonomies(
            profile.getSearchParametersMap(), profile.getTaxonomyIdentifierNumbers());

    // Determine the start date on the notification type

    Calendar calendar = new GregorianCalendar();

    Date endDate = calendar.getTime();

    calendar.add(Calendar.DATE, notificationType.equals(NotificationType.Weekly) ? -7 : -1);

    Date startDate = calendar.getTime();

    // Determine the start date depending on the user's last notification date, and retrieve the results

    Integer actualResults = totalResults != null
            ? (maximumResults == 0 ? totalResults : Math.min(totalResults, maximumResults))
            : defaultResults;

    List<SearchResult> searchResults = searchService.performSearch(profile.getQuery(), startDate, endDate,
            searchParameters, actualResults, locale.getLanguage());

    // Create the actual feed

    SyndFeed feed = new SyndFeedImpl();

    feed.setAuthor(messageSource.getMessage("feed.author", new String[] {}, locale));
    feed.setTitle(messageSource.getMessage("feed.title", new String[] {}, locale));
    feed.setDescription(
            messageSource.getMessage("feed.description", new String[] { String.valueOf(searchResults.size()),
                    profile.getQuery() != null ? profile.getQuery() : "" }, locale));
    feed.setLink(baseUrl);

    // Add the actual entries

    List<SyndEntry> entries = new ArrayList<SyndEntry>(searchResults.size());

    for (SearchResult searchResult : searchResults)
        entries.add(searchResult.toSyndEntry());

    feed.setEntries(entries);

    return feed;
}