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.monrai.cypher.lang.nl.registry.Pattern.java

License:Open Source License

public static long timeSpan(Date old, Date current) {
    if (old == null)
        return 0;
    DateTime dt = new DateTime(old.getTime());
    DateTime now = new DateTime(current.getTime());
    return new Interval(dt, now).toDurationMillis();
    //        Dim ts As TimeSpan = Date.Now.Subtract(lastTime);
    //        Return ts.TotalMilliseconds;
}

From source file:com.netflix.ice.basic.BasicTagGroupManager.java

License:Apache License

private Collection<Long> getMonthMillis(Interval interval) {
    Set<Long> result = Sets.newTreeSet();
    for (Long milli : tagGroups.keySet()) {
        DateTime monthDate = new DateTime(milli, DateTimeZone.UTC);
        if (new Interval(monthDate, monthDate.plusMonths(1)).overlap(interval) != null)
            result.add(milli);//from w ww . j  av  a2s. c  o m
    }

    return result;
}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

License:Apache License

private File createImage(ApplicationGroup appgroup) throws IOException {

    Map<String, Double> costs = Maps.newHashMap();
    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    Interval interval = new Interval(end.minusWeeks(numWeeks), end);

    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appgroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }//from w  w w  .ja v  a  2 s  .  c o m
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        TagLists tagLists = new TagLists(accounts, regions, null, Lists.newArrayList(product), null, null,
                resourceGroups);
        Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Product, AggregateType.none,
                false);
        for (Tag tag : data.keySet()) {
            for (int week = 0; week < numWeeks; week++) {
                String key = tag + "|" + week;
                if (costs.containsKey(key))
                    costs.put(key, data.get(tag)[week] + costs.get(key));
                else
                    costs.put(key, data.get(tag)[week]);
            }
        }
    }

    boolean hasData = false;
    for (Map.Entry<String, Double> entry : costs.entrySet()) {
        if (!entry.getKey().contains("monitor") && entry.getValue() != null && entry.getValue() >= 0.1) {
            hasData = true;
            break;
        }
    }
    if (!hasData)
        return null;

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (Product product : products) {
        for (int week = 0; week < numWeeks; week++) {
            String weekStr = String.format("%s - %s week",
                    formatter.print(end.minusWeeks(numWeeks - week)).substring(5),
                    formatter.print(end.minusWeeks(numWeeks - week - 1)).substring(5));
            dataset.addValue(costs.get(product + "|" + week), product.name, weekStr);
        }
    }

    JFreeChart chart = ChartFactory.createBarChart3D(appgroup.getDisplayName() + " Weekly AWS Costs", "",
            "Costs", dataset, PlotOrientation.VERTICAL, true, false, false);
    CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
    BarRenderer3D renderer = (BarRenderer3D) categoryplot.getRenderer();
    renderer.setItemLabelAnchorOffset(10.0);
    TextTitle title = chart.getTitle();
    title.setFont(title.getFont().deriveFont((title.getFont().getSize() - 3)));

    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator() {
        public java.lang.String generateLabel(org.jfree.data.category.CategoryDataset dataset, int row,
                int column) {
            return costFormatter.format(dataset.getValue(row, column));
        }
    });
    renderer.setBaseItemLabelsVisible(true);
    renderer.setBasePositiveItemLabelPosition(
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));

    NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
    numberaxis.setNumberFormatOverride(costFormatter);

    BufferedImage image = chart.createBufferedImage(1200, 400);
    File outputfile = File.createTempFile("awscost", "png");
    ImageIO.write(image, "png", outputfile);

    return outputfile;
}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

License:Apache License

private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body)
        throws IOException, MessagingException {

    if (index == 0 && !StringUtils.isEmpty(headerNote))
        body.append(headerNote);/*  w  w  w.j a  v a  2 s  .  c o  m*/

    numberFormatter.setMaximumFractionDigits(1);
    numberFormatter.setMinimumFractionDigits(1);

    File file = createImage(appGroup);

    if (file == null)
        return null;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
            end);
    body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link,
            appGroup.getDisplayName()));

    body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">");
    body.append(
            "<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>");
    for (int i = 0; i <= accounts.size(); i++) {
        int cols = i == accounts.size() ? 1 : regions.size();
        String accName = i == accounts.size() ? "total" : accounts.get(i).name;
        body.append(String.format(
                "<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols))
                .append(accName).append("</td>");
    }
    body.append("</tr>");
    body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>");
    for (int i = 0; i < accounts.size(); i++) {
        boolean first = true;
        for (Region region : regions) {
            body.append("<td style=\"font-weight: bold;padding: 4px;"
                    + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name)
                    .append("</td>");
            first = false;
        }
    }
    body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>");

    Map<String, Double> costs = Maps.newHashMap();

    Interval interval = new Interval(end.minusWeeks(numWeeks), end);
    double[] total = new double[numWeeks];
    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        for (int i = 0; i < accounts.size(); i++) {
            List<Account> accountList = Lists.newArrayList(accounts.get(i));
            TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null,
                    null, resourceGroups);
            Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region,
                    AggregateType.none, false);
            for (Tag tag : data.keySet()) {
                for (int week = 0; week < numWeeks; week++) {
                    String key = accounts.get(i) + "|" + tag + "|" + week;
                    if (costs.containsKey(key))
                        costs.put(key, data.get(tag)[week] + costs.get(key));
                    else
                        costs.put(key, data.get(tag)[week]);
                    total[week] += data.get(tag)[week];
                }
            }
        }
    }

    boolean firstLine = true;
    DateTime currentWeekEnd = end;
    for (int week = numWeeks - 1; week >= 0; week--) {
        String weekStr;
        if (week == numWeeks - 1)
            weekStr = "Last week";
        else
            weekStr = (numWeeks - week - 1) + " weeks ago";
        String background = week % 2 == 1 ? "background: whiteSmoke;" : "";
        body.append(String.format(
                "<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>",
                background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5),
                formatter.print(currentWeekEnd).substring(5)));
        for (int i = 0; i < accounts.size(); i++) {
            Account account = accounts.get(i);
            for (int j = 0; j < regions.size(); j++) {
                Region region = regions.get(j);
                String key = account + "|" + region + "|" + week;
                double cost = costs.get(key) == null ? 0 : costs.get(key);
                Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1));
                link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account),
                        Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd);
                body.append(getValueCell(cost, lastCost, link, firstLine));
            }
        }
        link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions,
                currentWeekEnd.minusWeeks(1), currentWeekEnd);
        body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine));
        body.append("</tr>");
        firstLine = false;
        currentWeekEnd = currentWeekEnd.minusWeeks(1);
    }
    body.append("</table>");

    numberFormatter.setMaximumFractionDigits(0);
    numberFormatter.setMinimumFractionDigits(0);

    if (!StringUtils.isEmpty(throughputMetrics))
        body.append(throughputMetrics);

    body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>");
    for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) {
        String product = entry.getKey();
        List<String> selected = entry.getValue();
        if (selected == null || selected.size() == 0)
            continue;
        link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
                end);
        body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>",
                getResourceGroupsDisplayName(product), link, appGroup.getDisplayName()));
        for (String name : selected)
            body.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").append(name).append("<br>");
    }
    body.append("<hr><br>");

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setFileName(file.getName());
    DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png");
    mimeBodyPart.setDataHandler(new DataHandler(ds));
    mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">");
    mimeBodyPart.setHeader("Content-Disposition", "inline");
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);

    file.delete();

    return mimeBodyPart;
}

From source file:com.netflix.ice.reader.ReaderConfig.java

License:Apache License

public void start() {

    Managers managers = ReaderConfig.getInstance().managers;
    Collection<Product> products = managers.getProducts();
    for (Product product : products) {
        TagGroupManager tagGroupManager = managers.getTagGroupManager(product);
        Interval interval = tagGroupManager.getOverlapInterval(new Interval(
                new DateTime(DateTimeZone.UTC).minusMonths(monthlyCacheSize), new DateTime(DateTimeZone.UTC)));
        if (interval == null)
            continue;
        for (ConsolidateType consolidateType : ConsolidateType.values()) {
            readData(product, managers.getCostManager(product, consolidateType), interval, consolidateType);
            readData(product, managers.getUsageManager(product, consolidateType), interval, consolidateType);
        }// w ww.jav a 2  s.  c o m
    }

    if (costEmailService != null)
        costEmailService.start();
}

From source file:com.nfsdb.journal.Journal.java

License:Apache License

public TempPartition<T> createTempPartition(String name) throws JournalException {
    int lag = getMetadata().getLag();
    if (lag <= 0) {
        throw new JournalRuntimeException("Journal doesn't support temp partitions: %s", this);
    }/*from   w  ww  . jav  a 2 s.  c o  m*/

    Interval interval = null;
    if (getMetadata().getPartitionType() != PartitionType.NONE) {
        if (nonLagPartitionCount() > 0) {
            Interval lastPartitionInterval = partitions.get(nonLagPartitionCount() - 1).getInterval();
            interval = new Interval(lastPartitionInterval.getStart(),
                    lastPartitionInterval.getEnd().plusHours(lag));
        } else {
            interval = Dates.intervalForDate(System.currentTimeMillis(), getMetadata().getPartitionType());
        }
    }
    return new TempPartition<>(this, interval, nonLagPartitionCount(), name);
}

From source file:com.nfsdb.journal.utils.Dates.java

License:Apache License

private static Interval lastMonths(DateTime endDateTime, int duration) {
    if (duration < 1) {
        throw new JournalRuntimeException("Duration should be >= 1: %d", duration);
    }/* w  w  w  . java  2s . co  m*/
    DateTime start = endDateTime.minusMonths(duration);
    return new Interval(start, endDateTime);
}

From source file:com.pacoapp.paco.shared.scheduling.EsmGenerator2.java

License:Open Source License

public List<DateTime> generateForSchedule(DateTime startDate, Schedule schedule2) {
    this.schedule = schedule2;
    this.periodStartDate = adjustStartDateToBeginningOfPeriod(startDate);
    times = new ArrayList<DateTime>();

    if (schedule2.getEsmFrequency() == null || schedule2.getEsmFrequency() == 0) {
        return times;
    }//from w  w  w  . ja  v a 2s  . c o m
    List<Integer> schedulableDays;
    switch (schedule2.getEsmPeriodInDays()) {
    case Schedule.ESM_PERIOD_DAY:
        if (!schedule2.getEsmWeekends() && TimeUtil.isWeekend(periodStartDate)) {
            return times;
        } else {
            schedulableDays = Arrays.asList(1);
        }
        break;
    case Schedule.ESM_PERIOD_WEEK:
        schedulableDays = getPeriodDaysForWeek();
        break;
    case Schedule.ESM_PERIOD_MONTH:
        schedulableDays = getPeriodDaysForMonthOf(periodStartDate);
        break;
    default:
        throw new IllegalStateException("Cannot get here.");
    }

    Minutes dayLengthIntervalInMinutes = Minutes
            .minutesIn(new Interval(schedule2.getEsmStartHour(), schedule2.getEsmEndHour()));
    Minutes totalMinutesInPeriod = dayLengthIntervalInMinutes.multipliedBy(schedulableDays.size());
    Minutes sampleBlockTimeInMinutes = totalMinutesInPeriod.dividedBy(schedule2.getEsmFrequency());
    Minutes timeoutInMinutes = Minutes.minutes(schedule2.getMinimumBuffer());
    Random rand = new Random();
    for (int signal = 0; signal < schedule2.getEsmFrequency(); signal++) {

        int candidateTimeInBlock;
        DateTime candidateTime;
        int periodAttempts = 1000;
        do {
            candidateTimeInBlock = rand.nextInt(sampleBlockTimeInMinutes.getMinutes());
            // map candidatePeriod and candidateTime back onto days of period
            // note, sometimes a candidate period will map across days in period
            // because start and end hours make for non-contiguous days
            int totalMinutesToAdd = sampleBlockTimeInMinutes.getMinutes() * signal + candidateTimeInBlock;
            int daysToAdd = totalMinutesToAdd / dayLengthIntervalInMinutes.getMinutes();
            int minutesToAdd = 0;
            if (totalMinutesToAdd <= dayLengthIntervalInMinutes.getMinutes()) { // within one day
                minutesToAdd = totalMinutesToAdd;
            } else {
                minutesToAdd = totalMinutesToAdd % dayLengthIntervalInMinutes.getMinutes();
            }

            DateTime plusDays = periodStartDate.plusDays(schedulableDays.get(daysToAdd) - 1);
            candidateTime = plusDays.withMillisOfDay(schedule2.getEsmStartHour().intValue())
                    .plusMinutes(minutesToAdd);
            periodAttempts--;
        } while (periodAttempts > 0
                && (!isMinimalBufferedDistanceFromOtherTimes(candidateTime, timeoutInMinutes)
                        || (!schedule2.getEsmWeekends() && TimeUtil.isWeekend(candidateTime))));
        if (isMinimalBufferedDistanceFromOtherTimes(candidateTime, timeoutInMinutes)
                && (schedule2.getEsmWeekends() || !TimeUtil.isWeekend(candidateTime))) {
            times.add(candidateTime);
        }

    }
    return times;
}

From source file:com.peertopark.java.dates.Intervals.java

License:Apache License

public static Interval getInterval(Date fromDate, Date untilDate) {
    return new Interval(convert(fromDate), convert(untilDate));
}

From source file:com.peertopark.java.dates.Intervals.java

License:Apache License

public static Interval getInterval(DateTime fromDate, DateTime untilDate) {
    return new Interval(fromDate, untilDate);
}