Example usage for org.joda.time Interval Interval

List of usage examples for org.joda.time Interval Interval

Introduction

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

Prototype

public Interval(Object interval, Chronology chronology) 

Source Link

Document

Constructs a time interval by converting or copying from another object, overriding the chronology.

Usage

From source file:com.quant.TimeSeries.java

License:Open Source License

/**
 * Returns a new time series which is a view of a subset of the current series.
 * <p>//from   w w  w .j  a v  a 2s.  c o  m
 * The new series has begin and end indexes which correspond to the bounds of the sub-set into the full series.<br>
 * The tick of the series are shared between the original time series and the returned one (i.e. no copy).
 * @param beginIndex the begin index (inclusive) of the time series
 * @param duration the duration of the time series
 * @return a constrained {@link TimeSeries time series} which is a sub-set of the current series
 */
public TimeSeries subseries(int beginIndex, Period duration) {

    // Calculating the sub-series interval
    DateTime beginInterval = getTick(beginIndex).getEndTime();
    DateTime endInterval = beginInterval.plus(duration);
    Interval subseriesInterval = new Interval(beginInterval, endInterval);

    // Checking ticks belonging to the sub-series (starting at the provided index)
    int subseriesNbTicks = 0;
    for (int i = beginIndex; i <= endIndex; i++) {
        // For each tick...
        DateTime tickTime = getTick(i).getEndTime();
        if (!subseriesInterval.contains(tickTime)) {
            // Tick out of the interval
            break;
        }
        // Tick in the interval
        // --> Incrementing the number of ticks in the subseries
        subseriesNbTicks++;
    }

    return subseries(beginIndex, beginIndex + subseriesNbTicks - 1);
}

From source file:com.quant.TimeSeries.java

License:Open Source License

/**
 * Builds a list of split indexes from splitDuration.
 * @param splitDuration the duration between 2 splits
 * @return a list of begin indexes after split
 *///from   ww  w.  j a  v a  2s  . co  m
private List<Integer> getSplitBeginIndexes(Period splitDuration) {
    ArrayList<Integer> beginIndexes = new ArrayList<Integer>();

    // Adding the first begin index
    beginIndexes.add(beginIndex);

    // Building the first interval before next split
    DateTime beginInterval = getTick(beginIndex).getEndTime();
    DateTime endInterval = beginInterval.plus(splitDuration);
    Interval splitInterval = new Interval(beginInterval, endInterval);

    for (int i = beginIndex; i <= endIndex; i++) {
        // For each tick...
        DateTime tickTime = getTick(i).getEndTime();
        if (!splitInterval.contains(tickTime)) {
            // Tick out of the interval
            if (!endInterval.isAfter(tickTime)) {
                // Tick after the interval
                // --> Adding a new begin index
                beginIndexes.add(i);
            }

            // Building the new interval before next split
            beginInterval = endInterval.isBefore(tickTime) ? tickTime : endInterval;
            endInterval = beginInterval.plus(splitDuration);
            splitInterval = new Interval(beginInterval, endInterval);
        }
    }
    return beginIndexes;
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.server.SecurityHeader.java

License:Open Source License

private boolean isTimestampValid() {
    DateTimeFormatter forPattern = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    try {/*from ww  w .  j a v a2s  .  c o  m*/
        DateTime parseDateTime = forPattern.parseDateTime(getTimestamp());
        Interval interval = new Interval(new DateTime().minusMinutes(5), new DateTime().plusMinutes(5));
        return interval.contains(parseDateTime);
    } catch (Throwable t) {
        t.printStackTrace();
        return false;
    }
}

From source file:com.rhythm.louie.server.MemoryAlertManager.java

License:Apache License

protected static void generateReport(String message) {

    List<RequestPB> requests = ProtoProcessor.getActiveRequests();
    StringBuilder report = new StringBuilder();
    report.append("Memory Usage Threshold has been surpassed.\n");
    report.append("Note that due to the typical speed of execution, ");
    report.append("some stack traces may not represent the activity of the listed Request.\n");
    report.append("The notification included this message: ").append(message).append("\n");
    report.append("Currently running requests:\n");
    report.append("\n-------------------------\n");
    for (RequestPB req : requests) {
        report.append("ID:         ").append(req.getId()).append("\n");
        report.append("service:    ").append(req.getService()).append("\n");
        report.append("method:     ").append(req.getMethod()).append("\n");
        report.append("thread ID:  ").append(req.getThreadId()).append("\n");
        DateTime start = new DateTime(req.getStartTime());
        report.append("Start time: ").append(dtFmt.print(start)).append("\n");
        report.append("Duration:   ");
        report.append(timeFmt.print(new Interval(start, new Instant()).toPeriod())).append("\n");
        report.append("\nStack trace:\n");
        report.append(ThreadInspector.INSTANCE.dumpStack(req.getThreadId(), 10));
        report.append("\n-------------------------\n");
        report.append("\n");
    }//from   ww  w .  j  av  a 2s  . c om
    String email = AlertProperties.getProperties(AlertProperties.MEMORY).getEmail();
    Server local = Server.getLocal();
    String subject = local.getHostName() + " (" + local.getIp() + "/" + local.getGateway() + ") ["
            + local.getName() + "] Memory usage threshold exceeded";
    try {
        EmailService.getInstance().sendMail(email, email, subject, report.toString());
    } catch (Exception ex) {
        LoggerFactory.getLogger(MemoryAlertManager.class).warn("Failed to send Memory Usage email: {}",
                ex.toString());
    }
    LoggerFactory.getLogger(MemoryAlertManager.class).error(report.toString());
}

From source file:com.sheepdog.mashmesh.models.VolunteerProfile.java

License:Apache License

private List<Interval> getAvailableIntervals(DateTime aroundDateTime) {
    List<Interval> intervals = new ArrayList<Interval>();
    Map<Integer, DateTime> adjacentDays = new HashMap<Integer, DateTime>(3);

    // Construct a map from days of the week to DateTimes representing adjacent days.
    for (int i = -1; i <= 1; i++) {
        DateTime dateTime = aroundDateTime.plusDays(i);
        int day = dateTime.getDayOfWeek();
        adjacentDays.put(day, dateTime);
    }/* w  w  w  .  ja  v a 2s.com*/

    // Construct Intervals from time periods in adjacent days.
    for (AvailableTimePeriod availableTimePeriod : availableTimePeriods) {
        if (adjacentDays.containsKey(availableTimePeriod.getDay())) {
            LocalDate date = adjacentDays.get(availableTimePeriod.getDay()).toLocalDate();
            DateTime start = date.toDateTime(availableTimePeriod.getStartTime(), aroundDateTime.getZone());
            DateTime end = date.toDateTime(availableTimePeriod.getEndTime(), aroundDateTime.getZone());

            // Allow 00:00 - 00:00 to express 00:00 - 24:00 as we can't serialize a
            //  LocalTime representing 24:00.
            if (end.compareTo(start) <= 0) {
                end = end.plusDays(1);
            }

            intervals.add(new Interval(start, end));
        }
    }

    // Sort the Intervals so that adjacent time periods abut. Assumes that intervals don't overlap.
    Collections.sort(intervals, new Comparator<Interval>() {
        @Override
        public int compare(Interval i1, Interval i2) {
            return new Long(i1.getStartMillis()).compareTo(i2.getStartMillis());
        }
    });

    // Merge abutting intervals together
    List<Interval> mergedIntervals = new ArrayList<Interval>();
    Interval lastInterval = null;

    for (Interval interval : intervals) {
        if (lastInterval != null && lastInterval.abuts(interval)) {
            mergedIntervals.remove(mergedIntervals.size() - 1);
            interval = lastInterval.withEnd(interval.getEnd());
        }

        lastInterval = interval;
        mergedIntervals.add(interval);
    }

    return mergedIntervals;
}

From source file:com.sheepdog.mashmesh.models.VolunteerProfile.java

License:Apache License

public boolean isTimeslotAvailable(DateTime startDateTime, DateTime endDateTime) {
    // Assuming that the total interval is less than a day long
    List<Interval> availableIntervals = getAvailableIntervals(startDateTime);
    Interval timeslot = new Interval(startDateTime, endDateTime);

    for (Interval availableInterval : availableIntervals) {
        if (availableInterval.contains(timeslot)) {
            return true;
        }//from  ww w.  j  a  va  2 s  . c o m
    }

    return false;
}

From source file:com.sheepdog.mashmesh.models.VolunteerProfile.java

License:Apache License

public boolean isTimeslotOccupied(DateTime startDateTime, DateTime endDateTime) {
    Interval requestedInterval = new Interval(startDateTime, endDateTime);

    for (AppointmentPeriod appointmentTime : appointmentTimes) {
        Interval appointmentInterval = new Interval(appointmentTime.startTimeMillis,
                appointmentTime.endTimeMillis);

        if (appointmentInterval.overlaps(requestedInterval)) {
            return true;
        }//from   w ww .j ava2s . c  o m
    }

    return false;
}

From source file:com.sloca.controller.NextPlaceServlet.java

/**
 * Processes requests for both HTTP/*from  ww w. j a va2  s.  c  o m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        String semPlace = request.getParameter("sem");
        String date_s = request.getParameter("date");
        String time_s = request.getParameter("time");
        String k = request.getParameter("kvalue");

        request.setAttribute("semanticplace", semPlace);
        request.setAttribute("date", date_s);
        request.setAttribute("time", time_s);
        request.setAttribute("kvalue", k);

        String year = date_s.substring(date_s.lastIndexOf("-") + 1);
        String month = date_s.substring(date_s.indexOf("-") + 1, date_s.lastIndexOf("-"));
        String day = date_s.substring(0, date_s.indexOf("-"));
        date_s = year + "-" + month + "-" + day;

        Timestamp ts = Timestamp.valueOf(date_s + " " + time_s);
        Timestamp tsBefore = getTimeBefore(ts);
        Timestamp tsAfter = getTimeAfter(ts);

        int totalUsers = 0;
        int nextPlaceUsers = 0;

        conn = ConnectionFactory.getConnection();

        String sql = "select temp.mac as mac2 from location t inner join "
                + "(select mac_address as mac, max(time_stamp) as time from location t "
                + "where time_stamp between '" + tsBefore + "' and '" + ts + "' "
                + "group by mac_address) as temp " + "on t.mac_address = temp.mac and t.time_stamp = temp.time "
                + "inner join location_lookup l on l.location_id = t.location_id where semanticplace = '"
                + semPlace + "'";
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getString(1));
            totalUsers++;
        }

        pstmt = conn.prepareStatement(
                "select l2.mac_address as mac, u2.semanticplace, l2.time_stamp from location l2 "
                        + "inner join ((" + sql + ") as temp2), location_lookup u2 "
                        + "where l2.mac_address = temp2.mac2 and u2.location_id = l2.location_id and l2.time_stamp between '"
                        + ts + "' and '" + tsAfter + "' " + "group by l2.mac_address, l2.time_stamp "
                        + "order by l2.mac_address, l2.time_stamp DESC");
        rs = pstmt.executeQuery();

        String mac = "";
        String semanticPlace = "";
        DateTime before = null;
        DateTime after = null;
        DateTime temp = null;
        DateTime last = new DateTime(tsAfter.getTime());
        boolean alrCount = false;
        HashMap<String, Integer> placeTime = new HashMap<String, Integer>();

        while (rs.next()) {
            if (mac.equals("") && semanticPlace.equals("")) {
                System.out.println("firstTime");
                mac = rs.getString(1);
                semanticPlace = rs.getString(2);
                after = last;
                temp = new DateTime(rs.getTimestamp(3).getTime());
            } else if (!mac.equals(rs.getString(1))) {
                System.out.println("changeName");
                before = temp;
                Interval in = new Interval(before, after);
                if (Seconds.secondsIn(in).getSeconds() >= 300 && !alrCount) {
                    Integer timeCount = placeTime.get(semanticPlace);
                    if (timeCount != null) {
                        placeTime.put(semanticPlace, (timeCount + 1));
                    } else {
                        placeTime.put(semanticPlace, 1);
                    }
                    nextPlaceUsers++;
                }
                alrCount = false;
                mac = rs.getString(1);
                semanticPlace = rs.getString(2);
                after = last;
                before = null;
                temp = new DateTime(rs.getTimestamp(3).getTime());
            } else if (!semanticPlace.equals(rs.getString(2))) {
                System.out.println("same user changePlace");
                before = temp;
                Interval in = new Interval(before, after);
                if (Seconds.secondsIn(in).getSeconds() >= 300 && !alrCount) {
                    Integer timeCount = placeTime.get(semanticPlace);
                    if (timeCount != null) {
                        placeTime.put(semanticPlace, (timeCount + 1));
                    } else {
                        placeTime.put(semanticPlace, 1);
                    }
                    nextPlaceUsers++;
                    alrCount = true;
                }
                semanticPlace = rs.getString(2);
                after = before;
                before = null;
                temp = new DateTime(rs.getTimestamp(3).getTime());
            } else {
                System.out.println("nothing changes!");
                temp = new DateTime(rs.getTimestamp(3).getTime());
                continue;
            }
        }
        before = temp;
        Interval in = new Interval(before, after);
        if (Seconds.secondsIn(in).getSeconds() >= 300 && !alrCount) {
            Integer timeCount = placeTime.get(semanticPlace);
            if (timeCount != null) {
                placeTime.put(semanticPlace, (timeCount + 1));
            } else {
                placeTime.put(semanticPlace, 1);
            }
            nextPlaceUsers++;
        }
        System.out.println(placeTime.size());

        SortedSet<Map.Entry<String, Integer>> newSet = entriesSortedByValues(placeTime);

        request.setAttribute("totalUsers", totalUsers);
        request.setAttribute("nextPlaceUsers", nextPlaceUsers);
        request.setAttribute("set", newSet);
        RequestDispatcher rd = request.getRequestDispatcher("top_k_next_places.jsp");
        rd.forward(request, response);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        request.setAttribute("error", "<b>Error!</b><br>Please enter a valid datetime format.");
        RequestDispatcher rd = request.getRequestDispatcher("top_k_next_places.jsp");
        rd.forward(request, response);
    } catch (Exception e) {
        request.setAttribute("error", "<b>Oops!</b><br> Something went wrong! Please check your input fields!");
        RequestDispatcher rd = request.getRequestDispatcher("top_k_next_places.jsp");
        rd.forward(request, response);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(NextPlaceServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.smoketurner.pipeline.application.aws.AmazonSNSNotification.java

License:Apache License

@JsonIgnore
public Duration getDelayDuration() {
    final Interval interval = new Interval(timestamp, DateTime.now(DateTimeZone.UTC));
    return interval.toDuration();
}

From source file:com.sos.jobnet.creator.FrequencyChecker.java

License:Apache License

public void processJobNet(JobNetPlanDBItem bootstrapOrder) {

    String uuid = bootstrapOrder.getUuid();
    logger.info(msg.getMsg(JOBNETCH_I_0001, uuid)); // processing jobnet with id %1$s.
    logger.debug(msg.getMsg(JOBNETCH_D_0002, bootstrapOrder.getNodeId())); // bootstrap order has node id %2$s.

    Date d = bootstrapOrder.getPlannedStartTime();
    if (d == null) {
        String msgText = msg.getMsg(JOBNETCH_E_0001); // bootstrap order has no single_start
        logger.error(msgText);/*  ww  w.j  a  v a 2s.co  m*/
        throw new JobNetException(msgText);
    }
    DateTime from = new DateTime(d);
    from = from.minusMillis(from.getMillisOfDay());
    DateTime to = from.plusDays(1);
    Interval baseInterval = new Interval(from, to);
    logger.debug(msg.getMsg(JOBNETCH_D_0001, fmtDateTime.print(from), fmtDateTime.print(to))); // searching for start times of job net nodes from %1$s to %2$s
    LocalDate forDay = new LocalDate(from);

    //      logger.debug(msg.getMsg(JOBNETCH_D_0003,fmtDate.print(baseInterval.getStart()))); // searching for starts at %2$s.
    List<JobNetPlanDBItem> jobnetOrders = getJobnet(uuid);
    if (jobnetOrders == null) {
        String msgText = msg.getMsg(JOBNETCH_E_0002, uuid);
        logger.error(msgText); // no jobnet found for UUID %1$s.
        throw new JobSchedulerException(msgText);
    }

    logger.debug(msg.getMsg(JOBNETCH_D_0004, jobnetOrders.size())); // the jobnet contains %1$s nodes.
    factory.setUseDefaultPeriod(true); // allows the use of runtime elements without or with incomplete periods

    planDbLayer.beginTransaction();
    for (JobNetPlanDBItem currentOrder : jobnetOrders) {
        JobNetNodeDBItem currentNode = getJobNetNode(currentOrder.getNodeId());
        if (!currentOrder.getBootstrap()) { // the properties for the bootstrap order has to be set in JobNetPlanCreator
            if (currentOrder.getIsRunnerSkipped()) {
                logger.info(msg.getMsg(JOBNETCH_I_0002, currentNode.getNode(), currentOrder.getNodeId())); // order %1$s (node id %2$s) is already skipped.
            } else {
                JSObjOrder jsOrder = getJSObjOrder(currentOrder.getOrderXml());
                JSObjRunTime runTime = jsOrder.getJSObjRunTime();
                if (runTime.hasSubsequentRunTimes()) {
                    LocalDate startDay = getNextStartDayInIntervalOrNull(runTime, baseInterval);
                    if (startDay == null) {
                        currentOrder.setIsRunnerSkipped(true);
                        // order %1$s (node id %2$s) has no start time for %3$s and will be skipped.
                        logger.info(msg.getMsg(JOBNETCH_I_0003, currentNode.getNode(), currentOrder.getNodeId(),
                                fmtDate.print(forDay)));
                    } else {
                        // order %1$s (node id %2$s) has a start time for %3$s and will NOT skipped.
                        logger.debug(msg.getMsg(JOBNETCH_I_0005, currentNode.getNode(),
                                currentOrder.getNodeId(), fmtDate.print(forDay)));
                        if (currentOrder.getIsRunnerOnDemand()) {
                            // order %1$s (node id %2$s) has to be started on demand.
                            logger.info(msg.getMsg(JOBNETCH_I_0006, currentNode.getNode(),
                                    currentOrder.getNodeId()));
                            currentOrder.setIsRunnerOnDemand(true);
                        }
                    }
                } else {
                    if (currentOrder.getIsRunnerOnDemand()) {
                        // order %1$s (node id %2$s) has no start time and will be NOT skipped.
                        currentOrder.setIsRunnerOnDemand(true);
                        logger.info(
                                msg.getMsg(JOBNETCH_I_0004, currentNode.getNode(), currentOrder.getNodeId()));
                    } else {
                        logger.debug(
                                "nothing to do - order has neither a start_time nor the parameter on_demand.");
                    }
                }
                logger.debug(currentOrder.getOrderXml().replace("\n", ""));
                planDbLayer.update(currentOrder);

            }
        }
        logRecord(currentNode, currentOrder);
    }
    planDbLayer.commit();
}