Example usage for java.util Locale toString

List of usage examples for java.util Locale toString

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Usage

From source file:org.openmrs.web.controller.concept.ConceptProposalFormControllerTest.java

/**
 * @see ConceptProposalFormController#onSubmit(HttpServletRequest,HttpServletResponse,Object,BindException)
 *///from  w  w w  .j a v  a  2  s .co m
@Test
@Verifies(value = "should create a single unique synonym and obs for all similar proposals", method = "onSubmit(HttpServletRequest,HttpServletResponse,Object,BindException)")
public void onSubmit_shouldCreateASingleUniqueSynonymAndObsForAllSimilarProposals() throws Exception {
    executeDataSet("org/openmrs/api/include/ConceptServiceTest-proposals.xml");

    ConceptService cs = Context.getConceptService();
    ObsService os = Context.getObsService();
    final Integer conceptproposalId = 5;
    ConceptProposal cp = cs.getConceptProposal(conceptproposalId);
    Concept obsConcept = cp.getObsConcept();
    Concept conceptToMap = cs.getConcept(5);
    Locale locale = Locale.ENGLISH;
    //sanity checks
    Assert.assertFalse(conceptToMap.hasName(cp.getOriginalText(), locale));
    Assert.assertEquals(0,
            os.getObservationsByPersonAndConcept(cp.getEncounter().getPatient(), obsConcept).size());
    List<ConceptProposal> proposals = cs.getConceptProposals(cp.getOriginalText());
    Assert.assertEquals(5, proposals.size());
    for (ConceptProposal conceptProposal : proposals) {
        Assert.assertNull(conceptProposal.getObs());
    }

    // set up the controller
    ConceptProposalFormController controller = (ConceptProposalFormController) applicationContext
            .getBean("conceptProposalForm");
    controller.setApplicationContext(applicationContext);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(new MockHttpSession(null));
    request.setMethod("POST");
    request.addParameter("conceptProposalId", conceptproposalId.toString());
    request.addParameter("finalText", cp.getOriginalText());
    request.addParameter("conceptId", conceptToMap.getConceptId().toString());
    request.addParameter("conceptNamelocale", locale.toString());
    request.addParameter("action", "");
    request.addParameter("actionToTake", "saveAsSynonym");

    HttpServletResponse response = new MockHttpServletResponse();
    ModelAndView mav = controller.handleRequest(request, response);
    assertNotNull(mav);
    assertTrue(mav.getModel().isEmpty());

    Assert.assertEquals(cp.getOriginalText(), cp.getFinalText());
    Assert.assertTrue(conceptToMap.hasName(cp.getOriginalText(), locale));
    Assert.assertNotNull(cp.getObs());
    //Obs should have been created for the 2 proposals with same text, obsConcept but different encounters
    Assert.assertEquals(2,
            os.getObservationsByPersonAndConcept(cp.getEncounter().getPatient(), obsConcept).size());

    //The proposal with a different obs concept should have been skipped
    proposals = cs.getConceptProposals(cp.getFinalText());
    Assert.assertEquals(1, proposals.size());
    Assert.assertEquals(21, proposals.get(0).getObsConcept().getConceptId().intValue());
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

/**
 * Returns the localized version of an English html file
 * English file is something like <root dir>/doc/webUI/userGuide.html
 * the localized file will be <root dir>/doc/webUI/locale/userGuide.html
 *//*from  w  w  w . java  2s .com*/
public String getLocalizedHTMLFile(String htmlFile) {

    if (htmlFile == null || htmlFile.equals(""))
        return htmlFile;

    // split the file into directory and file name. file name could be followed
    // by #anchor or \#anchor or something else
    int dirIndex = htmlFile.lastIndexOf('/');
    int extensionIndex = htmlFile.indexOf(".html");
    if (dirIndex == -1 || extensionIndex == -1 || (dirIndex + 1) > extensionIndex)
        return htmlFile;
    String dirName = htmlFile.substring(0, dirIndex);
    String fileName = htmlFile.substring(dirIndex + 1, extensionIndex);
    String anchor = htmlFile.substring(extensionIndex + 5);

    UserPreferencesBean userBean = new UserPreferencesBean();
    Locale uiLocale = userBean.getUiLocale();

    ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

    String localizedFile = dirName + "/" + uiLocale.toString() + "/" + fileName + ".html";
    // start with .. because the callers are passing the context path
    String realPath = ctx.getRealPath("../" + localizedFile);
    File f = new File(realPath);
    if (f.exists())
        return localizedFile + anchor;

    // try to use language country, without variant
    if (uiLocale.getVariant() != null && !"".equals(uiLocale.getVariant())) {
        localizedFile = dirName + "/" + uiLocale.getLanguage() + "_" + uiLocale.getCountry() + "/" + fileName
                + ".html";
        realPath = ctx.getRealPath("../" + localizedFile);
        f = new File(realPath);
        if (f.exists())
            return localizedFile + anchor;
    }

    // try to use language without country and variant
    if (uiLocale.getCountry() != null && !"".equals(uiLocale.getCountry())) {
        localizedFile = dirName + "/" + uiLocale.getLanguage() + "/" + fileName + ".html";
        realPath = ctx.getRealPath("../" + localizedFile);
        f = new File(realPath);
        if (f.exists())
            return localizedFile + anchor;
    }
    //fall back to original file
    return htmlFile;
}

From source file:com.erudika.para.client.ParaClient.java

/**
 * Formats a date in a specific format./*ww  w. j  a va2 s .com*/
 * @param format the date format
 * @param loc the locale instance
 * @return a formatted date
 */
public String formatDate(String format, Locale loc) {
    MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();
    params.putSingle("format", format);
    params.putSingle("locale", loc == null ? null : loc.toString());
    return getEntity(invokeGet("utils/formatdate", params), String.class);
}

From source file:com.octo.captcha.engine.bufferedengine.BufferedEngineContainer.java

/**
 * Method launch by a scheduler to swap captcha from disk buffer to the memory buffer. The ratio of swaping for each
 * locale is defined in the configuration component.
 *///  ww w  . ja va 2  s .  c om
public void swapCaptchasFromPersistentToVolatileMemory() {

    log.debug("entering swapCaptchasFromDiskBufferToMemoryBuffer()");

    MapIterator it = config.getLocaleRatio().mapIterator();

    //construct the map of swap size by locales;
    HashedMap captchasRatios = new HashedMap();
    while (it.hasNext()) {

        Locale locale = (Locale) it.next();
        double ratio = ((Double) it.getValue()).doubleValue();
        int ratioCount = (int) Math.round(config.getSwapSize().intValue() * ratio);

        //get the reminding size corresponding to the ratio
        int diff = (int) Math
                .round((config.getMaxVolatileMemorySize().intValue() - this.volatileBuffer.size()) * ratio);

        diff = diff < 0 ? 0 : diff;
        int toSwap = (diff < ratioCount) ? diff : ratioCount;

        captchasRatios.put(locale, new Integer(toSwap));
    }
    //get them from persistent buffer
    Iterator captchasRatiosit = captchasRatios.mapIterator();

    while (captchasRatiosit.hasNext() && !shutdownCalled) {
        Locale locale = (Locale) captchasRatiosit.next();
        int swap = ((Integer) captchasRatios.get(locale)).intValue();
        if (log.isDebugEnabled()) {
            log.debug("try to swap  " + swap + " Captchas from persistent to volatile memory with locale : "
                    + locale.toString());
        }

        Collection temp = this.persistentBuffer.removeCaptcha(swap, locale);

        this.volatileBuffer.putAllCaptcha(temp, locale);
        if (log.isDebugEnabled()) {
            log.debug("swaped  " + temp.size() + " Captchas from persistent to volatile memory with locale : "
                    + locale.toString());
        }
        //stats
        persistentMemoryHits += temp.size();
    }

    if (log.isDebugEnabled()) {
        log.debug("new volatil Buffer size : " + volatileBuffer.size());
    }
    // stats
    persistentToVolatileSwaps++;
}

From source file:org.itracker.services.implementations.ConfigurationServiceImpl.java

public void updateLanguage(Locale locale, List<Language> items) {

    if (locale != null && items != null) {
        Configuration configItem = new Configuration(Configuration.Type.locale, locale.toString(),
                getItrackerVersion());/*w ww .j  a  v  a2  s .co  m*/
        updateLanguage(locale, items, configItem);

    }

}

From source file:com.haulmont.cuba.restapi.ServerTokenStoreImpl.java

protected void storeAccessTokenToDatabase(String tokenValue, byte[] accessTokenBytes, String authenticationKey,
        byte[] authenticationBytes, Date tokenExpiry, String userLogin, @Nullable Locale locale,
        @Nullable String refreshTokenValue) {
    try (Transaction tx = persistence.getTransaction()) {
        EntityManager em = persistence.getEntityManager();
        AccessToken accessToken = metadata.create(AccessToken.class);
        accessToken.setCreateTs(timeSource.currentTimestamp());
        accessToken.setTokenValue(tokenValue);
        accessToken.setTokenBytes(accessTokenBytes);
        accessToken.setAuthenticationKey(authenticationKey);
        accessToken.setAuthenticationBytes(authenticationBytes);
        accessToken.setExpiry(tokenExpiry);
        accessToken.setUserLogin(userLogin);
        accessToken.setLocale(locale != null ? locale.toString() : null);
        accessToken.setRefreshTokenValue(refreshTokenValue);
        em.persist(accessToken);/*from   w w  w.  java2 s  .co  m*/
        tx.commit();
    }
}

From source file:org.itracker.services.implementations.ConfigurationServiceImpl.java

public List<Language> getLanguage(Locale locale) {
    Map<String, String> language = new HashMap<String, String>();
    if (locale == null) {
        locale = new Locale("");
    }/* w  ww  .j a  v a 2 s  .  c  om*/
    String localeString = (locale.toString().equals("") ? ITrackerResources.BASE_LOCALE : locale.toString());

    Collection<Language> items = languageDAO.findByLocale(localeString);
    for (Language item : items) {
        language.put(item.getResourceKey(), item.getResourceValue());
    }

    Language[] languageArray = new Language[language.size()];
    int i = 0;

    for (String key : language.keySet()) {
        languageArray[i] = new Language(localeString, key, language.get(key));
        i++;
    }
    return Arrays.asList(languageArray);
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractBillingController.java

@RequestMapping(value = { "/sendEmailPdfInvoice" }, method = RequestMethod.GET)
public void sendEmailPdfAccountStatement(@ModelAttribute("currentTenant") Tenant tenant,
        @RequestParam(value = "viewBy", required = false) String viewBy,
        @RequestParam(value = "tenant", required = false) String tenantParam,
        @RequestParam(value = "accountStatementUuid", required = false) String accountStatementUuid,
        @RequestParam(value = "page", required = false, defaultValue = "1") String currentPage, ModelMap map,
        HttpServletRequest request, HttpServletResponse response) {

    logger.debug("###Entering in sendEmailPdfAccountStaement method @GET");

    Tenant effectiveTenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);

    AccountStatement accountStatement = billingService.getAccountStatement(accountStatementUuid);
    Locale locale = getCurrentUser().getLocale() != null ? getCurrentUser().getLocale() : getDefaultLocale();
    String invoicePdfString = getInvoicePdfHtmlString(effectiveTenant, accountStatement, locale.toString());

    List<String> listUser = new ArrayList<String>();
    User currentUser = getCurrentUser();
    listUser.add(currentUser.getEmail());
    billingService.sendInvoiceEmail(currentUser, invoicePdfString, accountStatement, locale, listUser);
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Remove a precise number of captcha with a locale
 *
 * @param number The number of captchas to remove
 * @param locale The locale of the removed captchas
 *
 * @return a collection of captchas/*w  w w . j a v a 2 s.  c o  m*/
 */
public Collection removeCaptcha(int number, Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatement psdel = null;
    ResultSet rs = null;
    Collection collection = new UnboundedFifoBuffer();
    Collection temp = new UnboundedFifoBuffer();
    if (number < 1) {
        return collection;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("try to remove " + number + " captchas");
        }
        ;
        con = datasource.getConnection();

        ps = con.prepareStatement(
                "select *  from " + table + " where " + localeColumn + " = ? order by " + timeMillisColumn);

        psdel = con.prepareStatement(
                "delete from " + table + " where " + timeMillisColumn + "= ? and " + hashCodeColumn + "= ? ");//and " + localeColumn
        //+ "= ?");
        ps.setString(1, locale.toString());
        ps.setMaxRows(number);
        //read
        rs = ps.executeQuery();
        int i = 0;
        while (rs.next() && i < number) {
            try {
                i++;
                InputStream in = rs.getBinaryStream(captchaColumn);
                ObjectInputStream objstr = new ObjectInputStream(in);
                Object captcha = objstr.readObject();
                temp.add(captcha);
                //and delete
                long time = rs.getLong(timeMillisColumn);
                long hash = rs.getLong(hashCodeColumn);
                psdel.setLong(1, time);
                psdel.setLong(2, hash);
                //psdel.setString(3, rs.getString(localeColumn));
                psdel.addBatch();

                if (log.isDebugEnabled()) {
                    log.debug("remove captcha added to batch : " + time + ";" + hash);
                }

            } catch (IOException e) {
                log.error("error during captcha deserialization, "
                        + "check your class versions. removing row from database", e);
                psdel.execute();
            } catch (ClassNotFoundException e) {
                log.error("Serialized captcha class in database is not in your classpath!", e);
            }

        }
        //execute batch delete
        psdel.executeBatch();
        log.debug("batch executed");
        rs.close();
        //commit the whole stuff
        con.commit();
        log.debug("batch commited");
        //only add after commit
        collection.addAll(temp);
    } catch (SQLException e) {
        log.error(DB_ERROR, e);
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
        }

    } finally {

        if (ps != null) {
            try {
                ps.close();
            } // rollback on error
            catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } // rollback on error
            catch (SQLException e) {
            }
        }
    }
    return collection;
}

From source file:org.itracker.services.implementations.ConfigurationServiceImpl.java

@Override
public Language getLanguageItemByKey(String key, Locale locale) {
    String localeString = ITrackerResources.BASE_LOCALE;
    if (null != locale && !locale.equals(ITrackerResources.getLocale(ITrackerResources.BASE_LOCALE))) {
        localeString = locale.toString();
    }//from www .j av  a  2s  .  c  om
    Language languageItem = languageDAO.findByKeyAndLocale(key, localeString);
    // TODO: obsolete code:
    //        try {
    //            languageItem = languageDAO.findByKeyAndLocale(key, ITrackerResources.BASE_LOCALE);
    //        } catch (RuntimeException e) {
    //            logger.debug("could not find {}with BASE", key);
    //            languageItem = null;
    //        }
    //
    //        if (null == locale) {
    //            logger.debug("locale was null, returning BASE: {}", languageItem);
    //            return languageItem;
    //        }
    //        try {
    //            languageItem = languageDAO.findByKeyAndLocale(key, locale.getLanguage());
    //        } catch (RuntimeException re) {
    //            logger.debug("could not find {}with language {}", key, locale.getLanguage());
    //        }
    //        if (StringUtils.isNotEmpty(locale.getCountry())) {
    //            try {
    //                languageItem = languageDAO.findByKeyAndLocale(key, locale.toString());
    //            } catch (RuntimeException ex) {
    //                logger.debug("could not find {}with locale {}", key, locale);
    //            }
    //        }

    return languageItem;

}