Example usage for java.text MessageFormat MessageFormat

List of usage examples for java.text MessageFormat MessageFormat

Introduction

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

Prototype

public MessageFormat(String pattern) 

Source Link

Document

Constructs a MessageFormat for the default java.util.Locale.Category#FORMAT FORMAT locale and the specified pattern.

Usage

From source file:com.salesmanager.core.util.LabelUtil.java

public String getText(Locale locale, String key, List parameters) {

    Iterator bundleListIterator = bundleList.iterator();
    ResourceBundle myResources = null;
    String label = "";
    while (bundleListIterator.hasNext()) {
        String bundle = (String) bundleListIterator.next();

        try {//from   w  ww  . j a v  a 2  s .co m

            myResources = ResourceBundle.getBundle(bundle, locale);
            if (myResources != null) {
                String l = myResources.getString(key);
                if (l != null) {
                    MessageFormat mFormat = new MessageFormat(l);
                    String[] params = new String[parameters.size()];
                    params = (String[]) parameters.toArray(params);
                    l = mFormat.format(params);
                    label = l;
                    break;
                }
            }

        } catch (Exception e) {
            // Handle exception
        }

    }
    return label;
}

From source file:com.liusoft.dlog4j.util.RequestUtils.java

/**
 * ???/* w w w  .  j  ava2s  . c  om*/
 * @param req
 * @return
 */
public static String getRequestMobile(HttpServletRequest req) {
    String mobile = default_mobile;
    Iterator keys = header_map.keySet().iterator();
    while (keys.hasNext()) {
        String header = (String) keys.next();
        String value = getHeader(req, header);
        if (value != null) {
            String pattern = (String) header_map.get(header);
            MessageFormat mf = new MessageFormat(pattern);
            try {
                Object[] vs = mf.parse(value);
                mobile = (String) vs[0];
                if (mobile.startsWith("86"))
                    mobile = mobile.substring(2);
                break;
            } catch (Exception e) {
                log.warn("?header", e);
                dumpHeaders(req, System.err);
                continue;
            }
        }
    }
    return mobile;
}

From source file:org.rhq.enterprise.gui.legacy.taglib.Pagination.java

/**
 * Returns a string containing the nagivation bar that allows the user to move between pages within the list.
 *
 * <p/>The urlFormatString should be a URL that looks like the following:
 *
 * <p/>http://.../somepage.page?pn={0}
 *//*from w ww  .  j a v  a 2 s .  c o m*/
protected String createDots(int sets) {
    setAction(removeExistingPaginationParams(getAction(), this.postfix));

    // flag to determine if we should use a ? or a &
    int index = getAction().indexOf('?');
    String separator = (index == -1) ? "?" : "&";
    MessageFormat form = new MessageFormat(getAction() + separator + "pn" + postfix + "={0}");

    int currentPage = this.pageList.getPageControl().getPageNumber();
    int pageCount = determinePageCount();

    int startPage = 0;
    int endPage = Constants.MAX_PAGES.intValue();

    int currentSet = currentPage / Constants.MAX_PAGES.intValue();
    if (sets >= 1) {
        startPage = currentSet * Constants.MAX_PAGES.intValue();
        endPage = startPage + Constants.MAX_PAGES.intValue();

        if (endPage > pageCount) {
            endPage = pageCount;
        }
    }

    if ((pageCount == 1) || (pageCount == 0)) {
        return "&nbsp;";
    }

    if (currentPage < Constants.MAX_PAGES.intValue()) {
        if (pageCount < endPage) {
            endPage = pageCount;
        }
    }

    StringBuffer msg = new StringBuffer();

    //passing sorting, ordering, and pageSize along with every request.
    StringBuffer pagMsg = new StringBuffer();
    pagMsg.append("&").append(Constants.SORTCOL_PARAM + postfix).append("=")
            .append(this.pageList.getPageControl().getPrimarySortColumn()).append("&")
            .append(Constants.SORTORDER_PARAM + postfix).append("=")
            .append(this.pageList.getPageControl().getPrimarySortOrder()).append("&")
            .append(Constants.PAGESIZE_PARAM + postfix).append("=").append(pageSize);

    if (currentPage == startPage) {
        msg.append("<td><img src=\"").append(path)
                .append("/images/tbb_pageleft_gray.gif\" width=\"13\" height=\"16\" border=\"0\"/></td>");
    } else {
        Object[] objs = { new Integer(currentPage - 1) };
        Object[] v1 = { new Integer(1) };
        msg.append("<td><a href=\"").append(form.format(objs)).append(pagMsg.toString()).append("\">")
                .append("<img src=\"").append(path)
                .append("/images/tbb_pageleft.gif\" width=\"13\" height=\"16\" border=\"0\"/></a></td>");
    }

    int displayNumber = startPage;
    for (int i = startPage; i < endPage; i++) {
        displayNumber += 1;
        if (i == currentPage) {
            msg.append("<td>").append(displayNumber).append("</td>");
        } else {
            Object[] v = { new Integer(i) };
            msg.append("<td><a href=\"").append(form.format(v)).append(pagMsg.toString()).append("\">")
                    .append(displayNumber).append("</a></td>");
        }
    }

    if (currentPage == (endPage - 1)) {
        msg.append("<td><img src=\"").append(path)
                .append("/images/tbb_pageright_gray.gif\" width=\"13\" height=\"16\" border=\"0\"/></td>");
    } else {
        Object[] objs = { new Integer(currentPage + 1) };
        Object[] v1 = { new Integer(pageCount) };
        msg.append("<td><a href=\"").append(form.format(objs)).append(pagMsg.toString())
                .append("\"><img src=\"").append(path)
                .append("/images/tbb_pageright.gif\" width=\"13\" height=\"16\" border=\"0\"/></a></td>");
    }

    return msg.toString();
}

From source file:org.web4thejob.print.CsvPrinter.java

@Override
public File print(String title, RenderScheme renderScheme, Query query, List<Entity> entities) {
    Assert.notNull(renderScheme);/*  w w  w .  j av  a 2  s.c  o  m*/
    Assert.isTrue(renderScheme.getSchemeType() == SchemeType.LIST_SCHEME);

    if (entities == null) {
        Assert.notNull(query);
        entities = ContextUtil.getDRS().findByQuery(query);
    }

    File file;
    try {
        String crlf = System.getProperty("line.separator");
        file = createTempFile();
        BufferedWriter writer = createFileStream(file);
        writer.write(title + crlf);
        writer.newLine();

        if (query != null && query.hasMasterCriterion()) {
            writer.write(describeMasterCriteria(query));
            writer.newLine();
        }

        if (query != null) {
            writer.write(describeCriteria(query));
            writer.newLine();
        }

        CSVWriter csv = new CSVWriter(writer);
        List<String> header = new ArrayList<String>();
        for (RenderElement item : renderScheme.getElements()) {
            if (item.getPropertyPath().getLastStep().isBlobType())
                continue;
            header.add(item.getFriendlyName());
        }
        csv.writeNext(header.toArray(new String[header.size()]));

        ConversionService conversionService = ContextUtil.getBean(ConversionService.class);
        for (final Entity entity : entities) {
            writeLine(csv, conversionService, entity, renderScheme);
        }

        writer.newLine();

        //timestamp
        List<String> line = new ArrayList<String>();
        line.add(L10nMessages.L10N_LABEL_TIMESTAMP.toString());
        MessageFormat df = new MessageFormat("");
        df.setLocale(CoreUtil.getUserLocale());
        df.applyPattern("{0,date,yyyy-MM-dd hh:mm:ss}");
        line.add(df.format(new Object[] { new Date() }));
        csv.writeNext(line.toArray(new String[line.size()]));

        writer.newLine();

        writer.write("powered by web4thejob.org");
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return file;
}

From source file:com.dbschools.quickquiz.client.taker.MainWindow.java

private void processQuizOverMsg() {
    final MessageFormat formatter = new MessageFormat(Resources.getString("quizOver"));
    JOptionPane.showMessageDialog(MainWindow.this, formatter.format(new Object[] { getQuizName() }));
    deregister();//from  ww  w  . j  a v  a  2 s .co  m
    System.exit(0);
}

From source file:org.pentaho.platform.plugin.action.builtin.TestComponent.java

@Override
protected boolean executeAction() {
    message(Messages.getInstance().getString("TestComponent.DEBUG_EXECUTING_TEST")); //$NON-NLS-1$
    Node componentNode = getComponentDefinition();

    Set inputNames = getInputNames();
    Iterator inputNamesIterator = inputNames.iterator();
    String inputName;/*  www.  j av a2 s.  co m*/
    IActionParameter actionParameter;
    while (inputNamesIterator.hasNext()) {
        inputName = (String) inputNamesIterator.next();
        actionParameter = getInputParameter(inputName);

        message(Messages.getInstance().getString("TestComponent.DEBUG_INPUT_DESCRIPTION", inputName,
                actionParameter.getValue().getClass().toString() + "=" //$NON-NLS-1$
                        + actionParameter.getValue().toString())); //$NON-NLS-2$
    }

    String test = XmlDom4JHelper.getNodeText("test", componentNode); //$NON-NLS-1$
    if ((test == null) || (test.length() < 1)) {
        message(componentNode.asXML());
        return (true);
    }

    String newName = XmlDom4JHelper.getNodeText("newname", componentNode); //$NON-NLS-1$
    Object theResult = null;

    if ("format".equals(test)) { //$NON-NLS-1$
        MessageFormat mf = new MessageFormat(XmlDom4JHelper.getNodeText("p1", componentNode, "")); //$NON-NLS-1$ //$NON-NLS-2$
        Object[] obj = { getParamFromComponentNode("p2", componentNode), //$NON-NLS-1$
                getParamFromComponentNode("p3", componentNode) }; //$NON-NLS-1$
        theResult = mf.format(obj);
    } else {
        Object p1 = getParamFromComponentNode("p1", componentNode); //$NON-NLS-1$
        if (p1 == null) {
            return (false);
        } else if ("toupper".equals(test)) { //$NON-NLS-1$

            theResult = p1.toString().toUpperCase();
        } else if ("rename".equals(test)) { //$NON-NLS-1$
            theResult = p1;
        } else if ("map2params".equals(test)) { //$NON-NLS-1$

            if (!(p1 instanceof Map)) {
                error(Messages.getInstance().getErrorString("TestComponent.ERROR_0003_PARAMETER_NOT_MAP", //$NON-NLS-1$
                        "p1")); //$NON-NLS-1$
                return (false);
            }

            Map srcMap = (Map) p1;
            for (Iterator it = srcMap.keySet().iterator(); it.hasNext();) {
                String key = it.next().toString();
                setOutputValue(key, srcMap.get(key));
            }

        } else if ("print".equals(test)) { //$NON-NLS-1$

            String delim = "\r\n***************************************************************\r\n"; //$NON-NLS-1$
            theResult = delim + p1.toString() + delim;
        } else if ("getkeys".equals(test)) { //$NON-NLS-1$

            if (!(p1 instanceof Map)) {
                error(Messages.getInstance().getErrorString("TestComponent.ERROR_0003_PARAMETER_NOT_MAP", //$NON-NLS-1$
                        "p1")); //$NON-NLS-1$
                return (false);
            }
            theResult = new ArrayList(((Map) p1).keySet());
        } else {

            Object p2 = getParamFromComponentNode("p2", componentNode); //$NON-NLS-1$
            if (p2 == null) {
                return (false);
            }

            if ("concat".equals(test)) { //$NON-NLS-1$
                theResult = p1.toString() + p2.toString();
            } else if ("print2".equals(test)) { //$NON-NLS-1$

                String delim = Messages.getInstance().getString("TestComponent.CODE_PRINT_DELIM"); //$NON-NLS-1$
                theResult = delim + p1.toString() + " - " + p2.toString() + delim; //$NON-NLS-1$
            } else {

                Object p3 = getParamFromComponentNode("p3", componentNode); //$NON-NLS-1$
                if (p3 == null) {
                    return (false);
                }

                if ("merge".equals(test)) { //$NON-NLS-1$ 

                    // merge cycles through each property map in list p2.
                    // For each map, it cycles through the keys in map p1
                    // and compares the key name
                    // from p1 with a value from p2. p3 specifies the key in
                    // p2 to compare with. When a match is found, an entry
                    // is added to an output
                    // output list that is identical to the map from p2. The
                    // value specified by the key in p1 will be added to the
                    // output under the key "NewKey"

                    if (!(p1 instanceof Map) || !(p2 instanceof List) || !(p3 instanceof String)) {
                        error(Messages.getInstance()
                                .getErrorString("TestComponent.ERROR_0004_P1_P2_WRONG_TYPE")); //$NON-NLS-1$
                        return (false);
                    }

                    theResult = merge((Map) p1, (List) p2, (String) p3);
                } else {
                    message(Messages.getInstance()
                            .getErrorString("TestComponent.ERROR_0001_TEST_NODE_NOT_FOUND")); //$NON-NLS-1$
                    return false;
                }
            }
        }
    }

    if (newName != null) {
        message(newName + " = " + theResult); //$NON-NLS-1$
        try {
            setOutputValue(newName, theResult);
        } catch (Exception e) {
            //ignore
        } // setOutputValue logs an error mesage
    } else {
        message("The result = " + theResult); //$NON-NLS-1$
    }

    return (true);
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
    this.subject = subject;
    this.callbackHandler = callbackHandler;
    for (Object option : options.keySet()) {
        if (!supportedOptions.contains(option) && !JaasLoginModuleUse.supportedOptions.contains(option)
                && !WrappingLoginModule.supportedOptions.contains(option)) {
            log.warn("Ignoring option: " + option + ". Not supported.");
        }//  ww  w . ja va  2 s  .c o  m
    }
    headerNames = (String) options.get(HEADER_NAMES);
    authenticationAuthority = (String) options.get(AUTHENTICATION_AUTHORITY);
    initialContextFactory = (String) options.get(INITIAL_CONTEXT_FACTORY);
    connectionURL = (String) options.get(CONNECTION_URL);
    connectionUsername = (String) options.get(CONNECTION_USERNAME);
    connectionPassword = (String) options.get(CONNECTION_PASSWORD);
    connectionProtocol = (String) options.get(CONNECTION_PROTOCOL);
    authentication = (String) options.get(AUTHENTICATION);
    userBase = (String) options.get(USER_BASE);
    String userSearchMatching = (String) options.get(USER_SEARCH_MATCHING);
    String userSearchSubtree = (String) options.get(USER_SEARCH_SUBTREE);
    roleBase = (String) options.get(ROLE_BASE);
    roleName = (String) options.get(ROLE_NAME);
    String roleSearchMatching = (String) options.get(ROLE_SEARCH_MATCHING);
    String roleSearchSubtree = (String) options.get(ROLE_SEARCH_SUBTREE);
    userRoleName = (String) options.get(USER_ROLE_NAME);
    userSearchMatchingFormat = new MessageFormat(userSearchMatching);
    roleSearchMatchingFormat = new MessageFormat(roleSearchMatching);
    userSearchSubtreeBool = Boolean.valueOf(userSearchSubtree);
    roleSearchSubtreeBool = Boolean.valueOf(roleSearchSubtree);
}

From source file:org.openqa.selenium.server.htmlrunner.DatabaseTestResults.java

public synchronized String createSqlTestCaseStatement(String runId, String setName, String caseId,
        boolean testPassed, String message) {
    MessageFormat mf = new MessageFormat("insert into tsi_tests_case(RUN_ID, SET_NAME, CASE_ID, VARIANT_SEQ, "
            + "TEST_RESULT, IS_MANUAL, NOTE) values(''{0}'', ''{1}'', ''{2}'', 1, ''{3}'', ''N'', ''{4}'')");
    String testResult = "PASSED";
    String note = "";

    if (!testPassed) {
        testResult = "FAILED";
        note = message.replace('\u0000', ' ');
        note = note.replace('"', ' ');
        note = note.replace('\'', ' ');
    }/*  w ww.ja v a 2  s  . com*/
    if (setName.length() > 29)
        setName = setName.substring(0, 27); // column size = 30
    if (caseId.length() > 39)
        caseId = caseId.substring(0, 37); // column size = 40
    if (note.length() > 200) {
        int start = note.length() - 195;
        note = note.substring(start, note.length()) + "...";
    }

    Object[] caseRecord = { runId, setName, caseId, testResult, note };
    return mf.format(caseRecord);
}

From source file:net.solarnetwork.node.runtime.JobSettingSpecifierProvider.java

/**
 * Create appropriate {@link SettingSpecifier} instances for a given
 * {@link TriggerAndJobDetail}./*from   ww w  . j  a va 2  s. c  o  m*/
 * 
 * <p>
 * Call this method for every {@link TriggerAndJobDetail} published in the
 * system.
 * </p>
 * 
 * @param trigJob
 *        the service to generate specifiers for
 */
public void addSpecifier(TriggerAndJobDetail trigJob) {
    Trigger trig = trigJob.getTrigger();
    if (trig instanceof CronTrigger) {
        CronTrigger ct = (CronTrigger) trig;
        final String key = JobUtils.triggerKey(ct);
        BasicTextFieldSettingSpecifier tf = new BasicTextFieldSettingSpecifier(key, ct.getCronExpression());
        tf.setTitle(ct.getName());
        final String labelKey = key + ".key";
        final String descKey = key + ".desc";
        if (!hasMessage(this.messageSource, labelKey)) {
            if (hasMessage(trigJob.getMessageSource(), labelKey)) {
                messages.put(labelKey, new MessageFormat(
                        trigJob.getMessageSource().getMessage(labelKey, null, Locale.getDefault())));
            } else {
                messages.put(labelKey, new MessageFormat(ct.getName()));
            }
        }
        if (!hasMessage(this.messageSource, descKey)) {
            if (hasMessage(trigJob.getMessageSource(), labelKey)) {
                messages.put(descKey, new MessageFormat(
                        trigJob.getMessageSource().getMessage(descKey, null, Locale.getDefault())));
            } else {
                messages.put(descKey,
                        new MessageFormat(StringUtils.hasText(ct.getDescription()) ? ct.getDescription() : ""));
            }
        }
        synchronized (specifiers) {
            specifiers.add(tf);
        }
    }
}

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 w w  . ja v  a 2 s  .  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);
}