Example usage for org.springframework.util StringUtils parseLocaleString

List of usage examples for org.springframework.util StringUtils parseLocaleString

Introduction

In this page you can find the example usage for org.springframework.util StringUtils parseLocaleString.

Prototype

@Nullable
public static Locale parseLocaleString(String localeString) 

Source Link

Document

Parse the given String representation into a Locale .

Usage

From source file:com.iflytek.edu.cloud.frame.web.filter.CheckOpenServiceFilter.java

private Locale getLocale(ServletRequest request) {
    String localePart = request.getParameter(Constants.SYS_PARAM_KEY_LOCALE);
    if (!StringUtils.hasText(localePart))
        localePart = "zh_CN";

    Locale locale = StringUtils.parseLocaleString(localePart);
    return locale;
}

From source file:com.ei.itop.common.tag.MessageTag.java

private Locale getLocale() {
    Cookie cookie = WebUtils.getCookie((HttpServletRequest) pageContext.getRequest(), "locale");
    if (cookie != null) {
        return StringUtils.parseLocaleString(cookie.getValue());
    } else {/*from ww w . j  a  v a 2 s.  c  o  m*/
        return Locale.ENGLISH;
    }
}

From source file:MailSender.java

public void sendUserPassword(User user, String clearText) {
    // major: well, sender is null, so no email is going out...silently. Just a debug message.
    // This means that the initial configuration is not able to create a sender.
    // This control should no be here and the methods that handle jndi or configFile should throw a
    // ConfigurationException if the sender is not created.
    if (sender == null) {
        logger.debug("mail sender is null, not sending new user / password change notification");
        return;// www  . j  ava  2s. co  m
    }
    logger.debug("attempting to send mail for user password");

    String localeString = user.getLocale();
    Locale locale = null;
    if (localeString == null) {
        locale = defaultLocale;
    } else {
        locale = StringUtils.parseLocaleString(localeString);
    }

    // major: there is a bit of code duplication with the method send.
    // Apparently it seems that just the body is changing but the rest is
    // really similar. As suggested above the way a message is created should be
    // refactored in a collaborator. This method should just send a message.

    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
    try {
        helper.setTo(user.getEmail());
        helper.setSubject(prefix + " " + fmt("loginMailSubject", locale));
        StringBuffer sb = new StringBuffer();
        sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>");
        sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>");
        sb.append("<table class='jtrac'>");
        sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale)
                + "</th><td style='border: 1px solid black'>" + user.getLoginName() + "</td></tr>");
        sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale)
                + "</th><td style='border: 1px solid black'>" + clearText + "</td></tr>");
        sb.append("</table>");
        sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>");
        sb.append("<p><a href='" + url + "'>" + url + "</a></p>");
        helper.setText(addHeaderAndFooter(sb), true);
        helper.setSentDate(new Date());
        // helper.setCc(from);
        helper.setFrom(from);
        sendInNewThread(message);

        // major: generic exception, method too long, I don't understand what could fail.
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

From source file:com.citrix.g2w.webdriver.tests.attendee.registration.RegistrationConfirmationPageWebDriverTests.java

/**
 * <ol>/* w  w w . j  a v  a 2 s.c  o m*/
 * Verify Registration Confirmation Page with different locale
 * <li>Create a personal account based on locale</li>
 * <li>Go to schedule webinar page and schedule a webinar with name</li>
 * <li>Get the attendee registration URL from the manage webinar page and
 * submit the registration details</li>
 * <li>Verify the Registration confirmation page title in different locale.</li>
 * </ol>
 * 
 * @param locale
 *            (locale value)
 */
@Test(dataProvider = "locales", groups = { Groups.ATTENDEE_APP, Groups.PERSONAL, Groups.LOCALE,
        Groups.REGISTRATION }, description = "Registration Confirmation Page - using different locales, verify confirmation and registration pages appear in that language")
public void verifyRegistrationAndConfirmationPageWithDifferentLocales(final String locale) {
    String registrantfirstName = this.propertyUtil.getProperty("registrant.firstName");
    String registrantlastName = this.propertyUtil.getProperty("registrant.lastName");
    String registrantemailId = this.propertyUtil.getProperty("registrant.emailId");

    this.logger.log("Verify user can create account with different locales and schedule a Webinar");

    // Override locale object based on locale value
    this.locale = StringUtils.parseLocaleString(locale);
    // Create Personal account in given locale
    ManageWebinarPage manageWebinarPage = createPersonalAccountLoginAndScheduleWebinar(locale);
    // Get the attendee registration URL
    String registrationUrl = manageWebinarPage.getRegistrationURL();
    // go to attendee registration page
    RegistrationPage registrationPage = new RegistrationPage(registrationUrl, this.getWebDriver());

    Assert.assertEquals(this.messages.getMessage("registration.title", null, this.locale),
            registrationPage.getTitle());
    Assert.assertEquals(this.messages.getMessage("registrationFieldType.email", null, this.locale),
            registrationPage.getAttendeeEmailIdLabel());
    Assert.assertTrue(registrationPage.getAttendeeEmailId().isEmpty());
    Assert.assertEquals(this.messages.getMessage("registrationFieldType.givenname", null, this.locale),
            registrationPage.getAttendeeFirstNameLabel());
    Assert.assertTrue(registrationPage.getAttendeeFirstName().isEmpty());
    Assert.assertEquals(this.messages.getMessage("registrationFieldType.surname", null, this.locale),
            registrationPage.getAttendeeLastNameLabel());
    Assert.assertTrue(registrationPage.getAttendeeLastName().isEmpty());
    RegistrationConfirmationPage registrationConfirmationPage = setupRegistrationConfirmationPage(
            registrationUrl, registrantfirstName, registrantlastName, registrantemailId);
    Assert.assertEquals(this.messages.getMessage("registrationConfirmation.title", null, this.locale),
            registrationConfirmationPage.getTitle());
}

From source file:net.malariagen.alfresco.action.CustomMailAction.java

/**
 * Gets the specified user's preferred locale, if available.
 * /*  w  w  w . j a  va 2  s.  c  o  m*/
 * @param user
 *            the username of the user whose locale is sought.
 * @return the preferred locale for that user, if available, else
 *         <tt>null</tt>. The result would be <tt>null</tt> e.g. if the user
 *         does not exist in the system.
 */
private Locale getLocaleForUser(final String user) {
    Locale locale = null;
    String localeString = null;

    // get primary tenant for the specified user.
    //
    // This can have one of (at least) 3 values currently:
    // 1. In single-tenant (community/enterprise) this will be the empty
    // string.
    // 2. In the cloud, for a username such as this: joe.soap@acme.com:
    // 2A. If the acme.com tenant exists in the system, the primary domain
    // is "acme.com"
    // 2B. Id the acme.xom tenant does not exist in the system, the primary
    // domain is null.
    String domain = tenantService.getPrimaryDomain(user);

    if (domain != null) {
        // If the domain is not null, then the user exists in the system and
        // we may get a preferred locale.
        localeString = TenantUtil.runAsSystemTenant(new TenantRunAsWork<String>() {
            public String doWork() throws Exception {
                return (String) preferenceService.getPreference(user, "locale");
            }
        }, domain);
    } else {
        // If the domain is null, then the beahviour here varies depending
        // on whether it's a single tenant or multi-tenant cloud.
        if (personExists(user)) {
            localeString = AuthenticationUtil.runAsSystem(new RunAsWork<String>() {
                public String doWork() throws Exception {
                    return (String) preferenceService.getPreference(user, "locale");
                };
            });
        }
        // else leave it as null - there's no tenant, no user for that
        // username, so we can't get a preferred locale.
    }

    if (localeString != null) {
        locale = StringUtils.parseLocaleString(localeString);
    }

    return locale;
}

From source file:edu.jhuapl.openessence.i18n.InspectableResourceBundleMessageSource.java

public Collection<Locale> getLocales() throws IOException {
    String basename = basenames[0];
    Resource resource = resourceLoader.getResource(basename + ".properties");
    if (!resource.exists()) {
        return Collections.emptyList();
    }//w w w. j a va 2  s . co m

    File baseFile = resource.getFile();
    final String bundleName = FilenameUtils.getBaseName(baseFile.getPath());
    File[] files = resource.getFile().getParentFile().listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith(bundleName + "_") && name.endsWith(".properties");
        }
    });

    List<Locale> locales = new ArrayList<Locale>();
    for (File f : files) {
        String prefix = bundleName + "_";
        String code = f.getName().substring(prefix.length()).replace(".properties", "");

        locales.add(StringUtils.parseLocaleString(code));
    }

    return locales;
}

From source file:edu.jhuapl.openessence.i18n.InspectableResourceBundleMessageSource.java

/**
 * <p> Find a supported locale that is the best match to the given locale. For example, if we only support "en" and
 * "fr", then the best match for "en_US" would be "en". </p> The available locales are given by the properties files
 * for the 0th basename. For example, if the 0th element of the basenames array is "file:/home/messages", then this
 * method looks for all properties files in /home that begin with "messages". So if that directory has the files
 * "messages_en.properties" and "messages_fr.properties", then the available locales are "en" and "fr". The "best"
 * locale is given by the order of values returned by {@link #calculateFilenamesForLocale(String, Locale)}.
 *
 * @param locale the locale to match/*from w w w.j av a2s. co m*/
 * @return best match or default locale if no best match
 */
public Locale getBestMatchingLocale(Locale locale) {
    if (basenames == null || basenames.length == 0) {
        throw new IllegalStateException("no basenames set");
    }

    List<String> filenames = calculateFilenamesForLocale(basenames[0], locale);
    if (filenames.isEmpty()) {
        throw new IllegalStateException("no filenames found for locale " + locale);
    }

    for (String filename : filenames) {
        // only support properties files since that's all we use
        Resource resource = resourceLoader.getResource(filename + ".properties");
        if (resource.exists()) {
            String prefix = basenames[0] + "_";
            String code = filename.substring(prefix.length());

            return StringUtils.parseLocaleString(code);
        }
    }

    return Locale.getDefault();
}

From source file:gr.abiss.calipso.mail.MailSender.java

public MailSender(Map<String, String> config, MessageSource messageSource, String defaultLocale) {
    // initialize email sender
    this.messageSource = messageSource;
    this.defaultLocale = StringUtils.parseLocaleString(defaultLocale);
    String mailSessionJndiName = config.get("mail.session.jndiname");
    if (StringUtils.hasText(mailSessionJndiName)) {
        initMailSenderFromJndi(mailSessionJndiName);
    }//from   ww w  . java2  s . c  om
    if (sender == null) {
        initMailSenderFromConfig(config);
    }
    // if sender is still null the send* methods will not
    // do anything when called and will just return immediately

}

From source file:gr.abiss.calipso.mail.MailSender.java

/**
 * @param user/* w  w w  . ja v  a 2  s  .co  m*/
 * @return
 */
private Locale getUserLocale(User user) {
    Locale locale;
    String localeString = user.getLocale();
    if (localeString == null) {
        locale = defaultLocale;
    } else {
        locale = StringUtils.parseLocaleString(localeString);
    }
    return locale;
}

From source file:org.alfresco.repo.action.executer.MailActionExecuter.java

/**
 * Gets the specified user's preferred locale, if available.
 * /*from ww  w  .j a  va 2 s.  c o m*/
 * @param user the username of the user whose locale is sought.
 * @return the preferred locale for that user, if available, else <tt>null</tt>. The result would be <tt>null</tt>
 *         e.g. if the user does not exist in the system.
 */
private Locale getLocaleForUser(final String user) {
    Locale locale = null;
    String localeString = null;

    // get primary tenant for the specified user.
    //
    // This can have one of (at least) 3 values currently:
    // 1. In single-tenant (community/enterprise) this will be the empty string.
    // 2. In the cloud, for a username such as this: joe.soap@acme.com:
    //    2A. If the acme.com tenant exists in the system, the primary domain is "acme.com"
    //    2B. Id the acme.xom tenant does not exist in the system, the primary domain is null.
    String domain = tenantService.getPrimaryDomain(user);

    if (domain != null) {
        // If the domain is not null, then the user exists in the system and we may get a preferred locale.
        localeString = TenantUtil.runAsSystemTenant(new TenantRunAsWork<String>() {
            public String doWork() throws Exception {
                return (String) preferenceService.getPreference(user, "locale");
            }
        }, domain);
    } else {
        // If the domain is null, then the beahviour here varies depending on whether it's a single tenant or multi-tenant cloud.
        if (personExists(user)) {
            localeString = AuthenticationUtil.runAsSystem(new RunAsWork<String>() {
                public String doWork() throws Exception {
                    return (String) preferenceService.getPreference(user, "locale");
                };
            });
        }
        // else leave it as null - there's no tenant, no user for that username, so we can't get a preferred locale.
    }

    if (localeString != null) {
        locale = StringUtils.parseLocaleString(localeString);
    }

    return locale;
}