Example usage for org.joda.time DateTime parse

List of usage examples for org.joda.time DateTime parse

Introduction

In this page you can find the example usage for org.joda.time DateTime parse.

Prototype

public static DateTime parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a DateTime from the specified string using a formatter.

Usage

From source file:se.softhouse.jargo.addons.DateTimeParser.java

License:Apache License

@Override
public DateTime parse(final String value, Locale locale) throws ArgumentException {
    requireNonNull(locale);/*from   w  w  w  . j  a v a2  s  .  com*/
    try {
        return DateTime.parse(value, formatter);
    } catch (IllegalArgumentException wrongDateFormat) {
        throw ArgumentExceptions.withMessage(wrongDateFormat.getLocalizedMessage());
    }
}

From source file:tw.flink.jcconf2016.streaming.taxipractice.datamodel.TaxiRide.java

License:Apache License

public static TaxiRide fromString(String line) {

    String[] tokens = line.split(",");
    if (tokens.length != 9) {
        throw new RuntimeException("Invalid record: " + line);
    }/*from  w ww  .ja va2 s .com*/

    TaxiRide ride = new TaxiRide();

    try {
        ride.rideId = Long.parseLong(tokens[0]);

        switch (tokens[1]) {
        case "START":
            ride.isStart = true;
            ride.startTime = DateTime.parse(tokens[2], timeFormatter);
            ride.endTime = DateTime.parse(tokens[3], timeFormatter);
            break;
        case "END":
            ride.isStart = false;
            ride.endTime = DateTime.parse(tokens[2], timeFormatter);
            ride.startTime = DateTime.parse(tokens[3], timeFormatter);
            break;
        default:
            throw new RuntimeException("Invalid record: " + line);
        }

        ride.startLon = tokens[4].length() > 0 ? Float.parseFloat(tokens[4]) : 0.0f;
        ride.startLat = tokens[5].length() > 0 ? Float.parseFloat(tokens[5]) : 0.0f;
        ride.endLon = tokens[6].length() > 0 ? Float.parseFloat(tokens[6]) : 0.0f;
        ride.endLat = tokens[7].length() > 0 ? Float.parseFloat(tokens[7]) : 0.0f;
        ride.passengerCnt = Short.parseShort(tokens[8]);

    } catch (NumberFormatException nfe) {
        throw new RuntimeException("Invalid record: " + line, nfe);
    }

    return ride;
}

From source file:uk.ac.dundee.team7.eg_website.Servlet.EditEvent.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w w .  j  ava 2  s  .  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EventModel cm = new EventModel();
    ContentStore cs = new ContentStore();
    EventStore ns = new EventStore();

    String contentTitle = request.getParameter("editContentTitle");
    String contentPath = request.getParameter("editContentPath");
    contentPath = "/Event/" + contentPath;
    String contentSummary = request.getParameter("editContentSummary");
    String content = request.getParameter("editContent");
    String contentID = request.getParameter("contentID");
    String imagePath = request.getParameter("editEventImage");
    String evenPointType = request.getParameter("editPointType");
    String eventID = request.getParameter("editEventID");
    String eventValue = request.getParameter("editEventValue");

    String StartTime1 = request.getParameter("daterange");

    System.out.println(StartTime1);
    String StartTime2 = request.getParameter("timepicker");
    String StartTime3 = request.getParameter("timepicker1");

    System.out.println(StartTime2);
    String finalStarTime = StartTime1 + " " + StartTime2 + ":00";

    System.out.println(finalStarTime);
    DateTime date = DateTime.parse(finalStarTime, DateTimeFormat.forPattern("MM/dd/YYYY HH:mm:ss"));
    String finalEndTime = StartTime1 + " " + StartTime3 + ":00";
    DateTime date1 = DateTime.parse(finalEndTime, DateTimeFormat.forPattern("MM/dd/YYYY HH:mm:ss"));

    int tempEventID = Integer.parseInt(eventID);
    int tempEventValue = Integer.parseInt(eventValue);

    int tempContID = Integer.parseInt(contentID);

    cs.setContent(content);
    cs.setContentID(tempContID);
    cs.setContentPath(contentPath);
    cs.setContentSummary(contentSummary);
    cs.setContentTitle(contentTitle);
    ns.setEventImage(imagePath);
    ns.setEventStartTime(date);
    ns.setEventEndTime(date1);

    ns.setEventPointType(evenPointType);
    ns.setEventID(tempEventID);
    ns.setEventValue(tempEventValue);

    ns.setContent(cs);
    try {
        cm.updateEvent(ns);
    } catch (SQLException ex) {
        Logger.getLogger(EditContent.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(EditNews.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(EditNews.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(EditNews.class.getName()).log(Level.SEVERE, null, ex);
    }

    RequestDispatcher view = request.getRequestDispatcher("/Admin/EventOptions");
    view.include(request, response);
}

From source file:uk.ac.dundee.team7.eg_website.Servlet.EditNews.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww w. j  a v a 2  s  . co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    NewsModel cm = new NewsModel();
    ContentStore cs = new ContentStore();
    NewsStore ns = new NewsStore();
    String contentTitle = request.getParameter("editContentTitle");
    String contentPath = request.getParameter("editContentPath");
    contentPath = "/News/" + contentPath;
    String contentSummary = request.getParameter("editContentSummary");
    String content = request.getParameter("editContent");
    String contentID = request.getParameter("contentID");
    String imagePath = request.getParameter("editImagePath");
    String StartTime1 = request.getParameter("daterange");
    String StartTime2 = request.getParameter("timepicker");

    String finalStarTime = StartTime1 + " " + StartTime2 + ":00";

    System.out.println(finalStarTime);
    DateTime date = DateTime.parse(finalStarTime, DateTimeFormat.forPattern("MM/dd/YYYY HH:mm:ss"));

    int tempContID = Integer.parseInt(contentID);

    contentPath = "/News/" + contentPath;

    cs.setContent(content);
    cs.setContentID(tempContID);
    cs.setContentPath(contentPath);
    cs.setContentSummary(contentSummary);
    cs.setContentTitle(contentTitle);
    ns.setNewsImage(imagePath);
    ns.setDisplayTime(date);
    ns.setContent(cs);
    try {
        cm.updateContent(ns);
    } catch (SQLException ex) {
        Logger.getLogger(EditContent.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(EditNews.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(EditNews.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(EditNews.class.getName()).log(Level.SEVERE, null, ex);
    }

    RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/admin/editNews.jsp");
}

From source file:uniko.west.topology.bolts.DiscussionTreeBolt.java

/**
 * searches for locations in the message and computes related locations
 *
 * @param input/*w  w  w. j  ava 2s .  c  om*/
 *            standard Storm tuple input object (passed within Storm
 *            topology itself, not be a user)
 */
@Override
public void execute(Tuple input) {
    // Retrieve hash map tuple object from Tuple input at index 0, index 1
    // will be message delivery tag (not used here)
    Map<Object, Object> inputMap = (HashMap<Object, Object>) input.getValue(0);
    // Get JSON object from the HashMap from the Collections.singletonList
    Map<Object, Object> message = (Map<Object, Object>) inputMap.get("message");

    // Acknowledge the collector that we actually received the input
    this.collector.ack(input);

    if (!message.containsKey("created_at")) {
        return; // skip delete messages
    }
    // Print received message
    // this.logger.info("Received message: " + message.toJSONString());

    String timeStamp = (String) message.get("created_at");
    DateTime timestamp = DateTime.parse(timeStamp,
            DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy").withLocale(Locale.US));

    if (this.bufferStartTime == null) {
        this.bufferStartTime = timestamp;
        this.deadline = this.bufferStartTime.plusMinutes(this.intervalInMinutes);
    }

    String authorId = (String) ((Map<Object, Object>) message.get("user")).get("id_str");
    String authorScreenName = (String) ((Map<Object, Object>) message.get("user")).get("screen_name");
    String text = (String) message.get("text");
    String tweetId = (String) message.get("id_str");
    boolean retweet = false;

    String ancestorTweetId = (String) message.get("in_reply_to_status_id_str");
    String ancestorAuthorId = (String) message.get("in_reply_to_user_id_str");
    String ancestorAutorScreenName = (String) message.get("in_reply_to_screen_name");

    Map<Object, Object> retweeted_status = (Map<Object, Object>) message.get("retweeted_status");
    if (retweeted_status != null) {
        retweet = true;
        ancestorTweetId = (String) ((Map<Object, Object>) message.get("retweeted_status")).get("id_str");
    }

    Tweet tweet = new Tweet(authorId, authorScreenName, tweetId, timestamp, text, ancestorTweetId, true,
            retweet);

    if (ancestorTweetId != null) {
        if (this.rootTweetsMap.containsKey(tweet.getIn_reply_to())) {
            this.rootTweetsMap.get(tweet.getIn_reply_to()).getReplies().add(tweet);
        } else if (this.childrenTweetsMap.containsKey(tweet.getIn_reply_to())) {
            this.childrenTweetsMap.get(tweet.getIn_reply_to()).getReplies().add(tweet);
        } else {
            // tweet is a reply or retweet but its ancestor was'nt observed
            // by this bolt, therefore its ancestor is treated as a dummy
            // entry
            Tweet dummyTweet = new Tweet(ancestorAuthorId, ancestorAutorScreenName, ancestorTweetId, null, null,
                    null, false, false);
            dummyTweet.getReplies().add(tweet);
            this.rootTweetsMap.put(ancestorTweetId, dummyTweet);
        }
        this.childrenTweetsMap.put(tweetId, tweet);
    } else {
        // tweet is no reply or retweet
        this.rootTweetsMap.put(tweetId, tweet);
    }

    if (timestamp.isAfter(this.deadline) || timestamp.isEqual(this.deadline)) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonResultString;
            HashMap<String, Object> jsonResult = new HashMap<>();
            jsonResult.put("start", this.bufferStartTime.toString());
            jsonResult.put("end", timestamp.toString());
            jsonResult.put("result", this.rootTweetsMap.values());
            jsonResultString = mapper.writeValueAsString(jsonResult);
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.INFO,
                    "Deadline expired, Buffer size : " + this.rootTweetsMap.size());
            this.collector.emit(new Values(jsonResultString));
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            mapper.writeValue(
                    new File("/home/martin/test/discussionTreeBolt/discussionTree-" + this.bufferStartTime),
                    jsonResult);
            this.bufferStartTime = null;
            this.rootTweetsMap = new LinkedHashMap<>();
            this.childrenTweetsMap = new HashMap<>();
        } catch (JsonProcessingException ex) {
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:uniko.west.topology.bolts.InteractionGraphBolt.java

/**
 * searches for locations in the message and computes related locations
 *
 * @param input standard Storm tuple input object (passed within Storm
 * topology itself, not be a user)/*w w  w. j a  va 2 s .  c  o m*/
 */
@Override
public void execute(Tuple input) {
    // Retrieve hash map tuple object from Tuple input at index 0, index 1 will be message delivery tag (not used here)
    Map<Object, Object> inputMap = (HashMap<Object, Object>) input.getValue(0);
    // Get JSON object from the HashMap from the Collections.singletonList
    Map<Object, Object> message = (Map<Object, Object>) inputMap.get("message");

    // Acknowledge the collector that we actually received the input
    collector.ack(input);

    if (!message.containsKey("created_at")) {
        return; // skip delete messages
    }

    DateTime timestamp = DateTime.parse((String) message.get("created_at"),
            DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy").withLocale(Locale.US));

    if (bufferStartTime == null) {
        bufferStartTime = timestamp;
        deadline = bufferStartTime.plusMinutes(intervalInMinutes);
    }

    String authorId = (String) ((Map<Object, Object>) message.get("user")).get("id_str");

    if (!interactionGraph.containsKey(authorId)) {
        interactionGraph.put(authorId, new HashMap<String, ArrayList<Interaction>>());
    }
    HashMap<String, ArrayList<Interaction>> authorActions = interactionGraph.get(authorId);

    countReplies(message, authorActions);
    countMentions(message, authorActions);
    countRetweets(message, authorActions);

    if (timestamp.isAfter(deadline) || timestamp.isEqual(deadline)) {
        deadline.plusMinutes(intervalInMinutes);
        ObjectMapper mapper = new ObjectMapper();
        String jsonResult;
        try {
            Map<String, Object> jsonResultObject = new HashMap();
            jsonResultObject.put("start", bufferStartTime.toString());
            jsonResultObject.put("end", timestamp.toString());
            jsonResultObject.put("flat_graph", flattenGraph(interactionGraph));
            jsonResultObject.put("verbose_graph", interactionGraph);
            jsonResult = mapper.writeValueAsString(jsonResultObject);
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.INFO,
                    "Deadline expired, Buffer size : " + interactionGraph.size());
            this.collector.emit(new Values(jsonResult));
            //                mapper.enable(SerializationFeature.INDENT_OUTPUT);
            //                mapper.writeValue(new File("/home/nico/storm_topology_dir/logs/interactionGraph-"+bufferStartTime), jsonResultObject);
            this.interactionGraph = new HashMap<>();
            this.bufferStartTime = null;
        } catch (JsonProcessingException ex) {
            Logger.getLogger(InteractionGraphBolt.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //            catch (IOException ex) {
        //                Logger.getLogger(InteractionGraphBolt.class.getName()).log(Level.SEVERE, null, ex);
        //            }
    }
}

From source file:us.forkloop.trackor.trackable.UPSTrack.java

@Override
public List<Event> parse(final String response) {
    List<Event> events = new ArrayList<Event>();
    Log.d(TAG, response);/*w w  w . j  ava2s .  c om*/
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document dom = builder.parse(new InputSource(new StringReader(response)));
        NodeList status = dom.getElementsByTagName("ResponseStatusCode");
        if (status.getLength() > 0 && "1".equals(status.item(0).getTextContent())) {
            NodeList activities = dom.getElementsByTagName("Activity");
            for (int n = 0; n < activities.getLength(); n++) {
                try {
                    Element activity = (Element) activities.item(n);
                    StringBuilder location = new StringBuilder();
                    NodeList city = activity.getElementsByTagName("City");
                    if (city.getLength() > 0) {
                        location.append(city.item(0).getTextContent());
                    }
                    NodeList state = activity.getElementsByTagName("StateProvinceCode");
                    if (state.getLength() > 0) {
                        location.append(" ").append(state.item(0).getTextContent());
                    }
                    String zipcode = "";
                    NodeList postalCode = activity.getElementsByTagName("PostalCode");
                    if (postalCode.getLength() > 0) {
                        zipcode = postalCode.item(0).getTextContent();
                    }
                    String info = "";
                    NodeList stausDescription = activity.getElementsByTagName("Status");
                    if (stausDescription.getLength() > 0) {
                        NodeList description = ((Element) stausDescription.item(0))
                                .getElementsByTagName("Description");
                        if (description.getLength() > 0) {
                            info = description.item(0).getTextContent();
                            if (DELIVERED.equals(info)) {
                                isDelivered = true;
                            }
                        }
                    }
                    StringBuilder datetime = new StringBuilder();
                    NodeList date = activity.getElementsByTagName("Date");
                    if (date.getLength() > 0) {
                        datetime.append(date.item(0).getTextContent());
                    }
                    NodeList time = activity.getElementsByTagName("Time");
                    if (time.getLength() > 0) {
                        datetime.append(time.item(0).getTextContent());
                    }
                    Event event = new Event(DateTime.parse(datetime.toString(), FORMATTER), location.toString(),
                            zipcode, info);
                    Log.d(TAG, event.toString());
                    events.add(event);
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
    } catch (Exception e) {
    }
    return events;
}