List of usage examples for java.text MessageFormat format
public final String format(Object obj)
From source file:grails.plugin.searchable.internal.util.StringQueryUtils.java
/** * Highlights the different terms in the second query and returns a new query string. * This method is intended to be used with suggested queries to display the suggestion * to the user in highlighted format, as per Google, so the queries are expected to roughly match * @param first the original query// w ww .jav a 2 s.c o m * @param second the second query, in which to highlight differences * @param highlightPattern the pattern used to highlight; should be a {@link MessageFormat} pattern where argument * zero is the highlighted term text * @return a new copy of second with term differences highlighted * @throws ParseException if either first or second query is invalid * @see #highlightTermDiffs(String, String) */ public static String highlightTermDiffs(String first, String second, String highlightPattern) throws ParseException { final String defaultField = "$StringQueryUtils_highlightTermDiffs$"; Term[] firstTerms = LuceneUtils.realTermsForQueryString(defaultField, first, WhitespaceAnalyzer.class); Term[] secondTerms = LuceneUtils.realTermsForQueryString(defaultField, second, WhitespaceAnalyzer.class); if (firstTerms.length != secondTerms.length) { LOG.warn("Expected the same number of terms for first query [" + first + "] and second query [" + second + "], " + "but first query has [" + firstTerms.length + "] terms and second query has [" + secondTerms.length + "] terms " + "so unable to provide user friendly version. Returning second query as-is."); return second; } MessageFormat format = new MessageFormat(highlightPattern); StringBuilder diff = new StringBuilder(second); int offset = 0; for (int i = 0; i < secondTerms.length; i++) { Term firstTerm = firstTerms[i]; Term secondTerm = secondTerms[i]; boolean noField = defaultField.equals(secondTerm.field()); String snippet = noField ? secondTerm.text() : secondTerm.field() + ":" + secondTerm.text(); int pos = diff.indexOf(snippet, offset); if (!firstTerm.text().equals(secondTerm.text())) { if (!noField) { pos += secondTerm.field().length() + 1; } diff.replace(pos, pos + secondTerm.text().length(), format.format(new Object[] { secondTerm.text() })); } offset = pos; } return diff.toString(); }
From source file:ChoiceFormatDemo.java
static void displayMessages(Locale currentLocale) { System.out.println("currentLocale = " + currentLocale.toString()); System.out.println();//from ww w . j a v a 2 s .c o m ResourceBundle bundle = ResourceBundle.getBundle("ChoiceBundle", currentLocale); MessageFormat messageForm = new MessageFormat(""); messageForm.setLocale(currentLocale); double[] fileLimits = { 0, 1, 2 }; String[] fileStrings = { bundle.getString("noFiles"), bundle.getString("oneFile"), bundle.getString("multipleFiles") }; ChoiceFormat choiceForm = new ChoiceFormat(fileLimits, fileStrings); String pattern = bundle.getString("pattern"); Format[] formats = { choiceForm, null, NumberFormat.getInstance() }; messageForm.applyPattern(pattern); messageForm.setFormats(formats); Object[] messageArguments = { null, "XDisk", null }; for (int numFiles = 0; numFiles < 4; numFiles++) { messageArguments[0] = new Integer(numFiles); messageArguments[2] = new Integer(numFiles); String result = messageForm.format(messageArguments); System.out.println(result); } }
From source file:com.clustercontrol.util.apllog.AplLogger.java
private static void putFile(OutputBasicInfo notifyInfo) { /** ID,,ID,ID,ID,,? */ MessageFormat logfmt = new MessageFormat("{0,date,yyyy/MM/dd HH:mm:ss} {1},{2},{3},{4},{5},{6}"); // Locale?/*from w ww .j a v a 2s . c o m*/ Locale locale = NotifyUtil.getNotifyLocale(); // Object[] args = { notifyInfo.getGenerationDate(), notifyInfo.getPluginId(), notifyInfo.getApplication(), notifyInfo.getMonitorId(), notifyInfo.getPriority(), HinemosMessage.replace(notifyInfo.getMessage(), locale), notifyInfo.getMessageOrg() }; String logmsg = logfmt.format(args); // log.debug("putFile() logmsg = " + logmsg); FILE_LOGGER.info(logmsg); }
From source file:org.cyberoam.iview.charts.Chart.java
/** * This Method gives Title with Dynamic values of Parameter * @param title/* w w w .j ava 2s.com*/ * @param request * @param reportGroupBean * @return */ public static String getFormattedTitle(HttpServletRequest request, ReportGroupBean reportGroupBean, boolean isPDF) { String title = null; if (request != null) { Object[] paramValues = null; String paramName = null, paramVal = null; StringTokenizer stToken = new StringTokenizer(reportGroupBean.getInputParams(), ","); paramValues = new Object[stToken.countTokens()]; for (int i = 0; stToken.hasMoreTokens(); i++) { paramName = stToken.nextToken(); if (paramName != null && (paramName.equalsIgnoreCase("Application") || paramName.equalsIgnoreCase("Protocol Group") || paramName.equalsIgnoreCase("proto_group") && request.getParameter(paramName).indexOf(':') != -1)) { paramVal = request.getParameter(paramName); try { String data; data = ProtocolBean.getProtocolNameById( Integer.parseInt(paramVal.substring(0, paramVal.indexOf(':')))); data = data + paramVal.substring(paramVal.indexOf(':'), paramVal.length()); paramVal = data; } catch (Exception ex) { } } else if (paramName.equalsIgnoreCase("Severity")) { paramVal = TabularReportConstants.getSeverity(request.getParameter(paramName)); } else if (request.getParameter(paramName) == null || request.getParameter(paramName).equals("")) { paramVal = "N/A"; } else { paramVal = request.getParameter(paramName); } if (isPDF) { paramValues[i] = paramVal; } else { paramValues[i] = "<i>" + paramVal + "</i>"; } } MessageFormat queryFormat = new MessageFormat(reportGroupBean.getTitle()); title = queryFormat.format(paramValues); } if (title == null) { return reportGroupBean.getTitle(); } else { return title; } }
From source file:com.opensymphony.xwork2.util.LocalizedTextUtil.java
private static String formatWithNullDetection(MessageFormat mf, Object[] args) { String message = mf.format(args); if ("null".equals(message)) { return null; } else {/*from w w w.ja va2 s. c om*/ return message; } }
From source file:com.clustercontrol.util.apllog.AplLogger.java
private static void putSyslog(OutputBasicInfo notifyInfo) { /** syslog/*from www . j av a2s. c om*/ * ID,,ID,ID,,? */ MessageFormat syslogfmt = new MessageFormat("hinemos: {0},{1},{2},{3},{4}"); // Locale locale = NotifyUtil.getNotifyLocale(); String priorityStr = Messages.getString(PriorityConstant.typeToMessageCode(notifyInfo.getPriority()), locale); Object[] args = { notifyInfo.getPluginId(), notifyInfo.getApplication(), notifyInfo.getMonitorId(), priorityStr, HinemosMessage.replace(notifyInfo.getMessage(), locale), notifyInfo.getMessageOrg() }; String logmsg = syslogfmt.format(args); // ? SimpleDateFormat sdf = new SimpleDateFormat(SendSyslog.HEADER_DATE_FORMAT, Locale.US); sdf.setTimeZone(HinemosTime.getTimeZone()); String timeStamp = sdf.format(HinemosTime.getDateInstance()); ///// // ?(internal.syslog) //// String hosts = HinemosPropertyUtil.getHinemosPropertyStr("internal.syslog.host", "192.168.1.1,192.168.1.2"); String[] syslogHostList = hosts.split(","); int syslogPort = HinemosPropertyUtil.getHinemosPropertyNum("internal.syslog.port", Long.valueOf(514)) .intValue(); String syslogFacility = HinemosPropertyUtil.getHinemosPropertyStr("internal.syslog.facility", "daemon"); String syslogSeverity = HinemosPropertyUtil.getHinemosPropertyStr("internal.syslog.severity", "alert"); for (String syslogHost : syslogHostList) { log.debug("putSyslog() syslogHost = " + syslogHost + ", syslogPort = " + syslogPort + ", syslogFacility = " + syslogFacility + ", syslogSeverity = " + syslogSeverity + ", logmsg = " + logmsg + ", timeStamp = " + timeStamp); try { new NotifyControllerBean().sendAfterConvertHostname(syslogHost, syslogPort, syslogFacility, syslogSeverity, INTERNAL_SCOPE, logmsg, timeStamp); } catch (InvalidRole e) { log.warn("fail putSyslog monitorId=" + notifyInfo.getMonitorId() + ", message=" + notifyInfo.getMessage()); } catch (HinemosUnknown e) { log.warn("fail putSyslog monitorId=" + notifyInfo.getMonitorId() + ", message=" + notifyInfo.getMessage()); } } }
From source file:I18N.java
/** * Given a message and parameters, resolve all message's parameter * placeholders with the parameter value. The firstParam can change which * parameter relates to {0} placeholder in the message, and all increment * from this index. If any of the parameters also have placeholders, this * recursively calls itself to fill their placeholders, setting the * firstParam to the index following all parameters that are used by the * current message so params must be in the order p0..pN, p00..p0N..pMN, * p000..p00N..p0MN..pLMN... where each additional index is for nested * placeholders (ones in params) and assumes every message/param contains * N M L placeholders; any that don't contain placeholders can have their * pXXX.. taken out, so long as the order of remaining params don't change * @param message Message to format/*from w w w. j av a 2s . com*/ * @param firstParam Index of parameter that relates to {0} placeholder, * all parameters following this one relate to incrementing placeholders * @param params The parameters used to fill the placeholders * @return Message with all placeholders filled with relative parameters */ private static String formatMessage(String message, int firstParam, Object[] params) { // Only need to do any formatting if there are parameters to do the // formatting with. If there are none, the message input is returned // unmodified if (params != null && firstParam < params.length) { MessageFormat parser; Locale locale = Locale.getDefault(); Format[] formats; // Set up parser = new MessageFormat(""); parser.setLocale(locale); parser.applyPattern(message); // Used only to count how many parameters are needed by this message formats = parser.getFormatsByArgumentIndex(); // Recursively format the parameters used by this message for (int paramIndex = 0; paramIndex < formats.length; paramIndex++) if (params[firstParam + paramIndex] instanceof String) params[firstParam + paramIndex] = formatMessage(params[firstParam + paramIndex].toString(), firstParam + formats.length, params); // Format the message using the formatted parameters message = parser.format(getParams(params, firstParam, firstParam + formats.length)); } return message; }
From source file:com.agloco.util.StringUtil.java
private static String format(String s, String format) { if (s == null) return ""; MessageFormat f = new MessageFormat(format); return f.format(s); }
From source file:org.web4thejob.security.ADAuthenticationProvider.java
private String getPrincipal(String uname) { MessageFormat mf = new MessageFormat(pattern); return mf.format(new String[] { uname }); }
From source file:com.qcadoo.customTranslation.internal.CustomTranslationResolverImpl.java
@Override public String getCustomTranslation(final String key, final Locale locale, final String[] args) { String translation = customTranslationCacheService.getCustomTranslation(key, locale.getLanguage()); if (translation == null) { return null; } else {/* w w w .j av a2 s . c o m*/ translation = translation.replace("'", "''"); Object[] argsToUse = args; if (!ObjectUtils.isEmpty(argsToUse)) { argsToUse = ArrayUtils.EMPTY_OBJECT_ARRAY; } MessageFormat messageFormat = new MessageFormat(translation); return messageFormat.format(argsToUse); } }