Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:org.akaza.openclinica.service.rule.RulesPostImportContainerService.java

License:LGPL

private boolean isRunTimeValid(AuditableBeanWrapper<RuleSetBean> ruleSetBeanWrapper, String runTime) {
    boolean isValid = true;

    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
    try {/*from   w w w.  j  a  v a 2s  .c  o m*/
        formatter.parseDateTime(runTime);
        if (!runTime.matches("\\d{2}:\\d{2}")) {
            ruleSetBeanWrapper.error(createError("OCRERR_0047"));
            isValid = false;
        }

    } catch (Exception e) {
        ruleSetBeanWrapper.error(createError("OCRERR_0047"));
        isValid = false;
    }
    return isValid;
}

From source file:org.alfresco.dataprep.SitePagesService.java

License:Open Source License

/**
 * Add calendar event/*from   w  w w  .  j a v  a2  s .c o m*/
 * @param userName String user name
 * @param password String user password
 * @param siteName String site name
 * @param what String what
 * @param where String event location
 * @param description String event description
 * @param startDate Date event start date
 * @param endDate Date event end date
 * @param timeStart String event start time
 * @param timeEnd String event time finish
 * @param allDay boolean all day event
 * @param tag String tag the event
 * @return true if event is created
 */
@SuppressWarnings("unchecked")
public boolean addCalendarEvent(final String userName, final String password, final String siteName,
        final String what, final String where, final String description, final Date startDate,
        final Date endDate, String timeStart, String timeEnd, final boolean allDay, String tag) {
    if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(siteName)
            || StringUtils.isEmpty(what)) {
        throw new IllegalArgumentException("Parameter missing");
    }
    if (!siteService.exists(siteName, userName, password)) {
        throw new RuntimeException("Site doesn't exists " + siteName);
    }

    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String reqURL = client.getAlfrescoUrl() + "alfresco/s/calendar/create";
    // set default time if null
    if (StringUtils.isEmpty(timeStart)) {
        timeStart = "12:00";
    }
    if (StringUtils.isEmpty(timeEnd)) {
        timeEnd = "13:00";
    }
    Date currentDate = new Date();
    String pattern = "yyyy-MM-dd'T'Z";
    SimpleDateFormat fulldate = new SimpleDateFormat("EEEE, dd MMMM, yyyy");
    SimpleDateFormat fullFormat = new SimpleDateFormat(pattern);
    DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
    String fulldatefrom = "";
    String fulldateto = "";
    String timeStart24 = "";
    String startAt, endAt;
    if (timeStart.contains("AM") || timeStart.contains("PM")) {
        timeStart24 = convertTo24Hour(timeStart);
    } else {
        timeStart24 = timeStart;
    }
    String timeEnd24 = "";
    if (timeEnd.contains("AM") || timeEnd.contains("PM")) {
        timeEnd24 = convertTo24Hour(timeEnd);
    } else {
        timeEnd24 = timeEnd;
    }

    if (startDate == null) {
        // set the current date
        fulldatefrom = fulldate.format(currentDate);
        startAt = fullFormat.format(currentDate);
        DateTime dateTime = dtf.parseDateTime(startAt);
        startAt = dateTime.toString().replaceFirst("00:00", timeStart24);
    } else {
        fulldatefrom = fulldate.format(startDate);
        startAt = fullFormat.format(startDate);
        DateTime dateTime = dtf.parseDateTime(startAt);
        startAt = dateTime.toString().replaceFirst("00:00", timeStart24);
    }
    if (endDate == null) {
        // set the current date
        fulldateto = fulldate.format(currentDate);
        endAt = fullFormat.format(currentDate);
        DateTime dateTime = dtf.parseDateTime(endAt);
        endAt = dateTime.toString().replaceFirst("00:00", timeEnd24);
    } else {
        fulldateto = fulldate.format(endDate);
        endAt = fullFormat.format(endDate);
        DateTime dateTime = dtf.parseDateTime(endAt);
        endAt = dateTime.toString().replaceFirst("00:00", timeEnd24);
    }
    HttpPost post = new HttpPost(reqURL);
    JSONObject body = new JSONObject();
    body.put("fromdate", fulldatefrom);
    body.put("start", timeStart);
    body.put("todate", fulldateto);
    body.put("end", timeEnd);
    if (tag == null) {
        tag = "";
    }
    body.put("tags", tag);
    body.put("site", siteName);
    body.put("page", "calendar");
    body.put("docfolder", "");
    body.put("what", what);
    body.put("where", where);
    body.put("desc", description);
    body.put("startAt", startAt);
    body.put("endAt", endAt);
    if (allDay) {
        body.put("allday", "on");
    }
    HttpResponse response = client.executeRequest(userName, password, body, post);
    if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Event created successfully");
        }
        return true;
    }
    return false;
}

From source file:org.alfresco.dataprep.SitePagesService.java

License:Open Source License

/**
 * Update an event/*from   ww w  .j  a v  a 2  s  . c o m*/
 * @param userName String user name
 * @param password String user password
 * @param siteName String site name
 * @param eventName String even name to be updated should be returned by {@link #getEventName()}
 * @param newWhat String new what
 * @param newWhere String new event location
 * @param newStartDate Date new event start date
 * @param newEndDate Date new event end date
 * @param newTimeStart String new event start time
 * @param newTimeEnd String new event time finish
 * @param newAllDay boolean new all day event
 * @return boolean true if event is updated
 */
@SuppressWarnings("unchecked")
public boolean updateEvent(final String userName, final String password, final String siteName,
        final String eventName, final String newWhat, final String newWhere, Date newStartDate, Date newEndDate,
        String newTimeStart, String newTimeEnd, final boolean newAllDay) {
    if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(siteName)
            || StringUtils.isEmpty(eventName)) {
        throw new IllegalArgumentException("Parameter missing");
    }
    if (StringUtils.isEmpty(eventName)) {
        throw new RuntimeException("Event not found");
    }
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String reqURL = client.getAlfrescoUrl() + "alfresco/s/calendar/event/" + siteName + "/" + eventName;
    Date currentDate = new Date();
    String pattern = "yyyy-MM-dd'T'Z";
    SimpleDateFormat fulldate = new SimpleDateFormat("EEEE, dd MMMM, yyyy");
    SimpleDateFormat fullFormat = new SimpleDateFormat(pattern);
    DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
    String fulldatefrom = "";
    String fulldateto = "";
    String timeStart24 = "";
    String startAt, endAt;
    if (newTimeStart.contains("AM") || newTimeStart.contains("PM")) {
        timeStart24 = convertTo24Hour(newTimeStart);
    } else {
        timeStart24 = newTimeStart;
    }
    String timeEnd24 = "";
    if (newTimeEnd.contains("AM") || newTimeEnd.contains("PM")) {
        timeEnd24 = convertTo24Hour(newTimeEnd);
    } else {
        timeEnd24 = newTimeEnd;
    }

    if (newStartDate == null) {
        // set the current date
        fulldatefrom = fulldate.format(currentDate);
        startAt = fullFormat.format(currentDate);
        DateTime dateTime = dtf.parseDateTime(startAt);
        startAt = dateTime.toString().replaceFirst("00:00", timeStart24);
    } else {
        fulldatefrom = fulldate.format(newStartDate);
        startAt = fullFormat.format(newStartDate);
        DateTime dateTime = dtf.parseDateTime(startAt);
        startAt = dateTime.toString().replaceFirst("00:00", timeStart24);
    }
    if (newEndDate == null) {
        // set the current date
        fulldateto = fulldate.format(currentDate);
        endAt = fullFormat.format(currentDate);
        DateTime dateTime = dtf.parseDateTime(endAt);
        endAt = dateTime.toString().replaceFirst("00:00", timeEnd24);
    } else {
        fulldateto = fulldate.format(newEndDate);
        endAt = fullFormat.format(newEndDate);
        DateTime dateTime = dtf.parseDateTime(endAt);
        endAt = dateTime.toString().replaceFirst("00:00", timeEnd24);
    }
    HttpPut put = new HttpPut(reqURL);
    JSONObject body = new JSONObject();
    body.put("fromdate", fulldatefrom);
    body.put("start", newTimeStart);
    body.put("todate", fulldateto);
    body.put("end", newTimeEnd);
    body.put("site", siteName);
    body.put("page", "calendar");
    body.put("docfolder", "");
    body.put("what", newWhat);
    body.put("where", newWhere);
    body.put("startAt", startAt);
    body.put("endAt", endAt);
    if (newAllDay) {
        body.put("allday", "on");
    }
    HttpResponse response = client.executeRequest(userName, password, body, put);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
        return true;
    case HttpStatus.SC_NOT_FOUND:
        throw new RuntimeException("Invalid site " + siteName);
    default:
        logger.error("Unable to update event: " + response.toString());
        break;
    }
    return false;
}

From source file:org.alfresco.dataprep.WorkflowService.java

License:Open Source License

@SuppressWarnings("unchecked")
private String startWorkflow(final String userName, final String password, final WorkflowType workflowType,
        final String message, Date due, Priority priority, final List<String> assignedUsers,
        final String assignedGroup, final boolean docsByPath, final String documentsSite,
        final List<String> docsToAttach, final List<String> pathsToDocs, final int requiredApprovePercent,
        final boolean sendEmail) {
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String api = client.getAlfrescoUrl() + "alfresco/api/" + version + "processes";
    logger.info("Create process using url: " + api);
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'Z");
    SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd'T'Z");
    String dueDate = fullFormat.format(due);
    DateTime dateTime = dtf.parseDateTime(dueDate);
    HttpPost post = new HttpPost(api);
    JSONObject body = new JSONObject();
    body.put("processDefinitionId", workflowType.getId());
    JSONArray items = new JSONArray();
    if (!(docsToAttach == null) || !(pathsToDocs == null)) {
        if (!docsByPath) {
            for (int i = 0; i < docsToAttach.size(); i++) {
                items.add(getNodeRef(userName, password, documentsSite, docsToAttach.get(i)));
            }/* www.j  a v  a  2  s .co  m*/
        } else {
            for (int i = 0; i < pathsToDocs.size(); i++) {
                items.add(getNodeRefByPath(userName, password, pathsToDocs.get(i)));
            }
        }
    }
    JSONObject variables = new JSONObject();
    if (workflowType.equals(WorkflowType.GroupReview) || workflowType.equals(WorkflowType.PooledReview)) {
        variables.put("bpm_groupAssignee", "GROUP_" + assignedGroup);
    } else if (workflowType.equals(WorkflowType.MultipleReviewers)) {
        variables.put("bpm_assignees", assignedUsers);
    } else {
        variables.put("bpm_assignee", assignedUsers.get(0));
    }
    variables.put("bpm_workflowDescription", message);
    variables.put("bpm_sendEMailNotifications", sendEmail);
    variables.put("bpm_workflowPriority", priority.getLevel());
    variables.put("bpm_workflowDueDate", dateTime.toString());
    if (workflowType.equals(WorkflowType.GroupReview) || workflowType.equals(WorkflowType.MultipleReviewers)) {
        variables.put("wf_requiredApprovePercent", requiredApprovePercent);
    }
    body.put("variables", variables);
    body.put("items", items);
    post.setEntity(client.setMessageBody(body));
    try {
        HttpResponse response = client.execute(userName, password, post);
        logger.info("Response code: " + response.getStatusLine().getStatusCode());
        switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_CREATED:
            if (logger.isTraceEnabled()) {
                logger.trace("Successfuly started workflow: " + message);
            }
            return client.getParameterFromJSON(response, "id", "entry");
        default:
            logger.error("Unable to start workflow " + response.toString());
        }
    } finally {
        client.close();
        post.releaseConnection();
    }
    return "";
}

From source file:org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter.java

License:Open Source License

/**
 * Convert a date <tt>String</tt> to a <tt>Date</tt> object
 *///from   w w w.  j  av  a  2s .  co m
protected Date makeDate(String dateStr) {
    if (dateStr == null || dateStr.length() == 0) {
        return null;
    }

    Date date = null;
    try {
        date = DefaultTypeConverter.INSTANCE.convert(Date.class, dateStr);
    } catch (TypeConversionException e) {
        // Try one of the other formats
        if (this.supportedDateFormatters != null) {
            // Remove text such as " (PDT)" which cannot be parsed.
            String dateStr2 = (dateStr == null || dateStr.indexOf('(') == -1) ? dateStr
                    : dateStr.replaceAll(" \\(.*\\)", "");
            for (DateTimeFormatter supportedDateFormatter : supportedDateFormatters) {
                // supported DateFormats were defined
                /**
                 * Regional date format
                 */
                try {
                    DateTime dateTime = supportedDateFormatter.parseDateTime(dateStr2);
                    if (dateTime.getCenturyOfEra() > 0) {
                        return dateTime.toDate();
                    }
                } catch (IllegalArgumentException e1) {
                    // Didn't work
                }

                /**
                 * Date format can be locale specific - make sure English format always works
                 */
                /* 
                 * TODO MER 25 May 2010 - Added this as a quick fix for IMAP date parsing which is always 
                 * English regardless of Locale.  Some more thought and/or code is required to configure 
                 * the relationship between properties, format and locale.
                 */
                try {
                    DateTime dateTime = supportedDateFormatter.withLocale(Locale.US).parseDateTime(dateStr2);
                    if (dateTime.getCenturyOfEra() > 0) {
                        return dateTime.toDate();
                    }
                } catch (IllegalArgumentException e1) {
                    // Didn't work
                }
            }
        }

        if (date == null) {
            // Still no luck
            throw new TypeConversionException("Unable to convert string to date: " + dateStr);
        }
    }
    return date;
}

From source file:org.alfresco.repo.web.scripts.calendar.AbstractCalendarListingWebScript.java

License:Open Source License

/**
 * Returns a Comparator for (re-)sorting events, typically used after
 *  expanding out recurring instances.//from  w  ww .  j  a v  a2 s  . c  o  m
 */
protected static Comparator<Map<String, Object>> getEventDetailsSorter() {
    return new Comparator<Map<String, Object>>() {
        public int compare(Map<String, Object> resultA, Map<String, Object> resultB) {
            DateTimeFormatter fmtNoTz = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
            DateTimeFormatter fmtTz = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");

            String startA = (String) resultA.get(RESULT_START);
            String startB = (String) resultB.get(RESULT_START);

            startA = startA.replace("Z", "+00:00");
            startB = startB.replace("Z", "+00:00");

            //check and parse iso8601 date without time zone (All day events are stripped of time zone)
            DateTime sa = startA.length() > 23 ? fmtTz.parseDateTime(startA) : fmtNoTz.parseDateTime(startA);
            DateTime sb = startB.length() > 23 ? fmtTz.parseDateTime(startB) : fmtNoTz.parseDateTime(startB);

            int cmp = sa.compareTo(sb);
            if (cmp == 0) {
                String endA = (String) resultA.get(RESULT_END);
                String endB = (String) resultB.get(RESULT_END);

                DateTime ea = endA.length() > 23 ? fmtTz.parseDateTime(endA) : fmtNoTz.parseDateTime(endA);
                DateTime eb = endB.length() > 23 ? fmtTz.parseDateTime(endB) : fmtNoTz.parseDateTime(endB);

                cmp = ea.compareTo(eb);
                if (cmp == 0) {
                    String nameA = (String) resultA.get(RESULT_NAME);
                    String nameB = (String) resultB.get(RESULT_NAME);
                    return nameA.compareTo(nameB);
                }
                return cmp;
            }
            return cmp;
        }
    };
}

From source file:org.alfresco.util.CachingDateFormat.java

License:Open Source License

public static Pair<Date, Integer> lenientParse(String text, int minimumResolution) throws ParseException {
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    try {// ww w . j av  a 2  s  . co  m
        Date parsed = fmt.parseDateTime(text).toDate();
        return new Pair<Date, Integer>(parsed, Calendar.MILLISECOND);
    } catch (IllegalArgumentException e) {

    }

    SimpleDateFormatAndResolution[] formatters = getLenientFormatters();
    for (SimpleDateFormatAndResolution formatter : formatters) {
        if (formatter.resolution >= minimumResolution) {
            ParsePosition pp = new ParsePosition(0);
            Date parsed = formatter.simpleDateFormat.parse(text, pp);
            if ((pp.getIndex() < text.length()) || (parsed == null)) {
                continue;
            }
            return new Pair<Date, Integer>(parsed, formatter.resolution);
        }
    }

    throw new ParseException("Unknown date format", 0);

}

From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlDateExpressionTestBase.java

License:Apache License

static DateTime str2DateTime(String dateStr) {
    DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC();
    return format.parseDateTime(dateStr);
}

From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlDateExpressionTestBase.java

License:Apache License

static DateTime str2Date(String dateStr) {
    DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC();
    return format.parseDateTime(dateStr);
}

From source file:org.apache.bigtop.datagenerators.weatherman.internal.Driver.java

License:Apache License

/**
 * Returns local date from string in YYYY-MM-DD format
 *
 * @param text/*from  w  ww  . j  a  v  a 2s  .c o  m*/
 * @return
 */
private LocalDate parseDate(String text) {
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTime dt = dtFormatter.parseDateTime(text);

    return dt.toLocalDate();
}