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.hypersocket.i18n.I18N.java

public static String getResourceNoOveride(Locale locale, String resourceBundle, String key,
        Object... arguments) {//from   w  ww.  ja  va 2 s .c  o 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:org.isatools.isacreator.io.importisa.InvestigationImport.java

/**
 * Checks to make sure all required Investigation file sections have been entered
 *
 * @param investigationFile - Map containing investigation file structure
 * @return - true if valid, false otherwise.
 *///from   ww w  . java  2  s  .co  m
private boolean isValidInvestigationSections(
        OrderedMap<String, OrderedMap<InvestigationFileSection, OrderedMap<String, List<String>>>> investigationFile) {

    InvestigationStructureLoader loader = new InvestigationStructureLoader();
    Map<InvestigationFileSection, InvestigationSection> sections = loader.loadInvestigationStructure();

    MessageFormat fmt = new MessageFormat(
            "The field {0} is missing from the {1} section of the investigation file");

    for (String mainSection : investigationFile.keySet()) {

        // checking major section, e.g. study or investigation
        Set<InvestigationFileSection> majorSectionParts = new HashSet<InvestigationFileSection>();

        for (InvestigationFileSection section : investigationFile.get(mainSection).keySet()) {
            majorSectionParts.add(section);

            Set<String> minorSectionParts = new HashSet<String>();
            // we also want to check if the salient information for each minor section is in place.
            for (String sectionLabelsAndValues : investigationFile.get(mainSection).get(section).keySet()) {
                minorSectionParts.add(sectionLabelsAndValues.toLowerCase());
            }

            SetUtils<String> setUtils = new SetUtils<String>();

            Set<String> requiredValuesAsLowercase = setUtils
                    .getLowerCaseSetContents(sections.get(section).getRequiredValues());

            Pair<Boolean, Set<String>> equalityResult = setUtils.compareSets(minorSectionParts,
                    requiredValuesAsLowercase, false);
            if (!equalityResult.fst) {
                for (String sectionValue : equalityResult.snd) {
                    messages.add(new ErrorMessage(ErrorLevel.ERROR,
                            fmt.format(new Object[] { sectionValue, section })));
                }
            }
            // check minor section for salient information
        }

        // check major section for salient information

        // the mainsection string is investigation-1 or study-2 - here we strip away from - onwards.
        Set<InvestigationFileSection> requiredSections = loader
                .getRequiredSections(mainSection.substring(0, mainSection.lastIndexOf("-")));
        SetUtils<InvestigationFileSection> setUtils = new SetUtils<InvestigationFileSection>();
        Pair<Boolean, Set<InvestigationFileSection>> equalityResult = setUtils.compareSets(majorSectionParts,
                requiredSections, true);

        // if false,
        if (!equalityResult.fst) {
            if (equalityResult.snd != null) {
                for (InvestigationFileSection section : equalityResult.snd) {
                    messages.add(new ErrorMessage(ErrorLevel.ERROR, fmt.format(
                            new Object[] { section, mainSection.substring(0, mainSection.lastIndexOf("-")) })));
                }
            } else {
                messages.add(new ErrorMessage(ErrorLevel.ERROR, "Incorrect number of sections defined for "
                        + mainSection.substring(0, mainSection.lastIndexOf("-"))));
            }
        }
    }

    // if the message size is 0, there are no errors...
    return messages.size() == 0;
}

From source file:org.acmsl.commons.version.VersionUtils.java

/**
 * Compiles a version pattern using given wildcard.
 * @param wildcard the identifier used to identify "anything goes".
 * @param compiler the regexp compiler.//from   w  w w . j a  v a2 s  .c  o m
 * @param stringUtils the <code>StringUtils</code> instance.
 * @return such pattern.
 */
@NotNull
protected static final Pattern immutableCompileVersionPattern(@NotNull final String wildcard,
        @NotNull final Compiler compiler, @NotNull final StringUtils stringUtils) {
    @Nullable
    Pattern result = null;

    @NotNull
    final MessageFormat t_Formatter = new MessageFormat(VERSION_REGEXP);

    try {
        result = compiler.compile(t_Formatter.format(new Object[] { stringUtils.escapeRegexp(wildcard) }));
    } catch (@NotNull final MalformedPatternException exception) {
        /*
         * This should never happen. It's a compile-time
         * error not detected by the compiler, but it's
         * nothing dynamic. So, if it fails, fix it once
         * and forget.
         */
        LogFactory.getLog(VersionUtils.class).error("Invalid version pattern", exception);
    }

    return result;
}

From source file:org.pentaho.reporting.ui.datasources.jdbc.ui.XulDatabaseDialog.java

private void setData(final JdbcConnectionDefinition def) {
    if (def instanceof DriverConnectionDefinition) {
        final DriverConnectionDefinition jdbcDef = (DriverConnectionDefinition) def;
        this.meta = new DatabaseMeta();
        this.meta.setUsername(jdbcDef.getUsername());
        this.meta.setPassword(jdbcDef.getPassword());
        this.meta.setName(jdbcDef.getName());

        if (jdbcDef.getDatabaseType() != null) {
            log.debug("Database type is known: " + jdbcDef.getDatabaseType());
            try {
                this.meta.setDatabaseType(jdbcDef.getDatabaseType());
            } catch (RuntimeException re) {
                // sic!
            }/*from www  .  j a v a  2  s.  c o m*/
            this.meta.setDBName(jdbcDef.getDatabaseName());
            this.meta.setHostname(jdbcDef.getHostName());
            this.meta.setDBPort(jdbcDef.getPort());
            this.meta.getAttributes().setProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL,
                    jdbcDef.getConnectionString());
            this.meta.getAttributes().setProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS,
                    jdbcDef.getDriverClass());
        } else if (String.valueOf(jdbcDef.getConnectionString()).startsWith(HSQLDB_MEM_PREFIX)) {
            this.meta.setDatabaseType(DatabaseMapping.getGenericInterface().getPluginId());
            this.meta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL,
                    jdbcDef.getConnectionString());
            this.meta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS,
                    jdbcDef.getDriverClass());
        } else if (String.valueOf(jdbcDef.getConnectionString()).startsWith(HSQLDB_LOCAL_PREFIX)) {
            this.meta.setDatabaseType(DatabaseMapping.getGenericInterface().getPluginId());
            this.meta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL,
                    jdbcDef.getConnectionString());
            this.meta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS,
                    jdbcDef.getDriverClass());
        } else {
            final DatabaseInterface databaseInterface = DatabaseMapping
                    .getMappingForDriver(jdbcDef.getDriverClass());
            this.meta.setDatabaseType(databaseInterface.getPluginId());
            log.debug("Database type is unknown, using " + databaseInterface);
            try {
                final String pattern;
                if (databaseInterface instanceof HypersonicDatabaseMeta) {
                    final String connectionString = jdbcDef.getConnectionString();
                    if (connectionString.startsWith(HSQLDB_PREFIX)) {
                        if (connectionString.indexOf(':', HSQLDB_PREFIX.length()) == -1) {
                            pattern = HSQLDB_PREFIX + "{0}/{2}";
                        } else {
                            pattern = HSQLDB_PREFIX + "{0}:{1}/{2}";
                        }
                    } else {
                        pattern = databaseInterface.getURL("{0}", "{1}", "{2}");
                    }
                } else {
                    pattern = databaseInterface.getURL("{0}", "{1}", "{2}");
                }
                // knowing that most databases are written in C, we can be sure that the zero-character
                // is not a common value.
                if (pattern != null && pattern.length() > 0) {
                    final MessageFormat format = new MessageFormat(pattern);
                    final Object[] objects = format.parse(jdbcDef.getConnectionString());
                    if (objects[0] != null) {
                        this.meta.setHostname(String.valueOf(objects[0]));
                    }
                    if (objects[1] != null) {
                        this.meta.setDBPort(String.valueOf(objects[1]));
                    }
                    if (objects[2] != null) {
                        this.meta.setDBName(String.valueOf(objects[2]));
                    }
                }
            } catch (Exception e) {
                designTimeContext.error(new XulException(
                        "Unable to parse database-URL, please report "
                                + "your database driver to Pentaho to include it in our list of databases.",
                        e));
                this.meta.setDatabaseType(DatabaseMapping.getGenericInterface().getPluginId());
                this.meta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL,
                        jdbcDef.getConnectionString());
                this.meta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS,
                        jdbcDef.getDriverClass());
            }
        }

        final Properties properties = jdbcDef.getProperties();
        final Iterator entryIterator = properties.entrySet().iterator();
        while (entryIterator.hasNext()) {
            final Map.Entry entry = (Map.Entry) entryIterator.next();
            final String key = (String) entry.getKey();
            if (key.startsWith("::pentaho-reporting::")) {
                continue;
            }
            if ("user".equals(key) || "password".equals(key)) {
                continue;
            }
            // This line makes the database dialog crash later. This seems to be a Swing/Xul issue.
            this.meta.addExtraOption(meta.getPluginId(), key, (String) entry.getValue());
        }
    } else if (def instanceof JndiConnectionDefinition) {
        final JndiConnectionDefinition jndiDef = (JndiConnectionDefinition) def;
        this.meta = new DatabaseMeta();
        this.meta.setDBName(jndiDef.getJndiName()); //JNDI name stored in DBname
        this.meta.setName(jndiDef.getName());
        try {
            if (jndiDef.getDatabaseType() != null) {
                this.meta.setDatabaseType(jndiDef.getDatabaseType());
            }
        } catch (RuntimeException re) {
            // even invalid values should not kill us.
            // sic! Kettle throws generic Exceptions.
        }
        this.meta.setAccessType(DatabaseMeta.TYPE_ACCESS_JNDI);
    } else {
        this.meta = null;
    }
}

From source file:org.pepstock.jem.util.filters.predicates.JobPredicate.java

/**
 * Checks the filter name/*from  www  .ja  va 2 s  .co m*/
 * @param tokenValue filter passed
 * @param job job instance
 * @return true if matches
 */
private boolean checkName(String tokenValue, Job job) {
    // is able to manage for job name the * wildcard
    // matches ALWAYS if has got the star only
    if ("*".equalsIgnoreCase(tokenValue)) {
        return true;
    } else {
        // checks if ends with wildcard
        if (tokenValue.endsWith("*")) {
            // if yes, remove the stars
            String newTokenValue = StringUtils.substringBeforeLast(tokenValue, "*");
            // and compares if the value is in the job name
            return StringUtils.containsIgnoreCase(job.getName(), newTokenValue);
        } else {
            // testif a job id has been inserted
            MessageFormat jobIdFormat = new MessageFormat(Factory.JOBID_FORMAT);
            // checks if is by job id
            try {
                // try to parse the job id
                jobIdFormat.parse(tokenValue);
                // checks if the ID is the same
                return StringUtils.containsIgnoreCase(job.getId(), tokenValue);
            } catch (ParseException e) {
                // ignore
                LogAppl.getInstance().ignore(e.getMessage(), e);
                // if here means that is not a JOB ID
                // then it uses the job name
                return StringUtils.containsIgnoreCase(job.getName(), tokenValue);
            }
        }
    }
}

From source file:nl.toolforge.karma.core.vc.Authenticators.java

private static synchronized void flush(Map authenticators) throws IOException {

    StringBuffer buffer = new StringBuffer();

    buffer.append("<?xml version=\"1.0\"?>\n\n");
    buffer.append("<authenticators>\n");

    for (Iterator i = authenticators.values().iterator(); i.hasNext();) {
        MessageFormat formatter = null;

        Authenticator a = (Authenticator) i.next();
        if (a.getPassword() != null) {
            formatter = new MessageFormat(
                    "  <authenticator working-context=\"{0}\" id=\"{1}\" username=\"{2}\" password=\"{3}\"/>\n");

            // todo I guess there is some default toolie available for this (XML escaper).

            String password = a.getPassword();
            password = password.replaceAll("&", "&amp;");
            password = password.replaceAll("<", "&lt;");
            password = password.replaceAll(">", "&gt;");
            password = password.replaceAll("\"", "&quot;");
            password = password.replaceAll("'", "&apos;");

            buffer.append(formatter// w  ww .j  a  v  a  2  s .c  om
                    .format(new String[] { a.getWorkingContext(), a.getId(), a.getUsername(), password }));
        } else {
            formatter = new MessageFormat(
                    "  <authenticator working-context=\"{0}\" id=\"{1}\" username=\"{2}\"/>\n");
            buffer.append(formatter.format(new String[] { a.getWorkingContext(), a.getId(), a.getUsername() }));
        }
    }

    buffer.append("</authenticators>\n");

    FileWriter writer = null;
    // Write the manifest to the manifest store.
    //
    writer = new FileWriter(new File(WorkingContext.getConfigurationBaseDir(), "authenticators.xml"));
    try {

        writer.write(buffer.toString());
        writer.flush();

    } finally {
        writer.close();
    }
}

From source file:com.clustercontrol.util.apllog.AplLogger.java

private static void putSyslog(OutputBasicInfo notifyInfo) {
    /**   syslog/*from   w  w w  . jav  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:libepg.ts.packet.TsPacket.java

/**
 * payload_unit_start_indicator()<br>
 * 1??????PES?????PIS???????????(?)<br>
 * ??0??????????1?????<br>/* w  w  w. j av  a 2 s .c o m*/
 * ??(ID)?0xFF????<br>
 *
 * @return ?????
 * @throws IllegalStateException ????(0,1)????
 */
public synchronized PAYLOAD_UNIT_START_INDICATOR getPayload_unit_start_indicator()
        throws IllegalStateException {
    int temp;
    temp = ByteConverter.byteToInt(this.data.getData()[1]);
    temp = temp & 0x40;
    temp = temp >>> 6;
    switch (temp) {
    case 0:
        return TsPacket.PAYLOAD_UNIT_START_INDICATOR.NOT_START_POINT;
    case 1:
        return TsPacket.PAYLOAD_UNIT_START_INDICATOR.START_PES_OR_START_SECTION;
    }
    MessageFormat msg = new MessageFormat(
            "?????={0}");
    Object[] parameters = { temp };
    throw new IllegalStateException(msg.format(parameters));
}

From source file:org.pepstock.jem.gwt.server.services.JobsManager.java

/**
 * Returns a job status by filter.<br>
 * Filter must be job name (no pattern with wild-cards) or job id
 * //from  ww w  .ja v  a  2  s  . co m
 * @param filter
 *            job name (no pattern with wild-cards) or job id
 * @return job status
 * @throws ServiceMessageException 
 *             if any exception occurs
 */
public JobStatus getJobStatus(String filter) throws ServiceMessageException {
    // checks user authentication
    // if not, this method throws an exception
    checkAuthentication();

    // creates job status
    JobStatus status = new JobStatus();
    StringBuilder sb = new StringBuilder();

    // parses filter to understand if the request is done by
    // job name or job id
    try {
        MessageFormat jobIdFormat = new MessageFormat(Factory.JOBID_FORMAT);
        // checks if is by job id
        jobIdFormat.parse(filter);
        sb.append("id = '").append(filter).append("'");
    } catch (ParseException pe) {
        // otherwise is by job name
        // creates the right permission by job name
        String permission = Permissions.SEARCH_JOBS + filter;
        // checks if the user is authorized to get jobs
        // if not, this method throws an exception
        checkAuthorization(new StringPermission(permission));
        // creates SQL predicate string
        sb.append("name = '").append(filter).append("'");
    }

    // performs predicate on all maps to search job
    SqlPredicate predicate = new SqlPredicate(sb.toString());
    status.setJobsInput(loadQueuesJobs(Queues.INPUT_QUEUE, predicate));
    status.setJobsRunning(loadQueuesJobs(Queues.RUNNING_QUEUE, predicate));
    status.setJobsOutput(loadQueuesJobs(Queues.OUTPUT_QUEUE, predicate));
    status.setJobsRouting(loadQueuesJobs(Queues.ROUTING_QUEUE, predicate));
    return status;
}

From source file:org.openmrs.module.custommessage.CustomMessageSource.java

/**
 * @see AbstractMessageSource#resolveCode(String, Locale)
 *///from  w ww.ja va2 s  .  c  om
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
    if (showMessageCode) {
        return new MessageFormat(code);
    }
    PresentationMessage pm = getPresentation(code, locale); // Check exact match
    if (pm == null) {
        if (locale.getVariant() != null) {
            pm = getPresentation(code, new Locale(locale.getLanguage(), locale.getCountry())); // Try to match language and country
            if (pm == null) {
                pm = getPresentation(code, new Locale(locale.getLanguage())); // Try to match language only
            }
        }
    }
    if (pm != null) {
        return new MessageFormat(pm.getMessage());
    }
    return null;
}