Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

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

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>//from w  ww  . j a va  2  s .  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 LocalTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(PATTERN);
    return fmt.parseLocalTime(json.getAsString());
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

License:Apache License

/**
 * Try several different date formats (in order of descending specificity) to parse a potential
 * date string./*from w w  w.j a v  a  2 s . c  o  m*/
 * @param inVal
 * @return
 * @throws IllegalArgumentException if the string cannot be successfully parsed into a date.
 */
public static GregorianCalendar attemptDateParse(String inVal) {
    if (null == inVal || inVal.length() < 1)
        throw new IllegalArgumentException("Cannot parse null date/time string");

    // Attempt formats in order of reducing specificity
    try {
        DateTime d = ISODateTimeFormat.dateTime().parseDateTime(inVal);
        return d.toGregorianCalendar();
    } catch (IllegalArgumentException e) {
        try {
            LocalDate d = DateTimeFormat.forPattern("yyyy-MM-dd").parseLocalDate(inVal);
            return d.toDateTimeAtMidnight().toGregorianCalendar();
        } catch (IllegalArgumentException e2) {
            try {
                LocalDate d = DateTimeFormat.forPattern("MM/dd/yyyy").parseLocalDate(inVal);
                return d.toDateTimeAtMidnight().toGregorianCalendar();
            } catch (IllegalArgumentException e3) {
                try {
                    LocalDate d = DateTimeFormat.forPattern("MM/dd/yy").parseLocalDate(inVal);
                    return d.toDateTimeAtMidnight().toGregorianCalendar();
                } catch (IllegalArgumentException e4) {
                }
            }
        }
    }
    log.error("Cannot parse date/time string " + inVal);
    throw new IllegalArgumentException("Cannot parse date/time string " + inVal);
}

From source file:com.flooose.gpxkeeper.GPXFile.java

License:Open Source License

public void saveTrackingPointAsJSON() {
    DateTime timestamp = null;//from   ww w  .  j a va2  s. c o  m

    JSONObject trackingPoint = new JSONObject();

    for (int i = 0; i < parser.getAttributeCount(); i++) {
        try {
            if ("lon".equals(parser.getAttributeName(i))) {
                trackingPoint.put(LONGITUDE, parser.getAttributeValue(i));

            } else if ("lat".equals(parser.getAttributeName(i))) {
                trackingPoint.put(LATITUDE, parser.getAttributeValue(i));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    try {
        while (!trackPointEnd()) {
            if ("ele".equals(parser.getName()) && parser.getEventType() != parser.END_TAG) {
                while (parser.getEventType() != parser.TEXT)
                    parser.next();
                trackingPoint.put(GPXFile.ELEVATION, parser.getText());
            } else if ("time".equals(parser.getName()) && parser.getEventType() != parser.END_TAG) {
                while (parser.getEventType() != parser.TEXT)
                    parser.next();
                DateTimeFormatter dtf = DateTimeFormat.forPattern(GPX_DATE_FORMAT_STRING);
                timestamp = dtf.withZoneUTC().parseDateTime(parser.getText());

                if (startTime == null) {
                    startTime = timestamp.withZone(DateTimeZone.getDefault());

                    gpsActivity.put(GPXFile.START_TIME,
                            new SimpleDateFormat(DATE_FORMAT_STRING).format(startTime.getMillis()));
                }
            }
            parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        trackingPoint.put(GPXFile.TIMESTAMP, (timestamp.getMillis() - startTime.getMillis()) / 1000); // there should be a constant defined somewhere. Find it.
        trackingPoint.put(GPXFile.TRACKING_POINT_TYPE, "gps");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    gpsPath.put(trackingPoint);
}

From source file:com.francelabs.datafari.servlets.admin.alertsAdmin.java

License:Apache License

/**
 * Gets the required parameters parameters
 *
 * @throws IOException/*from  ww  w  .  jav  a 2  s.  c o  m*/
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    response.setContentType("application/json");
    final JSONObject json = new JSONObject();

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy/HH:mm");
    final DateTimeFormatter formatterbis = DateTimeFormat.forPattern("dd/MM/yyyy/ HH:mm");

    try {
        json.put("on", AlertsConfiguration.getProperty(AlertsConfiguration.ALERTS_ON_OFF));
        json.put("hourlyDate", AlertsConfiguration.getProperty(AlertsConfiguration.HOURLY_DELAY));
        json.put("dailyDate", AlertsConfiguration.getProperty(AlertsConfiguration.DAILY_DELAY));
        json.put("weeklyDate", AlertsConfiguration.getProperty(AlertsConfiguration.WEEKLY_DELAY));
        json.put("host", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_HOST));
        json.put("port", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_PORT));
        json.put("database", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_NAME));
        json.put("collection", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_COLLECTION));

        json.put("nextHourly",
                getNextEvent("hourly", AlertsConfiguration.getProperty(AlertsConfiguration.HOURLY_DELAY)));
        json.put("hourly",
                new DateTime(formatter
                        .parseDateTime(AlertsConfiguration.getProperty(AlertsConfiguration.LAST_HOURLY_EXEC)))
                                .toString(formatterbis));

        json.put("nextDaily",
                getNextEvent("daily", AlertsConfiguration.getProperty(AlertsConfiguration.DAILY_DELAY)));
        json.put("daily",
                new DateTime(formatter
                        .parseDateTime(AlertsConfiguration.getProperty(AlertsConfiguration.LAST_DAILY_EXEC)))
                                .toString(formatterbis));

        json.put("nextWeekly",
                getNextEvent("weekly", AlertsConfiguration.getProperty(AlertsConfiguration.WEEKLY_DELAY)));
        json.put("weekly",
                new DateTime(formatter
                        .parseDateTime(AlertsConfiguration.getProperty(AlertsConfiguration.LAST_WEEKLY_EXEC)))
                                .toString(formatterbis));

        json.put("smtp", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_ADDRESS));
        json.put("from", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_FROM));
        json.put("user", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_USER));
        json.put("pass", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_PASSWORD));

        json.put(OutputConstants.CODE, CodesReturned.ALLOK.getValue());
    } catch (final JSONException e) {
        LOGGER.error(
                "Error while building the JSON answer in the doGet of the alerts administration servlets, make sure the fields are filled correctly and that datafari.properties have the correct encoding charset(UTF_8). Error 69021",
                e);
        json.put("message",
                "Error while getting the parameters, please retry, if the problem persists contact your system administrator. Error code : 69021");
        json.put(OutputConstants.CODE, CodesReturned.PROBLEMQUERY.getValue());
    } catch (final IOException e) {
        LOGGER.error(
                "Error while reading the datafari.properties file in the doGet of the alerts administration Servlet . Error 69020 ",
                e);
        json.put("message",
                "Error while reading the datafari.properties file, please make sure the file exists and retry, if the problem persists contact your system administrator. Error code : 69020");
        json.put(OutputConstants.CODE, CodesReturned.GENERALERROR.getValue());
    }

    final PrintWriter out = response.getWriter();
    out.print(json);

}

From source file:com.francelabs.datafari.servlets.admin.alertsAdmin.java

License:Apache License

/**
 * Two uses : When user clicks on turn on/off button, starts or stops the
 * alerts When user clicks on the parameter saving button, saves all the
 * parameters/*from w ww  .  j av  a 2s. com*/
 *
 * @throws IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    response.setContentType("application/json");
    final JSONObject json = new JSONObject();

    try {
        if (request.getParameter("activated") != null) {
            AlertsConfiguration.setProperty(AlertsConfiguration.ALERTS_ON_OFF,
                    request.getParameter("activated"));
            if (request.getParameter("activated").equals("on")) {
                AlertsManager.getInstance().turnOn();
            } else {
                AlertsManager.getInstance().turnOff();
            }
        } else {

            final DateFormat df = new SimpleDateFormat("dd/MM/yyyy/ HH:mm"); // Create
            // a
            // date
            // format
            // and
            // get
            // current
            // time
            final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy/HH:mm");

            AlertsConfiguration.setProperty(AlertsConfiguration.HOURLY_DELAY,
                    new DateTime(df.parse(request.getParameter(AlertsConfiguration.HOURLY_DELAY)))
                            .toString(formatter));
            AlertsConfiguration.setProperty(AlertsConfiguration.DAILY_DELAY,
                    new DateTime(df.parse(request.getParameter(AlertsConfiguration.DAILY_DELAY)))
                            .toString(formatter));
            AlertsConfiguration.setProperty(AlertsConfiguration.WEEKLY_DELAY,
                    new DateTime(df.parse(request.getParameter(AlertsConfiguration.WEEKLY_DELAY)))
                            .toString(formatter));
            AlertsConfiguration.setProperty(AlertsConfiguration.DATABASE_HOST,
                    request.getParameter(AlertsConfiguration.DATABASE_HOST));
            AlertsConfiguration.setProperty(AlertsConfiguration.DATABASE_PORT,
                    request.getParameter(AlertsConfiguration.DATABASE_PORT));
            AlertsConfiguration.setProperty(AlertsConfiguration.DATABASE_NAME,
                    request.getParameter(AlertsConfiguration.DATABASE_NAME));
            AlertsConfiguration.setProperty(AlertsConfiguration.DATABASE_COLLECTION,
                    request.getParameter(AlertsConfiguration.DATABASE_COLLECTION));
            AlertsConfiguration.setProperty(AlertsConfiguration.SMTP_ADDRESS,
                    request.getParameter(AlertsConfiguration.SMTP_ADDRESS));
            AlertsConfiguration.setProperty(AlertsConfiguration.SMTP_FROM,
                    request.getParameter(AlertsConfiguration.SMTP_FROM));
            AlertsConfiguration.setProperty(AlertsConfiguration.SMTP_USER,
                    request.getParameter(AlertsConfiguration.SMTP_USER));
            AlertsConfiguration.setProperty(AlertsConfiguration.SMTP_PASSWORD,
                    request.getParameter(AlertsConfiguration.SMTP_PASSWORD));

            if (request.getParameter("restart") == null || request.getParameter("restart").equals("")
                    || request.getParameter("restart").equals("true")) { // restart
                // param
                // used
                // for
                // tests,
                // DO
                // NOT
                // REMOVE
                // Restart scheduler
                AlertsManager.getInstance().turnOff();
                AlertsManager.getInstance().turnOn();
            }

            json.put(OutputConstants.CODE, CodesReturned.ALLOK.getValue());

        }
    } catch (final Exception e) {
        LOGGER.error(
                "Error while accessing the alerts.properties file in the doPost of the alerts administration Servlet . Error 69020 ",
                e);
        json.put("message",
                "Error while accessing the alerts.properties file, please make sure the file exists and retry, if the problem persists contact your system administrator. Error code : 69020");
        json.put(OutputConstants.CODE, CodesReturned.GENERALERROR.getValue());
    }

    final PrintWriter out = response.getWriter();
    out.print(json);
}

From source file:com.francelabs.datafari.servlets.admin.alertsAdmin.java

License:Apache License

private String getNextEvent(final String frequency, final String initialDate) {
    final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy/HH:mm");
    final DateTime scheduledDate = new DateTime(formatter.parseDateTime(initialDate));
    final Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.SECOND, 0);/* ww w .ja  va 2  s  .  com*/
    cal.set(Calendar.MILLISECOND, 0);
    final DateTime currentDateTime = new DateTime(cal.getTime());
    DateTime scheduledDateTimeUpdate = new DateTime(cal.getTime());

    switch (frequency.toLowerCase()) {
    case "hourly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.HOUR_OF_DAY, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    case "daily":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    case "weekly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_WEEK, scheduledDate.getDayOfWeek() + 1); // +1
        // =
        // diff
        // between
        // Joda
        // and
        // Calendar
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    default:
        break;
    }
    return scheduledDateTimeUpdate.toString(formatter);
}

From source file:com.fusesource.examples.horo.model.StarSign.java

License:Apache License

public static StarSign getInstance(ReadableDateTime dateTime) {
    Validate.notNull(dateTime, "dateTime is null");
    StarSign starSign = null;//from   www.j a v  a2 s .co  m
    for (StarSign temp : values()) {
        if (temp.appliesTo(dateTime)) {
            starSign = temp;
            break;
        }
    }
    if (starSign == null) {
        throw new IllegalStateException(
                "Unable to find star sign for " + DateTimeFormat.forPattern("yyyyMMdd").print(dateTime));
    }
    return starSign;
}

From source file:com.garethahealy.elastawatch.elasticloader.processors.JsonParserProcessor.java

License:Apache License

@Override
public void process(Exchange exchange) throws Exception {
    Instant start = Instant.now();

    ObjectMapper objectMapper = new ObjectMapper();
    List<Map<String, String>> data = objectMapper.readValue(exchange.getIn().getBody(String.class), TYPE_REF);
    for (Map<String, String> line : data) {
        //Update the times to be now...
        start = start.plusSeconds(1);//from  w w  w  . j  a v  a 2 s. c  om
        line.put("timeMillis", String.valueOf(start.toEpochMilli()));

        DateTime date = new DateTime(Long.parseLong(line.get("timeMillis")));
        String value = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").print(date);

        line.put("@timestamp", value);
    }

    exchange.getIn().setBody(data);
}

From source file:com.garethahealy.elasticpostman.scraper.entities.EmailContent.java

License:Apache License

private String sanatizeValue(String header, String value) {
    if (header.equalsIgnoreCase("X-List-Received-Date") || header.equalsIgnoreCase("Date")) {
        //DateFormat examples:
        //X-List-Received-Date:     Wed, 11 May 2016 10:49:36 -0000
        //Date:     Wed, 11 May 2016 10:49:36 -0000
        //Date:     Wed, 11 May 2016 10:49:36 -0000 (EDT)

        //Some dates have trailing spaces, so trim all to be safe
        value = value.trim();// w w  w.ja  v a2s .  c  o m

        DateTime parsed = tryParseDate("EEE, dd MMM YYYY HH:mm:ss Z", value, false);
        if (parsed == null) {
            parsed = tryParseDate("EEE, dd MMM YYYY HH:mm:ss Z' ('zzz')'", value, true);

            if (parsed == null) {
                //Special case - Wed, 11 May 2016 10:49:36 -0000 (SGT)
                //Joda does not like the SGT bit, so remove and try again
                parsed = tryParseDate("EEE, dd MMM YYYY HH:mm:ss Z", value.substring(0, value.length() - 6),
                        true);
            }
        }

        if (parsed != null) {
            value = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").print(parsed);
        }
    }

    return value;
}

From source file:com.garethahealy.elasticpostman.scraper.entities.EmailContent.java

License:Apache License

private DateTime tryParseDate(String pattern, String value, Boolean isLogException) {
    DateTime parsed = null;/*from  w  w w  . ja  va  2s  .  c  o  m*/

    try {
        //http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html
        parsed = DateTimeFormat.forPattern(pattern).parseDateTime(value);
    } catch (UnsupportedOperationException ex) {
        if (isLogException) {
            LOG.error(ex.toString());
        }
    } catch (IllegalArgumentException ex) {
        if (isLogException) {
            LOG.error(ex.toString());
        }
    }

    return parsed;
}