Example usage for java.text MessageFormat parse

List of usage examples for java.text MessageFormat parse

Introduction

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

Prototype

public Object[] parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce an object array.

Usage

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

/**
 * ???/*  w  ww. ja va 2s  .  c  o  m*/
 * @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:com.clustercontrol.systemlog.bean.SyslogMessage.java

/**
 * syslog????????SyslogMessage????API<br>
 * <br>/*from w  w  w.ja v a  2  s.  c  om*/
 * <b>???</b><br>
 * 1. ???????????????<br>
 * 2. ???????????<br>
 * @param syslog syslog?
 * @return SyslogMessage
 * @throws ParseException syslog???????????
 * @throws HinemosUnknown 
 */
public static SyslogMessage parse(String syslog) throws ParseException, HinemosUnknown {
    if (log.isDebugEnabled()) {
        log.debug("parsing syslog : " + syslog);
    }

    // [0]:, [1]:(MMM), [2]:(dd), [3]:(HH), [4]:(mm), [5]:(ss), [6]:??, [7]:
    // ?{1,date,MMM dd HH:mm:ss}????????????1970????
    // ????????2/29???3/1?????(1970???????)
    MessageFormat syslogFormat = new MessageFormat("<{0,number,integer}>{1} {2} {3}:{4}:{5} {6} {7}",
            Locale.ENGLISH);

    // ??????
    Object[] syslogArgs = syslogFormat.parse(syslog);

    // RFC3164??????????????????
    if ("".equals(syslogArgs[SYSLOG_FORMAT_DAY])) {
        syslogFormat = new MessageFormat("<{0,number,integer}>{1}  {2} {3}:{4}:{5} {6} {7}", Locale.ENGLISH);
        syslogArgs = syslogFormat.parse(syslog);
    }

    if (syslogArgs == null)
        throw new HinemosUnknown("different syslog pattern");

    if (log.isDebugEnabled()) {
        int i = 0;
        for (Object arg : syslogArgs) {
            log.debug(String.format("syslog args [%d] : %s", i++, arg.toString()));
        }
    }

    // ???????(H)
    Integer syslogEffectiveTime = HinemosPropertyUtil
            .getHinemosPropertyNum("monitor.systemlog.period.hour", Long.valueOf(SYSLOG_DEFAULT_PERIOD_HOUR))
            .intValue();

    // 0???????????
    if (syslogEffectiveTime <= 0) {
        syslogEffectiveTime = SYSLOG_DEFAULT_PERIOD_HOUR;
    }

    Calendar nowCal = HinemosTime.getCalendarInstance();

    // ??(?)
    int year = nowCal.get(Calendar.YEAR) + 1;
    int month = editCalendarMonth((String) syslogArgs[SYSLOG_FORMAT_MONTH]);
    int dayOfMonth = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_DAY]);
    int hourOfDay = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_HH]);
    int minute = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_MM]);
    int second = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_SS]);

    // ?
    List<Calendar> checkCalList = new ArrayList<Calendar>();
    // (??
    Calendar syslogEffectiveCal = (Calendar) nowCal.clone();
    syslogEffectiveCal.add(Calendar.HOUR, syslogEffectiveTime);

    // ???
    for (int i = 0; checkCalList.size() < 2; i++) {

        // ??????
        if (LEAPYEAR_CHECK_COUNT <= i) {
            break;
        }
        Calendar syslogCheckCal = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
        year--;

        // ???????(??)
        if (syslogEffectiveCal.compareTo(syslogCheckCal) < 0) {
            continue;
        }
        // ??????????????
        if (dayOfMonth != syslogCheckCal.get(Calendar.DAY_OF_MONTH)) {
            continue;
        }
        // ????
        checkCalList.add(syslogCheckCal);
    }

    Calendar editSyslogCal = null;

    // ?????
    if (checkCalList.size() > 0) {
        long absMinMillis = Long.MAX_VALUE;
        for (int i = 0; i < checkCalList.size(); i++) {
            long absDiff = Math.abs(checkCalList.get(i).getTimeInMillis() - nowCal.getTimeInMillis());
            if (absDiff < absMinMillis) {
                // ??????
                absMinMillis = absDiff;
                editSyslogCal = checkCalList.get(i);
            }
        }
    } else {
        // ??????
        editSyslogCal = new GregorianCalendar(nowCal.get(Calendar.YEAR), month, dayOfMonth, hourOfDay, minute,
                second);
        log.warn("System log date is invalid : " + syslog);
    }

    int pri = ((Long) syslogArgs[SYSLOG_FORMAT_PRIORITY]).intValue();
    String hostname = (String) syslogArgs[SYSLOG_FORMAT_HOSTNAME];
    String msg = (String) syslogArgs[SYSLOG_FORMAT_MESSAGE];
    Date date = editSyslogCal.getTime();

    // ??
    SyslogMessage instance = new SyslogMessage(getFacility((int) pri), getSeverity((int) pri), date.getTime(),
            hostname, msg, syslog);
    if (log.isDebugEnabled()) {
        log.debug("parsed syslog : " + instance);
    }

    return instance;
}

From source file:com.github.arven.rest.schema.WebServiceTests.java

@Test
public void regularMessageFormat() throws Exception {
    JsonNode node = mapper.readTree(//from w  w w.j  a va  2  s .  c o  m
            new URL("file:///C:/Users/brian.becker/Git/java-rest-schema/target/test-classes/errorpage.json"));
    String error = node.get("error").asText();
    MessageFormat format = new MessageFormat(
            "{0} {1}: The server was unable to find the {3} that was requested from Article {2}");
    Object[] parsed = format.parse(error);
    println(Arrays.asList(parsed));
    Assert.assertEquals(parsed[0], "404");
    Assert.assertEquals(parsed[1], "Not Found");
    Assert.assertEquals(parsed[2], "123");
    Assert.assertEquals(parsed[3], "Comment resource");
}

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 w  w w. jav a 2  s  . co 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.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
 * /*w  w w.  j  a  v  a2s  .  c o  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.pepstock.jem.util.filters.predicates.JobPredicate.java

/**
 * Checks the filter name/*from  www  . j a va 2 s .  c  om*/
 * @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);
            }
        }
    }
}