List of usage examples for java.util Locale getISOLanguages
public static String[] getISOLanguages()
From source file:io.getlime.security.powerauth.app.server.service.PowerAuthServiceImpl.java
@Override public GetErrorCodeListResponse getErrorCodeList(GetErrorCodeListRequest request) throws Exception { String language = request.getLanguage(); // Check if the language is valid ISO language, use EN as default if (Arrays.binarySearch(Locale.getISOLanguages(), language) < 0) { language = Locale.ENGLISH.getLanguage(); }//from w w w .j a va2s . c om Locale locale = new Locale(language); GetErrorCodeListResponse response = new GetErrorCodeListResponse(); List<String> errorCodeList = ServiceError.allCodes(); for (String errorCode : errorCodeList) { GetErrorCodeListResponse.Errors error = new GetErrorCodeListResponse.Errors(); error.setCode(errorCode); error.setValue(localizationProvider.getLocalizedErrorMessage(errorCode, locale)); response.getErrors().add(error); } return response; }
From source file:com.activecq.samples.workflow.impl.LocalizedTagTitleExtractorProcessWorkflow.java
/** * Derive the locale from the parent path segments (/content/us/en/..) * * @param resource/*from w w w. j a v a 2 s .com*/ * @return */ private Locale getLocaleFromPath(final Resource resource) { final String[] segments = StringUtils.split(resource.getPath(), PATH_DELIMITER); String country = ""; String language = ""; for (final String segment : segments) { if (ArrayUtils.contains(Locale.getISOCountries(), segment)) { country = segment; } else if (ArrayUtils.contains(Locale.getISOLanguages(), segment)) { language = segment; } } if (StringUtils.isNotBlank(country) && StringUtils.isNotBlank(language)) { return LocaleUtils.toLocale(country + "-" + language); } else if (StringUtils.isNotBlank(country)) { return LocaleUtils.toLocale(country); } else if (StringUtils.isNotBlank(language)) { return LocaleUtils.toLocale(language); } return null; }
From source file:dhbw.clippinggorilla.userinterface.windows.NewSourceWindow.java
public static List<Locale> getLanguages() { return Arrays.asList(Locale.getISOLanguages()).parallelStream().map(s -> new Locale(s)) .sorted((l1, l2) -> l1.getDisplayLanguage(VaadinSession.getCurrent().getLocale()) .compareTo(l2.getDisplayLanguage(VaadinSession.getCurrent().getLocale()))) .collect(Collectors.toList()); }
From source file:org.obiba.mica.micaConfig.rest.MicaConfigResource.java
@GET @Path("/languages") @Timed//from www .jav a 2 s . c o m @RequiresAuthentication public Map<String, String> getAvailableLanguages(@QueryParam("locale") @DefaultValue("en") String languageTag) { Locale locale = Locale.forLanguageTag(languageTag); return Arrays.stream(Locale.getISOLanguages()) .collect(Collectors.toMap(lang -> lang, lang -> new Locale(lang).getDisplayLanguage(locale))); }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
private static Locale localeFrom(final String languageCode, final String courntryCode, final String variantCode) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final List<String> allowedLanguages = Arrays.asList(Locale.getISOLanguages()); if (!allowedLanguages.contains(languageCode.toLowerCase())) { final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale has an invalid language value " + languageCode + " .", "locale", languageCode);/*from ww w. j ava 2 s. c om*/ dataValidationErrors.add(error); } if (StringUtils.isNotBlank(courntryCode.toUpperCase())) { final List<String> allowedCountries = Arrays.asList(Locale.getISOCountries()); if (!allowedCountries.contains(courntryCode)) { final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.invalid.locale.format", "The parameter locale has an invalid country value " + courntryCode + " .", "locale", courntryCode); dataValidationErrors.add(error); } } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } return new Locale(languageCode.toLowerCase(), courntryCode.toUpperCase(), variantCode); }
From source file:eu.apenet.dpt.standalone.gui.ead2edm.EdmOptionsPanel.java
public String[] getAllLanguages() { String[] isoLanguages = Locale.getISOLanguages(); Map<String, String> languagesTemp = new LinkedHashMap<String, String>(isoLanguages.length); languages = new LinkedHashMap<String, String>(isoLanguages.length); for (String isoLanguage : isoLanguages) { languagesTemp.put(new Locale(isoLanguage).getDisplayLanguage(Locale.ENGLISH), isoLanguage); }//from w ww . j a va 2 s.co m List<String> tempList = new LinkedList<String>(languagesTemp.keySet()); Collections.sort(tempList, String.CASE_INSENSITIVE_ORDER); for (String tempLanguage : tempList) { languages.put(tempLanguage, languagesTemp.get(tempLanguage)); } return languages.keySet().toArray(new String[] {}); }
From source file:org.alfresco.repo.model.filefolder.FileFolderLoader.java
/** <p> * Attempt to create a given number of text files within a specified folder. The load tolerates failures unless these * prevent <b>any</b> files from being created. Options exist to control the file size and text content distributions. * The <b>cm:auditable</b> aspect automatically applied to each node as part of Alfresco. * Additionally, extra residual text properties can be added in order to increase the size of the database storage.</p> * <p>//from ww w . j a va 2 s .c o m * The files are created regardless of the read-write state of the server.</p> * <p> * The current thread's authentication determines the user context and the authenticated user has to have sufficient * permissions to {@link PermissionService#CREATE_CHILDREN create children} within the folder. This will be enforced * by the {@link FileFolderService}.</p> * * @param folderPath the full path to the folder within the context of the * {@link Repository#getCompanyHome() Alfresco Company Home} folder e.g. * <pre>/Sites/Site.default.00009/documentLibrary</pre>. * @param fileCount the number of files to create * @param filesPerTxn the number of files to create in a transaction. Any failures within a * transaction (batch) will force the transaction to rollback; normal * {@link RetryingTransactionHelper#doInTransaction(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) retrying semantics } * are employed. * @param minFileSize the smallest file size (all sizes within 1 standard deviation of the mean) * @param maxFileSize the largest file size (all sizes within 1 standard deviation of the mean) * @param maxUniqueDocuments the maximum number of unique documents that should be created globally. * A value of <tt>1</tt> means that all documents will be the same document; * <tt>10,000,000</tt> will mean that there will be 10M unique text sequences used. * @param forceBinaryStorage <tt>true</tt> to actually write the spoofed text data to the binary store * i.e. the physical underlying storage will contain the binary data, allowing * IO to be realistically stressed if that is a requirement. To save disk * space, set this value to <tt>false</tt>, which will see all file data get * generated on request using a repeatable algorithm. * @param descriptionCount the number of <b>cm:description</b> multilingual entries to create. The current locale * is used for the first entry and additional locales are added using the * {@link Locale#getISOLanguages() Java basic languages list}. The total count cannot * exceed the total number of languages available. * TODO: Note that the actual text stored is not (yet) localized. * @param descriptionSize the size (in bytes) for each <b>cm:description</b> property created; values from 16 bytes to 1024 bytes are supported * @return the number of files successfully created * @throws FileNotFoundException if the folder path does not exist * @throws IllegalStateException if the repository is not ready */ public int createFiles(final String folderPath, final int fileCount, final int filesPerTxn, final long minFileSize, long maxFileSize, final long maxUniqueDocuments, final boolean forceBinaryStorage, final int descriptionCount, final long descriptionSize) throws FileNotFoundException { if (repoState.isBootstrapping()) { throw new IllegalStateException("Repository is still bootstrapping."); } if (minFileSize > maxFileSize) { throw new IllegalArgumentException("Min/max file sizes incorrect: " + minFileSize + "-" + maxFileSize); } if (filesPerTxn < 1) { throw new IllegalArgumentException("'filesPerTxn' must be 1 or more."); } if (descriptionCount < 0 || descriptionCount > Locale.getISOLanguages().length) { throw new IllegalArgumentException("'descriptionCount' exceeds the number of languages available."); } if (descriptionSize < 16L || descriptionSize > 1024L) { throw new IllegalArgumentException("'descriptionSize' can be anything from 16 to 1024 bytes."); } RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper(); // Locate the folder; this MUST work RetryingTransactionCallback<NodeRef> findFolderWork = new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Throwable { String folderPathFixed = folderPath; // Homogenise the path if (!folderPath.startsWith("/")) { folderPathFixed = "/" + folderPath; } NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome(); // Special case for the root if (folderPath.equals("/")) { return companyHomeNodeRef; } List<String> folderPathElements = Arrays.asList(folderPathFixed.substring(1).split("/")); FileInfo folderInfo = fileFolderService.resolveNamePath(companyHomeNodeRef, folderPathElements, true); // Done return folderInfo.getNodeRef(); } }; NodeRef folderNodeRef = txnHelper.doInTransaction(findFolderWork, false, true); // Create files int created = createFiles(folderNodeRef, fileCount, filesPerTxn, minFileSize, maxFileSize, maxUniqueDocuments, forceBinaryStorage, descriptionCount, descriptionSize); // Done if (logger.isDebugEnabled()) { logger.debug("Created " + created + " files in folder " + folderPath); } return created; }
From source file:org.alfresco.repo.model.filefolder.FileFolderLoader.java
private int createFiles(final NodeRef folderNodeRef, final int fileCount, final int filesPerTxn, final long minFileSize, final long maxFileSize, final long maxUniqueDocuments, final boolean forceBinaryStorage, final int descriptionCount, final long descriptionSize) { final String nameBase = UUID.randomUUID().toString(); final AtomicInteger count = new AtomicInteger(0); RetryingTransactionCallback<Void> createFilesWork = new RetryingTransactionCallback<Void>() { @Override/* w w w. java 2 s . com*/ public Void execute() throws Throwable { // Disable timestamp propagation to the parent by disabling cm:auditable policyBehaviourFilter.disableBehaviour(folderNodeRef, ContentModel.ASPECT_AUDITABLE); for (int i = 0; i < filesPerTxn; i++) { // Only create files while we need; we may need to do fewer in the last txn if (count.get() >= fileCount) { break; } // Each load has it's own base name String name = String.format("%s-%6d.txt", nameBase, count.get()); // Create a file FileInfo fileInfo = fileFolderService.create(folderNodeRef, name, ContentModel.TYPE_CONTENT, ContentModel.ASSOC_CONTAINS); NodeRef fileNodeRef = fileInfo.getNodeRef(); // Spoofed document Locale locale = Locale.ENGLISH; long seed = (long) (Math.random() * maxUniqueDocuments); long size = normalDistribution.getValue(minFileSize, maxFileSize); String contentUrl = SpoofedTextContentReader.createContentUrl(locale, seed, size); SpoofedTextContentReader reader = new SpoofedTextContentReader(contentUrl); if (forceBinaryStorage) { // Stream the text into the real storage ContentWriter writer = contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true); writer.setEncoding("UTF-8"); writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); writer.putContent(reader); } else { // Just use the URL ContentData contentData = reader.getContentData(); nodeService.setProperty(fileNodeRef, ContentModel.PROP_CONTENT, contentData); } // Store the description, if required if (descriptionCount > 0) { // Add the cm:description additional properties boolean wasMLAware = MLPropertyInterceptor.setMLAware(true); try { MLText descriptions = new MLText(); String[] languages = Locale.getISOLanguages(); String defaultLanguage = Locale.getDefault().getLanguage(); // Create cm:description translations for (int descriptionNum = -1; descriptionNum < (descriptionCount - 1); descriptionNum++) { String language = null; // Use the default language for the first description if (descriptionNum == -1) { language = defaultLanguage; } else if (languages[descriptionNum].equals(defaultLanguage)) { // Skip the default language, if we hit it continue; } else { language = languages[descriptionNum]; } Locale languageLocale = new Locale(language); // For the cm:description, create new reader with a seed that changes each time String descriptionUrl = SpoofedTextContentReader.createContentUrl(locale, seed + descriptionNum, descriptionSize); SpoofedTextContentReader readerDescription = new SpoofedTextContentReader( descriptionUrl); String description = readerDescription.getContentString(); descriptions.put(languageLocale, description); } nodeService.setProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION, descriptions); } finally { MLPropertyInterceptor.setMLAware(wasMLAware); } } // Success count.incrementAndGet(); } return null; } }; // Batches RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper(); int txnCount = (int) Math.ceil((double) fileCount / (double) filesPerTxn); for (int i = 0; i < txnCount; i++) { txnHelper.doInTransaction(createFilesWork, false, true); } // Done return count.get(); }
From source file:org.alfresco.wcm.client.interceptor.ApplicationDataInterceptor.java
public void init() { countryCodes.addAll(Arrays.asList(Locale.getISOCountries())); languageCodes.addAll(Arrays.asList(Locale.getISOLanguages())); }
From source file:org.apache.maven.plugin.javadoc.AbstractJavadocMojo.java
/** * Checks for the validity of the Javadoc options used by the user. * * @throws MavenReportException if error *//*from w w w. ja va2s. com*/ private void validateJavadocOptions() throws MavenReportException { // encoding if (StringUtils.isNotEmpty(getEncoding()) && !JavadocUtil.validateEncoding(getEncoding())) { throw new MavenReportException("Unsupported option <encoding/> '" + getEncoding() + "'"); } // locale if (StringUtils.isNotEmpty(this.locale)) { StringTokenizer tokenizer = new StringTokenizer(this.locale, "_"); final int maxTokens = 3; if (tokenizer.countTokens() > maxTokens) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant."); } Locale localeObject = null; if (tokenizer.hasMoreTokens()) { String language = tokenizer.nextToken().toLowerCase(Locale.ENGLISH); if (!Arrays.asList(Locale.getISOLanguages()).contains(language)) { throw new MavenReportException( "Unsupported language '" + language + "' in option <locale/> '" + this.locale + "'"); } localeObject = new Locale(language); if (tokenizer.hasMoreTokens()) { String country = tokenizer.nextToken().toUpperCase(Locale.ENGLISH); if (!Arrays.asList(Locale.getISOCountries()).contains(country)) { throw new MavenReportException( "Unsupported country '" + country + "' in option <locale/> '" + this.locale + "'"); } localeObject = new Locale(language, country); if (tokenizer.hasMoreTokens()) { String variant = tokenizer.nextToken(); localeObject = new Locale(language, country, variant); } } } if (localeObject == null) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant."); } this.locale = localeObject.toString(); final List<Locale> availableLocalesList = Arrays.asList(Locale.getAvailableLocales()); if (StringUtils.isNotEmpty(localeObject.getVariant()) && !availableLocalesList.contains(localeObject)) { StringBuilder sb = new StringBuilder(); sb.append("Unsupported option <locale/> with variant '").append(this.locale); sb.append("'"); localeObject = new Locale(localeObject.getLanguage(), localeObject.getCountry()); this.locale = localeObject.toString(); sb.append(", trying to use <locale/> without variant, i.e. '").append(this.locale).append("'"); if (getLog().isWarnEnabled()) { getLog().warn(sb.toString()); } } if (!availableLocalesList.contains(localeObject)) { throw new MavenReportException("Unsupported option <locale/> '" + this.locale + "'"); } } }