List of usage examples for org.apache.commons.lang LocaleUtils toLocale
public static Locale toLocale(String str)
Converts a String to a Locale.
This method takes the string format of a locale and creates the locale object from it.
LocaleUtils.toLocale("en") = new Locale("en", "") LocaleUtils.toLocale("en_GB") = new Locale("en", "GB") LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
From source file:ninja.leaping.permissionsex.bukkit.BukkitCommander.java
@Override public Locale getLocale() { return commandSource instanceof Player ? LocaleUtils.toLocale(((Player) commandSource).spigot().getLocale()) : Locale.getDefault(); }
From source file:ninja.leaping.permissionsex.bukkit.BukkitMessageFormatter.java
@Override public BaseComponent tr(Translatable tr) { Object[] oldArgs = tr.getArgs(); Object[] args = new Object[oldArgs.length]; for (int i = 0; i < oldArgs.length; ++i) { args[i] = componentFrom(oldArgs[i]); }/*from w w w.j a va 2 s . c o m*/ return new TranslatableComponent( tr.translate(sender instanceof Player ? LocaleUtils.toLocale(((Player) sender).spigot().getLocale()) : Locale.getDefault()), args); }
From source file:org.agiso.tempel.Tempel.java
/** * //from w w w. j a v a2 s. c o m * * @param properties * @throws Exception */ private Map<String, Object> addRuntimeProperties(Map<String, Object> properties) throws Exception { Map<String, Object> props = new HashMap<String, Object>(); // Okrelanie lokalizacji daty/czasu uywanej do wypenienia paramtrw szablonw // zawierajcych dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL: Locale date_locale; if (properties.containsKey(UP_DATE_LOCALE)) { date_locale = LocaleUtils.toLocale((String) properties.get(UP_DATE_LOCALE)); Locale.setDefault(date_locale); } else { date_locale = Locale.getDefault(); } TimeZone time_zone; if (properties.containsKey(UP_TIME_ZONE)) { time_zone = TimeZone.getTimeZone((String) properties.get(UP_DATE_LOCALE)); TimeZone.setDefault(time_zone); } else { time_zone = TimeZone.getDefault(); } // Wyznaczanie daty, na podstawie ktrej zostan wypenione parametry szablonw // przechowujce dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL. // Odbywa si w oparciu o wartoci parametrw 'date_format' i 'date'. Parametr // 'date_format' definiuje format uywany do parsowania acucha reprezentujcego // dat okrelon parametrem 'date'. Parametr 'date_format' moe nie by okrelony. // W takiej sytuacji uyty jest format DateFormat.LONG aktywnej lokalizacji (tj. // systemowej, ktra moe by przedefiniowana przez parametr 'date_locale'), ktry // moe by przedefiniowany przez parametry 'date_format_long' i 'time_format_long': Calendar calendar = Calendar.getInstance(date_locale); if (properties.containsKey(RP_DATE)) { String date_string = (String) properties.get(RP_DATE); if (properties.containsKey(RP_DATE_FORMAT)) { String date_format = (String) properties.get(RP_DATE_FORMAT); DateFormat formatter = new SimpleDateFormat(date_format); formatter.setTimeZone(time_zone); calendar.setTime(formatter.parse(date_string)); } else if (properties.containsKey(UP_DATE_FORMAT_LONG) && properties.containsKey(UP_TIME_FORMAT_LONG)) { // TODO: Zaoenie, e format data-czas jest zoony z acucha daty i czasu rozdzelonych spacj: // 'UP_DATE_FORMAT_LONG UP_TIME_FORMAT_LONG' DateFormat formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG) + " " + (String) properties.get(UP_TIME_FORMAT_LONG), date_locale); formatter.setTimeZone(time_zone); calendar.setTime(formatter.parse(date_string)); } else { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, date_locale); formatter.setTimeZone(time_zone); calendar.setTime(formatter.parse(date_string)); } } // Jeli nie okrelono, wypenianie parametrw przechowujcych poszczeglne // skadniki daty, tj. rok, miesic i dzie: if (!properties.containsKey(TP_YEAR)) { props.put(TP_YEAR, calendar.get(Calendar.YEAR)); } if (!properties.containsKey(TP_MONTH)) { props.put(TP_MONTH, calendar.get(Calendar.MONTH)); } if (!properties.containsKey(TP_DAY)) { props.put(TP_DAY, calendar.get(Calendar.DAY_OF_MONTH)); } // Jeli nie okrelono, wypenianie parametrw przechowujcych dat i czas w // formatach SHORT, MEDIUM, LONG i FULL (na podstawie wyznaczonej lokalizacji): Date date = calendar.getTime(); if (!properties.containsKey(TP_DATE_SHORT)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_SHORT)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_SHORT), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.SHORT, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_SHORT, formatter.format(date)); } if (!properties.containsKey(TP_DATE_MEDIUM)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_MEDIUM)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_MEDIUM), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_MEDIUM, formatter.format(date)); } if (!properties.containsKey(TP_DATE_LONG)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_LONG)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.LONG, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_LONG, formatter.format(date)); } if (!properties.containsKey(TP_DATE_FULL)) { DateFormat formatter; if (properties.containsKey(UP_DATE_FORMAT_FULL)) { formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_FULL), date_locale); } else { formatter = DateFormat.getDateInstance(DateFormat.FULL, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_DATE_FULL, formatter.format(date)); } if (!properties.containsKey(TP_TIME_SHORT)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_SHORT)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_SHORT), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.SHORT, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_SHORT, formatter.format(date)); } if (!properties.containsKey(TP_TIME_MEDIUM)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_MEDIUM)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_MEDIUM), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_MEDIUM, formatter.format(date)); } if (!properties.containsKey(TP_TIME_LONG)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_LONG)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_LONG), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.LONG, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_LONG, formatter.format(date)); } if (!properties.containsKey(TP_TIME_FULL)) { DateFormat formatter; if (properties.containsKey(UP_TIME_FORMAT_FULL)) { formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_FULL), date_locale); } else { formatter = DateFormat.getTimeInstance(DateFormat.FULL, date_locale); } formatter.setTimeZone(time_zone); props.put(TP_TIME_FULL, formatter.format(date)); } return props; }
From source file:org.apache.nifi.processors.kite.ConvertAvroSchema.java
@Override public void onTrigger(ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile incomingAvro = session.get(); if (incomingAvro == null) { return;//from w ww .j a v a2s . c om } String inputSchemaProperty = context.getProperty(INPUT_SCHEMA).evaluateAttributeExpressions(incomingAvro) .getValue(); final Schema inputSchema; try { inputSchema = getSchema(inputSchemaProperty, DefaultConfiguration.get()); } catch (SchemaNotFoundException e) { getLogger().error("Cannot find schema: " + inputSchemaProperty); session.transfer(incomingAvro, FAILURE); return; } String outputSchemaProperty = context.getProperty(OUTPUT_SCHEMA).evaluateAttributeExpressions(incomingAvro) .getValue(); final Schema outputSchema; try { outputSchema = getSchema(outputSchemaProperty, DefaultConfiguration.get()); } catch (SchemaNotFoundException e) { getLogger().error("Cannot find schema: " + outputSchemaProperty); session.transfer(incomingAvro, FAILURE); return; } final Map<String, String> fieldMapping = new HashMap<>(); for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) { if (entry.getKey().isDynamic()) { fieldMapping.put(entry.getKey().getName(), entry.getValue()); } } // Set locale final String localeProperty = context.getProperty(LOCALE).getValue(); final Locale locale = localeProperty.equals(DEFAULT_LOCALE_VALUE) ? Locale.getDefault() : LocaleUtils.toLocale(localeProperty); final AvroRecordConverter converter = new AvroRecordConverter(inputSchema, outputSchema, fieldMapping, locale); final DataFileWriter<Record> writer = new DataFileWriter<>( AvroUtil.newDatumWriter(outputSchema, Record.class)); writer.setCodec(getCodecFactory(context.getProperty(COMPRESSION_TYPE).getValue())); final DataFileWriter<Record> failureWriter = new DataFileWriter<>( AvroUtil.newDatumWriter(outputSchema, Record.class)); failureWriter.setCodec(getCodecFactory(context.getProperty(COMPRESSION_TYPE).getValue())); try { final AtomicLong written = new AtomicLong(0L); final FailureTracker failures = new FailureTracker(); final List<Record> badRecords = Lists.newLinkedList(); FlowFile incomingAvroCopy = session.clone(incomingAvro); FlowFile outgoingAvro = session.write(incomingAvro, new StreamCallback() { @Override public void process(InputStream in, OutputStream out) throws IOException { try (DataFileStream<Record> stream = new DataFileStream<Record>(in, new GenericDatumReader<Record>(converter.getInputSchema()))) { try (DataFileWriter<Record> w = writer.create(outputSchema, out)) { for (Record record : stream) { try { Record converted = converter.convert(record); w.append(converted); written.incrementAndGet(); } catch (AvroConversionException e) { failures.add(e); getLogger().error("Error converting data: " + e.getMessage()); badRecords.add(record); } } } } } }); FlowFile badOutput = session.write(incomingAvroCopy, new StreamCallback() { @Override public void process(InputStream in, OutputStream out) throws IOException { try (DataFileWriter<Record> w = failureWriter.create(inputSchema, out)) { for (Record record : badRecords) { w.append(record); } } } }); long errors = failures.count(); // update only if file transfer is successful session.adjustCounter("Converted records", written.get(), false); // update only if file transfer is successful session.adjustCounter("Conversion errors", errors, false); if (written.get() > 0L) { session.transfer(outgoingAvro, SUCCESS); } else { session.remove(outgoingAvro); if (errors == 0L) { badOutput = session.putAttribute(badOutput, "errors", "No incoming records"); session.transfer(badOutput, FAILURE); } } if (errors > 0L) { getLogger().warn("Failed to convert {}/{} records between Avro Schemas", new Object[] { errors, errors + written.get() }); badOutput = session.putAttribute(badOutput, "errors", failures.summary()); session.transfer(badOutput, FAILURE); } else { session.remove(badOutput); } } catch (ProcessException | DatasetIOException e) { getLogger().error("Failed reading or writing", e); session.transfer(incomingAvro, FAILURE); } catch (DatasetException e) { getLogger().error("Failed to read FlowFile", e); session.transfer(incomingAvro, FAILURE); } finally { try { writer.close(); } catch (IOException e) { getLogger().warn("Unable to close writer ressource", e); } try { failureWriter.close(); } catch (IOException e) { getLogger().warn("Unable to close writer ressource", e); } } }
From source file:org.apache.nifi.processors.kite.TestAvroRecordConverter.java
/** * Tests the case where we don't use a mapping file and just map records by * name./*from ww w . j av a 2 s . co m*/ */ @Test public void testDefaultConversion() throws Exception { // We will convert s1 from string to long (or leave it null), ignore s2, // convert s3 to from string to double, convert l1 from long to string, // and leave l2 the same. Schema input = SchemaBuilder.record("Input").namespace("com.cloudera.edh").fields().nullableString("s1", "") .requiredString("s2").requiredString("s3").optionalLong("l1").requiredLong("l2").endRecord(); Schema output = SchemaBuilder.record("Output").namespace("com.cloudera.edh").fields().optionalLong("s1") .optionalString("l1").requiredLong("l2").requiredDouble("s3").endRecord(); AvroRecordConverter converter = new AvroRecordConverter(input, output, EMPTY_MAPPING, LocaleUtils.toLocale("en_US")); Record inputRecord = new Record(input); inputRecord.put("s1", null); inputRecord.put("s2", "blah"); inputRecord.put("s3", "5.5"); inputRecord.put("l1", null); inputRecord.put("l2", 5L); Record outputRecord = converter.convert(inputRecord); assertNull(outputRecord.get("s1")); assertNull(outputRecord.get("l1")); assertEquals(5L, outputRecord.get("l2")); assertEquals(5.5, outputRecord.get("s3")); inputRecord.put("s1", "500"); inputRecord.put("s2", "blah"); inputRecord.put("s3", "5.5e-5"); inputRecord.put("l1", 100L); inputRecord.put("l2", 2L); outputRecord = converter.convert(inputRecord); assertEquals(500L, outputRecord.get("s1")); assertEquals("100", outputRecord.get("l1")); assertEquals(2L, outputRecord.get("l2")); assertEquals(5.5e-5, outputRecord.get("s3")); }
From source file:org.apache.nifi.processors.kite.TestConvertAvroSchema.java
public void testBasicConversionWithLocale(String localeString) throws IOException { TestRunner runner = TestRunners.newTestRunner(ConvertAvroSchema.class); runner.assertNotValid();/*from www . j a v a 2 s . c om*/ runner.setProperty(ConvertAvroSchema.INPUT_SCHEMA, INPUT_SCHEMA.toString()); runner.setProperty(ConvertAvroSchema.OUTPUT_SCHEMA, OUTPUT_SCHEMA.toString()); Locale locale = LocaleUtils.toLocale(localeString); runner.setProperty(ConvertAvroSchema.LOCALE, localeString); runner.setProperty("primaryColor", "color"); runner.assertValid(); NumberFormat format = NumberFormat.getInstance(locale); // Two valid rows, and one invalid because "free" is not a double. Record goodRecord1 = dataBasic("1", "blue", null, null); Record goodRecord2 = dataBasic("2", "red", "yellow", format.format(5.5)); Record badRecord = dataBasic("3", "red", "yellow", "free"); List<Record> input = Lists.newArrayList(goodRecord1, goodRecord2, badRecord); runner.enqueue(streamFor(input)); runner.run(); long converted = runner.getCounterValue("Converted records"); long errors = runner.getCounterValue("Conversion errors"); Assert.assertEquals("Should convert 2 rows", 2, converted); Assert.assertEquals("Should reject 1 rows", 1, errors); runner.assertTransferCount("success", 1); runner.assertTransferCount("failure", 1); MockFlowFile incompatible = runner.getFlowFilesForRelationship("failure").get(0); GenericDatumReader<Record> reader = new GenericDatumReader<Record>(INPUT_SCHEMA); DataFileStream<Record> stream = new DataFileStream<Record>( new ByteArrayInputStream(runner.getContentAsByteArray(incompatible)), reader); int count = 0; for (Record r : stream) { Assert.assertEquals(badRecord, r); count++; } stream.close(); Assert.assertEquals(1, count); Assert.assertEquals("Should accumulate error messages", FAILURE_SUMMARY, incompatible.getAttribute("errors")); GenericDatumReader<Record> successReader = new GenericDatumReader<Record>(OUTPUT_SCHEMA); DataFileStream<Record> successStream = new DataFileStream<Record>( new ByteArrayInputStream( runner.getContentAsByteArray(runner.getFlowFilesForRelationship("success").get(0))), successReader); count = 0; for (Record r : successStream) { if (count == 0) { Assert.assertEquals(convertBasic(goodRecord1, locale), r); } else { Assert.assertEquals(convertBasic(goodRecord2, locale), r); } count++; } successStream.close(); Assert.assertEquals(2, count); }
From source file:org.apache.sling.scripting.sightly.impl.engine.extension.I18nRuntimeExtension.java
private String get(final Bindings bindings, String text, String locale, String basename, String hint) { final SlingScriptHelper slingScriptHelper = BindingsUtils.getHelper(bindings); final SlingHttpServletRequest request = BindingsUtils.getRequest(bindings); final ResourceBundleProvider resourceBundleProvider = slingScriptHelper .getService(ResourceBundleProvider.class); if (resourceBundleProvider != null) { String key = text;// w w w . j a v a 2 s . co m if (StringUtils.isNotEmpty(hint)) { key += " ((" + hint + "))"; } if (StringUtils.isEmpty(locale)) { Enumeration<Locale> requestLocales = request.getLocales(); while (requestLocales.hasMoreElements()) { Locale l = requestLocales.nextElement(); String translation = getTranslation(resourceBundleProvider, basename, key, l); if (translation != null) { return translation; } } } else { try { Locale l = LocaleUtils.toLocale(locale); String translation = getTranslation(resourceBundleProvider, basename, key, l); if (translation != null) { return translation; } } catch (IllegalArgumentException e) { LOG.warn("Invalid locale detected: {}.", locale); return text; } } } LOG.warn( "No translation found for string '{}' using expression provided locale '{}' or default locale '{}'", new String[] { text, locale, request.getLocale().getLanguage() }); return text; }
From source file:org.apache.solr.update.processor.ParseDateFieldUpdateProcessorFactory.java
@Override public void init(NamedList args) { Locale locale = Locale.ROOT; String localeParam = (String) args.remove(LOCALE_PARAM); if (null != localeParam) { locale = LocaleUtils.toLocale(localeParam); }/*from w w w . j a va2s .c om*/ Object defaultTimeZoneParam = args.remove(DEFAULT_TIME_ZONE_PARAM); DateTimeZone defaultTimeZone = DateTimeZone.UTC; if (null != defaultTimeZoneParam) { defaultTimeZone = DateTimeZone.forID(defaultTimeZoneParam.toString()); } Collection<String> formatsParam = args.removeConfigArgs(FORMATS_PARAM); if (null != formatsParam) { for (String value : formatsParam) { formats.put(value, DateTimeFormat.forPattern(value).withZone(defaultTimeZone).withLocale(locale)); } } super.init(args); }
From source file:org.apache.solr.update.processor.ParseNumericFieldUpdateProcessorFactory.java
@Override public void init(NamedList args) { String localeParam = (String) args.remove(LOCALE_PARAM); if (null != localeParam) { locale = LocaleUtils.toLocale(localeParam); }//from w w w. j a va2 s. c om super.init(args); }
From source file:org.apache.wicket.localizedurl.LocaleUrlCodingStrategyDecorator.java
/** * Decode the querystring of the URL. one. * // ww w . jav a2 s . c o m * @see org.apache.wicket.request.IRequestCodingStrategy#decode(org.apache.wicket.Request) */ @Override public RequestParameters decode(final Request request) { LOG.info("<decode>"); LOG.info("\trequestUrl: " + request.getURL()); try { final String requestPathLocale = getRequestPathLocale(request); final Locale locale = LocaleUtils.toLocale(requestPathLocale); if (requestPathLocale != null) { if (!Session.get().getLocale().equals(locale)) { LOG.info("Changing locale to: " + locale); Session.get().setLocale(locale); } final String url = request.decodeURL(request.getURL()); LOG.info("before decoding: " + url); final String localePath = requestPathLocale + "/";// getLocaleString(request.getLocale()); LOG.info("localePath: " + localePath); // remove locale from request final String urlWithoutLocale = url.replace(localePath, ""); LOG.info("DecodedUrl: " + urlWithoutLocale); // use decorator for decoding return getDecoratedStrategy().decode(new RequestDecorator(request) { @Override public String getURL() { return urlWithoutLocale; } }); } else if (!request.getPath().startsWith(WebRequestCodingStrategy.RESOURCES_PATH_PREFIX)) { // redirect to locale aware url for all request which are not resource related // ISSUE: Redirect any url's without i18n to the default /en/ versions of those // pages final String queryString = StringUtils.isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString(); throw new RedirectToUrlException("en/" + request.getPath() + queryString); } return getDecoratedStrategy().decode(request); } finally { LOG.info("</decode>"); } }