List of usage examples for java.util Locale getCountry
public String getCountry()
From source file:com.globalsight.connector.blaise.BlaiseCreateJobHandler.java
private void setEntryInfo(HttpServletRequest request) throws LocaleManagerException, RemoteException, GeneralException { HttpSession session = request.getSession(false); Locale uiLocale = (Locale) session.getAttribute(UILOCALE); HashMap<Long, String> id2FileNameMap = new HashMap<Long, String>(); HashMap<Long, String> id2LocaleMap = new HashMap<Long, String>(); for (TranslationInboxEntryVo entry : currPageEntries) { id2FileNameMap.put(entry.getId(), BlaiseHelper.getEntryFileName(entry)); Locale javaLocale = entry.getTargetLocale(); String localeCode = BlaiseHelper.fixLocale(javaLocale.getLanguage() + "_" + javaLocale.getCountry()); StringBuilder sb = new StringBuilder(localeCode).append(" (") .append(javaLocale.getDisplayLanguage(uiLocale)).append("_") .append(javaLocale.getDisplayCountry(uiLocale)).append(")"); id2LocaleMap.put(entry.getId(), sb.toString()); }/* w ww .j ava 2 s . c om*/ getSessionManager(request).setAttribute("id2FileNameMap", id2FileNameMap); getSessionManager(request).setAttribute("id2LocaleMap", id2LocaleMap); }
From source file:com.konakart.bl.modules.ordertotal.productdiscount.ProductDiscount.java
/** * Create and return an OrderTotal object for the discount amount. * * <p>//from w ww .j a v a 2 s .co m * Custom field usage: * <p> * <ul> * <li>custom1 = Minimum Order Value</li> * <li>custom2 = Minimum quantity of a single product</li> * <li>custom3 = Discount Applied</li> * <li>custom4 = Percentage discount if set to true</li> * <li>custom5 = Discount applied to pre-tax value if set to true</li> * </ul> * If the promotion applies to multiple products, we create an array of order total objects and * attach the array to the order total that we return (ot.setOrderTotals(otArray)). The reason * for doing this is to get a line item of the order for each discounted product. We still need * to populate the order total that we return with the total discount amount because this will * be used to compare this promotion with other promotions in order to decide which one to use. * * @param order * @param dispPriceWithTax * @param locale * @return Returns an OrderTotal object for this module * @throws Exception */ public OrderTotal getOrderTotal(Order order, boolean dispPriceWithTax, Locale locale) throws Exception { OrderTotal ot; StaticData sd = staticDataHM.get(getStoreId()); // Get the resource bundle ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, locale); if (rb == null) { throw new KKException("A resource file cannot be found for the country " + locale.getCountry()); } // Get the promotions Promotion[] promArray = getPromMgr().getPromotions(code, order); // List to contain an order total for each promotion List<OrderTotal> orderTotalList = new ArrayList<OrderTotal>(); if (promArray != null) { for (int i = 0; i < promArray.length; i++) { Promotion promotion = promArray[i]; /* * Get the configuration parameters from the promotion */ // Minimum value for order BigDecimal minTotalOrderVal = getCustomBigDecimal(promotion.getCustom1(), 1); // Need to order at least this quantity of a single product for promotion to apply int minProdQuantity = getCustomInt(promotion.getCustom2(), 2); // Actual discount. Could be a percentage or an amount. BigDecimal discountApplied = getCustomBigDecimal(promotion.getCustom3(), 3); // If set to true it is a percentage. Otherwise it is an amount. boolean percentageDiscount = getCustomBoolean(promotion.getCustom4(), 4); // If set to true, discount is applied to pre-tax value. Only relevant for // percentage discount. boolean applyBeforeTax = getCustomBoolean(promotion.getCustom5(), 5); // Don't bother going any further if there is no discount if (discountApplied == null || discountApplied.equals(new BigDecimal(0))) { continue; } // Get the order value BigDecimal orderValue = null; if (applyBeforeTax) { orderValue = order.getSubTotalExTax(); log.debug("Order value before tax: " + orderValue); } else { orderValue = order.getSubTotalIncTax(); log.debug("Order value after tax: " + orderValue); } // If promotion doesn't cover any of the products in the order then go on to the // next promotion if (promotion.getApplicableProducts() == null || promotion.getApplicableProducts().length == 0) { continue; } ot = new OrderTotal(); ot.setSortOrder(sd.getSortOrder()); ot.setClassName(code); ot.setPromotions(new Promotion[] { promotion }); // Does promotion only apply to a min order value ? if (minTotalOrderVal != null) { if (orderValue.compareTo(minTotalOrderVal) < 0) { // If we haven't reached the minimum amount then continue to the next // promotion continue; } } // Continue if promotion has no applicable products (should never happen) if (promotion.getApplicableProducts() == null) { continue; } /* * Create a new Order Total module for each discounted product and store in this * list */ ArrayList<OrderTotal> otList = new ArrayList<OrderTotal>(); // Loop through promotion products to determine whether to apply a discount boolean firstLoop = true; for (int j = 0; j < promotion.getApplicableProducts().length; j++) { OrderProductIf op = promotion.getApplicableProducts()[j]; if (op != null && op.getQuantity() >= minProdQuantity) { // Get the current total price of the product(s) BigDecimal currentPrice = null; if (applyBeforeTax) { currentPrice = op.getFinalPriceExTax(); } else { currentPrice = op.getFinalPriceIncTax(); } // Apply the discount BigDecimal discount = null; if (percentageDiscount) { // Apply a percentage discount discount = (currentPrice.multiply(discountApplied)).divide(new BigDecimal(100)); } else { // Apply an amount based discount discount = discountApplied.multiply(new BigDecimal(op.getQuantity())); } // Determine whether it is the first discounted product or not String formattedDiscount = getCurrMgr().formatPrice(discount, order.getCurrencyCode()); if (firstLoop) { // Set the order total attributes ot.setValue(discount); if (percentageDiscount) { try { ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT), "-", formattedDiscount)); ot.setTitle( String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE), "-", discountApplied, "%", op.getName())); } catch (MissingResourceException e) { ot.setText("-" + formattedDiscount); // Title looks like "-10% Philips TV" ot.setTitle("-" + discountApplied + "% " + op.getName()); } } else { try { ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT), "-", formattedDiscount)); ot.setTitle( String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE), "-", formattedDiscount, "", op.getName())); } catch (MissingResourceException e) { ot.setText("-" + formattedDiscount); // Title looks like "-10EUR Philips TV" ot.setTitle("-" + formattedDiscount + " " + op.getName()); } } } else { // Set the order total attributes ot.setValue(ot.getValue().add(discount)); ot.setText("-" + getCurrMgr().formatPrice(ot.getValue(), order.getCurrencyCode())); ot.setTitle(ot.getTitle() + "," + op.getName()); } firstLoop = false; /* * Create a new Order Total module for each product */ OrderTotal singleOt = new OrderTotal(); singleOt.setSortOrder(sd.getSortOrder()); singleOt.setClassName(code); singleOt.setValue(discount); singleOt.setText("-" + formattedDiscount); if (percentageDiscount) { singleOt.setTitle("-" + discountApplied + "% " + op.getName() + ":"); } else { singleOt.setTitle("-" + formattedDiscount + " " + op.getName() + ":"); } otList.add(singleOt); } } /* * If we have more than one discounted product we create an array of order totals * (one for each product) and add the array to the order total to be returned. */ if (otList.size() > 1) { OrderTotal[] otArray = new OrderTotal[otList.size()]; int k = 0; for (Iterator<OrderTotal> iterator = otList.iterator(); iterator.hasNext();) { OrderTotal lot = iterator.next(); otArray[k++] = lot; } ot.setOrderTotals(otArray); } if (ot.getValue() != null) { int scale = new Integer(order.getCurrency().getDecimalPlaces()).intValue(); ot.setValue(ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP)); log.debug("Order total is :" + ot.toString()); orderTotalList.add(ot); } } } else { // Return null if there are no promotions return null; } // Call a helper method to decide which OrderTotal we should return OrderTotal retOT = getDiscountOrderTotalFromList(order, orderTotalList); log.debug("Selected order total is: " + retOT); return retOT; }
From source file:DateLocaleServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //Get the client's Locale Locale locale = request.getLocale(); ResourceBundle bundle = ResourceBundle.getBundle("i18n.WelcomeBundle", locale); String welcome = bundle.getString("Welcome"); String date = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT, locale).format(new Date()); //Display the locale response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html><head><title>" + welcome + "</title></head><body>"); out.println("<h2>" + bundle.getString("Hello") + " " + bundle.getString("and") + " " + welcome + "</h2>"); out.println(date + "<br /><br />"); java.util.Enumeration e = bundle.getKeys(); while (e.hasMoreElements()) { out.println((String) e.nextElement()); out.println("<br /><br />"); }// w w w .ja v a 2 s.c o m out.println("Locale: "); out.println(locale.getLanguage() + "_" + locale.getCountry()); out.println("</body></html>"); }
From source file:hudson.model.Descriptor.java
private InputStream getHelpStream(Class c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = c.getName().replace('.', '/') + "/help" + suffix; ClassLoader cl = c.getClassLoader(); if (cl == null) return null; InputStream in;/*w ww . j ava 2 s.c o m*/ in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if (in != null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if (in != null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html"); if (in != null) return in; // default return cl.getResourceAsStream(base + ".html"); }
From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerDlg.java
@Override protected void applyButtonPressed() { Vector<DisplayLocale> list = new Vector<DisplayLocale>(); for (Locale locale : Locale.getAvailableLocales()) { if (StringUtils.isEmpty(locale.getCountry())) { list.add(new DisplayLocale(locale)); }//from w ww .j a va 2 s .c om } Collections.sort(list); ToggleButtonChooserDlg<DisplayLocale> dlg = new ToggleButtonChooserDlg<DisplayLocale>((Dialog) null, "CHOOSE_LOCALE", list, ToggleButtonChooserPanel.Type.RadioButton); dlg.setUseScrollPane(true); dlg.setVisible(true); if (!dlg.isCancelled()) { schemaLocPanel.localeChanged(dlg.getSelectedObject().getLocale()); setTitle(); } }
From source file:org.siberia.image.searcher.impl.GoogleImageSearcher.java
/** search */ public void search() { // http://images.google.fr/images?imgsz=xxlarge&gbv=2&hl=fr&q=b+e&btnG=Recherche+d%27images // http://images.google.fr/images?imgsz=xxlarge&hl=fr&q=b+e Runnable run = new Runnable() { public void run() { fireSearchHasBegan(new ImageSearcherEvent(GoogleImageSearcher.this)); StringBuffer buffer = new StringBuffer(50); if (getCriterions() != null) { boolean oneTokenAlreadyApplied = false; for (int i = 0; i < getCriterions().length; i++) { String current = getCriterions()[i]; if (current != null) { if (oneTokenAlreadyApplied) { buffer.append("+"); }/*from w w w . j av a 2 s . co m*/ buffer.append(current); oneTokenAlreadyApplied = true; } } } Locale locale = getLocale(); if (locale == null) { locale = Locale.getDefault(); } if (logger.isDebugEnabled()) { logger.debug("uri : " + buffer.toString()); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(GOOGLE_URL); NameValuePair[] pairs = new NameValuePair[3]; pairs[0] = new NameValuePair("imgsz", convertImageSizeCriterion(getImageSize())); pairs[1] = new NameValuePair("hl", locale.getCountry().toLowerCase()); pairs[2] = new NameValuePair("q", buffer.toString()); method.setQueryString(pairs); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); InputStream stream = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { /** on recherche partir des motifs suivants * la premire occurrence de http:// partir de l, on prend jusqu'au prochaine espace ou '>' : * * exemple : * <img src=http://tbn0.google.com/images?q=tbn:GIJo-j_dSy4FiM:http://www.discogs.com/image/R-378796-1136999170.jpeg width=135 height=135> * * on trouve le motif, puis, on prend partir de http://www.discogs jusqu'au prochain espace... * * --> http://www.discogs.com/image/R-378796-1136999170.jpeg */ String searchMotif = "<img src=http://tbn0.google.com/images?q"; String urlMotif = "http://"; int indexInSearchMotif = -1; int indexInUrlMotif = -1; boolean motifFound = false; boolean foundUrl = false; StringBuffer urlBuffer = new StringBuffer(50); // Read the response body. byte[] bytes = new byte[1024 * 8]; stream = method.getResponseBodyAsStream(); if (stream != null) { int read = -1; int linksRetrieved = 0; while ((read = stream.read(bytes)) != -1) { for (int i = 0; i < read; i++) { byte currentByte = bytes[i]; if (motifFound) { if (foundUrl) { if (currentByte == ' ' || currentByte == '>') { /* add current url to list of result */ try { URL url = new URL(urlBuffer.toString()); fireImageFound(new ImageFoundEvent(GoogleImageSearcher.this, url, linksRetrieved)); linksRetrieved++; if (linksRetrieved >= getMaximumLinksRetrieved()) { break; } } catch (Exception e) { e.printStackTrace(); } finally { urlBuffer.delete(0, urlBuffer.length()); foundUrl = false; motifFound = false; } } else { /* add current byte to url buffer */ urlBuffer.append((char) currentByte); } } else { if (indexInUrlMotif == urlMotif.length() - 1) { urlBuffer.append(urlMotif); urlBuffer.append((char) currentByte); foundUrl = true; indexInUrlMotif = -1; } /* if the current byte is the same as that attempted on the url motif let's continue */ if (((char) currentByte) == urlMotif.charAt(indexInUrlMotif + 1)) { indexInUrlMotif++; } else { indexInUrlMotif = -1; } } } else { if (indexInSearchMotif == searchMotif.length() - 1) { motifFound = true; indexInSearchMotif = -1; } if (((char) currentByte) == searchMotif.charAt(indexInSearchMotif + 1)) { indexInSearchMotif++; } else { indexInSearchMotif = -1; } } } if (linksRetrieved >= getMaximumLinksRetrieved()) { break; } } } } else { System.err.println("Method failed: " + method.getStatusLine()); } } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { if (stream != null) { try { stream.close(); } catch (IOException ex) { System.err.println("Fatal transport error: " + ex.getMessage()); } } System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); fireSearchFinished(new ImageSearcherEvent(GoogleImageSearcher.this)); } } }; this.service.submit(run); }
From source file:org.apache.jetspeed.services.template.JetspeedTemplateLocatorService.java
/** * Helper function for template locator to find a localized (NLS) resource. * Considers both language and country resources as well as all the possible * media-types for the request//from w w w.jav a2s . co m * * @param data * The rundata for the request. * @param locale * The locale for the request. * * @return The possible paths to a localized template ordered by descending * preference */ private List localizeTemplateName(RunData data, Locale inLocale) { List templates = new ArrayList(); Locale tmplocale = null; if (inLocale != null) { tmplocale = inLocale; } else { CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil .getServiceByName(LocalizationService.SERVICE_NAME); tmplocale = locService.getLocale(data); } // Get the locale store it in the user object if (tmplocale == null) { tmplocale = new Locale(TurbineResources.getString("locale.default.language", "en"), TurbineResources.getString("locale.default.country", "US")); } if (data.getUser() != null) { data.getUser().setTemp("locale", tmplocale); } StringBuffer templatePath = new StringBuffer(); // retrieve all the possible media types String type = data.getParameters().getString(Profiler.PARAM_MEDIA_TYPE, null); List types = new ArrayList(); CapabilityMap cm = ((JetspeedRunData) data).getCapability(); // Grab the Locale from the temporary storage in the User object Locale locale = data.getUser() != null ? (Locale) data.getUser().getTemp("locale") : tmplocale; String language = locale.getLanguage(); String country = locale.getCountry(); if (null != type) { types.add(type); } else { Iterator i = cm.listMediaTypes(); while (i.hasNext()) { types.add(i.next()); } } Iterator typeIterator = types.iterator(); while (typeIterator.hasNext()) { type = (String) typeIterator.next(); if ((type != null) && (type.length() > 0)) { templatePath.append(PATH_SEPARATOR).append(type); } if ((language != null) && (language.length() > 0)) { templatePath.append(PATH_SEPARATOR).append(language); } if ((country != null) && (country.length() > 0)) { templatePath.append(PATH_SEPARATOR).append(country); } templates.add(templatePath.toString()); templatePath.setLength(0); } return templates; }
From source file:nonjsp.application.XulViewHandlerImpl.java
/** * Attempts to find a matching locale based on <code>perf></code> and * list of supported locales, using the matching algorithm * as described in JSTL 8.3.2.// w ww .j a v a2s . com */ protected Locale findMatch(FacesContext context, Locale perf) { Locale result = null; Iterator it = context.getApplication().getSupportedLocales(); while (it.hasNext()) { Locale supportedLocale = (Locale) it.next(); if (perf.equals(supportedLocale)) { // exact match result = supportedLocale; break; } else { // Make sure the preferred locale doesn't have country set, when // doing a language match, For ex., if the preferred locale is // "en-US", if one of supported locales is "en-UK", even though // its language matches that of the preferred locale, we must // ignore it. if (perf.getLanguage().equals(supportedLocale.getLanguage()) && supportedLocale.getCountry().equals("")) { result = supportedLocale; } } } return result; }
From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerDlg.java
@Override public Vector<Locale> getLocalesInUse() { Hashtable<String, Boolean> localeHash = new Hashtable<String, Boolean>(); // Add any from the Database Vector<Locale> localeList = getLocalesInUseInDB(schemaType); for (Locale locale : localeList) { localeHash.put(SchemaLocalizerXMLHelper.makeLocaleKey(locale.getLanguage(), locale.getCountry(), locale.getVariant()), true); }//from w w w . j a v a2 s . c o m for (SpLocaleContainer container : tables) { SchemaLocalizerXMLHelper.checkForLocales(container, localeHash); for (LocalizableItemIFace f : container.getContainerItems()) { SchemaLocalizerXMLHelper.checkForLocales(f, localeHash); } } localeList.clear(); for (String key : localeHash.keySet()) { String[] toks = StringUtils.split(key, "_"); localeList.add(new Locale(toks[0], "", "")); } return localeList; }
From source file:org.sakaiproject.roster.tool.RosterTool.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId = sakaiProxy.getCurrentUserId(); if (null == userId) { // We are not logged in throw new ServletException("getCurrentUser returned null."); }/*from www. j ava 2 s.c o m*/ String siteLanguage = sakaiProxy.getCurrentSiteLocale(); Locale locale = null; ResourceLoader rl = null; if (siteLanguage != null) { String[] parts = siteLanguage.split("_"); if (parts.length == 1) { locale = new Locale(parts[0]); } else if (parts.length == 2) { locale = new Locale(parts[0], parts[1]); } else if (parts.length == 3) { locale = new Locale(parts[0], parts[1], parts[2]); } rl = new ResourceLoader("org.sakaiproject.roster.i18n.ui"); rl.setContextLocale(locale); } else { rl = new ResourceLoader(userId, "org.sakaiproject.roster.i18n.ui"); locale = rl.getLocale(); } if (locale == null || rl == null) { log.error("Failed to load the site or user i18n bundle"); } String language = locale.getLanguage(); String country = locale.getCountry(); if (country != null && !country.equals("")) { language += "_" + country; } request.setAttribute("sakaiHtmlHead", (String) request.getAttribute("sakai.html.head")); request.setAttribute("userId", userId); request.setAttribute("state", sakaiProxy.getDefaultRosterStateString()); request.setAttribute("siteId", sakaiProxy.getCurrentSiteId()); request.setAttribute("language", language); request.setAttribute("defaultSortColumn", sakaiProxy.getDefaultSortColumn()); request.setAttribute("firstNameLastName", sakaiProxy.getFirstNameLastName()); request.setAttribute("hideSingleGroupFilter", sakaiProxy.getHideSingleGroupFilter()); request.setAttribute("viewUserDisplayId", sakaiProxy.getViewUserDisplayId()); request.setAttribute("viewEmail", sakaiProxy.getViewEmail()); request.setAttribute("superUser", sakaiProxy.isSuperUser()); request.setAttribute("siteMaintainer", sakaiProxy.isSiteMaintainer(sakaiProxy.getCurrentSiteId())); response.setContentType("text/html"); request.getRequestDispatcher("/WEB-INF/bootstrap.jsp").include(request, response); }