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.powertac.hamweather.Parser.java

License:Apache License

public void processFiles() {
    try {//  w ww. ja va  2 s  .  com
        BufferedReader in = new BufferedReader(new FileReader(inputFile));
        Pattern observation = Pattern.compile("^-- observation: ([SMTWF][a-z]+ [A-Za-z]+ \\d+ [-0-9: ]+)");
        Pattern loc = Pattern.compile("^-- location: " + location);
        String line;
        State state = State.OBS;
        Matcher m;
        JSONParser jparser = new JSONParser();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM d HH:mm:ss Z YYYY");
        iso = ISODateTimeFormat.dateTimeNoMillis();
        DateTime lastObs = null;
        DateTime obsHour = null;
        while (true) {
            line = in.readLine();
            if (null == line || 0 == line.length())
                break;
            switch (state) {
            case OBS:
                m = observation.matcher(line);
                if (m.matches()) {
                    DateTime obsTime = dtf.parseDateTime(m.group(1));
                    if (null == lastObs) {
                        lastObs = obsTime;
                    } else if (obsTime.isAfter(lastObs.plus(MAX_INTERVAL))) {
                        System.out.println("Missed obs - last = " + iso.print(lastObs) + ", current = "
                                + iso.print(obsTime));
                    }
                    lastObs = obsTime;
                    obsHour = obsTime.plus(HOUR / 2).withMillisOfSecond(0).withSecondOfMinute(0)
                            .withMinuteOfHour(0);
                    state = State.LOC;
                }
                break;
            case LOC:
                m = loc.matcher(line);
                if (m.matches()) {
                    //System.out.println("Location: " + location);
                    state = State.JSON_OB;
                }
                break;
            case JSON_OB:
                // process new observation
                JSONObject obs = (JSONObject) jparser.parse(line);
                // check for errors
                Boolean success = (Boolean) obs.get("success");
                if (!success) {
                    System.out.println("Observation retrieval failed at " + iso.print(obsHour));
                    state = State.OBS;
                } else {
                    JSONObject err = (JSONObject) obs.get("error");
                    if (null != err) {
                        // error at server end
                        String msg = (String) err.get("description");
                        System.out.println("Observation error: " + msg + " at " + iso.print(obsHour));
                        state = State.OBS;
                    } else {
                        try {
                            JSONObject response = (JSONObject) obs.get("response");
                            JSONObject ob = (JSONObject) response.get("ob");
                            extractObservation(ob);
                            state = State.JSON_FCST;
                        } catch (ClassCastException cce) {
                            System.out.println("Faulty observation " + obs.toString());
                            state = State.OBS;
                        }
                    }
                }
                break;
            case JSON_FCST:
                // process new forecast
                JSONObject fcst = (JSONObject) jparser.parse(line);
                // check for errors
                Boolean success1 = (Boolean) fcst.get("success");
                if (!success1) {
                    // could not retrieve forecast
                    System.out.println("Forecast retrieval failed at " + iso.print(obsHour));
                    output.forecastMissing();
                } else {
                    JSONObject err = (JSONObject) fcst.get("error");
                    if (null != err) {
                        // error at server end
                        String msg = (String) err.get("description");
                        System.out.println("Forecast error: " + msg + " at " + iso.print(obsHour));
                        output.forecastMissing();
                    } else {
                        JSONArray response = (JSONArray) fcst.get("response");
                        if (response.size() == 0) {
                            // should never get here
                            System.out.println("Empty forecast at " + iso.print(obsHour));
                        }
                        JSONObject periods = (JSONObject) response.get(0);
                        JSONArray fcsts = (JSONArray) periods.get("periods");
                        if (fcsts.size() != FORECAST_HORIZON) {
                            System.out.println(
                                    "Missing forecasts (" + fcsts.size() + ") at " + iso.print(lastObs));
                        }
                        for (int i = 0; i < fcsts.size(); i++) {
                            JSONObject forecast = (JSONObject) fcsts.get(i);
                            extractForecast(forecast, i + 1, obsHour);
                        }
                    }
                }
                state = State.OBS;
                break;
            }
        }
        output.write();
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    }
}

From source file:org.richfaces.tests.page.fragments.impl.log.RichFacesLogEntry.java

License:Open Source License

@Override
public DateTime getTimeStamp() {
    DateTime dt = null;//from   ww w. j  a  va2  s.co m
    String text = labelElement.getText();
    String timeStamp = text.substring(text.indexOf('[') + 1, text.indexOf(']'));
    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:m:s.S");
    try {
        dt = formatter.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Something went wrong with parsing of log entry timestamp!", e);
    }
    return dt;
}

From source file:org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean.java

License:Educational Community License

public void setMetaData(SectionDataIfc section) {

    if (section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE) != null) {
        Integer authortype = new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE));
        setSectionAuthorType(authortype);

        if (section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE)
                .equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.toString())) {
            if (section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN) != null) {
                Integer numberdrawn = new Integer(
                        section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN));
                setNumberToBeDrawn(numberdrawn);
            }/*from w  w  w. j av  a  2 s  .  com*/

            if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW) != null) {
                Long poolid = new Long(
                        section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW));
                setPoolIdToBeDrawn(poolid);
            }
            if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW) != null) {
                String poolname = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
                setPoolNameToBeDrawn(poolname);

                String randomDrawDate = section
                        .getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_RANDOM_DRAW_DATE);
                if (randomDrawDate != null && !"".equals(randomDrawDate)) {

                    try {

                        // bjones86 - SAM-1604
                        DateTime drawDate;
                        DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); //The Date Time is in ISO format
                        try {
                            drawDate = fmt.parseDateTime(randomDrawDate);
                        } catch (Exception ex) {
                            Date date = null;
                            try {
                                // Old code produced dates that appeard like java.util.Date.toString() in the database
                                // This means it's possible that the database contains dates in multiple formats
                                // We'll try parsing Date.toString()'s format first.
                                // Date.toString is locale independent. So this SimpleDateFormat using Locale.US should guarantee that this works on all machines:
                                DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                                // parse can either throw an exception or return null
                                date = df.parse(randomDrawDate);
                            } catch (Exception e) {
                                // failed to parse. Not worth logging yet because we will try again with another format
                            }

                            if (date == null) {
                                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
                                // If this throws an exception, it's caught below. This is appropriate.
                                date = df.parse(randomDrawDate);
                            }

                            if (date == null) {
                                // Nothing has worked
                                throw new IllegalArgumentException("Unable to parse date " + randomDrawDate);
                            } else {
                                drawDate = new DateTime(date);
                            }
                        }

                        //We need the locale to localize the output string
                        Locale loc = new ResourceLoader().getLocale();
                        String drawDateString = DateTimeFormat.fullDate().withLocale(loc).print(drawDate);
                        String drawTimeString = DateTimeFormat.fullTime().withLocale(loc).print(drawDate);
                        setRandomQuestionsDrawDate(drawDateString);
                        setRandomQuestionsDrawTime(drawTimeString);

                    } catch (Exception e) {
                        log.error("Unable to parse date text: " + randomDrawDate, e);
                    }
                }
            }
        }

    } else {

        setSectionAuthorType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE);
    }
    if (section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING) != null) {
        Integer questionorder = new Integer(
                section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING));
        setQuestionOrdering(questionorder);
    } else {
        setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE);
    }

}

From source file:org.samcrow.ridgesurvey.data.ObservationDatabase.java

License:Open Source License

private static IdentifiedObservation createObservation(Cursor result) throws SQLException {
    final int idIndex = result.getColumnIndexOrThrow("id");
    final int uploadedIndex = result.getColumnIndexOrThrow("uploaded");
    final int siteIndex = result.getColumnIndexOrThrow("site");
    final int routeIndex = result.getColumnIndexOrThrow("route");
    final int timeIndex = result.getColumnIndexOrThrow("time");
    final int speciesIndex = result.getColumnIndexOrThrow("species");
    final int notesIndex = result.getColumnIndexOrThrow("notes");

    final int id = result.getInt(idIndex);
    final boolean uploaded = result.getInt(uploadedIndex) == 1;

    final int site = result.getInt(siteIndex);
    final String route = result.getString(routeIndex);

    final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    final String timeString = result.getString(timeIndex);
    DateTime time;//from ww  w.ja  v  a2 s  .  c  o  m
    try {
        time = formatter.parseDateTime(timeString);
    } catch (IllegalArgumentException e) {
        final SQLException e1 = new SQLException("Invalid date/time value: " + timeString);
        //noinspection UnnecessaryInitCause
        e1.initCause(e);
        throw e1;
    }

    final String speciesJson = result.getString(speciesIndex);

    final Map<String, Boolean> speciesPresent = new HashMap<>();
    // Try to parse
    try {
        final JSONObject species = new JSONObject(speciesJson);
        for (Iterator<String> iter = species.keys(); iter.hasNext();) {
            final String speciesName = iter.next();
            final boolean present = species.getBoolean(speciesName);
            speciesPresent.put(speciesName, present);
        }
    } catch (JSONException e) {
        final SQLException e1 = new SQLException("Species JSON could not be parsed", e);
        throw e1;
    }

    final String notes = result.getString(notesIndex);

    return new IdentifiedObservation(time, uploaded, site, route, speciesPresent, notes, id);
}

From source file:org.sindicato.beans.UserBean.java

private Date castFecha(String fecha) {
    Date result = null;//w  w  w  .  ja va2  s  . c o  m
    if (fecha != null && !fecha.isEmpty()) {
        String[] parts = fecha.split(", ");
        if (parts != null && parts.length == 2) {
            int day = Integer.valueOf(parts[0].split(" ")[0]);
            int mes = -1;
            switch (parts[0].split(" ")[1]) {
            case "Enero":
                mes = 1;
                break;
            case "Febrero":
                mes = 2;
                break;
            case "Marzo":
                mes = 3;
                break;
            case "Abril":
                mes = 4;
                break;
            case "Mayo":
                mes = 5;
                break;
            case "Junio":
                mes = 6;
                break;
            case "Julio":
                mes = 7;
                break;
            case "Agosto":
                mes = 8;
                break;
            case "Septiembre":
                mes = 9;
                break;
            case "Octubre":
                mes = 10;
                break;
            case "Noviembre":
                mes = 11;
                break;
            case "Diciembre":
                mes = 12;
                break;
            }
            int year = Integer.valueOf(parts[1]);
            org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
            DateTime dt = formatter.parseDateTime(day + "-" + mes + "-" + year);
            if (dt.isBeforeNow()) {
                result = dt.toDate();
            } else {
                util.error("La fecha de inicio de actividad no puede ser mayor a hoy", "Intentelo de nuevo");
            }
        } else {
            util.error("Error de formateo al convertir la cadena", "Intentelo de nuevo");
        }
    }
    return result;
}

From source file:org.sindicato.converters.DateMaterializeConverter.java

@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
    Date result = null;//from   ww  w  .ja va  2s.c o  m
    if (string != null && string.length() > 0) {
        String[] parts = string.split(", ");
        String[] parts1 = parts[0].split(" ");
        int year = Integer.valueOf(parts[1]);
        int day = Integer.valueOf(parts1[0]);
        String monthName = parts1[1];
        int month = -1;
        switch (monthName) {
        case "Enero":
            month = 1;
            break;
        case "Febrero":
            month = 2;
            break;
        case "Marzo":
            month = 3;
            break;
        case "Abril":
            month = 4;
            break;
        case "Mayo":
            month = 5;
            break;
        case "Junio":
            month = 6;
            break;
        case "Julio":
            month = 7;
            break;
        case "Agosto":
            month = 8;
            break;
        case "Septiembre":
            month = 9;
            break;
        case "Octubre":
            month = 10;
            break;
        case "Noviembre":
            month = 11;
            break;
        case "Diciembre":
            month = 12;
            break;
        }
        DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
        DateTime dt = formatter.parseDateTime(day + "/" + month + "/" + year);
        if (dt != null) {
            result = dt.toDate();
        } else {
            throw new ConverterException("Error al formatear la fecha");
        }
    } else {
        throw new ConverterException("No se recibi ninguna fecha (cadena de caracteres)");
    }
    return result;
}

From source file:org.smartdeveloperhub.harvesters.it.backend.crawler.jira.factories.IssueFactory.java

License:Apache License

private Set<Item> buildChangeLogItem(ChangelogItem jiraItem, Map<String, Contributor> contributors,
        DateTime timestamp, Stack<DateTime> openDate, Stack<DateTime> closeDate) {

    Set<Item> items = new HashSet<>();
    String field = jiraItem.getField();
    if (ChangeLogProperty.STATUS.is(field)) {

        Status oldStatus = fromMap(jiraItem.getFromString(), statusMapping);
        Status newStatus = fromMap(jiraItem.getToString(), statusMapping);

        if (!oldStatus.equals(newStatus)) {

            if (oldStatus.equals(Status.CLOSED)) {

                items.add(Item.builder().openedDate().oldValue(openDate.pop())
                        .newValue(openDate.push(timestamp)).build());

                items.add(Item.builder().closedDate().oldValue(closeDate.pop()).newValue(closeDate.peek())
                        .build());//from   w w  w .j av  a2  s. c o m

            } else if (newStatus.equals(Status.CLOSED)) {

                items.add(Item.builder().closedDate().oldValue(closeDate.peek())
                        .newValue(closeDate.push(timestamp)).build());
            }

            items.add(Item.builder().status().oldValue(oldStatus).newValue(newStatus).build());
        }

    } else if (ChangeLogProperty.PRIORITY.is(field)) {

        Item item = Item.builder().priority().oldValue(fromMap(jiraItem.getFromString(), priorityMapping))
                .newValue(fromMap(jiraItem.getToString(), priorityMapping)).build();
        items.add(item);

    } else if (ChangeLogProperty.SEVERITY.is(field)) {

        Item item = Item.builder().severity().oldValue(fromMap(jiraItem.getFromString(), severityMapping))
                .newValue(fromMap(jiraItem.getToString(), severityMapping)).build();
        items.add(item);

    } else if (ChangeLogProperty.ISSUE_TYPE.is(field)) {

        Item item = Item.builder().type().oldValue(fromMap(jiraItem.getFromString(), typeMapping))
                .newValue(fromMap(jiraItem.getToString(), typeMapping)).build();
        items.add(item);

    } else if (ChangeLogProperty.DUE_DATE.is(field)) {

        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SS").withZoneUTC();

        DateTime fromDate = (jiraItem.getFromString() != null
                ? formatter.parseDateTime(jiraItem.getFromString())
                : null);
        DateTime toDate = (jiraItem.getFromString() != null ? formatter.parseDateTime(jiraItem.getToString())
                : null);

        Item item = Item.builder().dueToDate().oldValue(fromDate).newValue(toDate).build();
        items.add(item);

    } else if (ChangeLogProperty.ESTIMATED_TIME.is(field)) {

        Duration oldDuration = (jiraItem.getFrom() != null
                ? Duration.standardSeconds(Integer.valueOf(jiraItem.getFrom()))
                : null);
        Duration newDuration = (jiraItem.getTo() != null
                ? Duration.standardSeconds(Integer.valueOf(jiraItem.getTo()))
                : null);

        Item item = Item.builder().estimatedTime().oldValue(oldDuration).newValue(newDuration).build();
        items.add(item);

    } else if (ChangeLogProperty.BLOCKERS.is(field)) {

        // Remove null values
        String fromValue = (jiraItem.getFromString() != null ? jiraItem.getFromString() : "");
        String toValue = (jiraItem.getToString() != null ? jiraItem.getToString() : "");

        // Only takes the "is blocked" relation
        String oldLink = (fromValue.contains("This issue is blocked by") ? jiraItem.getFrom() : null);
        String newLink = (toValue.contains("This issue is blocked by") ? jiraItem.getTo() : null);

        if (oldLink != null || newLink != null) {

            Item item = Item.builder().blockedIssues().oldValue(oldLink).newValue(newLink).build();
            items.add(item);
        }

    } else if (ChangeLogProperty.TAGS.is(field)) {

        Set<String> oldTags = Sets.newHashSet(jiraItem.getFromString().split(" "));
        Set<String> newTags = Sets.newHashSet(jiraItem.getToString().split(" "));

        // For these cases where there is no tag
        oldTags.remove("");
        newTags.remove("");

        Set<String> toAdd = Sets.difference(newTags, oldTags);
        Set<String> toDel = Sets.difference(oldTags, newTags);

        for (String tag : toAdd) {
            Item item = Item.builder().tags().newValue(tag).build();
            items.add(item);
        }

        for (String tag : toDel) {
            Item item = Item.builder().tags().oldValue(tag).build();
            items.add(item);
        }

    } else if (ChangeLogProperty.COMPONENT.is(field)) {

        Item item = Item.builder().components().oldValue(jiraItem.getFrom()).newValue(jiraItem.getTo()).build();
        items.add(item);

    } else if (ChangeLogProperty.TITLE.is(field)) {

        Item item = Item.builder().title().oldValue(jiraItem.getFromString()).newValue(jiraItem.getToString())
                .build();
        items.add(item);

    } else if (ChangeLogProperty.VERSION.is(field)) {

        Item item = Item.builder().versions().oldValue(jiraItem.getFrom()).newValue(jiraItem.getTo()).build();
        items.add(item);

    } else if (ChangeLogProperty.ASSIGNEE.is(field)) {

        String oldAssignee = null;
        String newAssignee = null;

        if (jiraItem.getFromString() != null) {
            oldAssignee = selectContributorByName(contributors, jiraItem.getFromString()).getId();
        }

        if (jiraItem.getToString() != null) {
            newAssignee = selectContributorByName(contributors, jiraItem.getToString()).getId();
        }

        Item item = Item.builder().assignee().oldValue(oldAssignee).newValue(newAssignee).build();
        items.add(item);

    } else if (ChangeLogProperty.DESCRIPTION.is(field)) {

        Item item = Item.builder().description().oldValue(jiraItem.getFromString())
                .newValue(jiraItem.getToString()).build();
        items.add(item);

    }

    return items;
}

From source file:org.solovyev.android.messenger.accounts.AccountSyncDataImpl.java

License:Apache License

@Nonnull
static AccountSyncDataImpl newInstance(@Nullable String lastContactsSyncDateString,
        @Nullable String lastChatsSyncDateString, @Nullable String lastUserIconsSyncDateString) {
    final DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.basicDateTime();
    final DateTime lastContactsSyncDate = lastContactsSyncDateString == null ? null
            : dateTimeFormatter.parseDateTime(lastContactsSyncDateString);
    final DateTime lastChatsSyncDate = lastChatsSyncDateString == null ? null
            : dateTimeFormatter.parseDateTime(lastChatsSyncDateString);
    final DateTime lastUserIconsSyncDate = lastUserIconsSyncDateString == null ? null
            : dateTimeFormatter.parseDateTime(lastUserIconsSyncDateString);
    return AccountSyncDataImpl.newInstance(lastContactsSyncDate, lastChatsSyncDate, lastUserIconsSyncDate);
}

From source file:org.solovyev.android.messenger.chats.ChatMapper.java

License:Apache License

@Nonnull
@Override/*from   w  ww  .j  ava  2  s  . c om*/
public Chat convert(@Nonnull Cursor c) {
    final Entity chat = EntityMapper.newInstanceFor(0).convert(c);

    final DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.basicDateTime();
    final String lastMessagesSyncDateString = c.getString(3);
    final DateTime lastMessagesSyncDate = lastMessagesSyncDateString == null ? null
            : dateTimeFormatter.parseDateTime(lastMessagesSyncDateString);

    final List<AProperty> properties = chatDao.readPropertiesById(chat.getEntityId());

    return Chats.newChat(chat, properties, lastMessagesSyncDate);
}

From source file:org.solovyev.android.messenger.messages.MessageMapper.java

License:Apache License

@Nonnull
@Override/*from  w  ww. j a va  2  s .c om*/
public Message convert(@Nonnull Cursor cursor) {
    final Entity entity = EntityMapper.newInstanceFor(0).convert(cursor);

    final MutableMessage message = newMessage(entity);
    message.setChat(newEntityFromEntityId(cursor.getString(3)));
    message.setAuthor(newEntityFromEntityId(cursor.getString(4)));
    if (!cursor.isNull(5)) {
        final String recipientId = cursor.getString(5);
        message.setRecipient(newEntityFromEntityId(recipientId));
    }
    message.setState(MessageState.valueOf(cursor.getString(11)));
    final DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.basicDateTime();

    message.setSendDate(dateTimeFormatter.parseDateTime(cursor.getString(6)));
    final Long sendTime = cursor.getLong(7);
    message.setTitle(cursor.getString(8));
    message.setBody(cursor.getString(9));

    final boolean read = cursor.getInt(10) == 1;
    message.setRead(read);

    message.setProperties(dao.readPropertiesById(entity.getEntityId()));

    return message;
}