List of usage examples for java.text MessageFormat MessageFormat
public MessageFormat(String pattern, Locale locale)
From source file:org.jahia.utils.i18n.Messages.java
/** * Returns the formatted messages with placeholders substituted by argument values. * /*from ww w . j av a 2 s . c o m*/ * @param text * the message text with placeholders * @param locale * the current locale * @param arguments * an array of arguments to be used for substitution * @return the formatted messages with placeholders substituted by argument values */ public static String format(String text, Locale locale, Object... arguments) { if (text == null || arguments == null || arguments.length == 0) { return text; } return locale != null ? new MessageFormat(StringUtils.replace(text, "'", "''"), locale).format(arguments) : MessageFormat.format(StringUtils.replace(text, "'", "''"), arguments); }
From source file:dk.netarkivet.common.utils.I18n.java
/** * Get a localized message for a given resource bundle, locale and label. * * In contrast to {@link java.util.ResourceBundle#getString}, this method is * forgiving on errors/*from ww w .j av a 2 s .c o m*/ * * I18n.getString("dk.netarkivet.common.Translations", * Locale.default, "job.unknown.id", 17) * * @param bundleName The name of the resource bundle, fully qualified, but * without the properties. * See {@link java.util.ResourceBundle#getBundle(String)} * @param locale The locale to get the string for * @param label The label of the string in the resource bundle * @param args Any args required for formatting the label * @return The localised string, or the label if the string could not be * found or the format is invalid or does not match the args. * @throws ArgumentNotValid on null bundleName, locale or label. */ public static String getString(String bundleName, Locale locale, String label, Object... args) { ArgumentNotValid.checkNotNullOrEmpty(bundleName, "String bundleName"); ArgumentNotValid.checkNotNull(locale, "Locale locale"); ArgumentNotValid.checkNotNullOrEmpty(label, "String label"); try { ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale); String message = bundle.getString(label); try { return new MessageFormat(message, locale).format(args); } catch (IllegalArgumentException e) { log.warn("I18n bundle '" + bundleName + "' has wrong format '" + message + "' for label '" + label + "'", e); return label; } } catch (MissingResourceException e) { log.warn("I18n bundle '" + bundleName + "' is missing label '" + label + "'", e); return label; } }
From source file:org.openvpms.component.system.common.i18n.Messages.java
/** * Formats a string using the string with id <tt>key</tt>, for the specified locale, from the resource bundle. * * @param key the message key, corresponding to an entry in the resource bundle * @param locale the locale/* w w w .ja va2s . c o m*/ * @param args the format arguments * @return a new message */ protected String getString(String key, Locale locale, Object... args) { String result = getValue(key, locale); if (result == null) { result = formatMissingKey(key, args); } else if (args.length != 0) { MessageFormat format = new MessageFormat(result, locale); try { result = format.format(args); } catch (Throwable exception) { result = formatFailed(key, result, args, exception); } } return result; }
From source file:org.dstadler.commons.logging.jdk.PatternFormatter.java
public final void setLogPattern(String logFormatIn) { String logFormat = logFormatIn.replace("%LOGGER%", "{0}"); logFormat = logFormat.replace("%LEVEL%", "{1}"); logFormat = logFormat.replace("%TIME%", "{2}"); logFormat = logFormat.replace("%MESSAGE%", "{3}"); logFormat = logFormat.replace("%SOURCECLASS%", "{4}"); logFormat = logFormat.replace("%SOURCEMETHOD%", "{5}"); this.logPattern = logFormat; logMessageFormat = new MessageFormat(logPattern, Locale.ROOT); }
From source file:org.mycore.frontend.cli.MCRCommand.java
/** * Creates a new MCRCommand./* ww w . j a va 2 s .c o m*/ * * @param format * the command syntax, e.g. "save document {0} to directory {1}" * @param methodSignature * the method to invoke, e.g. "miless.commandline.DocumentCommands.saveDoc int String" * @param helpText * the helpt text for this command */ public MCRCommand(String format, String methodSignature, String helpText) { StringTokenizer st = new StringTokenizer(methodSignature, " "); String token = st.nextToken(); int point = token.lastIndexOf("."); className = token.substring(0, point); methodName = token.substring(point + 1); int numParameters = st.countTokens(); parameterTypes = new Class<?>[numParameters]; messageFormat = new MessageFormat(format, Locale.ROOT); for (int i = 0; i < numParameters; i++) { token = st.nextToken(); Format f = null; switch (token) { case "int": parameterTypes[i] = Integer.TYPE; f = NumberFormat.getIntegerInstance(Locale.ROOT); break; case "long": parameterTypes[i] = Long.TYPE; f = NumberFormat.getIntegerInstance(Locale.ROOT); break; case "String": parameterTypes[i] = String.class; break; default: unsupportedArgException(methodSignature, token); } messageFormat.setFormat(i, f); } int pos = format.indexOf("{"); suffix = pos == -1 ? format : format.substring(0, pos); if (helpText != null) { help = helpText; } else { help = "No help text available for this command"; } }
From source file:org.polymap.rhei.um.operations.NewUserOperation.java
@Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { try {// w w w . j a v a 2 s . com // password hash PasswordEncryptor encryptor = PasswordEncryptor.instance(); String password = encryptor.createPassword(8); String hash = encryptor.encryptPassword(password); user.passwordHash().set(hash); // username <= email String username = user.email().get(); assert username != null && username.length() > 0; user.username().set(username); log.info("username: " + user.username().get()); // commit UserRepository.instance().commitChanges(); String salu = user.salutation().get() != null ? user.salutation().get() : ""; String header = (salu.equalsIgnoreCase("Herr") ? "r " : " ") + salu + " " + user.name().get(); Email email = new SimpleEmail(); email.setCharset("ISO-8859-1"); email.addTo(username).setSubject(emailSubject) .setMsg(new MessageFormat(emailContent, Polymap.getSessionLocale()) .format(new Object[] { header, username, password })); // .setMsg( i18n.get( "email", header, username, password ) ); EmailService.instance().send(email); return Status.OK_STATUS; } catch (EmailException e) { throw new ExecutionException(i18n.get("errorMsg", e.getLocalizedMessage()), e); } }
From source file:nz.co.senanque.localemanagement.XMLMessageSource.java
@Override protected MessageFormat resolveCode(String code, Locale locale) { String ret = null;//from w ww . j av a 2 s .c om String country = locale.getCountry(); String language = locale.getLanguage(); String variant = locale.getVariant(); logger.debug("Code {} Initial locale {}", code, locale.toString()); Locale thisLocale = null; if (!StringUtils.isEmpty(variant)) { thisLocale = new Locale(language, country, variant); Map<String, String> m = m_map.get(thisLocale); if (m != null) { ret = m.get(code); } logger.debug("tried locale {} result: {}", thisLocale.toString(), ret); } if (ret == null) { if (!StringUtils.isEmpty(country)) { thisLocale = new Locale(language, country); Map<String, String> m = m_map.get(thisLocale); if (m != null) { ret = m.get(code); } logger.debug("tried locale {} result: {}", thisLocale.toString(), ret); } } if (ret == null) { if (!StringUtils.isEmpty(language)) { thisLocale = new Locale(language); Map<String, String> m = m_map.get(thisLocale); if (m != null) { ret = m.get(code); } logger.debug("tried locale {} result: {}", thisLocale.toString(), ret); } } if (ret == null) { thisLocale = Locale.getDefault(); Map<String, String> m = m_map.get(thisLocale); if (m != null) { ret = m.get(code); } logger.debug("tried locale {} result: {}", thisLocale.toString(), ret); } if (ret == null) { return null; } return new MessageFormat(ret, locale); }
From source file:com.clustercontrol.systemlog.bean.SyslogMessage.java
/** * syslog????????SyslogMessage????API<br> * <br>//from w w w .ja v a2s. c om * <b>???</b><br> * 1. ???????????????<br> * 2. ???????????<br> * @param syslog syslog? * @return SyslogMessage * @throws ParseException syslog??????????? * @throws HinemosUnknown */ public static SyslogMessage parse(String syslog) throws ParseException, HinemosUnknown { if (log.isDebugEnabled()) { log.debug("parsing syslog : " + syslog); } // [0]:, [1]:(MMM), [2]:(dd), [3]:(HH), [4]:(mm), [5]:(ss), [6]:??, [7]: // ?{1,date,MMM dd HH:mm:ss}????????????1970???? // ????????2/29???3/1?????(1970???????) MessageFormat syslogFormat = new MessageFormat("<{0,number,integer}>{1} {2} {3}:{4}:{5} {6} {7}", Locale.ENGLISH); // ?????? Object[] syslogArgs = syslogFormat.parse(syslog); // RFC3164?????????????????? if ("".equals(syslogArgs[SYSLOG_FORMAT_DAY])) { syslogFormat = new MessageFormat("<{0,number,integer}>{1} {2} {3}:{4}:{5} {6} {7}", Locale.ENGLISH); syslogArgs = syslogFormat.parse(syslog); } if (syslogArgs == null) throw new HinemosUnknown("different syslog pattern"); if (log.isDebugEnabled()) { int i = 0; for (Object arg : syslogArgs) { log.debug(String.format("syslog args [%d] : %s", i++, arg.toString())); } } // ???????(H) Integer syslogEffectiveTime = HinemosPropertyUtil .getHinemosPropertyNum("monitor.systemlog.period.hour", Long.valueOf(SYSLOG_DEFAULT_PERIOD_HOUR)) .intValue(); // 0??????????? if (syslogEffectiveTime <= 0) { syslogEffectiveTime = SYSLOG_DEFAULT_PERIOD_HOUR; } Calendar nowCal = HinemosTime.getCalendarInstance(); // ??(?) int year = nowCal.get(Calendar.YEAR) + 1; int month = editCalendarMonth((String) syslogArgs[SYSLOG_FORMAT_MONTH]); int dayOfMonth = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_DAY]); int hourOfDay = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_HH]); int minute = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_MM]); int second = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_SS]); // ? List<Calendar> checkCalList = new ArrayList<Calendar>(); // (?? Calendar syslogEffectiveCal = (Calendar) nowCal.clone(); syslogEffectiveCal.add(Calendar.HOUR, syslogEffectiveTime); // ??? for (int i = 0; checkCalList.size() < 2; i++) { // ?????? if (LEAPYEAR_CHECK_COUNT <= i) { break; } Calendar syslogCheckCal = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second); year--; // ???????(??) if (syslogEffectiveCal.compareTo(syslogCheckCal) < 0) { continue; } // ?????????????? if (dayOfMonth != syslogCheckCal.get(Calendar.DAY_OF_MONTH)) { continue; } // ???? checkCalList.add(syslogCheckCal); } Calendar editSyslogCal = null; // ????? if (checkCalList.size() > 0) { long absMinMillis = Long.MAX_VALUE; for (int i = 0; i < checkCalList.size(); i++) { long absDiff = Math.abs(checkCalList.get(i).getTimeInMillis() - nowCal.getTimeInMillis()); if (absDiff < absMinMillis) { // ?????? absMinMillis = absDiff; editSyslogCal = checkCalList.get(i); } } } else { // ?????? editSyslogCal = new GregorianCalendar(nowCal.get(Calendar.YEAR), month, dayOfMonth, hourOfDay, minute, second); log.warn("System log date is invalid : " + syslog); } int pri = ((Long) syslogArgs[SYSLOG_FORMAT_PRIORITY]).intValue(); String hostname = (String) syslogArgs[SYSLOG_FORMAT_HOSTNAME]; String msg = (String) syslogArgs[SYSLOG_FORMAT_MESSAGE]; Date date = editSyslogCal.getTime(); // ?? SyslogMessage instance = new SyslogMessage(getFacility((int) pri), getSeverity((int) pri), date.getTime(), hostname, msg, syslog); if (log.isDebugEnabled()) { log.debug("parsed syslog : " + instance); } return instance; }
From source file:org.apache.openejb.math.MathRuntimeException.java
/** * Builds a message string by from a pattern and its arguments. * * @param locale Locale in which the message should be translated * @param pattern format specifier//from ww w .jav a 2 s . com * @param arguments format arguments * @return a message string */ private static String buildMessage(final Locale locale, final String pattern, final Object... arguments) { return pattern == null ? "" : new MessageFormat(translate(pattern, locale), locale).format(arguments); }