List of usage examples for java.util Locale Locale
public Locale(String language)
From source file:jp.terasoluna.fw.beans.jxpath.DynamicPointerFactoryExTest.java
/** * testCreateNodePointerQname01() <br> * <br>//from www. j a v a2 s . co m * () <br> * A <br> * <br> * () name:not null<br> * () bean:new HashMap() {<br> * key="value"<br> * }<br> * () locale:Locale("ja")<br> * () bi.isDynamic():true<br> * <br> * () NodePointer:new DynamicPointerEX {<br> * locale=?locale<br> * name=?name<br> * bean=?bean<br> * }<br> * <br> * Map?? <br> * @throws Exception ????? */ @Test public void testCreateNodePointerQname01() throws Exception { // ?? DynamicPointerFactoryEx factory = new DynamicPointerFactoryEx(); QName qName = new QName("name"); Object bean = new HashMap<Object, Object>(); Locale locale = new Locale("ja"); // NodePointer result = factory.createNodePointer(qName, bean, locale); // assertSame(DynamicPointerEx.class, result.getClass()); assertSame(locale, result.getLocale()); assertSame(qName, result.getName()); assertSame(bean, ReflectionTestUtils.getField(result, "bean")); }
From source file:it.cnr.icar.eric.common.AbstractResourceBundle.java
/** * Parse a locale string, return corresponding Locale instance. * * @param localeString//w w w .j av a 2 s .c om * Name for the locale of interest. If null, use VM default locale. * @return New Locale instance. */ public static Locale parseLocale(String localeString) { Locale locale = null; if (localeString == null) { log.trace(CommonResourceBundle.getInstance() .getString("message.TheLocaleStringIsNullUsingDefaultLocale")); locale = Locale.getDefault(); } else { try { String[] args = localeString.split("_"); if (args.length == 1) { locale = new Locale(args[0]); } else if (args.length == 2) { locale = new Locale(args[0], args[1]); } else if (args.length == 3) { locale = new Locale(args[0], args[1], args[2]); } } catch (Throwable t) { log.error(CommonResourceBundle.getInstance() .getString("message.CouldNotCreateLocaleFromEriccommonlocaleProperty"), t); log.error(CommonResourceBundle.getInstance().getString("message.UsingDefaultLocaleInstead", new Object[] { Locale.getDefault().toString() })); locale = Locale.getDefault(); } } return locale; }
From source file:ru.mystamps.web.config.ServicesConfig.java
@Bean public MailService getMailService() { boolean isProductionEnvironment = env.acceptsProfiles("prod"); boolean enableTestMode = !isProductionEnvironment; return new MailServiceImpl(mailSender, messageSource, env.getProperty("app.mail.admin.email", "root@localhost"), new Locale(env.getProperty("app.mail.admin.lang", "en")), env.getRequiredProperty("app.mail.robot.email"), enableTestMode); }
From source file:io.github.felsenhower.stine_calendar_bot.main.CallLevelWrapper.java
public CallLevelWrapper(String[] args) throws IOException { String username = null;//from w w w . j a v a2 s . c o m String password = null; boolean echoPages = false; Path calendarCache = null; Path outputFile = null; boolean echoCalendar = false; // These temporary options don't have descriptions and have their // required-value all set to false final Options tempOptions = getOptions(); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; StringProvider strings = null; // Get the StringProvider try { cmd = parser.parse(tempOptions, args, true); if (cmd.hasOption("language")) { String lang = cmd.getOptionValue("language").toLowerCase(); if (lang.equals("de")) { strings = new StringProvider(Locale.GERMAN); } else { strings = new StringProvider(Locale.ENGLISH); if (!lang.equals("en")) { System.err.println(strings.get("HumanReadable.CallLevel.LangNotRecognised", lang)); } } } else { strings = new StringProvider(new Locale(Locale.getDefault().getLanguage())); } } catch (Exception e) { strings = new StringProvider(Locale.ENGLISH); } this.strings = strings; this.cliStrings = strings.from("HumanReadable.CallLevel"); this.messages = strings.from("HumanReadable.Messages"); this.appInfo = strings.from("MachineReadable.App"); // Get the localised options, with all required fields enabled as well. // Note that we are not yet applying the options to any command line, // because we still want to exit if only the help screen shall be // displayed first, but of course, we do need the localised options // here. this.isLangInitialised = true; this.options = getOptions(); try { // If no arguments are supplied, or --help is used, we will exit // after printing the help screen if (cmd.hasOption("help") || (cmd.hasOption("language") && cmd.getOptions().length == 1)) { printHelp(); } cmd = parser.parse(this.options, args, false); username = cmd.getOptionValue("user"); // URL-decode the password (STiNE doesn't actually allow special // chars in passwords, but meh...) password = URLDecoder.decode(cmd.getOptionValue("pass"), "UTF-8"); // Double-dash signals that the password shall be read from stdin if (password.equals("--")) { password = readPassword(messages.get("PasswordQuery"), messages.get("PasswordFallbackMsg")); } echoPages = cmd.hasOption("echo"); // the cache-dir argument is optional, so we read it with a default // value calendarCache = Paths .get(cmd.getOptionValue("cache-dir", strings.get("MachineReadable.Paths.CalendarCache"))) .toAbsolutePath(); // output-argument is optional as well, but this time we check if // double-dash is specified (for echo to stdout) String outputStr = cmd.getOptionValue("output", strings.get("MachineReadable.Paths.OutputFile")); if (outputStr.equals("--")) { echoCalendar = true; outputFile = null; } else { echoCalendar = false; outputFile = Paths.get(outputStr).toAbsolutePath(); } } catch (UnrecognizedOptionException e) { System.err.println(messages.get("UnrecognisedOption", e.getOption().toString())); this.printHelp(); } catch (MissingOptionException e) { // e.getMissingOptions() is just extremely horribly designed and // here is why: // // It returns an unparametrised list, to make your job especially // hard, whose elements may be: // - String-instances, if there are single independent options // missing (NOT the stupid Option itself, just why????) // - OptionGroup-instances, if there are whole OptionGroups missing // (This time the actual OptionGroup and not an unparametrised Set // that may or may not contain an Option, how inconsequential). // - Basically anything because the programmer who wrote that // function was clearly high and is most probably not to be trusted. // // This makes the job of actually displaying all the options as a // comma-separated list unnecessarily hard and hence leads to this // ugly contraption of Java-8-statements. But hey, at least it's not // as ugly as the Java 7 version (for me at least). // Sorry! // TODO: Write better code. // TODO: Write my own command line interpreter, with blackjack and // hookers. try { System.err.println(messages.get("MissingRequiredOption", ((List<?>) (e.getMissingOptions())) .stream().filter(Object.class::isInstance).map(Object.class::cast).map(o -> { if (o instanceof String) { return Collections.singletonList(options.getOption((String) o)); } else { return ((OptionGroup) o).getOptions(); } }).flatMap(o -> o.stream()).filter(Option.class::isInstance).map(Option.class::cast) .map(o -> o.getLongOpt()).collect(Collectors.joining(", ")))); this.printHelp(); } catch (Exception totallyMoronicException) { throw new RuntimeException("I hate 3rd party libraries!", totallyMoronicException); } } catch (MissingArgumentException e) { System.err.println(messages.get("MissingRequiredArgument", e.getOption().getLongOpt())); this.printHelp(); } catch (ParseException e) { System.err.println(messages.get("CallLevelParsingException", e.getMessage())); } this.username = username; this.password = password; this.echoPages = echoPages; this.calendarCache = calendarCache; this.outputFile = outputFile; this.echoCalendar = echoCalendar; }
From source file:de.damdi.fitness.db.parser.ExerciseTagJSONParser.java
/** * Parses the JSON-String to a list of {@link ExerciseTag}s. * /*from w w w. jav a 2s.com*/ * * @param jsonString The String to parse. * * @return A list of {@link ExerciseTag}s, null if an error occurs. * */ @Override public List<ExerciseTag> parse(String jsonString) { List<ExerciseTag> exerciseTagList = new ArrayList<ExerciseTag>(); JSONArray jsonArray; try { jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject SportsEquipmentObject = jsonArray.getJSONObject(i); ExerciseTag exerciseTag = null; for (String locale : TAG_LOCALES) { if (SportsEquipmentObject.has(locale)) { JSONObject languageObject = SportsEquipmentObject.getJSONObject(locale); // name String name = languageObject.getString(TAG_NAME); List<String> nameList = new ArrayList<String>(); nameList.add(name); String description = null; // description if (languageObject.has(TAG_DESCRIPTION)) { //JSONObject descriptionJSONObject = languageObject.getJSONObject(TAG_DESCRIPTION); // description description = languageObject.getString(TAG_DESCRIPTION); } if (exerciseTag == null) { exerciseTag = new ExerciseTag(new Locale(locale), nameList, description); } else { exerciseTag.addNames(new Locale(locale), nameList, description); } } } // Log.d(TAG, "Finished parsing ExerciseTag: \n" + exerciseTag.toDebugString()); exerciseTagList.add(exerciseTag); } } catch (JSONException e) { Log.e(TAG, "Error during parsing JSON File.", e); return null; } if (exerciseTagList.isEmpty()) throw new AssertionError("JSON parsing failed: no ExerciseTag parsed."); return exerciseTagList; }
From source file:com.joliciel.talismane.posTagger.PosTagSetImpl.java
void load(List<String> descriptors) { boolean nameFound = false; boolean localeFound = false; for (String descriptor : descriptors) { LOG.debug(descriptor);/*from www . j av a 2s .c o m*/ if (descriptor.startsWith("#")) { continue; } else if (!nameFound) { this.name = descriptor; nameFound = true; } else if (!localeFound) { this.locale = new Locale(descriptor); localeFound = true; } else { String[] parts = descriptor.split("\t"); tags.add(new PosTagImpl(parts[0], parts[1], PosTagOpenClassIndicator.valueOf(parts[2]))); } } }
From source file:at.alladin.rmbt.controlServer.QualityOfServiceResultResource.java
@Post("json") public String request(final String entity) { final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY"); addAllowOrigin();/*from ww w . j av a 2 s.c o m*/ JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); System.out.println(MessageFormat.format(labels.getString("NEW_QOS_RESULT"), getIP())); if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); final String lang = request.optString("client_language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } // System.out.println(request.toString(4)); if (conn != null) { ResultOptions resultOptions = new ResultOptions(new Locale(lang)); conn.setAutoCommit(false); final Test test = new Test(conn); if (request.optString("test_token").length() > 0) { final String[] token = request.getString("test_token").split("_"); try { // Check if UUID final UUID testUuid = UUID.fromString(token[0]); final String data = token[0] + "_" + token[1]; final String hmac = Helperfunctions.calculateHMAC(secret, data); if (hmac.length() == 0) errorList.addError("ERROR_TEST_TOKEN"); if (token[2].length() > 0 && hmac.equals(token[2])) { final List<String> clientNames = Arrays .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*")); final List<String> clientVersions = Arrays .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*")); if (test.getTestByUuid(testUuid) > 0) if (clientNames.contains(request.optString("client_name")) && clientVersions.contains(request.optString("client_version"))) { //save qos test results: JSONArray qosResult = request.optJSONArray("qos_result"); if (qosResult != null) { QoSTestResultDao resultDao = new QoSTestResultDao(conn); Set<String> excludeTestTypeKeys = new TreeSet<>(); excludeTestTypeKeys.add("test_type"); excludeTestTypeKeys.add("qos_test_uid"); for (int i = 0; i < qosResult.length(); i++) { JSONObject testObject = qosResult.optJSONObject(i); //String hstore = Helperfunctions.json2hstore(testObject, excludeTestTypeKeys); JSONObject resultJson = new JSONObject(testObject, JSONObject.getNames(testObject)); for (String excludeKey : excludeTestTypeKeys) { resultJson.remove(excludeKey); } QoSTestResult testResult = new QoSTestResult(); //testResult.setResults(hstore); testResult.setResults(resultJson.toString()); testResult.setTestType(testObject.getString("test_type")); testResult.setTestUid(test.getUid()); long qosTestId = testObject.optLong("qos_test_uid", Long.MIN_VALUE); testResult.setQoSTestObjectiveId(qosTestId); resultDao.save(testResult); } } QoSTestResultDao resultDao = new QoSTestResultDao(conn); PreparedStatement updateCounterPs = resultDao .getUpdateCounterPreparedStatement(); List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid()); //map that contains all test types and their result descriptions determined by the test result <-> test objectives comparison Map<TestType, TreeSet<ResultDesc>> resultKeys = new HashMap<>(); //test description set: Set<String> testDescSet = new TreeSet<>(); //test summary set: Set<String> testSummarySet = new TreeSet<>(); //iterate through all result entries for (QoSTestResult testResult : testResultList) { //reset test counters testResult.setFailureCounter(0); testResult.setSuccessCounter(0); //get the correct class of the result; TestType testType = TestType .valueOf(testResult.getTestType().toUpperCase()); Class<? extends AbstractResult<?>> clazz = testType.getClazz(); //parse hstore data final JSONObject resultJson = new JSONObject(testResult.getResults()); AbstractResult<?> result = QoSUtil.HSTORE_PARSER.fromJSON(resultJson, clazz); result.setResultJson(resultJson); if (result != null) { //add each test description key to the testDescSet (to fetch it later from the db) if (testResult.getTestDescription() != null) { testDescSet.add(testResult.getTestDescription()); } if (testResult.getTestSummary() != null) { testSummarySet.add(testResult.getTestSummary()); } testResult.setResult(result); } //compare test results with expected results QoSUtil.compareTestResults(testResult, result, resultKeys, testType, resultOptions); //resultList.put(testResult.toJson()); //update all test results after the success and failure counters have been set resultDao.updateCounter(testResult, updateCounterPs); //System.out.println("UPDATING: " + testResult.toString()); } } else errorList.addError("ERROR_CLIENT_VERSION"); } else errorList.addError("ERROR_TEST_TOKEN_MALFORMED"); } catch (final IllegalArgumentException e) { e.printStackTrace(); errorList.addError("ERROR_TEST_TOKEN_MALFORMED"); } catch (HstoreParseException e) { e.printStackTrace(); errorList.addError("ERROR_DB_CONNECTION"); } catch (IllegalAccessException e) { e.printStackTrace(); errorList.addError("ERROR_TEST_TOKEN_MALFORMED"); } } else errorList.addError("ERROR_TEST_TOKEN_MISSING"); conn.commit(); } else errorList.addError("ERROR_DB_CONNECTION"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); //System.out.println("Error parsing JSDON Data " + e.toString()); e.printStackTrace(); } catch (final SQLException e) { //System.out.println("Error while storing data " + e.toString()); e.printStackTrace(); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } return answer.toString(); }
From source file:ch.wisv.areafiftylan.utils.mail.MailServiceImpl.java
private String prepareHtmlContent(String name, String message) { // Prepare the evaluation context final Context ctx = new Context(new Locale("en")); ctx.setVariable("name", name); ctx.setVariable("message", message); return this.templateEngine.process("mailTemplate", ctx); }
From source file:com.anrisoftware.globalpom.format.locale.LocaleFormat.java
private Locale parseValue(String string, ParsePosition pos) throws ParseException { String[] strs = split(string, SEP); if (strs.length == 0) { return new Locale(""); }//from w w w . j av a 2s .c o m String lang = strs[0]; String country = null; String variant = null; if (strs.length > 1) { country = strs[1]; } if (strs.length > 2) { variant = strs[2]; } return variant != null ? new Locale(lang, country, variant) : country != null ? new Locale(lang, country) : new Locale(lang); }
From source file:com.github.haixing_hu.ilibrary.AppConfig.java
/** * Constructs a {@link AppConfig}./*www.ja v a 2 s . co m*/ */ public AppConfig(final String contexFile) { logger = LoggerFactory.getLogger(AppConfig.class); context = new ClassPathXmlApplicationContext(contexFile); config = context.getBean(Configuration.class); final String localeName = config.getString(Application.ID + LOCALE); if (StringUtils.isEmpty(localeName)) { locale = Locale.getDefault(); } else { locale = new Locale(localeName); } name = context.getMessage(Application.ID + NAME, null, locale); version = config.getString(Application.ID + VERSION); final String css = config.getString(Application.ID + STYLE); stylesheet = this.getClass().getResource(css).toExternalForm(); logger.info("{} {}", name, version); logger.info("Sets the locale to {}.", locale); }