Example usage for org.joda.time MutableDateTime MutableDateTime

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

Introduction

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

Prototype

public MutableDateTime(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:controllers.api.SearchApiController.java

License:Open Source License

/**
 * Create a list with histogram results that would be serialized to JSON like this
 * <p/>/*from  ww  w  .j a  v  a 2s  .co  m*/
 * [{ x: -1893456000, y: 92228531 }, { x: -1577923200, y: 106021568 }]
 */
protected List<Map<String, Long>> formatHistogramResults(DateHistogramResult histogram, int maxDataPoints,
        boolean allQuery) {
    final List<Map<String, Long>> points = Lists.newArrayList();
    final Map<String, Long> histogramResults = histogram.getResults();

    DateTime from;
    if (allQuery) {
        String firstTimestamp = histogramResults.entrySet().iterator().next().getKey();
        from = new DateTime(Long.parseLong(firstTimestamp) * 1000, DateTimeZone.UTC);
    } else {
        from = DateTime.parse(histogram.getHistogramBoundaries().getFrom());
    }
    final DateTime to = DateTime.parse(histogram.getHistogramBoundaries().getTo());
    final MutableDateTime currentTime = new MutableDateTime(from);

    final Duration step = estimateIntervalStep(histogram.getInterval());
    final int dataPoints = (int) ((to.getMillis() - from.getMillis()) / step.getMillis());

    // using the absolute value guarantees, that there will always be enough values for the given resolution
    final int factor = (maxDataPoints != -1 && dataPoints > maxDataPoints) ? dataPoints / maxDataPoints : 1;

    int index = 0;
    floorToBeginningOfInterval(histogram.getInterval(), currentTime);
    while (currentTime.isBefore(to) || currentTime.isEqual(to)) {
        if (index % factor == 0) {
            String timestamp = Long.toString(currentTime.getMillis() / 1000);
            Long result = histogramResults.get(timestamp);
            Map<String, Long> point = Maps.newHashMap();
            point.put("x", Long.parseLong(timestamp));
            point.put("y", result != null ? result : 0);
            points.add(point);
        }
        index++;
        nextStep(histogram.getInterval(), currentTime);
    }

    return points;
}

From source file:ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.java

License:Open Source License

private void createSummary(Workbook wb, List<String> metricNames, String metricsDir, long startTime,
        long endTime, SUMMARY_INTERVALS summaryInterval) throws IOException, MetricsGraphException {
    // convert seconds to milliseconds
    startTime = TimeUnit.SECONDS.toMillis(startTime);
    endTime = TimeUnit.SECONDS.toMillis(endTime);
    DateTime reportStart = new DateTime(startTime, DateTimeZone.UTC);
    DateTime reportEnd = new DateTime(endTime, DateTimeZone.UTC);

    Sheet sheet = wb.createSheet();//from   ww  w.j a va  2  s  .  co  m
    wb.setSheetName(0,
            reportStart.toString(SUMMARY_TIMESTAMP) + " to " + reportEnd.toString(SUMMARY_TIMESTAMP));
    Row headingRow = sheet.createRow(0);

    int columnMax = 1;
    for (String metricName : metricNames) {
        MutableDateTime chunkStart = new MutableDateTime(reportStart);
        MutableDateTime chunkEnd = new MutableDateTime(chunkStart);
        Row row = sheet.createRow(metricNames.indexOf(metricName) + 1);
        int columnCounter = 1;
        Boolean isSum = null;

        while (reportEnd.compareTo(chunkEnd) > 0 && columnCounter < EXCEL_MAX_COLUMNS) {
            increment(chunkEnd, summaryInterval);
            if (chunkEnd.isAfter(reportEnd)) {
                chunkEnd.setMillis(reportEnd);
            }

            // offset range by one millisecond so rrd will calculate granularity correctly
            chunkEnd.addMillis(-1);
            MetricData metricData = getMetricData(getRrdFilename(metricsDir, metricName),
                    TimeUnit.MILLISECONDS.toSeconds(chunkStart.getMillis()),
                    TimeUnit.MILLISECONDS.toSeconds(chunkEnd.getMillis()));
            isSum = metricData.hasTotalCount();
            chunkEnd.addMillis(1);

            if (headingRow.getCell(columnCounter) == null) {
                Cell headingRowCell = headingRow.createCell(columnCounter);
                headingRowCell.getCellStyle().setWrapText(true);
                headingRowCell.setCellValue(getTimestamp(chunkStart, chunkEnd, columnCounter, summaryInterval));
            }

            Cell sumOrAvg = row.createCell(columnCounter);
            if (isSum) {
                sumOrAvg.setCellValue((double) metricData.getTotalCount());
            } else {
                sumOrAvg.setCellValue(cumulativeRunningAverage(metricData.getValues()));
            }

            chunkStart.setMillis(chunkEnd);
            columnCounter++;
        }
        columnMax = columnCounter;

        if (isSum != null) {
            row.createCell(0).setCellValue(convertCamelCase(metricName) + " (" + (isSum ? "sum" : "avg") + ")");
        }
    }
    for (int i = 0; i < columnMax; i++) {
        sheet.autoSizeColumn(i);
    }
}

From source file:de.pro.dbw.util.impl.DateConverter.java

License:Open Source License

public String convertLongToDateTime(Long millis, String pattern) {
    final MutableDateTime mdt = new MutableDateTime(millis);
    return mdt.toString(pattern);
}

From source file:de.pro.dbw.util.impl.DateConverter.java

License:Open Source License

public Boolean isAfter(int days, Long time) {
    final MutableDateTime mdtNow = MutableDateTime.now();
    mdtNow.addDays(days);//from  w w  w  .ja  va  2 s  .c  o m

    final MutableDateTime mdtTime = new MutableDateTime(time);
    return mdtTime.isAfter(mdtNow);
}

From source file:de.pro.dbw.util.impl.DateConverter.java

License:Open Source License

public Boolean isBefore(int days, Long time) {
    final MutableDateTime mdtNow = MutableDateTime.now();
    mdtNow.addDays(days);/*from  w ww  .java2s.  co m*/

    final MutableDateTime mdtTime = new MutableDateTime(time);
    return mdtTime.isBefore(mdtNow);
}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.models.data.Commitment.java

License:Open Source License

/**
 * this is primarily used for multiday events
 * /*from w  w  w .ja  v a  2s. c om*/
 * @param givenDay gets the time that this event starts on a given day
 * @return when this event starts
 */
public DateTime getStartTimeOnDay(DateTime givenDay) {
    MutableDateTime mDisplayedDay = new MutableDateTime(givenDay);
    mDisplayedDay.setMillisOfDay(1);
    //if it starts before the beginning of the day then its a multi day event, or all day event
    if (this.getStart().isBefore(mDisplayedDay)) {
        mDisplayedDay.setMillisOfDay(0);
        return (mDisplayedDay.toDateTime());
    } else
        return this.getStart();
}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.models.data.Event.java

License:Open Source License

@Override
public void setTime(DateTime newTime) {
    if (new Interval(new DateTime(this.start), new DateTime(this.end)).contains(newTime)) {
        //this is what stops the events from being dragged to the next day. leaving it in case we might want it later
        //return;
    }// ww  w . j  a va  2s.c  o  m

    Interval i;
    int daysBetween = 0;
    if (new DateTime(this.start).isAfter(newTime)) {
        i = new Interval(newTime, new DateTime(this.start));
        daysBetween = 0 - (int) i.toDuration().getStandardDays();
    } else {
        i = new Interval(new DateTime(this.start), newTime);
        daysBetween = (int) i.toDuration().getStandardDays();
    }

    MutableDateTime newEnd = new MutableDateTime(this.end);
    newEnd.addDays(daysBetween);

    MutableDateTime newStart = new MutableDateTime(this.start);
    newStart.addDays(daysBetween);

    this.end = newEnd.toDate();
    this.start = newStart.toDate();

}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.ui.navigation.MiniMonth.java

License:Open Source License

public MiniMonth(DateTime time, final MiniCalendarHostIface mc, boolean monthOnly) {
    this.setLayout(new GridLayout(7, 7));
    MutableDateTime prevMonth = new MutableDateTime(time);
    prevMonth.setDayOfMonth(1);//from www.  jav  a  2s  .  c  o  m
    prevMonth.addMonths(-1); // What is prevMonth for?
    String[] dayLabel = { "S", "M", "T", "W", "R", "F", "S" };

    MouseListener monthChanger = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }

        @Override
        public void mousePressed(MouseEvent me) {
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            DayLabel d = (DayLabel) (me.getSource());
            if (!(d instanceof DescriptiveDayLabel)) {
                mc.display(d.getMonth());
            }
        }
    };

    MutableDateTime referenceDay = new MutableDateTime(time);
    // reset to the first of the month at midnight, then find Sunday
    referenceDay.setDayOfMonth(1);
    referenceDay.setMillisOfDay(0);
    int first = referenceDay.getDayOfWeek();
    referenceDay.addDays(-first);
    boolean flipFlop = false;

    // add day labels
    for (int i = 0; i < 7; i++) {
        DayLabel day = new DescriptiveDayLabel(dayLabel[i], time);
        day.borderize((i % 7) == 0, i >= 5 * 7, (i % 7) == 6);
        add(day);
        day.addMouseListener(monthChanger);
    }

    // generate days, 6*7 covers all possible months, so we just loop
    // through and add each day
    for (int i = 0; i < (6 * 7); i++) {
        DayLabel day;
        if (monthOnly || MainPanel.getInstance().getView() == ViewSize.Month) {
            if (referenceDay.getDayOfMonth() == 1)
                flipFlop ^= true; // flops the flip flop flappity flip
        } else if (MainPanel.getInstance().getView() == ViewSize.Day)
            flipFlop = referenceDay.getDayOfYear() == time.getDayOfYear()
                    && referenceDay.getYear() == time.getYear();
        else if (MainPanel.getInstance().getView() == ViewSize.Week) {
            if (Months.getWeekStart(time).getMonthOfYear() == 12
                    && Months.getWeekStart(time).getDayOfMonth() >= 26) // Exception case for weeks between years
                flipFlop = time.getMonthOfYear() == 12 ? i >= 35 : i <= 6;
            else
                flipFlop = referenceDay.getDayOfYear() >= Months.getWeekStart(time).getDayOfYear()
                        && referenceDay.getDayOfYear() <= Months.getWeekStart(time).getDayOfYear() + 6;
        }

        if (flipFlop)
            day = new ActiveDayLabel(referenceDay.toDateTime());
        else
            day = new InactiveDayLabel(referenceDay.toDateTime());

        day.borderize((i % 7) == 0, i >= 5 * 7, (i % 7) == 6);
        add(day);
        day.addMouseListener(monthChanger);
        referenceDay.addDays(1); // go to next day
    }
}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.ui.views.day.DayCalendar.java

License:Open Source License

/**
 * Get visible events for the current day view
 * @return returns the list of events to display
 *///from  w  w w  . jav a2 s .  c o m
private List<Displayable> getVisibleDisplayables() {
    // Set up from and to datetime for search
    MutableDateTime f = new MutableDateTime(time);
    f.setMillisOfDay(0);
    DateTime from = f.toDateTime();
    f.addDays(1);
    DateTime to = f.toDateTime();

    // Return list of events to be displayed
    List<Displayable> visibleDisplayables = new ArrayList<Displayable>();
    visibleDisplayables.addAll(EventClient.getInstance().getEvents(from, to));
    visibleDisplayables.addAll(CommitmentClient.getInstance().getCommitments(from, to));

    Collections.sort(visibleDisplayables, new Comparator<Displayable>() {
        public int compare(Displayable d1, Displayable d2) {
            return d1.getStart().getMinuteOfDay() < d2.getStart().getMinuteOfDay() ? -1
                    : d1.getStart().getMinuteOfDay() > d2.getStart().getMinuteOfDay() ? 1 : 0;
        }
    });

    return visibleDisplayables;
}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.ui.views.month.MonthDay.java

License:Open Source License

public MonthDay(DateTime initDay, DayStyle style, final MonthCalendar parent) {
    this.day = initDay;
    this.parent = parent;
    this.style = style;
    Color grayit = Colors.TABLE_GRAY_HEADER, textit = Colors.TABLE_TEXT, bg = Colors.TABLE_BACKGROUND;
    switch (style) {
    case Normal://  w w  w  . j av  a 2  s.  c om
        grayit = Colors.TABLE_GRAY_HEADER;
        textit = Colors.TABLE_GRAY_TEXT;
        break;
    case OutOfMonth:
        grayit = bg;
        break;
    case Today:
        grayit = Colors.TABLE_GRAY_HEADER;
        textit = Colors.TABLE_GRAY_TEXT;
        break;
    default:
        throw new IllegalStateException("DayStyle is not a valid DayStyle!");
    }
    setBackground(bg);
    setForeground(textit);
    borderTop = grayit.equals(bg);
    setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));

    header.setBackground(grayit);
    header.setForeground(textit);
    header.setFont(new java.awt.Font("DejaVu Sans", style == DayStyle.Today ? Font.BOLD : Font.PLAIN, 12));
    header.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    header.setText(Integer.toString(initDay.getDayOfMonth()));
    header.setAutoscrolls(true);
    header.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
    header.setMaximumSize(new java.awt.Dimension(10000, 17));
    header.setOpaque(true);

    if (style == DayStyle.Today) {
        Font font = header.getFont();
        Map attributes = font.getAttributes();
        attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        header.setFont(font.deriveFont(attributes));
    }

    add(header);

    addMouseListener(new MouseListener() {
        @Override
        public void mousePressed(MouseEvent e) {
            parent.dispatchEvent(e);
            MainPanel.getInstance().setSelectedDay(day);
            MainPanel.getInstance().clearSelected();
            parent.setEscaped(false);
        }

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (parent.isEscaped()) {
                MonthDay releasedDay = parent.getMonthDayAtCursor();
                Displayable selected = MainPanel.getInstance().getSelectedEvent();
                if (selected != null) {
                    MutableDateTime newTime = new MutableDateTime(selected.getStart());

                    newTime.setYear(releasedDay.day.getYear());
                    newTime.setDayOfYear(releasedDay.day.getDayOfYear());

                    selected.setTime(newTime.toDateTime());

                    selected.update();
                }
            }
            parent.dispatchEvent(e);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            parent.dispatchEvent(e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            setBackground(Colors.TABLE_BACKGROUND);
            parent.setEscaped(true);

        }
    });

    header.addMouseListener(new MouseListener() {

        @Override
        public void mousePressed(MouseEvent e) {
            MainPanel.getInstance().setSelectedDay(day);
            MainPanel.getInstance().clearSelected();
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            MainPanel.getInstance().miniMove(day);
            MainPanel.getInstance().viewDay();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
            setBackground(Colors.TABLE_BACKGROUND);
        }
    });

    addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseDragged(MouseEvent e) {
            parent.repaint();
            parent.dispatchEvent(e);
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            parent.dispatchEvent(e);
        }

    });
}