Example usage for org.joda.time DateTime plusMonths

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

Introduction

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

Prototype

public DateTime plusMonths(int months) 

Source Link

Document

Returns a copy of this datetime plus the specified number of months.

Usage

From source file:org.springframework.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *//*from  w ww  .ja  v  a2s.  c om*/
@Override
public AggregateCounter getCounts(String name, Interval interval, AggregateCounterResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCounterResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCounterResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(name, interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCount getCounts(Interval interval, AggregateCountResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCountResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCountResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }//from   ww w.  j  av a 2  s. c o m
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(getName(), interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *///from www.j  ava2 s  .c o m
@Override
public AggregateCount getCounts(String name, Interval interval, AggregateCountResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCountResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCountResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(name, interval, counts, resolution);
}

From source file:pl.aptekhurt.service.PharmacyOrderService.java

public void createPharmacyOrder(List<NewPharmacyOrderDTO> productOrderDTOs, Principal principal) {
    for (NewPharmacyOrderDTO productOrderDTO : productOrderDTOs) {
        Pharmacy_order pharmacy_order = new Pharmacy_order();
        Product_option productOption = product_optionRepository.getOne(productOrderDTO.getProductOptionId());
        pharmacy_order.setProduct_Option(productOption);
        pharmacy_order.setQuantity(productOrderDTO.getQuantity());
        pharmacy_order.setCreation_date(new DateTime(DateTimeZone.getDefault()));
        DateTime temporaryDateTime = new DateTime(DateTimeZone.getDefault());
        switch (productOrderDTO.getTermin()) {
        case 1:/*from w w w .j av a  2s.  co m*/
            temporaryDateTime = new DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
            break;
        case 16:
            temporaryDateTime = new DateTime().withDayOfMonth(16).withTimeAtStartOfDay();
            break;
        }
        if (temporaryDateTime.isBeforeNow()) {
            temporaryDateTime = temporaryDateTime.plusMonths(1);
        }
        pharmacy_order.setTermin(temporaryDateTime);
        Pharmacy pharmacy = userRepository.findOneByLogin(principal.getName()).get().getPharmacy();
        pharmacy_order.setPharmacy(pharmacy);
        log.debug("REST request to save Pharmacy_order : {}", pharmacy_order);
        if (hasNewLimitBeenReached(productOption, productOrderDTO.getQuantity())) {
            if (ADMIN_USER == null) {
                ADMIN_USER = userRepository.findOneByLogin("admin").get();
            }
            mailService.sendNewLimitReachedEmail(ADMIN_USER, productOption,
                    pharmacy_order.getQuantity() + productOrderDTO.getQuantity());
        }
        pharmacy_orderRepository.save(pharmacy_order);
    }
    //TODO: Send email with all that products
}

From source file:projectresurrection.Schedule.java

public void run() {
    while (true) {
        DateTime date = Eve.clock.getCurrent();
        try {//  ww  w.j  av a 2  s  .  c om
            for (int i = 0; i < container.get(0).size(); i++) {
                DateTime setDate = new DateTime(container.get(0).get(i).get(1));
                if (date.getMillis() > setDate.getMillis()) {
                    Eve.addCommand(container.get(0).get(i).get(2).toString());
                    container.get(0).remove(i);
                    save();
                }
            }
            for (int i = 0; i < container.get(1).size(); i++) {
                DateTime setDate = new DateTime(container.get(1).get(i).get(1));
                if (date.getMillis() > setDate.getMillis()) {
                    announce(container.get(1).get(i).get(0).toString());
                    container.get(1).remove(i);
                    save();
                }
            }
            for (int i = 0; i < container.get(2).size(); i++) {
                DateTime setDate = new DateTime(container.get(2).get(i).get(1));
                if (date.getMillis() > setDate.getMillis()) {
                    announce(container.get(2).get(i).get(0).toString());
                    DateTime temp = new DateTime(container.get(2).get(i).get(1));
                    container.get(2).get(i).remove(1);
                    switch (container.get(2).get(i).get(1).toString()) {
                    case "Annual":
                        container.get(2).get(i).add(1, new DateTime(temp.plusYears(1)));
                        break;
                    case "Bi-annaul":
                        container.get(2).get(i).add(1, new DateTime(temp.plusMonths(6)));
                        break;
                    case "Monthly":
                        container.get(2).get(i).add(1, new DateTime(temp.plusMonths(1)));
                        break;
                    case "Weekly":
                        container.get(2).get(i).add(1, new DateTime(temp.plusWeeks(1)));
                        break;
                    case "Daily":
                        container.get(2).get(i).add(1, new DateTime(temp.plusDays(1)));
                        break;
                    }
                    save();
                }
            }
            Thread.sleep(1000);
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:py.com.palermo.proyectosgob.web.ProyectoController.java

public void addTramite() {
    if (selected.getTramites() == null) {
        selected.setTramites(new ArrayList<Tramite>());
    }/*from   w  ww.  j  a v  a2  s.  com*/

    tramiteNuevo.setProyecto(selected);
    if (tramiteNuevo.getTipoResultado() == TipoResultado.TEXTO_MEDIA_SANCION
            && tramiteNuevo.getFecha() != null) {
        DateTime dt = new DateTime(tramiteNuevo.getFecha());
        Date fechaFicta = dt.plusMonths(3).toDate();
        selected.setProyectosfechaficta(fechaFicta);
    }
    selected.getTramites().add(tramiteNuevo);
    tramiteNuevo = new Tramite();
}

From source file:ru.touchin.templates.calendar.CalendarUtils.java

License:Apache License

/**
 * Create list of {@link CalendarItem} according to start and end Dates.
 *
 * @param startDate Start date of the range;
 * @param endDate   End date of the range;
 * @return List of CalendarItems that could be one of these: {@link CalendarHeaderItem}, {@link CalendarDayItem} or {@link CalendarEmptyItem}.
 *///from  w ww  .j av a 2  s . c  o  m
@NonNull
@SuppressWarnings("checkstyle:MethodLength")
public static List<CalendarItem> fillRanges(@NonNull final DateTime startDate,
        @NonNull final DateTime endDate) {
    final DateTime cleanStartDate = startDate.withTimeAtStartOfDay();
    final DateTime cleanEndDate = endDate.plusDays(1).withTimeAtStartOfDay();

    DateTime tempTime = cleanStartDate;

    final List<CalendarItem> calendarItems = fillCalendarTillCurrentDate(cleanStartDate, tempTime);

    tempTime = tempTime.plusDays(Days.ONE.getDays());

    final int totalDaysCount = Days.daysBetween(tempTime, cleanEndDate).getDays();
    int shift = calendarItems.get(calendarItems.size() - 1).getEndRange();
    int firstDate = tempTime.getDayOfMonth() - 1;
    int daysEnded = 1;

    while (true) {
        final int daysInCurrentMonth = tempTime.dayOfMonth().getMaximumValue();
        final long firstRangeDate = tempTime.getMillis();

        if ((daysEnded + (daysInCurrentMonth - firstDate)) <= totalDaysCount) {
            tempTime = tempTime.plusMonths(1).withDayOfMonth(1);

            calendarItems.add(new CalendarDayItem(firstRangeDate, firstDate + 1, shift + daysEnded,
                    shift + daysEnded + (daysInCurrentMonth - firstDate) - 1, ComparingToToday.AFTER_TODAY));
            daysEnded += daysInCurrentMonth - firstDate;
            if (daysEnded == totalDaysCount) {
                break;
            }
            firstDate = 0;

            final int firstDayInWeek = tempTime.getDayOfWeek() - 1;

            if (firstDayInWeek != 0) {
                calendarItems.add(new CalendarEmptyItem(shift + daysEnded,
                        shift + daysEnded + (DAYS_IN_WEEK - firstDayInWeek - 1)));
                shift += (DAYS_IN_WEEK - firstDayInWeek);
            }

            calendarItems.add(new CalendarHeaderItem(tempTime.getYear(), tempTime.getMonthOfYear() - 1,
                    shift + daysEnded, shift + daysEnded));
            shift += 1;

            if (firstDayInWeek != 0) {
                calendarItems
                        .add(new CalendarEmptyItem(shift + daysEnded, shift + daysEnded + firstDayInWeek - 1));
                shift += firstDayInWeek;
            }

        } else {
            calendarItems.add(new CalendarDayItem(firstRangeDate, firstDate + 1, shift + daysEnded,
                    shift + totalDaysCount, ComparingToToday.AFTER_TODAY));
            break;
        }
    }

    return calendarItems;
}

From source file:singlejartest.StrategyTesterLoop.java

License:Open Source License

public static void main(String[] args) throws Exception {
    final ClimberProperties properties = new ClimberProperties();
    if (args.length < 1) {
        LOGGER.error("One argument needed (name of config file)");
        System.exit(1);/* ww w .j  av a2 s.c o  m*/
    }

    try {
        properties.load(new FileInputStream(args[0]));
    } catch (IOException e) {
        LOGGER.error("Can't open or can't read properties file " + args[0] + "...");
        System.exit(1);
    }
    if (properties.getProperty("noConsoleOutput", "no").equals("yes"))
        System.setOut(new PrintStream(
                ".\\Strategy_log_" + FXUtils.getFileTimeStamp(System.currentTimeMillis()) + ".log"));

    properties.validate(LOGGER);

    // get the instance of the IClient interface
    final ITesterClient client = TesterFactory.getDefaultInstance();
    // set the listener that will receive system events
    client.setSystemListener(new ISystemListener() {
        @Override
        public void onStart(long processId) {
            LOGGER.info("Strategy started: " + processId);
        }

        @Override
        public void onStop(long processId) {
            LOGGER.info("Strategy stopped: " + processId);
            File reportFile = new File(properties.getProperty("reportDirectory", ".") + "\\Strategy_run_report_"
                    + FXUtils.getFileTimeStamp(System.currentTimeMillis()) + ".html");
            try {
                client.createReport(processId, reportFile);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }

        }

        @Override
        public void onConnect() {
            LOGGER.info("Connected");
        }

        @Override
        public void onDisconnect() {
            // tester doesn't disconnect
        }
    });

    FXUtils.setDbToUse(properties.getProperty("dbToUse"));

    String timePeriod = properties.getProperty("period");
    if (timePeriod == null || timePeriod.length() == 0
            || !(timePeriod.equalsIgnoreCase("y") || timePeriod.equalsIgnoreCase("m"))) {
        LOGGER.error("property period needed, must by either m - for months or y - for years");
        System.exit(1);
    }
    String repeat = properties.getProperty("repeat");
    int repeatNo = -1;
    if (repeat == null || repeat.length() == 0) {
        LOGGER.error("repeat property must be set !");
        System.exit(1);
    } else {
        try {
            repeatNo = Integer.parseInt(repeat);
        } catch (NumberFormatException e) {
            LOGGER.error("Format of repeat property wrong, must be integer: " + repeat + ", exception "
                    + e.getMessage());
            System.exit(1);
        }
    }
    String noOfPeriodsStr = properties.getProperty("howManyPeriods");
    int noOfPeriods = -1;
    if (noOfPeriodsStr == null || noOfPeriodsStr.length() == 0) {
        LOGGER.error("howManyPeriods property must be set !");
        System.exit(1);
    } else {
        try {
            noOfPeriods = Integer.parseInt(noOfPeriodsStr);
        } catch (NumberFormatException e) {
            LOGGER.error("Format of repeat property wrong, must be integer: " + repeat + ", exception "
                    + e.getMessage());
            System.exit(1);
        }
    }

    // set instruments that will be used in testing
    StringTokenizer st = new StringTokenizer(properties.getProperty("pairsToCheck"), ";");
    Set<Instrument> instruments = new HashSet<Instrument>();
    String pair = null;
    while (st.hasMoreTokens()) {
        String nextPair = st.nextToken();
        instruments.add(Instrument.fromString(nextPair));
        if (pair == null)
            pair = new String(nextPair);
    }
    Instrument selectedInstrument = Instrument.fromString(pair);

    DateTime startDate = new DateTime(properties.getTestIntervalStart().getMillis());
    for (int j = 0; j < repeatNo; j++) {
        DateTime endDate = null;
        if (timePeriod.equalsIgnoreCase("m"))
            endDate = startDate.plusMonths(noOfPeriods);
        else
            endDate = startDate.plusYears(noOfPeriods);
        LOGGER.info("Starting backtest for the period: " + startDate.toString("dd.MM.yyyy") + " to "
                + endDate.toString("dd.MM.yyyy"));

        LOGGER.info("Connecting...");
        // connect to the server using jnlp, user name and password
        // connection is needed for data downloading
        client.connect(jnlpUrl, properties.getProperty("username"), properties.getProperty("password"));

        // wait for it to connect
        int i = 10; // wait max ten seconds
        while (i > 0 && !client.isConnected()) {
            Thread.sleep(1000);
            i--;
        }
        if (!client.isConnected()) {
            LOGGER.error("Failed to connect Dukascopy servers");
            System.exit(1);
        }

        LOGGER.info("Subscribing instruments...");
        client.setCacheDirectory(new File(properties.getProperty("cachedir")));
        client.setSubscribedInstruments(instruments);
        // setting initial deposit
        client.setInitialDeposit(Instrument.EURUSD.getSecondaryJFCurrency(),
                Double.parseDouble(properties.getProperty("initialdeposit", "100000.0")));
        client.setDataInterval(Period.TICK, null, null, startDate.getMillis(), endDate.getMillis());
        // load data
        LOGGER.info("Downloading data");
        Future<?> future = client.downloadData(null);
        // wait for downloading to complete
        Thread.sleep(10000); // this timeout helped
        future.get();
        // start the strategy
        LOGGER.info("Starting strategy");
        // client.startStrategy(new IchiAutoEntry(properties,
        // properties.getTestIntervalStart().getMillis(),
        // properties.getTestIntervalEnd().getMillis(), startTime),
        tradeTestRunningSignal = new File("strategyTestRunning.bin");
        if (tradeTestRunningSignal.exists())
            tradeTestRunningSignal.delete();
        tradeTestRunningSignal.createNewFile();
        // once test run is finished this file should be deleted !
        client.startStrategy(//new SimpleMAsIDCrossTrendFollow(properties),
                new FlatCascTest(selectedInstrument, properties), new LoadingProgressListener() {
                    @Override
                    public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
                        LOGGER.info(information);
                    }

                    @Override
                    public void loadingFinished(boolean allDataLoaded, long startTime, long endTime,
                            long currentTime) {
                    }

                    @Override
                    public boolean stopJob() {
                        return false;
                    }
                });
        // now it's running         
        while (tradeTestRunningSignal.exists()) {
        }

        startDate = endDate;
    }

    if (client.getStartedStrategies().size() == 0) {
        System.exit(0);
    }

}

From source file:stroom.entity.server.util.PeriodUtil.java

License:Apache License

/**
 * Create a month period./*  ww w.j  a v a  2  s  .c o m*/
 *
 * @param year
 *            e.g. 2001
 */
public static Period createYearMonthPeriod(final Integer year, final Integer month) {
    final DateTime startOfMonth = new DateTime(year, month, 1, 0, 0, 0, 0);
    return new Period(startOfMonth.getMillis(), startOfMonth.plusMonths(1).getMillis());
}

From source file:stroom.index.server.IndexShardKeyUtil.java

License:Apache License

public static IndexShardKey createTimeBasedKey(final Index index, final long timeMs, final int shardNo) {
    String partition = ALL;/*from   w w  w  .  ja v a 2 s.  co  m*/
    DateTime dateFrom = null;
    DateTime dateTo = null;

    if (index.getPartitionBy() != null && index.getPartitionSize() > 0) {
        dateFrom = new DateTime(timeMs);
        if (PartitionBy.YEAR.equals(index.getPartitionBy())) {
            int year = dateFrom.get(DateTimeFieldType.year());
            year = fix(year, index.getPartitionSize());

            dateFrom = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
            dateTo = dateFrom.plusYears(index.getPartitionSize());
            partition = DateUtil.createFileDateTimeString(dateFrom.getMillis());
            partition = partition.substring(0, 4);

        } else if (PartitionBy.MONTH.equals(index.getPartitionBy())) {
            final int year = dateFrom.get(DateTimeFieldType.year());
            int month = dateFrom.get(DateTimeFieldType.monthOfYear());
            month = fix(month, index.getPartitionSize());
            if (month < 1) {
                month = 1;
            }

            dateFrom = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
            dateFrom = dateFrom.plusMonths(month - 1);
            dateTo = dateFrom.plusMonths(index.getPartitionSize());
            partition = DateUtil.createFileDateTimeString(dateFrom.getMillis());
            partition = partition.substring(0, 7);

        } else if (PartitionBy.WEEK.equals(index.getPartitionBy())) {
            final int year = dateFrom.get(DateTimeFieldType.year());
            int week = dateFrom.get(DateTimeFieldType.weekOfWeekyear());
            week = fix(week, index.getPartitionSize());
            if (week < 1) {
                week = 1;
            }

            dateFrom = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
            dateFrom = dateFrom.plusWeeks(week - 1);
            dateTo = dateFrom.plusWeeks(index.getPartitionSize());
            partition = DateUtil.createFileDateTimeString(dateFrom.getMillis());
            partition = partition.substring(0, 10);

        } else if (PartitionBy.DAY.equals(index.getPartitionBy())) {
            final int year = dateFrom.get(DateTimeFieldType.year());
            int day = dateFrom.get(DateTimeFieldType.dayOfYear());
            day = fix(day, index.getPartitionSize());
            if (day < 1) {
                day = 1;
            }

            dateFrom = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
            dateFrom = dateFrom.plusDays(day - 1);
            dateTo = dateFrom.plusDays(index.getPartitionSize());
            partition = DateUtil.createFileDateTimeString(dateFrom.getMillis());
            partition = partition.substring(0, 10);
        }
    }

    Long partitionFromTime = null;
    if (dateFrom != null) {
        partitionFromTime = dateFrom.getMillis();
    }

    Long partitionToTime = null;
    if (dateTo != null) {
        partitionToTime = dateTo.getMillis();
    }

    return new IndexShardKey(index, partition, partitionFromTime, partitionToTime, shardNo);
}