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:info.magnolia.cms.i18n.DefaultI18nContentSupport.java

/**
 * Adds the language prefix to the uri.//from   w ww  .java  2s .  c o m
 */
@Override
protected String toI18NURI(String uri, Locale locale) {
    // don't extend the uri for the default fallback language
    if (locale.equals(getDefaultLocale())) {
        return uri;
    }

    // nothing to do for relative links
    if (uri.startsWith("/")) {
        return "/" + locale.toString() + uri;
    }
    return uri;
}

From source file:com.vmware.identity.WebssoMetadataController.java

/**
 * Handle GET request for the metadata//from   w ww .ja  v a  2s .co  m
 */
@RequestMapping(value = "/websso/SAML2/Metadata/{tenant:.*}", method = RequestMethod.GET)
public void metadata(Locale locale, @PathVariable(value = "tenant") String tenant, Model model,
        HttpServletResponse response) throws IOException {
    logger.info("Welcome to Metadata handler! " + "The client locale is " + locale.toString() + ", tenant is "
            + tenant);

    //TODO - check for correlation id in the headers PR1561606
    String correlationId = UUID.randomUUID().toString();
    DefaultIdmAccessorFactory factory = new DefaultIdmAccessorFactory(correlationId);
    try {
        IdmAccessor accessor = factory.getIdmAccessor();
        accessor.setTenant(tenant);
        String metadata = accessor.exportConfigurationAsString();
        Validate.notNull(metadata);
        response.setHeader("Content-Disposition", "attachment; filename=" + SAML_METADATA_FILENAME);
        Shared.sendResponse(response, Shared.METADATA_CONTENT_TYPE, metadata);
    } catch (Exception e) {
        logger.error("Caught exception", e);
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        String message = vr.getMessage(messageSource, locale);
        response.sendError(vr.getResponseCode(), message);
        logger.info("Responded with ERROR " + vr.getResponseCode() + ", message " + message);
    }

    model.addAttribute("tenant", tenant);
}

From source file:com.wisemapping.ncontroller.MindmapController.java

@RequestMapping(value = "maps/")
public String showListPage(@NotNull Model model) {
    final Locale locale = LocaleContextHolder.getLocale();
    // @Todo: This should be more flexible  ...
    String localeStr = locale.toString().toLowerCase();
    if ("es".equals(locale.getLanguage()) || "pt".equals(locale.getLanguage())) {
        localeStr = locale.getLanguage();
    }//from  w  w  w  .  j a  v a  2s. c  o m
    model.addAttribute("locale", localeStr);
    return "mindmapList";
}

From source file:com.switchfly.inputvalidation.sanitizer.LocaleCodeSanitizer.java

@Override
public String execute(String content) {
    if (StringUtils.isBlank(content)) {
        return content;
    }/*  w w w. j a va 2 s  .co m*/
    Locale locale;
    try {
        locale = LocaleUtils.toLocale(content);
    } catch (Exception e) {
        return getDefaultLocale(content);
    }
    if (!Arrays.asList(Locale.getAvailableLocales()).contains(locale)) {
        return getDefaultLocale(content);
    }
    return locale.toString();
}

From source file:org.jboss.dashboard.export.ExportManagerImpl.java

public void formatDataProviders(ExportOptions options, PrintWriter out, int indent) throws Exception {
    for (DataProvider dataProvider : options.getDataProviders()) {
        DataLoader dataLoader = dataProvider.getDataLoader();
        DataProviderType providerType = dataLoader.getDataProviderType();

        printIndent(out, indent++);/*from ww w.  j  a  va 2s .c o  m*/
        out.println("<dataprovider code=\"" + StringEscapeUtils.escapeXml(dataProvider.getCode()) + "\" type=\""
                + StringEscapeUtils.escapeXml(providerType.getUid()) + "\">");

        Map<Locale, String> descriptions = dataProvider.getDescriptionI18nMap();
        for (Locale key : descriptions.keySet()) {
            printIndent(out, indent);
            out.print("<description language");
            out.print("=\"" + StringEscapeUtils.escapeXml(key.toString()) + "\">");
            out.print(StringEscapeUtils.escapeXml(descriptions.get(key)));
            out.println("</description>");
        }

        if (!dataProvider.isCanEdit()) {
            printIndent(out, indent);
            out.println("<canEdit>false</canEdit>");
        }

        if (!dataProvider.isCanEditProperties()) {
            printIndent(out, indent);
            out.println("<canEditProperties>false</canEditProperties>");
        }

        if (!dataProvider.isCanDelete()) {
            printIndent(out, indent);
            out.println("<canDelete>false</canDelete>");
        }

        // The loader
        DataLoaderXMLFormat providerXMLFormat = providerType.getXmlFormat();
        providerXMLFormat.format(dataLoader, out, indent);

        // Provider properties
        dataProvider.getDataSet().formatXMLProperties(out, indent);

        // End
        printIndent(out, --indent);
        out.println("</dataprovider>");
    }
}

From source file:org.lockss.util.TestMetadataUtil.java

String findClosestAvailableLocale(String str) {
    Locale l = MetadataUtil.findClosestAvailableLocale(LocaleUtils.toLocale(str));
    return l != null ? l.toString() : null;
}

From source file:org.mifos.application.servicefacade.LoginServiceFacadeWebTier.java

@Override
public LoginDto login(String username, String password) {

    PersonnelBO user = this.personnelDao.findPersonnelByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException(LoginConstants.KEYINVALIDUSER);
    }/*w ww  .j a  v a  2 s . co m*/
    MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
    List<ValueListElement> localeList = personnelServiceFacade.getDisplayLocaleList();
    Locale preferredLocale = new Locale(configMgr.getString(LANGUAGE_CODE), configMgr.getString(COUNTRY_CODE));
    String listElement = "[" + preferredLocale.toString() + "]";
    Short localeId = user.getPreferredLocale();

    for (ValueListElement element : localeList) {
        if (element.getName().contains(listElement)) {
            localeId = element.getId().shortValue();
            break;
        }
    }

    user.setPreferredLocale(localeId);
    UserContext userContext = new UserContext();
    userContext.setPreferredLocale(preferredLocale);
    userContext.setLocaleId(localeId);
    userContext.setId(user.getPersonnelId());
    userContext.setName(user.getDisplayName());
    userContext.setLevel(user.getLevelEnum());
    userContext.setRoles(user.getRoles());
    userContext.setLastLogin(user.getLastLogin());
    userContext.setPasswordChanged(user.getPasswordChanged());
    userContext.setBranchId(user.getOffice().getOfficeId());
    userContext.setBranchGlobalNum(user.getOffice().getGlobalOfficeNum());
    userContext.setOfficeLevelId(user.getOffice().getLevel().getId());

    user.updateDetails(userContext);
    try {
        this.transactionHelper.startTransaction();
        this.transactionHelper.beginAuditLoggingFor(user);
        user.login(password);
        this.personnelDao.save(user);
        this.transactionHelper.commitTransaction();

        boolean isPasswordExpired = new LocalDate(user.getPasswordExpirationDate()).isBefore(new LocalDate());

        return new LoginDto(user.getPersonnelId(), user.getOffice().getOfficeId(), user.isPasswordChanged(),
                isPasswordExpired);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    } catch (Exception e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } finally {
        this.transactionHelper.closeSession();
    }
}

From source file:com.bstek.dorado.core.resource.DefaultGlobalResourceBundleManager.java

protected Resource findResourceInPath(String searchPath, String bundleName, Locale locale) throws Exception {
    Resource resource = null;/*from  w w w.j  a va  2s.c  o m*/

    bundleName = StringUtils.replace(bundleName, ".", "/");
    String path = PathUtils.concatPath(searchPath, bundleName);
    if (locale != null) {
        String localeSuffix = '.' + locale.toString();
        resource = ResourceUtils.getResource(path + localeSuffix + RESOURCE_FILE_SUFFIX);
        if (resource != null && resource.exists()) {
            return resource;
        }
    }

    resource = ResourceUtils.getResource(path + RESOURCE_FILE_SUFFIX);
    if (resource != null && resource.exists()) {
        return resource;
    }

    return null;
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySparqlPrep.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (request.getAttribute("WebappDaoFactorySDBPrep.setup") != null) {
        // don't run multiple times
        filterChain.doFilter(request, response);
        return;//from   www.j  av  a  2s  .c o  m
    }

    for (Pattern skipPattern : skipPatterns) {
        Matcher match = skipPattern.matcher(((HttpServletRequest) request).getRequestURI());
        if (match.matches()) {
            log.debug("request matched a skipPattern, skipping VitroRequestPrep");
            filterChain.doFilter(request, response);
            return;
        }
    }

    javax.sql.DataSource ds = JenaDataSourceSetupBase.getApplicationDataSource(_ctx);
    StoreDesc storeDesc = (StoreDesc) _ctx.getAttribute("storeDesc");
    OntModelSelector oms = (OntModelSelector) _ctx.getAttribute("unionOntModelSelector");
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    Connection sqlConn = null;
    SDBConnection conn = null;
    Store store = null;
    Dataset dataset = null;
    WebappDaoFactory wadf = null;

    try {
        if (ds == null || storeDesc == null || oms == null) {
            throw new RuntimeException("SDB store not property set up");
        }

        try {
            sqlConn = ds.getConnection();
            conn = new SDBConnection(sqlConn);
        } catch (SQLException sqe) {
            throw new RuntimeException("Unable to connect to database", sqe);
        }
        if (conn != null) {
            store = SDBFactory.connectStore(conn, storeDesc);
            dataset = SDBFactory.connectDataset(store);
            VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

            log.info("---------");

            Enumeration<String> headStrs = vreq.getHeaderNames();
            while (headStrs.hasMoreElements()) {
                String head = headStrs.nextElement();
                log.info(head + " : " + vreq.getHeader(head));
            }

            List<String> langs = new ArrayList<String>();

            log.info("Accept-Language: " + vreq.getHeader("Accept-Language"));
            Enumeration<Locale> locs = vreq.getLocales();
            while (locs.hasMoreElements()) {
                Locale locale = locs.nextElement();
                langs.add(locale.toString().replace("_", "-"));
                log.info(locale.toString() + " / " + locale.getLanguage() + " + " + locale.getCountry() + " : "
                        + locale.getDisplayCountry() + " | " + locale.getLanguage() + " : "
                        + locale.getDisplayLanguage());
            }
            WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
            config.setDefaultNamespace(defaultNamespace);
            config.setPreferredLanguages(langs);

            //okay let's make a graph-backed model
            String endpointURI = ConfigurationProperties.getBean(request)
                    .getProperty("VitroConnection.DataSource.endpointURI");

            Graph g = new SparqlGraphMultilingual(endpointURI, langs);
            //Graph g = new SparqlGraph(endpointURI);

            Model m = ModelFactory.createModelForGraph(g);
            OntModel om = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m);
            oms = new SingleContentOntModelSelector(om, oms.getDisplayModel(), oms.getUserAccountsModel());

            dataset = DatasetFactory.create(new SparqlDatasetGraph(endpointURI));

            //DataSource datasource = DatasetFactory.create();
            //datasource.addNamedModel("fake:fake", m);
            //dataset = datasource;         

            vreq.setAssertionsWebappDaoFactory(wadf);

            wadf = new WebappDaoFactoryJena(oms, config);
            //wadf = new WebappDaoFactorySDB(oms, dataset, config);
            vreq.setWebappDaoFactory(wadf);
            vreq.setFullWebappDaoFactory(wadf);
            vreq.setUnfilteredWebappDaoFactory(wadf);
            vreq.setWebappDaoFactory(wadf);
            vreq.setDataset(dataset);
            vreq.setJenaOntModel(om);
            vreq.setOntModelSelector(oms);
        }
    } catch (Throwable t) {
        log.error("Unable to filter request to set up SDB connection", t);
    }

    request.setAttribute("WebappDaoFactorySDBPrep.setup", 1);

    try {
        filterChain.doFilter(request, response);
        return;
    } finally {
        if (conn != null) {
            conn.close();
        }
        if (dataset != null) {
            dataset.close();
        }
        if (store != null) {
            store.close();
        }
        if (wadf != null) {
            wadf.close();
        }
    }

}

From source file:org.chromium.ChromeI18n.java

private void getAcceptLanguages(final CordovaArgs args, final CallbackContext callbackContext) {
    try {//  ww w . ja va2  s .c o  m
        JSONArray ret = new JSONArray();
        Locale locale = Locale.getDefault();
        String localString = locale.toString().replace('_', '-');
        ret.put(localString);
        callbackContext.success(ret);
    } catch (Exception e) {
        callbackContext.error("Could not retrieve supported locales");
        Log.e(LOG_TAG, "Could not retrieve supported locales", e);
    }
}