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

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

Introduction

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

Prototype

public LocalDateTime parseLocalDateTime(String text) 

Source Link

Document

Parses only the local date-time from the given text, returning a new LocalDateTime.

Usage

From source file:com.fatboyindustrial.gsonjodatime.LocalDateTimeConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>//w  ww . ja  v a 2s.  c o m
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 *
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
    return fmt.parseLocalDateTime(json.getAsString());
}

From source file:com.google.api.ads.adwords.jaxws.extensions.report.model.util.DateUtil.java

License:Open Source License

/**
 * Attempts to parse the given {@code String} to a {@code DateTime} using one of the known
 * formatters./*from w  w  w  .java  2 s .  c  o  m*/
 *
 * The attempt falls back to all the formatters, and if the format is unknown, {@code null} is
 * returned.
 *
 * @param timestamp the time stamp in {@code String} format.
 * @return the parsed {@code DateTime}, or {@code null} in case that the format is unknown.
 */
public static DateTime parseDateTime(String timestamp) {

    if (timestamp != null) {

        for (DateTimeFormatter formatter : DateUtil.formatters) {
            try {
                LocalDateTime localDateTime = formatter.parseLocalDateTime(timestamp);
                return localDateTime.plusHours(12).toDateTime(DateTimeZone.UTC);

            } catch (IllegalArgumentException e) {
                // silently skips to the next formatter
            }
        }
    }
    return null;
}

From source file:com.google.gerrit.server.config.ScheduleConfig.java

License:Apache License

private static long initialDelay(Config rc, String section, String subsection, String keyStartTime,
        DateTime now, long interval) {
    long delay = MISSING_CONFIG;
    String start = rc.getString(section, subsection, keyStartTime);
    try {/*from   ww  w  .ja v a  2s . co m*/
        if (start != null) {
            DateTimeFormatter formatter;
            MutableDateTime startTime = now.toMutableDateTime();
            try {
                formatter = ISODateTimeFormat.hourMinute();
                LocalTime firstStartTime = formatter.parseLocalTime(start);
                startTime.hourOfDay().set(firstStartTime.getHourOfDay());
                startTime.minuteOfHour().set(firstStartTime.getMinuteOfHour());
            } catch (IllegalArgumentException e1) {
                formatter = DateTimeFormat.forPattern("E HH:mm").withLocale(Locale.US);
                LocalDateTime firstStartDateTime = formatter.parseLocalDateTime(start);
                startTime.dayOfWeek().set(firstStartDateTime.getDayOfWeek());
                startTime.hourOfDay().set(firstStartDateTime.getHourOfDay());
                startTime.minuteOfHour().set(firstStartDateTime.getMinuteOfHour());
            }
            startTime.secondOfMinute().set(0);
            startTime.millisOfSecond().set(0);
            long s = startTime.getMillis();
            long n = now.getMillis();
            delay = (s - n) % interval;
            if (delay <= 0) {
                delay += interval;
            }
        } else {
            log.info(MessageFormat.format("{0} schedule parameter \"{0}.{1}\" is not configured", section,
                    keyStartTime));
        }
    } catch (IllegalArgumentException e2) {
        log.error(MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, keyStartTime),
                e2);
        delay = INVALID_CONFIG;
    }
    return delay;
}

From source file:com.pipit.agc.util.LocalDateTimeConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>//from ww  w.j a  v  a2s  .  c o  m
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    // Do not try to deserialize null or empty values
    if (json.getAsString() == null || json.getAsString().isEmpty()) {
        return null;
    }

    final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
    return fmt.parseLocalDateTime(json.getAsString());
}

From source file:com.sonicle.webtop.calendar.Service.java

License:Open Source License

public void processGetPlanning(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    CoreUserSettings cus = getEnv().getCoreUserSettings();
    CoreManager core = WT.getCoreManager();
    ArrayList<MapItem> items = new ArrayList<>();
    Connection con = null;/* www. j a  va 2 s.  c  o m*/

    try {
        String eventStartDate = ServletUtils.getStringParameter(request, "startDate", true);
        String eventEndDate = ServletUtils.getStringParameter(request, "endDate", true);
        String timezone = ServletUtils.getStringParameter(request, "timezone", true);
        JsEvent.Attendee.List attendees = ServletUtils.getObjectParameter(request, "attendees",
                new JsEvent.Attendee.List(), JsEvent.Attendee.List.class);
        //JsAttendeeList attendees = ServletUtils.getObjectParameter(request, "attendees", new JsAttendeeList(), JsAttendeeList.class);

        // Parses string parameters
        DateTimeZone eventTz = DateTimeZone.forID(timezone);
        DateTime eventStartDt = DateTimeUtils.parseYmdHmsWithZone(eventStartDate, eventTz);
        DateTime eventEndDt = DateTimeUtils.parseYmdHmsWithZone(eventEndDate, eventTz);

        UserProfile up = getEnv().getProfile();
        DateTimeZone profileTz = up.getTimeZone();

        LocalTime localStartTime = eventStartDt.toLocalTime();
        LocalTime localEndTime = eventEndDt.toLocalTime();
        LocalTime fromTime = DateTimeUtils.min(localStartTime, us.getWorkdayStart());
        LocalTime toTime = DateTimeUtils.max(localEndTime, us.getWorkdayEnd());

        // Defines useful date/time formatters
        DateTimeFormatter ymdhmFmt = DateTimeUtils.createYmdHmFormatter();
        DateTimeFormatter tFmt = DateTimeUtils.createFormatter(cus.getShortTimeFormat());
        DateTimeFormatter dFmt = DateTimeUtils.createFormatter(cus.getShortDateFormat());

        ArrayList<String> spans = manager.generateTimeSpans(60, eventStartDt.toLocalDate(),
                eventEndDt.toLocalDate(), us.getWorkdayStart(), us.getWorkdayEnd(), profileTz);

        // Generates fields and columnsInfo dynamically
        ArrayList<FieldMeta> fields = new ArrayList<>();
        ArrayList<GridColumnMeta> colsInfo = new ArrayList<>();

        GridColumnMeta col = null;
        fields.add(new FieldMeta("recipient"));
        colsInfo.add(new GridColumnMeta("recipient"));
        for (String spanKey : spans) {
            LocalDateTime ldt = ymdhmFmt.parseLocalDateTime(spanKey);
            fields.add(new FieldMeta(spanKey));
            col = new GridColumnMeta(spanKey, tFmt.print(ldt));
            col.put("date", dFmt.print(ldt));
            col.put("overlaps", (ldt.compareTo(eventStartDt.toLocalDateTime()) >= 0)
                    && (ldt.compareTo(eventEndDt.toLocalDateTime()) < 0));
            colsInfo.add(col);
        }

        // Collects attendees availability...
        OUser user = null;
        UserProfileId profileId = null;
        LinkedHashSet<String> busyHours = null;
        MapItem item = null;
        for (JsEvent.Attendee attendee : attendees) {
            item = new MapItem();
            item.put("recipient", attendee.recipient);

            user = guessUserByAttendee(core, attendee.recipient);
            if (user != null) {
                profileId = new UserProfileId(user.getDomainId(), user.getUserId());
                busyHours = manager.calculateAvailabilitySpans(60, profileId, eventStartDt.withTime(fromTime),
                        eventEndDt.withTime(toTime), eventTz, true);
                for (String hourKey : spans) {
                    item.put(hourKey, busyHours.contains(hourKey) ? "busy" : "free");
                }
            } else {
                for (String spanKey : spans) {
                    item.put(spanKey, "unknown");
                }
            }
            items.add(item);
        }

        GridMetadata meta = new GridMetadata(true);
        meta.setFields(fields);
        meta.setColumnsInfo(colsInfo);
        new JsonResult(items, meta, items.size()).printTo(out);

    } catch (Exception ex) {
        logger.error("Error in GetPlanning", ex);
        new JsonResult(false, "Error").printTo(out);

    } finally {
        DbUtils.closeQuietly(con);
    }
}

From source file:com.trifork.stamdata.importer.jobs.cpr.CPRParser.java

License:Mozilla Public License

private static Date parseDateAndCheckValidity(String dateString, DateTimeFormatter format, String line)
        throws ParseException, Exception {
    dateString = fixWeirdDate(dateString);
    LocalDateTime date = format.parseLocalDateTime(dateString);
    String formattedDate = format.print(date);

    if (!formattedDate.equals(dateString)) {
        String errorMessage = "Ugyldig dato: " + dateString + " fra linjen [" + line + "]";

        if (haltOnDateErrors) {
            throw new Exception(errorMessage);
        } else {//from  w  ww  . j a  v  a 2s .c o  m
            logger.error(errorMessage);
        }
    }

    return date.toDate();
}

From source file:com.vaushell.superpipes.nodes.buffer.Slot.java

License:Open Source License

/**
 * Create a slot and parse value.//from  w  ww.j  a v  a 2 s. c o m
 *
 * @param days List of days, separated by a comma.
 * @param start Inclusive starting hour (format: HH:mm:ss)
 * @param end Exclusive ending hour (format: HH:mm:ss)
 * @return the slot
 */
public static Slot parse(final String days, final String start, final String end) {
    // Days
    final DateTimeFormatter fmtDay = DateTimeFormat.forPattern("E");

    final TreeSet<Integer> rDays = new TreeSet<>();
    for (final String sDay : days.split(",")) {
        final int dayOfWeek = fmtDay.parseLocalDate(sDay).getDayOfWeek();

        rDays.add(dayOfWeek);
    }

    // Hours (HH:mm:ss)
    final DateTimeFormatter fmtHour = DateTimeFormat.forPattern("HH:mm:ss");

    final LocalDateTime min = fmtHour.parseLocalDateTime(start).withMillisOfSecond(0);
    final LocalDateTime max = fmtHour.parseLocalDateTime(end).withMillisOfSecond(0);

    return new Slot(rDays, min.getMillisOfDay(), max.getMillisOfDay());
}

From source file:io.renren.common.utils.DateUtils.java

License:Apache License

/**
 * ??/*from  ww  w . j  a  v  a  2s. co m*/
 * @param strDate 
 * @param pattern ?DateUtils.DATE_TIME_PATTERN
 */
public static Date stringToDate(String strDate, String pattern) {
    if (StringUtils.isBlank(strDate)) {
        return null;
    }

    DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
    return fmt.parseLocalDateTime(strDate).toDate();
}

From source file:ke.co.tawi.babblesms.server.sendsms.tawismsgw.PostSMS.java

License:Open Source License

/**
 * //from   w  ww .  j  a  v  a 2s  .  c  o  m
 */
@Override
public void run() {
    HttpEntity responseEntity = null;
    Map<String, String> params;

    if (urlValidator.isValid(smsGateway.getUrl())) {

        // Prepare the parameters to send
        params = new HashMap<>();

        params.put("username", smsGateway.getUsername());
        params.put("password", smsGateway.getPasswd());
        params.put("source", smsSource.getSource());
        params.put("message", message);

        switch (smsSource.getNetworkuuid()) {
        case Network.SAFARICOM_KE:
            params.put("network", "safaricom_ke");
            break;

        case Network.AIRTEL_KE:
            params.put("network", "safaricom_ke"); // TODO: change to airtel_ke
            break;
        }

        // When setting the destination, numbers beginning with '07' are edited
        // to begin with '254'
        phoneMap = new HashMap<>();
        StringBuffer phoneBuff = new StringBuffer();
        String phoneNum;

        for (Phone phone : phoneList) {
            phoneNum = phone.getPhonenumber();

            if (StringUtils.startsWith(phoneNum, "07")) {
                phoneNum = "254" + StringUtils.substring(phoneNum, 1);
            }

            phoneMap.put(phoneNum, phone);
            phoneBuff.append(phoneNum).append(";");
        }

        params.put("destination", StringUtils.removeEnd(phoneBuff.toString(), ";"));

        // Push to the URL
        try {
            URL url = new URL(smsGateway.getUrl());

            if (StringUtils.equalsIgnoreCase(url.getProtocol(), "http")) {
                responseEntity = doPost(smsGateway.getUrl(), params, retry);

            }
            //            else if(StringUtils.equalsIgnoreCase(url.getProtocol(), "https")) {
            //               doPostSecure(smsGateway.getUrl(), params, retry);
            //            }

        } catch (MalformedURLException e) {
            logger.error("MalformedURLException for URL: '" + smsGateway.getUrl() + "'");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    } // end 'if(urlValidator.isValid(urlStr))'

    // Process the response from the SMS Gateway
    // Assuming all is ok, it would have the following pattern:
    // requestStatus=ACCEPTED&messageIds=254726176878:b265ce23;254728932844:367941a36d2e4ef195;254724300863:11fca3c5966d4d
    if (responseEntity != null) {

        OutgoingLog outgoingLog;

        try {
            String response = EntityUtils.toString(responseEntity);
            GatewayDAO.getInstance().logResponse(account, response, new Date());

            String[] strTokens = StringUtils.split(response, '&');
            String tmpStr = "", dateStr = "";
            for (String str : strTokens) {
                if (StringUtils.startsWith(str, "messageIds")) {
                    tmpStr = StringUtils.removeStart(str, "messageIds=");
                } else if (StringUtils.startsWith(str, "datetime")) {
                    dateStr = StringUtils.removeStart(str, "datetime=");
                }
            }

            strTokens = StringUtils.split(tmpStr, ';');
            String phoneStr, uuid;
            Phone phone;
            DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis();

            for (String str : strTokens) {
                phoneStr = StringUtils.split(str, ':')[0];
                uuid = StringUtils.split(str, ':')[1];
                phone = phoneMap.get(phoneStr);

                outgoingLog = new OutgoingLog();
                outgoingLog.setUuid(uuid);
                outgoingLog.setOrigin(smsSource.getSource());
                outgoingLog.setMessage(message);
                outgoingLog.setDestination(phone.getPhonenumber());
                outgoingLog.setNetworkUuid(phone.getNetworkuuid());
                outgoingLog.setMessagestatusuuid(MsgStatus.SENT);
                outgoingLog.setSender(account.getUuid());
                outgoingLog.setPhoneUuid(phone.getUuid());

                // Set the date of the OutgoingLog to match the SMS Gateway time

                LocalDateTime datetime = timeFormatter.parseLocalDateTime(dateStr);
                outgoingLog.setLogTime(datetime.toDate());

                outgoingLogDAO.put(outgoingLog);
            }

        } catch (ParseException e) {
            logger.error("ParseException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));

        } catch (IOException e) {
            logger.error("IOException when reading responseEntity");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.sms.callback.Callback.java

License:Open Source License

/**     
 * @param request /*from w  ww  .ja v  a 2s  .c  o  m*/
 * @param response 
 * @throws ServletException, IOException     
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis();

    String callbackType = request.getParameter("callbackType");
    String messageId;
    LocalDateTime datetime;

    switch (callbackType) {

    case "status": // A notification of an SMS Status change
        messageId = request.getParameter("messageId");

        datetime = timeFormatter.parseLocalDateTime(request.getParameter("datetime"));
        String status = request.getParameter("status");

        OutgoingLog log = outgoingLogDAO.get(messageId);
        log.setLogTime(datetime.toDate());
        log.setMessagestatusuuid(dlrstatusMap.get(status));

        outgoingLogDAO.put(log);

        break;

    case "incomingSms":
        String network = request.getParameter("network").toLowerCase();
        datetime = timeFormatter.parseLocalDateTime(request.getParameter("datetime"));

        IncomingLog incomingLog = new IncomingLog();
        incomingLog.setDestination(request.getParameter("destination"));
        incomingLog.setUuid(request.getParameter("messageId"));
        incomingLog.setMessage(request.getParameter("message"));
        incomingLog.setLogTime(datetime.toDate());
        incomingLog.setNetworkUuid(networkMap.get(network));

        // The source saved in the address book may begin with "07"
        // but the one received for Kenya would begin with "254"
        // We have to reconcile the two
        String source = request.getParameter("source");

        String phoneNum = "";
        if (StringUtils.startsWith(source, "254")) {
            phoneNum = "07" + StringUtils.substring(source, 4);
        }

        if (phoneDAO.getPhones(phoneNum).size() > 0) {
            incomingLog.setOrigin(phoneNum);

        } else {
            incomingLog.setOrigin(source);
        }

        // Determine the account that it is destined for
        // This assumes that the same shortcode number cannot
        // be owned by multiple accounts
        for (Shortcode shortcode : shortcodeList) {
            if (shortcode.getCodenumber().equals(incomingLog.getDestination())) {
                incomingLog.setRecipientUuid(shortcode.getAccountuuid());
                break;
            }
        }

        incomingLogDAO.putIncomingLog(incomingLog);
        break;
    }

}