Example usage for java.util Locale Locale

List of usage examples for java.util Locale Locale

Introduction

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

Prototype

public Locale(String language) 

Source Link

Document

Construct a locale from a language code.

Usage

From source file:org.openmrs.module.rwandaprimarycare.MyPropertiesController.java

@RequestMapping("/module/rwandaprimarycare/languageChanged.form")
public String changeUserLanguage(ModelMap model, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) throws PrimaryCareException {
    try {//from  w  w  w  .j  av  a2s. co m
        String locale = request.getParameter("locales");
        User user = Context.getAuthenticatedUser();
        Map<String, String> properties = user.getUserProperties();
        properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, locale);
        Context.getUserService().saveUser(user, null);
        Context.setLocale(new Locale(locale));

    } catch (Exception e) {
        throw new PrimaryCareException(e);
    }
    return "/module/rwandaprimarycare/homepage";
}

From source file:de.damdi.fitness.db.parser.MuscleJSONParser.java

/**
 * Parses the JSON-String to a list of {@link Muscle}s.
 * // w ww. j  a v a 2 s  . c o  m
 * Example for such a .json File:
 * 
 *  [{
  *     "de": { "name" : "Bizeps" },
  *     "en": { "name" : "Biceps", "alternative_names":["Biceps muscle"] }
  *   }, ...]
  *   
  * @param jsonString The String to parse.
  * 
  * @return A list of {@link Muscle}s, null if an Error occurs..
  * 
 */
@Override
public List<Muscle> parse(String jsonString) {
    List<Muscle> muscleList = new ArrayList<Muscle>();

    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject muscleObject = jsonArray.getJSONObject(i);

            Muscle m = null;

            for (String locale : TAG_LOCALES) {
                if (muscleObject.has(locale)) {
                    JSONObject languageObject = muscleObject.getJSONObject(locale);

                    // name
                    String name = languageObject.getString(TAG_NAME);

                    // first name is primary name, all other names are alternative names
                    List<String> nameList = new ArrayList<String>();
                    nameList.add(name);

                    // alternative names   
                    if (languageObject.has(TAG_ALTERNATIVE_NAMES)) {
                        JSONArray alternativeNameJSONArray = languageObject.getJSONArray(TAG_ALTERNATIVE_NAMES);
                        String[] alternativeNameArray = this.jsonArrayToStringArray(alternativeNameJSONArray);

                        for (int t = 0; t < alternativeNameArray.length; t++) {
                            String altName = alternativeNameArray[t];
                            nameList.add(altName);
                        }
                    }

                    if (m == null) {
                        m = new Muscle(new Locale(locale), nameList);
                    } else {
                        m.addNames(new Locale(locale), nameList);
                    }
                }
            }

            // Log.d(TAG, "Finished parsing Muscle: \n" + m.toDebugString());
            muscleList.add(m);

        }

    } catch (JSONException e) {
        Log.e(TAG, "Error during parsing JSON File.", e);
        return null;
    }

    if (muscleList.isEmpty())
        throw new AssertionError("JSON parsing failed: no muscles parsed.");
    return muscleList;
}

From source file:com.ct.speech.TTS.java

@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {/*  w  w w .  j av  a 2  s.c om*/
        if (action.equals("speak")) {
            String text = args.getString(0);
            if (isReady()) {
                mTts.speak(text, TextToSpeech.QUEUE_ADD, null);
                return new PluginResult(status, result);
            } else {
                JSONObject error = new JSONObject();
                error.put("message", "TTS service is still initialzing.");
                error.put("code", TTS.INITIALIZING);
                return new PluginResult(PluginResult.Status.ERROR, error);
            }
        } else if (action.equals("silence")) {
            if (isReady()) {
                mTts.playSilence(args.getLong(0), TextToSpeech.QUEUE_ADD, null);
                return new PluginResult(status, result);
            } else {
                JSONObject error = new JSONObject();
                error.put("message", "TTS service is still initialzing.");
                error.put("code", TTS.INITIALIZING);
                return new PluginResult(PluginResult.Status.ERROR, error);
            }
        } else if (action.equals("startup")) {
            if (mTts == null) {
                this.startupCallbackId = callbackId;
                state = TTS.INITIALIZING;
                mTts = new TextToSpeech((Context) ctx, this);
                //mTts.setLanguage(Locale.US);         
            }
            PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING);
            pluginResult.setKeepCallback(true);
            return pluginResult;
        } else if (action.equals("shutdown")) {
            if (mTts != null) {
                mTts.shutdown();
            }
            return new PluginResult(status, result);
        } else if (action.equals("stop")) {
            if (mTts != null) {
                mTts.stop();
            }
            return new PluginResult(status, result);
        } else if (action.equals("getLanguage")) {
            if (mTts != null) {
                result = mTts.getLanguage().toString();
                return new PluginResult(status, result);
            }
        } else if (action.equals("isLanguageAvailable")) {
            if (mTts != null) {
                Locale loc = new Locale(args.getString(0));
                int available = mTts.isLanguageAvailable(loc);
                result = (available < 0) ? "false" : "true";
                return new PluginResult(status, result);
            }
        } else if (action.equals("setLanguage")) {
            if (mTts != null) {
                Locale loc = new Locale(args.getString(0));
                int available = mTts.setLanguage(loc);
                result = (available < 0) ? "false" : "true";
                return new PluginResult(status, result);
            }
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        e.printStackTrace();
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}

From source file:de.ingrid.iplug.sns.gssoil.GsSoilIndexingInterfaceTestLocal.java

public void testFullClassifyDirectly() throws Exception {
    SpringUtil springUtil = new SpringUtil("spring/external-services.xml");
    final Class<FullClassifyService> _fullClassifyService = null;
    FullClassifyService fullClassify = springUtil.getBean("fullClassifyService", _fullClassifyService);

    // autoClassifyText
    // --------------------
    FullClassifyResult res = fullClassify.autoClassifyText("lisbon soil", 10, true, FilterType.ONLY_TERMS,
            new Locale("en"));
    assertTrue(res.getTerms() != null);/*from   ww w  .j av a2s .  com*/
    assertTrue(res.getTerms().size() > 0);
    res = fullClassify.autoClassifyText("lisbon soil", 10, true, FilterType.ONLY_LOCATIONS, new Locale("en"));
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);
    res = fullClassify.autoClassifyText("lisbon soil", 10, true, null, new Locale("en"));
    assertTrue(res.getTerms() != null);
    assertTrue(res.getTerms().size() > 0);
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);

    // autoClassifyURL
    // --------------------
    //        String url = "http://www.visitlisboa.com";
    String url = "http://www.berlin.de/";

    log.info("START -> autoClassifyURL 1000 ONLY_TERMS ignoreCase=true 'en' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, true, FilterType.ONLY_TERMS, new Locale("en"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getTerms() != null);
    assertTrue(res.getTerms().size() > 0);
    log.info("res.getTerms().size() " + res.getTerms().size());
    log.info("res.getTerms() " + getTermListOutput(res.getTerms()));
    System.out.println();

    // ignore case
    log.info("START -> autoClassifyURL 1000 ONLY_LOCATIONS ignoreCase=true 'pt' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, true, FilterType.ONLY_LOCATIONS, new Locale("pt"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);
    log.info("res.getLocations().size() " + res.getLocations().size());
    log.info("res.getLocations() " + getLocationListOutput(res.getLocations()));
    System.out.println();

    // IGNORE CASE, results with "de"
    log.info("START -> autoClassifyURL 1000 ONLY_LOCATIONS ignoreCase=true 'de' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, true, FilterType.ONLY_LOCATIONS, new Locale("de"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);
    log.info("res.getLocations().size() " + res.getLocations().size());
    log.info("res.getLocations() " + getLocationListOutput(res.getLocations()));
    System.out.println();

    // DO NOT IGNORE CASE, results with "de"
    log.info("START -> autoClassifyURL 1000 ONLY_LOCATIONS ignoreCase=FALSE 'de' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, false, FilterType.ONLY_LOCATIONS, new Locale("de"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);
    log.info("res.getLocations().size() " + res.getLocations().size());
    log.info("res.getLocations() " + getLocationListOutput(res.getLocations()));
    System.out.println();

    // DO NOT IGNORE CASE, NO results with "en" (only uppercase "Berlin" on page !
    log.info("START -> autoClassifyURL 1000 ONLY_LOCATIONS ignoreCase=FALSE 'en' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, false, FilterType.ONLY_LOCATIONS, new Locale("en"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getLocations() != null);
    //        assertTrue(res.getLocations().size() == 0);
    log.info("res.getLocations().size() " + res.getLocations().size());
    log.info("res.getLocations() " + getLocationListOutput(res.getLocations()));
    System.out.println();

    // get all in "en", IGNORE CASE
    log.info("START -> autoClassifyURL 1000 ALL ignoreCase=true 'en' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, true, null, new Locale("en"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getTerms() != null);
    assertTrue(res.getTerms().size() > 0);
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);
    log.info("res.getTerms().size() " + res.getTerms().size());
    log.info("res.getTerms() " + getTermListOutput(res.getTerms()));
    log.info("res.getLocations().size() " + res.getLocations().size());
    log.info("res.getLocations() " + getLocationListOutput(res.getLocations()));
    System.out.println();

    // get all in "de"
    log.info("START -> autoClassifyURL 1000 ALL ignoreCase=true 'de' " + url);
    res = fullClassify.autoClassifyURL(new URL(url), 1000, true, null, new Locale("de"));
    log.info("END -> autoClassifyURL " + url);
    assertTrue(res.getTerms() != null);
    assertTrue(res.getTerms().size() > 0);
    assertTrue(res.getLocations() != null);
    assertTrue(res.getLocations().size() > 0);
    log.info("res.getTerms().size() " + res.getTerms().size());
    log.info("res.getTerms() " + getTermListOutput(res.getTerms()));
    log.info("res.getLocations().size() " + res.getLocations().size());
    log.info("res.getLocations() " + getLocationListOutput(res.getLocations()));
    System.out.println();
}

From source file:net.bible.android.BibleApplication.java

/** Allow user interface locale override by changing Settings
 *///from   w  ww.j ava2  s . c om
private void allowLocaleOverride() {
    // Has the user selected a custom locale?
    Configuration config = getBaseContext().getResources().getConfiguration();
    String lang = CommonUtils.getLocalePref();
    if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
        overrideLocale = new Locale(lang);
        Locale.setDefault(overrideLocale);
        config.locale = overrideLocale;
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());
    }
}

From source file:de.damdi.fitness.db.parser.SportsEquipmentJSONParser.java

/**
 * Parses the JSON-String to a list of {@link SportsEquipment}s.
 * //from w w  w .j  a  v a 2  s.  co  m
 * Example for such a .json File:
 * 
 * [{
  *  "de": { "name" : "bungsmatte", "alternative_names": ["Gymnastikmatte"] },
 *  "en": { "name" : "Exercise Mat" }
 * }, ...]
  *   
  * @param jsonString The String to parse.
  * 
  * @return A list of {@link SportsEquipment}s, null if an Error occurs.
  * 
 */
@Override
public List<SportsEquipment> parse(String jsonString) {
    List<SportsEquipment> sportsEquipmentList = new ArrayList<SportsEquipment>();

    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject SportsEquipmentObject = jsonArray.getJSONObject(i);

            SportsEquipment m = null;

            for (String locale : TAG_LOCALES) {
                if (SportsEquipmentObject.has(locale)) {
                    JSONObject languageObject = SportsEquipmentObject.getJSONObject(locale);

                    // name
                    String name = languageObject.getString(TAG_NAME);

                    // first name is primary name, all other names are alternative names
                    List<String> nameList = new ArrayList<String>();
                    nameList.add(name);

                    // alternative names   
                    if (languageObject.has(TAG_ALTERNATIVE_NAMES)) {
                        JSONArray alternativeNameJSONArray = languageObject.getJSONArray(TAG_ALTERNATIVE_NAMES);
                        String[] alternativeNameArray = this.jsonArrayToStringArray(alternativeNameJSONArray);

                        for (int t = 0; t < alternativeNameArray.length; t++) {
                            String altName = alternativeNameArray[t];
                            nameList.add(altName);
                        }
                    }

                    if (m == null) {
                        m = new SportsEquipment(new Locale(locale), nameList);
                    } else {
                        m.addNames(new Locale(locale), nameList);
                    }
                }
            }

            // Log.d(TAG, "Finished parsing SportsEquipment: \n" + m.toDebugString());
            sportsEquipmentList.add(m);

        }

    } catch (JSONException e) {
        Log.e(TAG, "Error during parsing JSON File.", e);
        return null;
    }

    if (sportsEquipmentList.isEmpty())
        throw new AssertionError("JSON parsing failed: no SportsEquipments parsed.");
    return sportsEquipmentList;
}

From source file:org.openmrs.module.emrapi.account.AccountComponentTest.java

@Test
public void shouldSavePersonAndUserAndProvider() {

    Role fullPrivileges = userService.getRole("Privilege Level: Full");
    Role archives = userService.getRole("Application Role: Archives");
    Role registration = userService.getRole("Application Role: Registration");

    ProviderRole nurse = providerManagementService.getProviderRole(1001);

    Person person = new Person();

    AccountDomainWrapper account = accountService.getAccountByPerson(person);
    account.setGivenName("Mark");
    account.setFamilyName("Jones");
    account.setGender("M");

    account.setUserEnabled(true);// w w w.j  a  va  2s.  com
    account.setUsername("mjones");
    account.setPassword("Mjones123");
    account.setDefaultLocale(new Locale("fr"));
    account.setPrivilegeLevel(fullPrivileges);

    Set<Role> capabilities = new HashSet<Role>();
    capabilities.add(registration);
    capabilities.add(archives);
    account.setCapabilities(capabilities);

    account.setProviderRole(nurse);

    account.save();

    Integer personId = account.getPerson().getPersonId();
    Assert.assertNotNull(personId);

    Integer userId = account.getUser().getUserId();
    Assert.assertNotNull(userId);

    Context.flushSession();
    Context.clearSession();

    Person expectedPerson = personService.getPerson(personId);

    Assert.assertEquals("Mark", expectedPerson.getGivenName());
    Assert.assertEquals("Jones", expectedPerson.getFamilyName());
    Assert.assertEquals("M", expectedPerson.getGender());
    Assert.assertEquals(Context.getAuthenticatedUser(), expectedPerson.getPersonCreator());
    Assert.assertNotNull(expectedPerson.getPersonDateCreated());

    User expectedUser = userService.getUser(userId);

    Assert.assertFalse(expectedUser.isRetired());
    Assert.assertEquals("mjones", expectedUser.getUsername());
    Assert.assertEquals(person, expectedUser.getPerson());
    Assert.assertEquals("fr",
            expectedUser.getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE).toString());
    Assert.assertTrue(expectedUser.hasRole(fullPrivileges.toString()));
    Assert.assertTrue(expectedUser.hasRole(archives.toString()));
    Assert.assertTrue(expectedUser.hasRole(registration.toString()));

    // note that we don't expose the provider object outside of the account domain wrapper; saves confusion between the
    // two Provider object types
    List<Provider> providers = providerManagementService.getProvidersByPerson(expectedPerson, false);
    Assert.assertEquals(1, providers.size());
    Assert.assertEquals(nurse, providers.get(0).getProviderRole());
}

From source file:com.assetmanager.service.mail.MailService.java

/**
 * Sends the activation e-mail to the given user.
 *
 * @param user the user//from  w ww . j  ava 2s.  co m
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
    final Properties props = new Properties();
    final Session session = Session.getDefaultInstance(props, null);
    final Message message = new MimeMessage(session);
    final Multipart multipart = new MimeMultipart();
    final MimeBodyPart htmlPart = new MimeBodyPart();
    final MimeBodyPart textPart = new MimeBodyPart();

    message.setFrom(new InternetAddress(getFromAddress()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));

    message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));

    textPart.setContent(messageSource.getMessage("mail.body.txt",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");

    htmlPart.setContent(messageSource.getMessage("mail.body.html",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");

    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);

    Transport.send(message);
}

From source file:alpha.portal.webapp.filter.LocaleFilterTest.java

/**
 * Test set locale in session when session not null.
 * //from w  w w.ja va  2 s.  c  om
 * @throws Exception
 *             the exception
 */
public void testSetLocaleInSessionWhenSessionNotNull() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("locale", "es");

    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setSession(new MockHttpSession(null));

    this.filter.doFilter(request, response, new MockFilterChain());

    // session not null, should result in not null
    final Locale locale = (Locale) request.getSession().getAttribute(Constants.PREFERRED_LOCALE_KEY);
    Assert.assertNotNull(locale);
    Assert.assertNotNull(LocaleContextHolder.getLocale());
    Assert.assertEquals(new Locale("es"), locale);
}

From source file:org.openmrs.projectbuendia.ClientConceptNamer.java

/**
 * Gets the best available concept name string to display in the client.
 * The configured locale is checked for a preferred name string, first
 * with and then without the "_client" variant, and then without the
 * region if any.  If this does not succeed, then English is checked,
 * first with and then without the "_client" variant.  For example, if the
 * locale is "es_419", the following locales will be tried, in order:
 * <ol>/*from   ww  w  .  ja va 2  s. co  m*/
 * <li>es_419_client
 * <li>es_419
 * <li>es
 * <li>en_GB_client
 * <li>en
 * </ol>
 * <p/>
 * If the configured locale is "fr", the sequence will be:
 * <ol>
 * <li>fr_GB_client
 * <li>fr
 * <li>en_GB_client
 * <li>en
 * </ol>
 * @param concept the concept to get a name for
 * @return a String for the client with the best match we can get for that locale
 */
public String getClientName(Concept concept) {
    String variant = locale.getVariant();
    Locale.Builder builder = new Locale.Builder().setLocale(locale);
    if (!VARIANT.equals(variant)) {
        builder.setVariant(VARIANT);
        // getCountry() and setRegion() refer to the same field.  Oy.
        if ("".equals(locale.getCountry())) {
            builder.setRegion(CLIENT_REGION);
        }
    }
    // If we already have a client extension, try it, before falling back to English.
    // Don't use the client fallback logic.
    String name = getPreferredStringInLocaleOrNull(concept, builder.build());
    if (name != null)
        return name;

    // try specifically what was requested. This might try the client variant again, never mind.
    name = getPreferredStringInLocaleOrNull(concept, locale);
    if (name != null)
        return name;

    // If the requested had a country/region, try it without the region
    if ("".equals(locale.getCountry())) {
        name = getPreferredStringInLocaleOrNull(concept, new Locale(locale.getLanguage()));
        if (name != null)
            return name;
    }

    // By the time we reach here the locale asked for has failed. Try our two defaults.
    name = getPreferredStringInLocaleOrNull(concept, DEFAULT_CLIENT);
    if (name != null)
        return name;
    name = getPreferredStringInLocaleOrNull(concept, DEFAULT);
    if (name != null)
        return name;
    // fail over to anything we can get
    ConceptName defaultName = concept.getName();
    if (defaultName == null) {
        log.error("No name found for concept: uuid=" + concept.getUuid() + ", id=" + concept.getId());
        return "[Concept " + concept.getId() + "]";
    }
    return defaultName.getName();
}