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, String parameter) {
    Iterator bundleListIterator = bundleList.iterator();
    ResourceBundle myResources = null;
    String label = "";
    while (bundleListIterator.hasNext()) {
        String bundle = (String) bundleListIterator.next();

        try {/*from   ww w .  j a  va 2  s.c om*/

            myResources = ResourceBundle.getBundle(bundle, locale);
            if (myResources != null) {
                String l = myResources.getString(key);
                if (l != null) {
                    MessageFormat mFormat = new MessageFormat(l);
                    l = mFormat.format(parameter);
                    label = l;
                    break;
                }
            }

        } catch (Exception e) {
            // TODO: handle exception
        }

    }
    return label;
}

From source file:libepg.epg.section.descriptor.servicedescriptor.SERVICE_ID.java

private SERVICE_ID(String serviceType, Integer serviceId, Integer... serviceIds) {
    this.serviceType = serviceType;
    if ((this.serviceType == null) || (this.serviceType.equals(""))) {
        throw new IllegalArgumentException("??????");
    }/*w w  w  .j ava2  s.com*/

    List<Integer> t = new ArrayList<>();
    if (serviceId != null) {
        t.add(serviceId);
    } else {
        throw new NullPointerException("ID??????");
    }
    if (serviceIds != null) {
        t.addAll(Arrays.asList(serviceIds));
    }
    Range<Integer> r = Range.between(0x0, 0xFF);
    for (Integer i : t) {
        if (!r.contains(i)) {
            MessageFormat msg = new MessageFormat(
                    "ID????ID={0}");
            Object[] parameters = { Integer.toHexString(i) };
            throw new IllegalArgumentException(msg.format(parameters));
        }
    }

    Set<Integer> temp = Collections.synchronizedSet(new HashSet<Integer>());
    temp.addAll(t);
    this.serviceIds = Collections.unmodifiableSet(temp);
}

From source file:libepg.epg.section.descriptor.DESCRIPTOR_TAG.java

private DESCRIPTOR_TAG(String tagName, Class<? extends Descriptor> dataType, Integer tag, Integer... tags) {

    this.tagName = tagName;
    if ((this.tagName == null) || ("".equals(this.tagName))) {
        throw new IllegalArgumentException("???????????");
    }//from  w ww . ja  v a 2 s  .c o  m

    List<Integer> t = new ArrayList<>();
    if (tag != null) {
        t.add(tag);
    } else {
        throw new NullPointerException("??????");
    }
    if (tags != null) {
        t.addAll(Arrays.asList(tags));
    }
    Range<Integer> r = Range.between(0x0, 0xFF);
    for (Integer i : t) {
        if (!r.contains(i)) {
            MessageFormat msg = new MessageFormat("????={0}");
            Object[] parameters = { Integer.toHexString(i) };
            throw new IllegalArgumentException(msg.format(parameters));
        }
    }
    Set<Integer> temp = Collections.synchronizedSet(new HashSet<Integer>());
    temp.addAll(t);
    this.tags = Collections.unmodifiableSet(temp);
    this.dataType = dataType;
}

From source file:org.gtdfree.GTDFree.java

/**
 * @param args/*w  ww . j a va2 s .  c om*/
 */
@SuppressWarnings("static-access")
public static void main(final String[] args) {

    //ApplicationHelper.changeDefaultFontSize(6, "TextField");
    //ApplicationHelper.changeDefaultFontSize(6, "TextArea");
    //ApplicationHelper.changeDefaultFontSize(6, "Table");
    //ApplicationHelper.changeDefaultFontSize(6, "Tree");

    //ApplicationHelper.changeDefaultFontStyle(Font.BOLD, "Tree");

    final Logger logger = Logger.getLogger(GTDFree.class);
    logger.setLevel(Level.ALL);
    BasicConfigurator.configure();

    Options op = new Options();
    op.addOption("data", true, Messages.getString("GTDFree.Options.data")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("eodb", true, Messages.getString("GTDFree.Options.eodb")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("exml", true, Messages.getString("GTDFree.Options.exml")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("h", "help", false, Messages.getString("GTDFree.Options.help")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    op.addOption("log", true, Messages.getString("GTDFree.Options.log")); //$NON-NLS-1$ //$NON-NLS-2$

    Options op2 = new Options();
    op2.addOption(OptionBuilder.hasArg().isRequired(false)
            .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.lang")) //$NON-NLS-1$
                    .format(new Object[] { "'en'", "'de', 'en'" })) //$NON-NLS-1$ //$NON-NLS-2$
            .withArgName("de|en") //$NON-NLS-1$
            .withLongOpt("Duser.language") //$NON-NLS-1$
            .withValueSeparator('=').create());
    op2.addOption(OptionBuilder.hasArg().isRequired(false)
            .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.laf")).format(new Object[] { //$NON-NLS-1$
                    "'com.jgoodies.looks.plastic.Plastic3DLookAndFeel', 'com.jgoodies.looks.plastic.PlasticLookAndFeel', 'com.jgoodies.looks.plastic.PlasticXPLookAndFeel', 'com.jgoodies.looks.windows.WindowsLookAndFeel' (only on MS Windows), 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel' (only on Linux with GTK), 'com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel', 'javax.swing.plaf.metal.MetalLookAndFeel'" })) //$NON-NLS-1$
            .withLongOpt("Dswing.crossplatformlaf") //$NON-NLS-1$
            .withValueSeparator('=').create());

    CommandLineParser clp = new GnuParser();
    CommandLine cl = null;
    try {
        cl = clp.parse(op, args);
    } catch (ParseException e1) {
        logger.error("Parse error.", e1); //$NON-NLS-1$
    }

    System.out.print("GTD-Free"); //$NON-NLS-1$
    String ver = ""; //$NON-NLS-1$
    try {
        System.out.println(" version " + (ver = ApplicationHelper.getVersion())); //$NON-NLS-1$

    } catch (Exception e) {
        System.out.println();
        // ignore
    }

    if (true) { // || cl.hasOption("help") || cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java [Java options] -jar gtd-free.jar [gtd-free options]" //$NON-NLS-1$
                , "[gtd-free options] - " + Messages.getString("GTDFree.Options.appop") //$NON-NLS-1$ //$NON-NLS-2$
                , op, "[Java options] - " + new MessageFormat(Messages.getString("GTDFree.Options.javaop")) //$NON-NLS-1$//$NON-NLS-2$
                        .format(new Object[] { "'-jar'" }) //$NON-NLS-1$
                , false);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        hf.setLongOptPrefix("-"); //$NON-NLS-1$
        hf.setWidth(88);
        hf.printOptions(pw, hf.getWidth(), op2, hf.getLeftPadding(), hf.getDescPadding());
        String s = sw.getBuffer().toString();
        s = s.replaceAll("\\A {3}", ""); //$NON-NLS-1$ //$NON-NLS-2$
        s = s.replaceAll("\n {3}", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        s = s.replaceAll(" <", "=<"); //$NON-NLS-1$ //$NON-NLS-2$
        System.out.print(s);
    }

    String val = cl.getOptionValue("data"); //$NON-NLS-1$
    if (val != null) {
        System.setProperty(ApplicationHelper.DATA_PROPERTY, val);
        System.setProperty(ApplicationHelper.TITLE_PROPERTY, "1"); //$NON-NLS-1$
    } else {
        System.setProperty(ApplicationHelper.TITLE_PROPERTY, "0"); //$NON-NLS-1$
    }

    val = cl.getOptionValue("log"); //$NON-NLS-1$
    if (val != null) {
        Level l = Level.toLevel(val, Level.ALL);
        logger.setLevel(l);
    }

    if (!ApplicationHelper.tryLock(null)) {
        System.out.println("Instance of GTD-Free already running, pushing it to be visible..."); //$NON-NLS-1$
        remotePushVisible();
        System.out.println("Instance of GTD-Free already running, exiting."); //$NON-NLS-1$
        System.exit(0);
    }

    if (!"OFF".equalsIgnoreCase(val)) { //$NON-NLS-1$
        RollingFileAppender f = null;
        try {
            f = new RollingFileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN),
                    ApplicationHelper.getLogFileName(), true);
            f.setMaxBackupIndex(3);
            BasicConfigurator.configure(f);
            f.rollOver();
        } catch (IOException e2) {
            logger.error("Logging error.", e2); //$NON-NLS-1$
        }
    }
    logger.info("GTD-Free " + ver + " started."); //$NON-NLS-1$ //$NON-NLS-2$
    logger.debug("Args: " + Arrays.toString(args)); //$NON-NLS-1$
    logger.info("Using data in: " + ApplicationHelper.getDataFolder()); //$NON-NLS-1$

    if (cl.getOptionValue("exml") != null || cl.getOptionValue("eodb") != null) { //$NON-NLS-1$ //$NON-NLS-2$

        GTDFreeEngine engine = null;

        try {
            engine = new GTDFreeEngine();
        } catch (Exception e1) {
            logger.fatal("Fatal error, exiting.", e1); //$NON-NLS-1$
        }

        val = cl.getOptionValue("exml"); //$NON-NLS-1$
        if (val != null) {
            File f1 = new File(val);
            if (f1.isDirectory()) {
                f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            try {
                f1.getParentFile().mkdirs();
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
            try {
                engine.getGTDModel().exportXML(f1);
                logger.info("Data successfully exported as XML to " + f1.toString()); //$NON-NLS-1$
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
        }

        val = cl.getOptionValue("eodb"); //$NON-NLS-1$
        if (val != null) {
            File f1 = new File(val);
            if (f1.isDirectory()) {
                f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".odb-xml"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            try {
                f1.getParentFile().mkdirs();
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
            try {
                GTDData data = engine.getGTDModel().getDataRepository();
                if (data instanceof GTDDataODB) {
                    try {
                        ((GTDDataODB) data).exportODB(f1);
                    } catch (Exception e) {
                        logger.error("Export error.", e); //$NON-NLS-1$
                    }
                    logger.info("Data successfully exported as ODB to " + f1.toString()); //$NON-NLS-1$
                } else {
                    logger.info("Data is not stored in ODB database, nothing is exported."); //$NON-NLS-1$
                }
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
        }

        try {
            engine.close(true, false);
        } catch (Exception e) {
            logger.error("Internal error.", e); //$NON-NLS-1$
        }

        return;
    }

    logger.debug("Using OS '" + System.getProperty("os.name") + "', '" + System.getProperty("os.version") //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
            + "', '" + System.getProperty("os.arch") + "'."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    logger.debug("Using Java '" + System.getProperty("java.runtime.name") + "' version '" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            + System.getProperty("java.runtime.version") + "'."); //$NON-NLS-1$ //$NON-NLS-2$

    Locale[] supported = { Locale.ENGLISH, Locale.GERMAN };

    String def = Locale.getDefault().getLanguage();
    boolean toSet = true;
    for (Locale locale : supported) {
        toSet &= !locale.getLanguage().equals(def);
    }

    if (toSet) {
        logger.debug("System locale '" + def + "' not supported, setting to '" + Locale.ENGLISH.getLanguage() //$NON-NLS-1$//$NON-NLS-2$
                + "'."); //$NON-NLS-1$
        try {
            Locale.setDefault(Locale.ENGLISH);
        } catch (Exception e) {
            logger.warn("Setting default locale failed.", e); //$NON-NLS-1$
        }
    } else {
        logger.debug("Using locale '" + Locale.getDefault().toString() + "'."); //$NON-NLS-1$ //$NON-NLS-2$
    }

    try {
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "javax.swing.plaf.metal.MetalLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        if (System.getProperty("swing.crossplatformlaf") == null) { //$NON-NLS-1$
            String osName = System.getProperty("os.name"); //$NON-NLS-1$
            if (osName != null && osName.toLowerCase().indexOf("windows") != -1) { //$NON-NLS-1$
                UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel"); //$NON-NLS-1$
            } else {
                try {
                    // we prefer to use native L&F, many systems support GTK, even if Java thinks it is not supported
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); //$NON-NLS-1$
                } catch (Throwable e) {
                    logger.debug("GTK L&F not supported.", e); //$NON-NLS-1$
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }
            }
        }
    } catch (Throwable e) {
        logger.warn("Setting L&F failed.", e); //$NON-NLS-1$
    }
    logger.debug("Using L&F '" + UIManager.getLookAndFeel().getName() + "' by " //$NON-NLS-1$//$NON-NLS-2$
            + UIManager.getLookAndFeel().getClass().getName());

    try {
        final GTDFree application = new GTDFree();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {

                    application.getJFrame();
                    application.restore();
                    //application.getJFrame().setVisible(true);
                    application.pushVisible();

                    ApplicationHelper.executeInBackground(new Runnable() {
                        @Override
                        public void run() {
                            if (SystemTray.isSupported() && application.getEngine().getGlobalProperties()
                                    .getBoolean(GlobalProperties.SHOW_TRAY_ICON, false)) {
                                try {
                                    SystemTray.getSystemTray().add(application.getTrayIcon());
                                } catch (AWTException e) {
                                    logger.error("Failed to activate system tray icon.", e); //$NON-NLS-1$
                                }
                            }
                        }
                    });

                    ApplicationHelper.executeInBackground(new Runnable() {

                        @Override
                        public void run() {
                            application.exportRemote();
                        }
                    });

                    if (application.getEngine().getGlobalProperties()
                            .getBoolean(GlobalProperties.CHECK_FOR_UPDATE_AT_START, true)) {
                        ApplicationHelper.executeInBackground(new Runnable() {

                            @Override
                            public void run() {
                                application.checkForUpdates(false);
                            }
                        });
                    }

                } catch (Throwable t) {
                    t.printStackTrace();
                    logger.fatal("Failed to start application, exiting.", t); //$NON-NLS-1$
                    if (application != null) {
                        application.close(true);
                    }
                    System.exit(0);
                }
            }
        });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    application.close(true);
                } catch (Exception e) {
                    logger.warn("Failed to stop application.", e); //$NON-NLS-1$
                }
                logger.info("Closed."); //$NON-NLS-1$
                ApplicationHelper.releaseLock();
                LogManager.shutdown();
            }
        });
    } catch (Throwable t) {
        logger.fatal("Initialization failed, exiting.", t); //$NON-NLS-1$
        t.printStackTrace();
        System.exit(0);
    }
}

From source file:org.freeplane.core.resources.components.OptionPanel.java

private String formatErrors(final String key, final ArrayList<String> errors) {
    // TextUtils.format() xml escapes the format arguments - we don't want that
    final MessageFormat formatter = new MessageFormat(TextUtils.getText(key));
    return formatter.format(new Object[] { StringUtils.join(errors.iterator(), "<br>") });
}

From source file:libepg.epg.section.sectionreconstructor.PayLoadSplitter.java

/**
 * 1:payload_unit_start_indicator?1?????0?????2??????????1?<br>
 * 2:payload_unit_start_indicator?1?????0????<br>
 * ?2???????????????<br>/*from   w  w w.j a v  a2 s  .c om*/
 * ????+1??????????2?<br>
 * 3:payload_unit_start_indicator?0????????1?
 *
 * @return ??? <br>
 */
public synchronized Map<PAYLOAD_PART_KEY, byte[]> getSplittedPayLoad() {

    if (LOG.isTraceEnabled()) {
        LOG.trace(this.packet);
    }

    Map<PAYLOAD_PART_KEY, byte[]> temp = new HashMap<>();
    EXEC: {
        if (this.packet
                .getPayload_unit_start_indicator() == TsPacket.PAYLOAD_UNIT_START_INDICATOR.NOT_START_POINT) {
            LOG.trace("????");
            temp.put(PAYLOAD_PART_KEY.ALL_PAYLOAD, this.packet.getPayload());
            break EXEC;
        }
        if (this.packet
                .getPayload_unit_start_indicator() == TsPacket.PAYLOAD_UNIT_START_INDICATOR.START_PES_OR_START_SECTION) {
            LOG.trace("???");
            int pointerField = ByteConverter.byteToInt(this.packet.getPayload()[0]);
            int tempLength = this.packet.getPayload().length - 1;
            byte[] tempArray = new byte[tempLength];
            System.arraycopy(this.packet.getPayload(), 1, tempArray, 0, tempArray.length);
            if (LOG.isTraceEnabled()) {
                MessageFormat msg1 = new MessageFormat(
                        "?={0} ={1} 2??={2}");
                Object[] parameters1 = { pointerField, Hex.encodeHexString(this.packet.getPayload()),
                        Hex.encodeHexString(tempArray) };
                LOG.trace(msg1.format(parameters1));
            }
            if (pointerField == 0) {
                temp.put(PAYLOAD_PART_KEY.PAYLOAD_AFTER_2_BYTE, tempArray);
                break EXEC;
            } else {
                byte[] prev = new byte[pointerField];
                System.arraycopy(tempArray, 0, prev, 0, prev.length);
                temp.put(PAYLOAD_PART_KEY.PREV_POINTER, prev);
                byte[] next = new byte[tempArray.length - pointerField];
                System.arraycopy(tempArray, pointerField, next, 0, next.length);
                temp.put(PAYLOAD_PART_KEY.NEXT_POINTER, next);
                break EXEC;
            }
        }
    }

    dumpMap(temp);

    return Collections.unmodifiableMap(temp);
}

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.// www  . j a va  2s. c  o m
 */
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:de.iew.services.impl.MessageBundleServiceImpl.java

@Override
protected MessageFormat resolveCode(String code, Locale locale) {
    MessageFormat mf = null;//from ww  w .  j a  v a 2 s.  com
    try {
        MessageBundleStore messageBundleStore = getMessageBundle(locale, null);
        if (messageBundleStore == null || !messageBundleStore.contains(code)) {
            messageBundleStore = getDefaultMessageBundle(null);
        }

        String message = messageBundleStore.get(code);
        if (message != null) {
            mf = new MessageFormat(message);
        }
    } catch (UnsupportedBasenameException e) {
        if (log.isErrorEnabled()) {
            log.error("Fehler beim Auflsen des Message-Key " + code + ".", e);
        }
    }
    return mf;
}

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

/**
 * Given a message key, locale, and formatting parameters, return a
 * locale-specific message./*from   w  ww.  j av  a 2  s.com*/
 *
 * @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);
}

From source file:libepg.epg.section.descriptor.servicedescriptor.SERVICE_TYPE.java

@Override
public synchronized String toString() {
    StringBuilder s = new StringBuilder();
    for (int i : this.typeIds) {
        s.append("[");
        s.append(Integer.toHexString(i));
        s.append("]");
    }//from   w ww. j a  va2  s.c o m
    String set = s.toString();
    MessageFormat msg = new MessageFormat("{0}({1},serviceIds={2})");
    Object[] parameters = { super.toString(), this.getServiceType(), set };
    return msg.format(parameters);
}