Example usage for org.apache.commons.lang.time DateUtils parseDate

List of usage examples for org.apache.commons.lang.time DateUtils parseDate

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils parseDate.

Prototype

public static Date parseDate(String str, String... parsePatterns) throws ParseException 

Source Link

Document

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn.

Usage

From source file:org.stormcat.jvbeans.common.lang.DateUtil.java

public static Date parseDate(String target, String format) {
    if (StringUtil.isBlank(target)) {
        return null;
    }/*  w  w w  .j  av  a2 s  .  c  om*/
    try {
        return DateUtils.parseDate(target, new String[] { format });
    } catch (ParseException e) {
        throw new ParseRuntimeException(e);
    }
}

From source file:org.structr.core.entity.AbstractRelationship.java

@Override
public Date getDateProperty(final PropertyKey<Date> key) {

    Object propertyValue = getProperty(key);

    if (propertyValue != null) {

        if (propertyValue instanceof Date) {

            return (Date) propertyValue;
        } else if (propertyValue instanceof Long) {

            return new Date((Long) propertyValue);
        } else if (propertyValue instanceof String) {

            try {

                // try to parse as a number
                return new Date(Long.parseLong((String) propertyValue));
            } catch (NumberFormatException nfe) {

                try {

                    Date date = DateUtils.parseDate(((String) propertyValue), new String[] {
                            "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyymmdd", "yyyymm", "yyyy" });

                    return date;

                } catch (ParseException ex2) {

                    logger.log(Level.WARNING, "Could not parse " + propertyValue + " to date", ex2);

                }/*from   ww w. ja  v a 2  s .  c o  m*/

                logger.log(Level.WARNING, "Can''t parse String {0} to a Date.", propertyValue);

                return null;

            }

        } else {

            logger.log(Level.WARNING,
                    "Date property is not null, but type is neither Long nor String, returning null");

            return null;

        }

    }

    return null;

}

From source file:org.syncope.core.persistence.validation.attrvalue.AbstractValidator.java

private <T extends AbstractAttrValue> void parseValue(final String value, final T attributeValue)
        throws ParsingValidationException {

    Exception exception = null;//  ww  w .  ja v a  2 s  .  c  o m

    switch (schema.getType()) {

    case String:
    case Enum:
        attributeValue.setStringValue(value);
        break;

    case Boolean:
        attributeValue.setBooleanValue(Boolean.parseBoolean(value));
        break;

    case Long:
        try {
            if (schema.getFormatter() == null) {
                attributeValue.setLongValue(Long.valueOf(value));
            } else {
                attributeValue.setLongValue(
                        Long.valueOf(((DecimalFormat) schema.getFormatter()).parse(value).longValue()));
            }
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    case Double:
        try {
            if (schema.getFormatter() == null) {
                attributeValue.setDoubleValue(Double.valueOf(value));
            } else {
                attributeValue.setDoubleValue(
                        Double.valueOf(((DecimalFormat) schema.getFormatter()).parse(value).doubleValue()));
            }
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    case Date:
        try {
            if (schema.getFormatter() == null) {
                attributeValue.setDateValue(DateUtils.parseDate(value, SyncopeConstants.DATE_PATTERNS));
            } else {
                attributeValue
                        .setDateValue(new Date(((DateFormat) schema.getFormatter()).parse(value).getTime()));
            }
        } catch (Exception pe) {
            exception = pe;
        }
        break;

    default:
    }

    if (exception != null) {
        throw new ParsingValidationException("While trying to parse '" + value + "'", exception);
    }
}

From source file:org.syncope.core.util.ImportExport.java

private void setParameters(final String tableName, final Attributes atts, final Query query) {

    Map<String, Integer> colTypes = new HashMap<String, Integer>();

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;//from  www .  jav  a2 s. co  m
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM " + tableName);
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            colTypes.put(rs.getMetaData().getColumnName(i + 1).toUpperCase(),
                    rs.getMetaData().getColumnType(i + 1));
        }
    } catch (SQLException e) {
        LOG.error("While", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing statement", e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    for (int i = 0; i < atts.getLength(); i++) {
        Integer colType = colTypes.get(atts.getQName(i).toUpperCase());
        if (colType == null) {
            LOG.warn("No column type found for {}", atts.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }

        switch (colType) {
        case Types.NUMERIC:
        case Types.REAL:
        case Types.INTEGER:
        case Types.TINYINT:
            try {
                query.setParameter(i + 1, Integer.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Integer '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DECIMAL:
        case Types.BIGINT:
            try {
                query.setParameter(i + 1, Long.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Long '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DOUBLE:
            try {
                query.setParameter(i + 1, Double.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Double '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.FLOAT:
            try {
                query.setParameter(i + 1, Float.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Float '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            try {
                query.setParameter(i + 1, DateUtils.parseDate(atts.getValue(i), SyncopeConstants.DATE_PATTERNS),
                        TemporalType.TIMESTAMP);
            } catch (ParseException e) {
                LOG.error("Unparsable Date '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            query.setParameter(i + 1, "1".equals(atts.getValue(i)) ? Boolean.TRUE : Boolean.FALSE);
            break;

        default:
            query.setParameter(i + 1, atts.getValue(i));
        }
    }
}

From source file:org.talend.dataprofiler.core.ui.utils.CheckValueUtils.java

/**
 * DOC Zqin Comment method "isAoverB".//from  w w w. j av a2  s.c  o m
 * 
 * @param a
 * @param b
 * @return
 */
public static boolean isAoverB(String a, String b) {
    if (!isEmpty(a, b) && (isNumberValue(a, b) || isRealNumberValue(a, b))) {
        Double da = new Double(a);
        Double db = new Double(b);
        return da > db;
    }

    if (!isEmpty(a, b) && isDateValue(a) && isDateValue(b)) {
        try {

            String[] patterns = new String[2];
            patterns[0] = "yyyy-MM-dd"; //$NON-NLS-1$
            patterns[1] = "yyyy-MM-dd HH:mm:ss"; //$NON-NLS-1$

            Date ad = DateUtils.parseDate(a, patterns);
            Date bd = DateUtils.parseDate(b, patterns);

            return ad.after(bd);
        } catch (Exception e) {
            log.error(e, e);
            return false;

        }

    }
    return false;
}

From source file:org.unitils.dbmaintainer.version.impl.DefaultExecutedScriptInfoSourceTest.java

@Before
public void initTestData() throws ParseException {
    executedScript1 = new ExecutedScript(new Script("1_script1.sql", 10L, "xxx"),
            DateUtils.parseDate("20/05/2008 10:20:00", new String[] { "dd/MM/yyyy hh:mm:ss" }), true);
    executedScript2 = new ExecutedScript(new Script("script2.sql", 20L, "yyy"),
            DateUtils.parseDate("20/05/2008 10:25:00", new String[] { "dd/MM/yyyy hh:mm:ss" }), false);
}

From source file:org.usergrid.services.assets.data.AssetUtils.java

/**
 * Attempt to parse the Date from a Date-based header, primarily If-Modified-Since
 * @param headerValue/*from   w  w w. ja v  a 2  s.  c  om*/
 * @return
 */
public static Date fromIfModifiedSince(String headerValue) {
    Date moded = null;
    if (!StringUtils.isEmpty(headerValue)) {
        try {
            moded = DateUtils.parseDate(headerValue, DEFAULT_PATTERNS);
        } catch (ParseException pe) {
            logger.error("Could not parse date format from If-Modified-Since header: " + headerValue);
        }
    }
    return moded;
}

From source file:org.wesam.nutch.indexer.bbcc.BbccIndexingFilter.java

private Date formatDate(String dateTime) {
    Date parseDate = null;//  ww w .  j  a  va 2s .co m
    try {
        parseDate = DateUtils.parseDate(dateTime, new String[] { "EEE, MMM dd HH:mm:ss yyyy zzz" });
    } catch (ParseException e) {
        LOG.warn("can't parse date" + dateTime);
    }
    return parseDate;
}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormRequestAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    EctConsultationFormRequestForm frm = (EctConsultationFormRequestForm) form;

    String appointmentHour = frm.getAppointmentHour();
    String appointmentPm = frm.getAppointmentPm();

    if (appointmentPm.equals("PM") && Integer.parseInt(appointmentHour) < 12) {
        appointmentHour = Integer.toString(Integer.parseInt(appointmentHour) + 12);
    } else if (appointmentHour.equals("12") && appointmentPm.equals("AM")) {
        appointmentHour = "0";
    }/*from  w ww. j a  v  a2  s.co m*/

    String sendTo = frm.getSendTo();
    String submission = frm.getSubmission();
    String providerNo = frm.getProviderNo();
    String demographicNo = frm.getDemographicNo();

    String requestId = "";

    boolean newSignature = request.getParameter("newSignature") != null
            && request.getParameter("newSignature").equalsIgnoreCase("true");
    String signatureId = "";
    String signatureImg = frm.getSignatureImg();
    if (StringUtils.isBlank(signatureImg)) {
        signatureImg = request.getParameter("newSignatureImg");
        if (signatureImg == null)
            signatureImg = "";
    }

    ConsultationRequestDao consultationRequestDao = (ConsultationRequestDao) SpringUtils
            .getBean("consultationRequestDao");
    ConsultationRequestExtDao consultationRequestExtDao = (ConsultationRequestExtDao) SpringUtils
            .getBean("consultationRequestExtDao");
    ProfessionalSpecialistDao professionalSpecialistDao = (ProfessionalSpecialistDao) SpringUtils
            .getBean("professionalSpecialistDao");

    String[] format = new String[] { "yyyy-MM-dd", "yyyy/MM/dd" };

    if (submission.startsWith("Submit")) {

        try {
            if (newSignature) {
                LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
                DigitalSignature signature = DigitalSignatureUtils.storeDigitalSignatureFromTempFileToDB(
                        loggedInInfo, signatureImg, Integer.parseInt(demographicNo));
                if (signature != null) {
                    signatureId = "" + signature.getId();
                }
            }

            ConsultationRequest consult = new ConsultationRequest();
            Date date = DateUtils.parseDate(frm.getReferalDate(), format);
            consult.setReferralDate(date);
            consult.setServiceId(new Integer(frm.getService()));

            consult.setSignatureImg(signatureId);

            consult.setLetterheadName(frm.getLetterheadName());
            consult.setLetterheadAddress(frm.getLetterheadAddress());
            consult.setLetterheadPhone(frm.getLetterheadPhone());
            consult.setLetterheadFax(frm.getLetterheadFax());

            if (frm.getAppointmentYear() != null && !frm.getAppointmentYear().equals("")) {
                date = DateUtils.parseDate(frm.getAppointmentYear() + "-" + frm.getAppointmentMonth() + "-"
                        + frm.getAppointmentDay(), format);
                consult.setAppointmentDate(date);
                date = DateUtils.setHours(date, new Integer(appointmentHour));
                date = DateUtils.setMinutes(date, new Integer(frm.getAppointmentMinute()));
                consult.setAppointmentTime(date);
            }
            consult.setReasonForReferral(frm.getReasonForConsultation());
            consult.setClinicalInfo(frm.getClinicalInformation());
            consult.setCurrentMeds(frm.getCurrentMedications());
            consult.setAllergies(frm.getAllergies());
            consult.setProviderNo(frm.getProviderNo());
            consult.setDemographicId(new Integer(frm.getDemographicNo()));
            consult.setStatus(frm.getStatus());
            consult.setStatusText(frm.getAppointmentNotes());
            consult.setSendTo(frm.getSendTo());
            consult.setConcurrentProblems(frm.getConcurrentProblems());
            consult.setUrgency(frm.getUrgency());
            consult.setSiteName(frm.getSiteName());
            Boolean pWillBook = false;
            if (frm.getPatientWillBook() != null) {
                pWillBook = frm.getPatientWillBook().equals("1");
            }
            consult.setPatientWillBook(pWillBook);

            if (frm.getFollowUpDate() != null && !frm.getFollowUpDate().equals("")) {
                date = DateUtils.parseDate(frm.getFollowUpDate(), format);
                consult.setFollowUpDate(date);
            }

            consultationRequestDao.persist(consult);

            Integer specId = new Integer(frm.getSpecialist());
            ProfessionalSpecialist professionalSpecialist = professionalSpecialistDao.find(specId);
            if (professionalSpecialist != null) {
                consult.setProfessionalSpecialist(professionalSpecialist);
                consultationRequestDao.merge(consult);
            }
            MiscUtils.getLogger().info("saved new consult id " + consult.getId());
            requestId = String.valueOf(consult.getId());

            Enumeration e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                if (name.startsWith("ext_")) {
                    String value = request.getParameter(name);
                    consultationRequestExtDao
                            .persist(createExtEntry(requestId, name.substring(name.indexOf("_") + 1), value));
                }
            }
            // now that we have consultation id we can save any attached docs as well
            // format of input is D2|L2 for doc and lab
            String[] docs = frm.getDocuments().split("\\|");

            for (int idx = 0; idx < docs.length; ++idx) {
                if (docs[idx].length() > 0) {
                    if (docs[idx].charAt(0) == 'D')
                        EDocUtil.attachDocConsult(providerNo, docs[idx].substring(1), requestId);
                    else if (docs[idx].charAt(0) == 'L')
                        ConsultationAttachLabs.attachLabConsult(providerNo, docs[idx].substring(1), requestId);
                }
            }
        } catch (ParseException e) {
            MiscUtils.getLogger().error("Invalid Date", e);
        }

        request.setAttribute("transType", "2");

    } else

    if (submission.startsWith("Update")) {

        requestId = frm.getRequestId();

        try {

            if (newSignature) {
                LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
                DigitalSignature signature = DigitalSignatureUtils.storeDigitalSignatureFromTempFileToDB(
                        loggedInInfo, signatureImg, Integer.parseInt(demographicNo));
                if (signature != null) {
                    signatureId = "" + signature.getId();
                } else {
                    signatureId = signatureImg;
                }
            } else {
                signatureId = signatureImg;
            }

            ConsultationRequest consult = consultationRequestDao.find(new Integer(requestId));
            Date date = DateUtils.parseDate(frm.getReferalDate(), format);
            consult.setReferralDate(date);
            consult.setServiceId(new Integer(frm.getService()));

            consult.setSignatureImg(signatureId);

            consult.setProviderNo(frm.getProviderNo());

            consult.setLetterheadName(frm.getLetterheadName());
            consult.setLetterheadAddress(frm.getLetterheadAddress());
            consult.setLetterheadPhone(frm.getLetterheadPhone());
            consult.setLetterheadFax(frm.getLetterheadFax());

            Integer specId = new Integer(frm.getSpecialist());
            ProfessionalSpecialist professionalSpecialist = professionalSpecialistDao.find(specId);
            consult.setProfessionalSpecialist(professionalSpecialist);
            if (frm.getAppointmentYear() != null && !frm.getAppointmentYear().equals("")) {
                date = DateUtils.parseDate(frm.getAppointmentYear() + "-" + frm.getAppointmentMonth() + "-"
                        + frm.getAppointmentDay(), format);
                consult.setAppointmentDate(date);
                date = DateUtils.setHours(date, new Integer(appointmentHour));
                date = DateUtils.setMinutes(date, new Integer(frm.getAppointmentMinute()));
                consult.setAppointmentTime(date);
            }
            consult.setReasonForReferral(frm.getReasonForConsultation());
            consult.setClinicalInfo(frm.getClinicalInformation());
            consult.setCurrentMeds(frm.getCurrentMedications());
            consult.setAllergies(frm.getAllergies());
            consult.setDemographicId(new Integer(frm.getDemographicNo()));
            consult.setStatus(frm.getStatus());
            consult.setStatusText(frm.getAppointmentNotes());
            consult.setSendTo(frm.getSendTo());
            consult.setConcurrentProblems(frm.getConcurrentProblems());
            consult.setUrgency(frm.getUrgency());
            consult.setSiteName(frm.getSiteName());
            Boolean pWillBook = false;
            if (frm.getPatientWillBook() != null) {
                pWillBook = frm.getPatientWillBook().equals("1");
            }
            consult.setPatientWillBook(pWillBook);

            if (frm.getFollowUpDate() != null && !frm.getFollowUpDate().equals("")) {
                date = DateUtils.parseDate(frm.getFollowUpDate(), format);
                consult.setFollowUpDate(date);
            }
            consultationRequestDao.merge(consult);

            consultationRequestExtDao.clear(Integer.parseInt(requestId));
            Enumeration e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                if (name.startsWith("ext_")) {
                    String value = request.getParameter(name);
                    consultationRequestExtDao
                            .persist(createExtEntry(requestId, name.substring(name.indexOf("_") + 1), value));
                }
            }
        }

        catch (ParseException e) {
            MiscUtils.getLogger().error("Error", e);
        }

        request.setAttribute("transType", "1");

    } else if (submission.equalsIgnoreCase("And Print Preview")) {
        requestId = frm.getRequestId();
    }

    frm.setRequestId("");

    request.setAttribute("teamVar", sendTo);

    if (submission.endsWith("And Print Preview")) {

        request.setAttribute("reqId", requestId);
        if (OscarProperties.getInstance().isConsultationFaxEnabled()) {
            return mapping.findForward("printIndivica");
        } else if (IsPropertiesOn.propertiesOn("CONSULT_PRINT_PDF")) {
            return mapping.findForward("printpdf");
        } else if (IsPropertiesOn.propertiesOn("CONSULT_PRINT_ALT")) {
            return mapping.findForward("printalt");
        } else {
            return mapping.findForward("print");
        }

    } else if (submission.endsWith("And Fax")) {

        request.setAttribute("reqId", requestId);
        if (OscarProperties.getInstance().isConsultationFaxEnabled()) {
            return mapping.findForward("faxIndivica");
        } else {
            return mapping.findForward("fax");
        }

    } else if (submission.endsWith("esend")) {
        // upon success continue as normal with success message
        // upon failure, go to consultation update page with message
        try {
            doHl7Send(Integer.parseInt(requestId));
            WebUtils.addResourceBundleInfoMessage(request,
                    "oscarEncounter.oscarConsultationRequest.ConfirmConsultationRequest.msgCreatedUpdateESent");
        } catch (Exception e) {
            logger.error("Error contacting remote server.", e);

            WebUtils.addResourceBundleErrorMessage(request,
                    "oscarEncounter.oscarConsultationRequest.ConfirmConsultationRequest.msgCreatedUpdateESendError");
            ParameterActionForward forward = new ParameterActionForward(mapping.findForward("failESend"));
            forward.addParameter("de", demographicNo);
            forward.addParameter("requestId", requestId);
            return forward;
        }
    }

    ParameterActionForward forward = new ParameterActionForward(mapping.findForward("success"));
    forward.addParameter("de", demographicNo);
    return forward;
}

From source file:ru.codeinside.gws.core.cproto.ExportChargeITest.java

private DummyContext createContext() throws ParseException {
    DummyContext ctx = new DummyContext();
    ctx.setVariable("operationType", "exportData");
    ctx.setVariable("postBlockTimeStamp",
            DateUtils.parseDate("2001-12-17 09:30:47", new String[] { "yyyy-MM-dd HH:mm:ss" })); //  ?
    ctx.setVariable("postBlockId", "1538442"); // ??
    ctx.setVariable("postBlockSenderIdentifier", "002811");

    ctx.setVariable("SupplierBillIDBlock", 1L);
    ctx.setVariable("SupplierBillID_1", "0028112706131146519");
    ctx.setVariable("-SupplierBillIDBlock", "");
    return ctx;//from  ww  w .  ja v  a2  s  .  co  m
}