Example usage for java.text SimpleDateFormat parseObject

List of usage examples for java.text SimpleDateFormat parseObject

Introduction

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

Prototype

public Object parseObject(String source) throws ParseException 

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss Z");
    Date date = (Date) formatter.parseObject("22:14:02 -0500");
    System.out.println(date);//from  w  ww .  ja v  a  2s .  com
}

From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java

/**
 * Sets the default value on the attribute model (translates a String to the appropriate type)
 * /*from   ww w .j a v a2  s. c  om*/
 * @param model
 * @param defaultValue
 */
@SuppressWarnings("unchecked")
private void setDefaultValue(AttributeModelImpl model, String defaultValue) {
    if (model.getType().isEnum()) {
        model.setDefaultValue(Enum.valueOf(model.getType().asSubclass(Enum.class), defaultValue));
    } else if (model.getType().equals(Date.class)) {
        SimpleDateFormat fmt = new SimpleDateFormat(model.getDisplayFormat());
        try {
            model.setDefaultValue(fmt.parseObject(defaultValue));
        } catch (ParseException e) {
            throw new OCSRuntimeException("Cannot parse default date value: " + defaultValue + " with format: "
                    + model.getDisplayFormat());
        }
    } else {
        model.setDefaultValue(ClassUtils.instantiateClass(model.getType(), defaultValue));
    }
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

@Override
public void mailOnError(final String subject, final Message previousMailMessage, final String batchClassName,
        final String userName, final String mailTemplatePath) throws DCMAApplicationException {
    LOGGER.debug("Creating  mailMetaData odr mail or error.");
    if (null != subject && null != batchClassName && null != userName && null != previousMailMessage) {
        final MailMetaData metaData = new MailMetaData();
        metaData.setFromAddress(fromMail);
        metaData.setFromName(fromMail);//w w w.  j ava2  s  . c o m
        metaData.setSubject(subject);
        metaData.setToAddresses(new ArrayList<String>(StringUtils.commaDelimitedListToSet(toMail)));
        final MailContentModel model = new MailContentModel();
        model.add(MailConstants.BATCH_CLASS, batchClassName);
        model.add(MailConstants.USER_ID, userName);
        try {
            String ccString = Arrays.toString(previousMailMessage.getHeader(MailConstants.CC))
                    .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE)
                    .replace(MailConstants.CLOSING_BRACKET, MailConstants.EMPTY_STRING);
            String toString = Arrays.toString(previousMailMessage.getHeader(MailConstants.TO))
                    .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE)
                    .replace(MailConstants.CLOSING_BRACKET, MailConstants.EMPTY_STRING);

            // below date format will be used to format date string received
            // from mail header. Mail header can provide a lot more
            // info.
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MailConstants.DATE_FORMAT);
            model.add(MailConstants.SUBJECT, previousMailMessage.getSubject());
            model.add(MailConstants.FROM,
                    Arrays.toString(previousMailMessage.getHeader(MailConstants.FROM))
                            .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE)
                            .replace(MailConstants.CLOSING_BRACKET, ""));
            model.add(MailConstants.TO,
                    toString.equalsIgnoreCase(MailConstants.NULL_STRING) ? MailConstants.EMPTY_STRING
                            : toString);
            model.add(MailConstants.CC,
                    ccString.equalsIgnoreCase(MailConstants.NULL_STRING) ? MailConstants.EMPTY_STRING
                            : ccString);
            model.add(MailConstants.RECEIVED_DATE,
                    simpleDateFormat
                            .parseObject(previousMailMessage.getHeader(MailConstants.DATE_STRING)[0].toString())
                            .toString());
        } catch (javax.mail.MessagingException mailException) {
            LOGGER.error("Error encountered while extarcting info from previos mail object", mailException);
            throw new DCMAApplicationException(
                    "Error encountered while extarcting infor from previos mail object", mailException);
        } catch (java.text.ParseException parseException) {
            LOGGER.error(
                    "Error encountered while parsing date extracted from mail header of previos mail object",
                    parseException);
            throw new DCMAApplicationException(
                    "Error encountered while parsing received date from previos mail object", parseException);
        }
        LOGGER.debug(
                EphesoftStringUtil.concatenate("Batch Class Name: ", batchClassName, "  UserName: ", userName));
        sendTextMailWithClasspathTemplate(metaData, mailTemplatePath, model, previousMailMessage);
    } else {
        LOGGER.error(
                "Either or all of the following values are null. Error notification mail cann't be sent. \n Subject,BatchClassName, UserName");
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcQuerySenderBase.java

protected String fillParamArray(Object[] paramArray, String message) throws SenderException {
    int lengthMessage = message.length();
    int startHaakje = message.indexOf('(');
    int eindHaakje = message.indexOf(')');
    int beginOutput = message.indexOf('?');
    if (startHaakje < 1)
        return message;
    if (beginOutput < 0)
        beginOutput = eindHaakje;/*from  ww w.j  a  va2s .c o  m*/
    // Watch out, this cannot handle nested parentheses
    //      String packageCall = message.substring(startHaakje, eindHaakje + 1);
    String packageInput = message.substring(startHaakje + 1, beginOutput);
    int idx = 0;
    if (message.indexOf(',') == -1) {
        if (message.indexOf('?') == -1) {
            idx = 1;
        } else {
            idx = 0;
        }
    }
    int ix = 1;
    String element = null;
    try {
        if (packageInput.lastIndexOf(',') > 0) {
            while ((packageInput.charAt(packageInput.length() - ix) != ',') && (ix < packageInput.length())) {
                ix++;
            }
            int eindInputs = beginOutput - ix;
            /*
               Copyright 2013 Nationale-Nederlanden
                    
               Licensed under the Apache License, Version 2.0 (the "License");
               you may not use this file except in compliance with the License.
               You may obtain a copy of the License at
                    
                   http://www.apache.org/licenses/LICENSE-2.0
                    
               Unless required by applicable law or agreed to in writing, software
               distributed under the License is distributed on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
               See the License for the specific language governing permissions and
               limitations under the License.
            */
            packageInput = message.substring(startHaakje + 1, eindInputs);
            StringTokenizer st2 = new StringTokenizer(packageInput, ",");
            if (idx != 1) {
                while (st2.hasMoreTokens()) {
                    element = st2.nextToken().trim();
                    if (element.startsWith("'")) {
                        int x = element.indexOf('\'');
                        int y = element.lastIndexOf('\'');
                        paramArray[idx] = (String) element.substring(x + 1, y);
                    } else {
                        if (element.indexOf('-') >= 0) {
                            if (element.length() > 10) {
                                String pattern = "yyyy-MM-dd HH:mm:ss";
                                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                                java.util.Date nDate = (java.util.Date) sdf.parseObject(element.toString());
                                java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(nDate.getTime());
                                paramArray[idx] = (Timestamp) sqlTimestamp;

                            } else {
                                String pattern = "yyyy-MM-dd";
                                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                                java.util.Date nDate;
                                nDate = sdf.parse(element.toString());
                                java.sql.Date sDate = new java.sql.Date(nDate.getTime());
                                paramArray[idx] = (java.sql.Date) sDate;
                            }
                        } else {
                            if (element.indexOf('.') >= 0) {
                                paramArray[idx] = new Float(element);
                            } else {
                                paramArray[idx] = new Integer(element);
                            }
                        }
                    }
                    idx++;
                }
            }
        }
        StringBuffer newMessage = new StringBuffer(message.substring(0, startHaakje + 1));
        if (idx > 0) {
            newMessage.append("?");
        }
        for (int i = 0; i < idx; i++) {
            if (i < idx - 1) {
                newMessage.append(",?");
            }
        }
        if (idx >= 0) {
            //check if output parameter exists is expected in original message and append an ending ?(out-parameter)
            if (message.indexOf('?') > 0) {
                if (idx == 0) {
                    newMessage.append("?");
                } else {
                    newMessage.append(",?");
                }
                newMessage.append(message.substring(eindHaakje, lengthMessage));
            } else {
                newMessage.append(message.substring(eindHaakje, lengthMessage));
            }
        }
        return newMessage.toString();
    } catch (ParseException e) {
        throw new SenderException(
                getLogPrefix() + "got exception parsing a date string from element [" + element + "]", e);
    }
}

From source file:org.geoserver.backuprestore.BackupRestoreTestSupport.java

protected void setUpInternal(SystemTestData data) throws Exception {

    root = File.createTempFile("template", "tmp", new File("target"));
    root.delete();//  w w  w. j  a  v  a 2  s  . com
    root.mkdir();

    // setup an H2 datastore for the purpose of doing joins
    // run all the tests against a store that can do native paging (h2) and one that
    // can't (property)
    Catalog cat = getCatalog();
    DataStoreInfo ds = cat.getFactory().createDataStore();
    ds.setName("foo");
    ds.setWorkspace(cat.getDefaultWorkspace());

    Map params = ds.getConnectionParameters();
    params.put("dbtype", "h2");
    params.put("database", getTestData().getDataDirectoryRoot().getAbsolutePath() + "/foo");
    cat.add(ds);

    FeatureSource fs1 = getFeatureSource(SystemTestData.FORESTS);
    FeatureSource fs2 = getFeatureSource(SystemTestData.LAKES);
    FeatureSource fs3 = getFeatureSource(SystemTestData.PRIMITIVEGEOFEATURE);

    DataStore store = (DataStore) ds.getDataStore(null);
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();

    tb.init((SimpleFeatureType) fs1.getSchema());
    // tb.remove("boundedBy");
    store.createSchema(tb.buildFeatureType());

    tb.init((SimpleFeatureType) fs2.getSchema());
    // tb.remove("boundedBy");
    store.createSchema(tb.buildFeatureType());

    tb.init((SimpleFeatureType) fs3.getSchema());
    tb.remove("surfaceProperty");
    tb.remove("curveProperty");
    tb.remove("uriProperty");
    store.createSchema(tb.buildFeatureType());

    CatalogBuilder cb = new CatalogBuilder(cat);
    cb.setStore(ds);

    FeatureStore fs = (FeatureStore) store.getFeatureSource("Forests");
    fs.addFeatures(fs1.getFeatures());
    addFeature(fs,
            "MULTIPOLYGON (((0.008151604330777 -0.0023208963631571, 0.0086527358638763 -0.0012374917185382, 0.0097553137885805 -0.0004505798694767, 0.0156132468328575 0.001226912691216, 0.0164282119026783 0.0012863836826631, 0.0171241513076058 0.0011195104764988, 0.0181763809803841 0.0003258121477801, 0.018663180519973 -0.0007914339515293, 0.0187 -0.0054, 0.0185427596344991 -0.0062643098258021, 0.0178950534559435 -0.0072336706251426, 0.0166538015456463 -0.0078538015456464, 0.0160336706251426 -0.0090950534559435, 0.0150643098258021 -0.0097427596344991, 0.0142 -0.0099, 0.0086 -0.0099, 0.0077356901741979 -0.0097427596344991, 0.0067663293748574 -0.0090950534559435, 0.0062572403655009 -0.0082643098258021, 0.0061 -0.0074, 0.0061055767515099 -0.0046945371967831, 0.0062818025956546 -0.0038730531083409, 0.0066527358638763 -0.0032374917185382, 0.0072813143786463 -0.0026800146279973, 0.008151604330777 -0.0023208963631571)))",
            "110", "Foo Forest");
    addFeature(fs,
            "MULTIPOLYGON (((-0.0023852705061082 -0.005664537521815, -0.0026781637249217 -0.0063716443030016, -0.0033852705061082 -0.006664537521815, -0.0040923772872948 -0.0063716443030016, -0.0043852705061082 -0.005664537521815, -0.0040923772872947 -0.0049574307406285, -0.0033852705061082 -0.004664537521815, -0.0026781637249217 -0.0049574307406285, -0.0023852705061082 -0.005664537521815)))",
            "111", "Bar Forest");
    FeatureTypeInfo ft = cb.buildFeatureType(fs);
    cat.add(ft);

    fs = (FeatureStore) store.getFeatureSource("Lakes");
    fs.addFeatures(fs2.getFeatures());
    addFeature(fs,
            "POLYGON ((0.0049784771992108 -0.0035817570010558, 0.0046394552911414 -0.0030781256232061, 0.0046513167019495 -0.0024837722339832, 0.0051238379318686 -0.0011179833712748, 0.0057730295670053 -0.0006191988155468, 0.0065631962428717 -0.0022312008226987, 0.0065546368796182 -0.0027977724434409, 0.0060815583363558 -0.0033764140395305, 0.0049784771992108 -0.0035817570010558))",
            "102", "Red Lake");
    addFeature(fs,
            "POLYGON ((0.0057191452206184 -0.0077928768384869, 0.0051345315543621 -0.0076850644756826, 0.0046394552911414 -0.0070781256232061, 0.0046513167019495 -0.0064837722339832, 0.0051238379318686 -0.0051179833712748, 0.0054994549090862 -0.0047342895334108, 0.0070636636030018 -0.0041582580884052, 0.0078667798947931 -0.0042156264760765, 0.0082944271909999 -0.0046527864045, 0.0089944271909999 -0.0060527864045, 0.0090938616646936 -0.0066106299753791, 0.0089805097233498 -0.0069740280868118, 0.0084059445811345 -0.007452049322921, 0.0057191452206184 -0.0077928768384869))",
            "103", "Green Lake");
    addFeature(fs,
            "POLYGON ((0.0007938800267961 -0.0056175636045986, 0.0011573084862925 -0.0051229419555271, 0.0017412204815544 -0.0049337922722299, 0.0023617041415903 -0.0050976945961703, 0.0029728059060882 -0.0055503031602247, 0.0034289873678372 -0.0063805324543033, 0.0035801692478343 -0.0074485059825999, 0.0034823709081135 -0.008013559804892, 0.0032473247836666 -0.008318888359415, 0.0029142821960289 -0.0085126790755088, 0.0023413406005588 -0.0085369332611115, 0.0011766812981572 -0.0078593563537122, 0.0006397573417165 -0.0067622385244755, 0.0007938800267961 -0.0056175636045986))",
            "110", "Black Lake");
    ft = cb.buildFeatureType(fs);
    cat.add(ft);

    fs = (FeatureStore) store.getFeatureSource("PrimitiveGeoFeature");
    fs.addFeatures(fs3.getFeatures());
    ft = cb.buildFeatureType(fs);
    cat.add(ft);

    tb = new SimpleFeatureTypeBuilder();
    tb.setName("TimeFeature");
    tb.add("name", String.class);
    tb.add("dateTime", Date.class);

    SimpleFeatureType timeFeatureType = tb.buildFeatureType();
    store.createSchema(timeFeatureType);

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    DefaultFeatureCollection features = new DefaultFeatureCollection(null, null);
    SimpleFeatureBuilder fb = new SimpleFeatureBuilder(timeFeatureType);
    fb.add("one");
    fb.add(dateFormat.parseObject("2006-04-04 22:00:00"));
    features.add(fb.buildFeature(null));

    fb.add("two");
    fb.add(dateFormat.parseObject("2006-05-05 20:00:00"));
    features.add(fb.buildFeature(null));

    fb.add("three");
    fb.add(dateFormat.parseObject("2006-06-28 18:00:00"));
    features.add(fb.buildFeature(null));

    fs = (FeatureStore) store.getFeatureSource("TimeFeature");
    fs.addFeatures(features);
    ft = cb.buildFeatureType(fs);
    cat.add(ft);

    // add three joinable types with same code, but different type names
    SimpleFeatureType ft1 = DataUtilities.createType(SystemTestData.CITE_URI, "t1",
            "g1:Point:srid=4326,code1:int,name1:String");
    store.createSchema(ft1);
    fs = (FeatureStore) store.getFeatureSource("t1");
    addFeature(fs, "POINT(1 1)", Integer.valueOf(1), "First");
    ft = cb.buildFeatureType(fs);
    cat.add(ft);

    SimpleFeatureType ft2 = DataUtilities.createType(SystemTestData.CITE_URI, "t2",
            "g2:Point:srid=4326,code2:int,name2:String");
    store.createSchema(ft2);
    fs = (FeatureStore) store.getFeatureSource("t2");
    addFeature(fs, "POINT(2 2)", Integer.valueOf(1), "Second");
    ft = cb.buildFeatureType(fs);
    cat.add(ft);

    SimpleFeatureType ft3 = DataUtilities.createType(SystemTestData.CITE_URI, "t3",
            "g3:Point:srid=4326,code3:int,name3:String");
    store.createSchema(ft3);
    fs = (FeatureStore) store.getFeatureSource("t3");
    addFeature(fs, "POINT(3 3)", Integer.valueOf(1), "Third");
    ft = cb.buildFeatureType(fs);
    cat.add(ft);
}

From source file:org.openmrs.module.hospitalcore.db.hibernate.HibernatePatientDashboardDAO.java

public List<Encounter> getEncounter(Patient patient, Location location, EncounterType encType, String date)
        throws DAOException {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    crit.add(Expression.eq("patient", patient));
    if (location != null && location.getLocationId() != null) {
        crit.add(Expression.eq("location", location));
    }//from www .  j  av  a 2 s  .  c  o  m
    if (StringUtils.isNotBlank(date)) {
        String startDate = "";
        String endDate = "";
        if ("recent".equalsIgnoreCase(date)) {
            SimpleDateFormat formatter = Context.getDateFormat();
            Calendar cal = Calendar.getInstance();
            String today = Context.getDateFormat().format(cal.getTime());
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1);
            date = formatter.format(cal.getTime());
            startDate = date + " 00:00:00";
            endDate = today + " 23:59:59";
        } else {
            startDate = date + " 00:00:00";
            endDate = date + " 23:59:59";
        }
        try {
            crit.add(Restrictions.and(Restrictions.ge("encounterDatetime", formatter.parseObject(startDate)),
                    Restrictions.le("encounterDatetime", formatter.parseObject(endDate))));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    crit.add(Expression.eq("voided", false));

    crit.add(Expression.eq("encounterType", encType));

    crit.addOrder(org.hibernate.criterion.Order.desc("encounterDatetime"));
    return crit.list();
}