Example usage for java.text MessageFormat format

List of usage examples for java.text MessageFormat format

Introduction

In this page you can find the example usage for java.text MessageFormat format.

Prototype

public final String format(Object obj) 

Source Link

Document

Formats an object to produce a string.

Usage

From source file:modula.parser.io.ModelUpdater.java

/**
 * /*from  w  w  w . j  a  v  a2 s.c  o  m*/
 */
private static void logAndThrowModelError(final String errType, final Object[] msgArgs) throws ModelException {
    MessageFormat msgFormat = new MessageFormat(errType);
    String errMsg = msgFormat.format(msgArgs);
    org.apache.commons.logging.Log log = LogFactory.getLog(ModelUpdater.class);
    log.error(errMsg);
    throw new ModelException(errMsg);
}

From source file:net.mlw.vlh.web.util.JspUtils.java

public static String format(Object value, String format, Locale loc) {
    if (value == null) {
        return "";
    } else {/*from  w  w w . j  a v  a 2  s  . co m*/
        if (value instanceof Number) {
            if (format == null || format.length() == 0) {
                return value.toString();
            }
            MessageFormat mf = new MessageFormat("{0,number," + format + "}");
            if (loc != null) {
                mf.setLocale(loc);
                mf.applyPattern(mf.toPattern());
            }

            return mf.format(new Object[] { value });
        } else if (value instanceof java.util.Date) {
            if (format == null || format.length() == 0) {
                //TODO: get the default date format in here somehow. format =
                // SystemProperties.getProperty("default.dateFormat", "EEE, MMM
                // d, ''yy");
                format = "EEE, MMM d, ''yy";
            }
            MessageFormat mf = new MessageFormat("{0,date," + format + "}");
            if (loc != null) {
                mf.setLocale(loc);
                mf.applyPattern(mf.toPattern());
            }
            return mf.format(new Object[] { value });
        } else if (value instanceof Calendar) {
            Calendar calendar = (Calendar) value;
            if (format == null || format.length() == 0) {
                //TODO: get the default date format in here somehow. format =
                // SystemProperties.getProperty("default.dateFormat", "EEE, MMM
                // d, ''yy");
                format = "EEE, MMM d, ''yy";
            }

            MessageFormat mf = new MessageFormat("{0,date," + format + "}");
            if (loc != null) {
                mf.setLocale(loc);
                mf.applyPattern(mf.toPattern());
            }
            return mf.format(new Object[] { value });
        } else {
            return value.toString();
        }

    }
}

From source file:com.jslsolucoes.tagria.lib.util.TagUtil.java

public static String getLocalizedForLib(String key, JspContext jspContext, Object... args) {
    try {/*from  w  w w.ja va  2s .c  om*/
        MessageFormat messageFormat = new MessageFormat(
                ResourceBundle.getBundle("messages_tagrialib", locale(jspContext)).getString(key));
        return messageFormat.format(args);
    } catch (MissingResourceException e) {
        logger.error("could not find key resource", e);
        return '!' + key + '!';
    }
}

From source file:com.hypersocket.i18n.I18N.java

public static String getResourceNoOveride(Locale locale, String resourceBundle, String key,
        Object... arguments) {//from  www .j a v  a 2 s  . co  m
    if (key == null) {
        throw new IllegalArgumentException("You must specify a key!");
    }
    if (resourceBundle == null) {
        throw new IllegalArgumentException("You must specify a resource bundle for key " + key);
    }

    if (!resourceBundle.startsWith("i18n/")) {
        resourceBundle = "i18n/" + resourceBundle;
    }

    try {
        ResourceBundle resource = ResourceBundle.getBundle(resourceBundle, locale, I18N.class.getClassLoader());
        String localizedString = resource.getString(key);
        if (arguments == null || arguments.length == 0) {
            return localizedString;
        }

        MessageFormat messageFormat = new MessageFormat(localizedString);
        messageFormat.setLocale(locale);
        return messageFormat.format(formatParameters(arguments));
    } catch (MissingResourceException mre) {
        return "[i18n/" + resourceBundle + "/" + key + "]";
    }
}

From source file:libepg.epg.util.datetime.DateTimeFieldConverter.java

private static Map<HMS_KEY, Integer> BcdTimeToMap(byte[] hms) throws ParseException {
    Map<HMS_KEY, Integer> ret = new HashMap<>();
    if (hms.length != 3) {
        throw new IndexOutOfBoundsException(
                "?????3????????"
                        + " ?=" + Hex.encodeHexString(hms));
    }//  ww  w .  j  a  v a2  s  .  c  o m

    //ARIB????????????????
    if (Arrays.equals(hms, UNDEFINED_BCD_TIME_BLOCK.getData())) {
        throw new ParseException("???????????" + " ?="
                + Hex.encodeHexString(hms), 0);
    }
    Object[] parameters = null;

    final int hour = new BCD(hms[0]).getDecimal();
    final int minute = new BCD(hms[1]).getDecimal();
    final int second = new BCD(hms[2]).getDecimal();
    CHECK: {
        final Range<Integer> HOUR_RANGE = Range.between(0, 23);

        if (!HOUR_RANGE.contains(hour)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", hour };
            break CHECK;
        }

        final Range<Integer> MINUTE_AND_SECOND_RANGE = Range.between(0, 59);

        if (!MINUTE_AND_SECOND_RANGE.contains(minute)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", minute };
            break CHECK;
        }

        if (!MINUTE_AND_SECOND_RANGE.contains(second)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", second };
            break CHECK;
        }
    }

    if (parameters != null) {
        MessageFormat msg = new MessageFormat(
                "????????????={0} ={1} ={2}");
        throw new ParseException(msg.format(parameters), 0);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("hour=" + hour + " minute=" + minute + " second=" + second);
    }

    ret.put(HMS_KEY.HOUR, hour);
    ret.put(HMS_KEY.MINUTE, minute);
    ret.put(HMS_KEY.SECOND, second);

    return ret;
}

From source file:com.hypersocket.i18n.I18N.java

public static String getResource(Locale locale, String resourceBundle, String key, Object... arguments) {

    if (key == null) {
        throw new IllegalArgumentException("You must specify a key!");
    }//from w  ww .  j  a v  a2  s.c om
    if (resourceBundle == null) {
        throw new IllegalArgumentException("You must specify a resource bundle for key " + key);
    }

    File overideFile = getOverrideFile(locale, resourceBundle);

    if (overideFile.exists()) {

        if (!overideProperties.containsKey(overideFile)) {

            Properties properties = new Properties();
            try {
                InputStream in = new FileInputStream(overideFile);
                try {
                    properties.load(in);
                } catch (IOException ex) {
                } finally {
                    FileUtils.closeQuietly(in);
                }

                overideProperties.put(overideFile, properties);
            } catch (FileNotFoundException e) {

            }
        }

        if (overideProperties.containsKey(overideFile)) {
            Properties properties = overideProperties.get(overideFile);

            if (properties.containsKey(key)) {
                String localizedString = properties.getProperty(key);
                if (arguments == null || arguments.length == 0) {
                    return localizedString;
                }

                MessageFormat messageFormat = new MessageFormat(localizedString);
                messageFormat.setLocale(locale);
                return messageFormat.format(formatParameters(arguments));
            }
        }
    }

    String bundlePath = resourceBundle;
    if (!bundlePath.startsWith("i18n/")) {
        bundlePath = "i18n/" + resourceBundle;
    }

    try {
        ResourceBundle resource = ResourceBundle.getBundle(bundlePath, locale, I18N.class.getClassLoader());
        String localizedString = resource.getString(key);
        if (arguments == null || arguments.length == 0) {
            return localizedString;
        }

        MessageFormat messageFormat = new MessageFormat(localizedString);
        messageFormat.setLocale(locale);
        return messageFormat.format(formatParameters(arguments));
    } catch (MissingResourceException mre) {
        return "Missing resource key [i18n/" + resourceBundle + "/" + key + "]";
    }
}

From source file:com.qpark.eip.core.failure.BaseFailureHandler.java

private static String format(final FailureMessagePhraseableType m, final Object... data) {
    StringBuffer sb = new StringBuffer(1024);
    if (m != null) {
        if (m.getText() != null && m.getText().trim().length() > 0) {
            if (data != null && data.length > 0) {
                MessageFormat mf = new MessageFormat(checkUnnumberedBrackets(m.getText()));
                sb.append(mf.format(data));
            } else {
                sb.append(m.getText());//from   w  ww . j  a va 2 s.  c o m
            }
        }
        if (m.getPhraseKey() != null) {
            for (String key : m.getPhraseKey()) {
                if (phrases.get(key) != null && phrases.get(key).length() > 0) {
                    if (sb.length() > 0) {
                        sb.append(" ");
                    }
                }
                sb.append(phrases.get(key));
            }
        }
    }
    return sb.toString();
}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Returns a phone number for display in the application.
 *
 * @param phoneNumber The phone number to format.
 * @return The formatted phone number./*from w ww .j a va 2s  . c  om*/
 */
public static String getFormattedPhoneNumber(String phoneNumber) {
    if (phoneNumber.length() == 10) {
        MessageFormat phoneNumberFormat = new MessageFormat("({0}) {1}-{2}");
        String[] phoneNumberArray = new String[] { phoneNumber.substring(0, 3), phoneNumber.substring(3, 6),
                phoneNumber.substring(6) };
        phoneNumber = phoneNumberFormat.format(phoneNumberArray);
    } else if (phoneNumber.length() == 11 && phoneNumber.charAt(0) == '1') {
        MessageFormat phoneNumberFormat = new MessageFormat("({0}) {1}-{2}");
        String[] phoneNumberArray = new String[] { phoneNumber.substring(1, 4), phoneNumber.substring(4, 7),
                phoneNumber.substring(7) };
        phoneNumber = phoneNumberFormat.format(phoneNumberArray);
    }

    return phoneNumber;
}

From source file:com.clustercontrol.platform.util.apllog.EventLogger.java

public static void internal(Integer priority, OutputBasicInfo info) {
    /**     ID,,ID,ID,ID,,? */
    MessageFormat logfmt = new MessageFormat("{0,date,yyyy/MM/dd HH:mm:ss}  {1},{2},{3},{4},{5},{6}");
    // Locale?/*from  www.jav a2  s .  c  o  m*/
    Locale locale = NotifyUtil.getNotifyLocale();
    //
    Object[] args = { info.getGenerationDate(), info.getPluginId(), info.getApplication(), info.getMonitorId(),
            PriorityConstant.typeToMessageCode(info.getPriority()),
            HinemosMessage.replace(info.getMessage(), locale), info.getMessageOrg() };
    String logmsg = logfmt.format(args);

    switch (priority) {
    case PriorityConstant.TYPE_CRITICAL:
        error(logmsg);
        break;
    case PriorityConstant.TYPE_WARNING:
        warn(logmsg);
        break;
    case PriorityConstant.TYPE_INFO:
        info(logmsg);
        break;
    default:
        break;
    }
}

From source file:org.jamwiki.utils.Utilities.java

/**
 * Given a message key, locale, and formatting parameters, return a
 * locale-specific message.//w  w  w  .jav a  2 s.c  om
 *
 * @param key The message key that corresponds to the formatted message
 *  being retrieved.
 * @param locale The locale for the message that is to be retrieved.
 * @param params An array of formatting parameters to use in the message
 *  being returned.
 * @return A formatted message string that is specific to the locale.
 */
public static String formatMessage(String key, Locale locale, Object[] params) {
    MessageFormat formatter = new MessageFormat("");
    formatter.setLocale(locale);
    String message = Utilities.formatMessage(key, locale);
    formatter.applyPattern(message);
    return formatter.format(params);
}