Example usage for org.joda.time DateTime plusMinutes

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

Introduction

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

Prototype

public DateTime plusMinutes(int minutes) 

Source Link

Document

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

Usage

From source file:org.fracturedatlas.athena.helper.lock.manager.AthenaLockManager.java

License:Open Source License

public AthenaLock createLock(HttpServletRequest request, AthenaLock tran) throws Exception {
    //Load all the tickets
    Set<PTicket> tickets = new HashSet<PTicket>();
    Set<String> ticketIds = tran.getTickets();
    for (String id : ticketIds) {

        PTicket t = apa.getRecord(LOCK_TYPE, id);
        if (t == null) {
            throw new TicketsLockedException("Invalid ticket involved with transaction");
        }/*  w ww. j  av a  2s.c o  m*/

        if (isInvolvedInActiveTransaction(t)) {
            throw new TicketsLockedException("Unable to obtain lock on tickets");
        }
    }

    tran.setId(UUID.randomUUID().toString());
    tran.setLockedByApi(getCurrentUsername());
    tran.setLockedByIp(request.getRemoteAddr());
    tran.setStatus(AthenaLockStatus.OK);

    DateTime lockExpires = new DateTime(new Date());
    lockExpires = lockExpires
            .plusMinutes(Integer.parseInt(props.getProperty("athena.lock.lock_time_in_minutes")));
    tran.setLockExpires(lockExpires.toDate());

    lockTickets(ticketIds, tran);
    return tran;
}

From source file:org.fracturedatlas.athena.helper.lock.manager.AthenaLockManager.java

License:Open Source License

public AthenaLock updateLock(String id, HttpServletRequest request, AthenaLock tran) throws Exception {
    //Load all the tickets
    Set<String> ticketIds = new HashSet<String>();
    Set<PTicket> ticketsInTransaction = getTicketsInTransaction(tran.getId());

    //This looks a little stupid: loading the tickets from apa even though the client is sending us
    //an array of tickets.  We do this though to prevent the client from adding in extra tickets
    //beyond those that were locked with the initial lock
    for (PTicket ticket : ticketsInTransaction) {
        ticketIds.add(ticket.getId().toString());
    }/*from  w  w w .ja va  2 s  . co m*/

    PropField lockTimesField = apa.getPropField(AthenaLockManager.LOCK_TIMES);

    AthenaLock transactionFromTickets = null;

    for (String ticketId : ticketIds) {
        PTicket t = apa.getRecord(LOCK_TYPE, ticketId);

        if (t == null) {
            throw new TicketsLockedException("Invalid ticket involved with transaction");
        }

        Integer numTimesLocked = Integer.parseInt(t.get(lockTimesField.getName()));
        logger.debug("", numTimesLocked);
        logger.debug(props.getProperty("athena.transaction.number_of_renewals"));
        logger.debug("", isRenewing(tran));

        if (numTimesLocked > Integer.parseInt(props.getProperty("athena.lock.number_of_renewals"))
                && isRenewing(tran)) {
            throw new AthenaException("Cannot lock tickets");
        }

        transactionFromTickets = loadTransactionFromTicket(t);

        if (!isOwnerOfTransaction(request, transactionFromTickets)) {
            throw new AthenaException("Cannot process the transaction");
        }
    }

    DateTime now = new DateTime();
    DateTime expiresOn = now
            .plusMinutes(Integer.parseInt(props.getProperty("athena.lock.renewal_time_in_minutes")));
    tran.setLockExpires(expiresOn.toDate());
    tran.setTickets(ticketIds);

    if (isCompleting(tran)) {
        completeTicketPurchase(tran);
    } else if (isRenewing(tran)) {
        renewLockOnTickets(tran);
    } else {
        throw new AthenaException("Did not understand status of [" + tran.getStatus() + "]");
    }

    tran.setStatus(AthenaLockStatus.OK);

    return tran;
}

From source file:org.hortonmachine.gvsig.epanet.core.EpanetRunner.java

License:Open Source License

public void run(String tStart, double hydraulicTimestep, IHMProgressMonitor pm, EpanetRun run,
        // table maps
        HashMap<String, JunctionsTable> jId2Table, //
        HashMap<String, PipesTable> piId2Table, //
        HashMap<String, PumpsTable> puId2Table, //
        HashMap<String, ValvesTable> vId2Table, //
        HashMap<String, TanksTable> tId2Table, //
        HashMap<String, ReservoirsTable> rId2Table, //
        ConnectionSource connectionSource //
) throws Exception {

    Dao<JunctionsResultsTable, Long> junctionsResultsDao = DaoManager.createDao(connectionSource,
            JunctionsResultsTable.class);
    Dao<PipesResultsTable, Long> pipesResultsDao = DaoManager.createDao(connectionSource,
            PipesResultsTable.class);
    Dao<PumpsResultsTable, Long> pumpsResultsDao = DaoManager.createDao(connectionSource,
            PumpsResultsTable.class);
    Dao<ValvesResultsTable, Long> valvesResultsDao = DaoManager.createDao(connectionSource,
            ValvesResultsTable.class);
    Dao<TanksResultsTable, Long> tanksResultsDao = DaoManager.createDao(connectionSource,
            TanksResultsTable.class);
    Dao<ReservoirsResultsTable, Long> reservoirsResultsDao = DaoManager.createDao(connectionSource,
            ReservoirsResultsTable.class);

    OmsEpanet epanet = new OmsEpanet();
    DateTime startDate = fromStringWithSeconds("1970-01-01 00:00:00");
    try {//from  w w w  .j  a v  a 2  s  .  c om
        startDate = fromStringWithSeconds(tStart);
        epanet.tStart = tStart;
    } catch (Exception e) {
        // ignore if wrong, will start at 1970-01-01
    }
    epanet.pm = pm;
    epanet.inDll = dllPath;
    epanet.inInp = inpFilePath;

    DateTime runningDate = startDate;
    epanet.initProcess();
    while (epanet.doProcess) {
        epanet.process();
        String tCurrent = epanet.tCurrent;

        String warnings = epanet.warnings;
        if (warnings != null) {
            warningsBuilder.append(tCurrent).append(":").append(warnings).append("\n");
        }

        DateTime dt = fromStringWithSeconds(tCurrent);
        boolean isEqualDate = dt.equals(runningDate);
        if (!isEqualDate) {
            // jump over intermediate timesteps
            pm.message("Jumping over timestep: " + tCurrent);
            continue;
        }
        pm.message("Processing: " + tCurrent);

        runningDate = runningDate.plusMinutes((int) hydraulicTimestep);

        /*
         * insert records in the database
         */
        List<Junction> junctionsList = epanet.junctionsList;
        for (Junction junction : junctionsList) {
            epanet.checkCancel();
            String id = junction.id;
            JunctionsResultsTable jrt = new JunctionsResultsTable();
            jrt.setWork(jId2Table.get(id));
            jrt.setRun(run);
            jrt.setUtcTime(dt);
            jrt.setDemand(junction.demand);
            jrt.setHead(junction.head);
            jrt.setPressure(junction.pressure);
            jrt.setQuality(junction.quality);
            junctionsResultsDao.create(jrt);
        }
        List<Reservoir> reservoirsList = epanet.reservoirsList;
        for (Reservoir reservoir : reservoirsList) {
            epanet.checkCancel();
            String id = reservoir.id;
            ReservoirsResultsTable rrt = new ReservoirsResultsTable();
            rrt.setWork(rId2Table.get(id));
            rrt.setRun(run);
            rrt.setUtcTime(dt);
            rrt.setDemand(reservoir.demand);
            rrt.setHead(reservoir.head);
            rrt.setQuality(reservoir.quality);
            reservoirsResultsDao.create(rrt);
        }
        List<Tank> tankList = epanet.tanksList;
        for (Tank tank : tankList) {
            epanet.checkCancel();
            String id = tank.id;
            TanksResultsTable trt = new TanksResultsTable();
            trt.setWork(tId2Table.get(id));
            trt.setRun(run);
            trt.setUtcTime(dt);
            trt.setDemand(tank.demand);
            trt.setHead(tank.head);
            trt.setPressure(tank.pressure);
            trt.setQuality(tank.quality);
            tanksResultsDao.create(trt);
        }
        List<Pipe> pipesList = epanet.pipesList;
        for (Pipe pipe : pipesList) {
            epanet.checkCancel();
            String id = pipe.id;
            PipesResultsTable pirt = new PipesResultsTable();
            pirt.setWork(piId2Table.get(id));
            pirt.setRun(run);
            pirt.setUtcTime(dt);
            pirt.setFlow1(pipe.flow[0]);
            pirt.setFlow2(pipe.flow[1]);
            pirt.setHeadloss(pipe.headloss);
            pirt.setVelocity1(pipe.velocity[0]);
            pirt.setVelocity2(pipe.velocity[1]);
            pirt.setStatus(pipe.status);
            pipesResultsDao.create(pirt);
        }
        List<Pump> pumpsList = epanet.pumpsList;
        for (Pump pump : pumpsList) {
            epanet.checkCancel();
            String id = pump.id;
            PumpsResultsTable purt = new PumpsResultsTable();
            purt.setWork(puId2Table.get(id));
            purt.setRun(run);
            purt.setUtcTime(dt);
            purt.setFlow1(pump.flow);
            purt.setFlow2(pump.flow);
            purt.setHeadloss(pump.headloss);
            purt.setVelocity1(pump.velocity);
            purt.setVelocity2(pump.velocity);
            purt.setStatus(pump.status);
            pumpsResultsDao.create(purt);
        }
        List<Valve> valvesList = epanet.valvesList;
        for (Valve valve : valvesList) {
            epanet.checkCancel();
            String id = valve.id;
            ValvesResultsTable purt = new ValvesResultsTable();
            purt.setWork(vId2Table.get(id));
            purt.setRun(run);
            purt.setUtcTime(dt);
            purt.setFlow1(valve.flow);
            purt.setFlow2(valve.flow);
            purt.setHeadloss(valve.headloss);
            purt.setVelocity1(valve.velocity);
            purt.setVelocity2(valve.velocity);
            purt.setStatus(valve.status);
            valvesResultsDao.create(purt);
        }
    }
}

From source file:org.jevis.jecalc.calculation.JEVisSampleCreator.java

public static List<JEVisSample> getSamples(Integer minutes, DateTime start, DateTime end) {
    DateTime currentDate = start;
    List<JEVisSample> samples = new ArrayList<>();
    Random random = new Random();
    while (!currentDate.isAfter(end)) {
        JEVisSample currentSample = new VirtuelSample(currentDate, random.nextDouble());
        samples.add(currentSample);//from w  w  w. jav a  2  s  .c  o m
        currentDate = currentDate.plusMinutes(minutes);
    }
    return samples;
}

From source file:org.jgrasstools.hortonmachine.modules.networktools.trento_p.net.NetworkCalibration.java

License:Open Source License

private void getNetData() {
    int nTime = lastTimeDischarge.length;
    int length = lastTimeDischarge[0].length;
    HashMap<Integer, double[]> tmpHMDis = new LinkedHashMap<Integer, double[]>();
    HashMap<Integer, double[]> tmpHMFill = new LinkedHashMap<Integer, double[]>();
    // order the outpt.

    int netLength = networkPipes.length;
    double[] one = new double[netLength];
    double[] two = new double[netLength];
    for (int i = 0; i < netLength; i++) {
        one[i] = i;//from w  ww  .ja va2 s  . c om
        two[i] = networkPipes[i].getId();
    }

    QuickSortAlgorithm sort = new QuickSortAlgorithm(pm);
    sort.sort(two, one);

    for (int i = 0; i < length - 1; i++) {
        int index = (int) one[i];
        tmpHMDis.put(networkPipes[index].getId(), new double[] { lastTimeDischarge[0][index] });
        tmpHMFill.put(networkPipes[index].getId(), new double[] { lastTimeFillDegree[0][index] });

    }
    discharge.put(first, tmpHMDis);
    fillDegree.put(first, tmpHMFill);
    DateTime tmp = first;
    for (int i = 1; i < nTime; ++i) {
        tmp = tmp.plusMinutes(dt);
        tmpHMDis = new LinkedHashMap<Integer, double[]>();
        tmpHMFill = new LinkedHashMap<Integer, double[]>();
        for (int j = 0; j < length - 1; j++) {
            int index = (int) one[j];
            tmpHMDis.put(networkPipes[index].getId(), new double[] { lastTimeDischarge[i][index] });
            tmpHMFill.put(networkPipes[index].getId(), new double[] { lastTimeFillDegree[i][index] });

        }
        discharge.put(tmp, tmpHMDis);
        fillDegree.put(tmp, tmpHMFill);
    }
}

From source file:org.jgrasstools.hortonmachine.modules.networktools.trento_p.OmsTrentoP.java

License:Open Source License

private boolean verifyParameter() {
    // checkNull(inPipes,pAccuracy);
    boolean isAreaAllDry;

    if (pMode < 0 || pMode > 1) {
        pm.errorMessage(msg.message("trentoP.error.mode"));
        throw new IllegalArgumentException(msg.message("trentoP.error.mode"));

    }/*w  ww . j av a  2s. com*/

    if (inPipes == null) {
        pm.errorMessage(msg.message("trentoP.error.inputMatrix") + " geometry file");
        throw new IllegalArgumentException(msg.message("trentoP.error.inputMatrix") + " geometry file");
    }

    /* Il numero di giunzioni in un nodo non puo' superiore a 7 */
    if (pMaxJunction <= 0 || pMaxJunction > 6) {
        pm.errorMessage(msg.message("trentoP.error.maxJunction"));
        throw new IllegalArgumentException();
    }

    /*
     * Il numero di iterazioni ammesso non puo' essere troppo piccolo ne'
     * eccessivamente grande
     */
    if (pJMax < 3 || pJMax > 1000) {
        pm.errorMessage(msg.message("trentoP.error.jMax"));
        throw new IllegalArgumentException(msg.message("trentoP.error.jMax"));
    }

    /*
     * La precisione con cui si cercano alcune soluzioni non puo' essere
     * negativa
     */
    if (pAccuracy == null || pAccuracy <= 0) {
        pm.errorMessage(msg.message("trentoP.error.accuracy"));
        throw new IllegalArgumentException();
    }
    /* Intervallo in cui puo variare il riempimento minimo */
    if (pMinG <= 0 || pMinG > 0.1) {
        pm.errorMessage(msg.message("trentoP.error.minG"));
        throw new IllegalArgumentException();
    }
    /* Non sono ammesse portate minime negative nei tubi */
    if (pMinDischarge <= 0) {
        pm.errorMessage(msg.message("trentoP.error.minDischarge"));
        throw new IllegalArgumentException();
    }

    /* Il fattore di celerita' deve essere compreso tra 1 e 1.6 */
    if (pCelerityFactor < 1 || pCelerityFactor > 1.6) {
        pm.errorMessage(msg.message("trentoP.error.celerity"));
        throw new IllegalArgumentException();
    }

    /* EXPONENT non puo' essere negativo */
    if (pExponent <= 0) {
        pm.errorMessage(msg.message("trentoP.error.exponent"));
        throw new IllegalArgumentException();
    }

    /* La tolleranza non puo' essere nulla tantomeno negativa */
    if (pTolerance <= 0) {
        pm.errorMessage(msg.message("trentoP.error.tolerance"));
        throw new IllegalArgumentException();
    }

    if (pGamma <= 0) {
        pm.errorMessage(msg.message("trentoP.error.gamma"));
        throw new IllegalArgumentException();
    }

    if (pEspInflux <= 0) {
        pm.errorMessage(msg.message("trentoP.error.eps1"));
        throw new IllegalArgumentException();
    }

    SimpleFeatureType schema = inPipes.getSchema();

    if (pMode == 0) {
        // checkNull(pA,pN,pTau,inDiameters);

        isAreaAllDry = Utility.verifyProjectType(schema, pm);

        if (pA == null || pA <= 0) {
            pm.errorMessage(msg.message("trentoP.error.a"));
            throw new IllegalArgumentException(msg.message("trentoP.error.a"));
        }
        if (pN == null || pN < 0.05 || pN > 0.95) {
            pm.errorMessage(msg.message("trentoP.error.n"));
            throw new IllegalArgumentException(msg.message("trentoP.error.n"));
        }
        if (pTau == null || pTau <= 0) {
            pm.errorMessage(msg.message("trentoP.error.tau"));
            throw new IllegalArgumentException(msg.message("trentoP.error.tau"));
        }

        if (pG == null || pG <= 0 || pG > 0.99) {
            pm.errorMessage(msg.message("trentoP.error.g"));

            throw new IllegalArgumentException(msg.message("trentoP.error.g"));
        }
        if (pAlign != 0 && pAlign != 1) {
            pm.errorMessage(msg.message("trentoP.error.align"));
            throw new IllegalArgumentException(msg.message("trentoP.error.align"));
        }
        /* Lo scavo minimo non puo' essere uguale o inferiore a 0 */
        if (pMinimumDepth <= 0) {
            pm.errorMessage(msg.message("trentoP.error.scavomin"));
            throw new IllegalArgumentException();

        }
        /* Pecisione con cui si ricerca la portata nelle aree non di testa. */
        if (pEpsilon <= 0 || pEpsilon > 1) {
            pm.errorMessage(msg.message("trentoP.error.epsilon"));
            throw new IllegalArgumentException();
        }
        /*
         * L'angolo di riempimento minimo non puo' essere inferiore a 3.14
         * [rad]
         */
        if (pMaxTheta < 3.14) {
            pm.errorMessage(msg.message("trentoP.error.maxtheta"));
            throw new IllegalArgumentException();
        }
        if (pC <= 0) {
            pm.errorMessage(msg.message("trentoP.error.c"));
            throw new IllegalArgumentException();
        }
        if (inDiameters == null) {

            throw new IllegalArgumentException();
        }

        /*
         * Il passo temporale con cui valutare le portate non puo' essere
         * inferiore a 0.015 [min]
         */
        if (tDTp < 0.015) {
            pm.errorMessage(msg.message("trentoP.error.dtp"));
            throw new IllegalArgumentException();
        }

        /*
         * Tempo di pioggia minimo da considerare nella massimizzazione
         * delle portate non puo' essere superiore a 5 [min]
         */
        if (tpMin > 5) {
            pm.errorMessage(msg.message("trentoP.error.tpmin"));
            throw new IllegalArgumentException();
        }

        /*
         * Tempo di pioggia massimo da adottare nella ricerca della portata
         * massima non puo' essere inferiore a 5 [min]
         */
        if (tpMax < 30) {
            pm.errorMessage(msg.message("trentoP.error.tpmax"));
            throw new IllegalArgumentException();
        }
    } else {
        // checkNull(inRain);
        isAreaAllDry = Utility.verifyCalibrationType(schema, pm);

        /*
         * If the inRain is null and the users set the a and n parameters then create the rain data.
         */
        if (pA != null && pN != null) {
            // set it to true in order to search the time at max discharge.
            if (tpMaxCalibration != null) {
                foundTp = true;
            } else {
                tpMaxCalibration = tMax;
            }
            if (dt == null) {
                pm.errorMessage(msg.message("trentoP.error.dtp"));
                throw new IllegalArgumentException();
            }
            if (tMax < tpMaxCalibration) {
                tpMaxCalibration = tMax;
            }

            double tMaxApproximate = ModelsEngine.approximate2Multiple(tMax, dt);
            // initialize the output.
            int iMax = (int) (tMaxApproximate / dt);
            int iRainMax = (int) (Math.floor((double) tpMaxCalibration / (double) dt));
            DateTime startTime = new DateTime(System.currentTimeMillis());
            inRain = new LinkedHashMap<DateTime, double[]>();
            double tp = ((double) dt) / 2;
            DateTime newDate = startTime;
            for (int i = 0; i <= iMax; i++) {
                newDate = newDate.plusMinutes(dt);
                double hourTime = tp / Constants.HOUR2MIN;
                double value;
                if (i < iRainMax) {
                    value = pA * pow(hourTime, pN - 1) / Constants.HOUR2MIN;
                } else {
                    value = 0.0;
                }
                inRain.put(newDate, new double[] { value });
                tp = tp + dt;
            }

        } else {
            // force the time steep to null in order to read it to the file.
            dt = null;
        }
        if (inRain == null) {

            pm.errorMessage(msg.message("trentoP.error.inputRainMatrix") + " rain file");
            throw new IllegalArgumentException(msg.message("trentoP.error.inputRainMatrix") + " rain file");
        }

        // verificy if the field exist.

    }
    return isAreaAllDry;
}

From source file:org.jmxtrans.samples.graphite.GraphiteDataInjector.java

License:Open Source License

public void generateLoad() throws Exception {
    System.out.println("Inject data on Graphite server " + this.graphiteHost);

    TimeSeries timeSeries = new TimeSeries("shopping-cart.raw");

    DateTime now = new DateTime();
    DateTime end = now.plusDays(1);//  w  ww  .  ja v a  2  s . c o m

    DateTime date = now.minusDays(15);
    DateTime twoDaysAfterBegin = date.plusDays(2);

    int integratedValue = 0;

    MathContext mathContext = new MathContext(1, RoundingMode.CEILING);

    int randomFactor = 0;

    while (date.isBefore(end)) {
        if (timeSeries.getItemCount() % 120 == 0) {
            randomFactor = 10 + random.nextInt(2);
        }
        int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear());
        int value = new BigDecimal(randomFactor) // random factor
                .multiply(new BigDecimal(10)) // go to cents of USD
                .multiply(new BigDecimal(weekGrowthFactor))
                .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()]))
                .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()]))
                .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes

        integratedValue += value;
        for (int i1 = 0; i1 < 3; i1++) {
            timeSeries.add(new Minute(date.toDate()), integratedValue);
            date = date.plusMinutes(1);
        }
    }

    TimeSeries ordersPriceInCentsTimeSeries = MovingAverage.createMovingAverage(timeSeries,
            "shopping-cart.OrdersPriceInCents", 60 * 7, 0);

    TimeSeries ordersPriceInCentsSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrdersPriceInCents");
    TimeSeries ordersPriceInCentsSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrdersPriceInCents");
    int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics
    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        TimeSeriesDataItem dataItem = ordersPriceInCentsTimeSeries.getDataItem(i);
        int value = dataItem.getValue().intValue();
        // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing
        int value1 = Math.min((int) (value * 1.05 / 2), value);

        {
            // simulate srv2 restart
            DateTime currentDate = new DateTime(dataItem.getPeriod().getStart());
            boolean shouldResetValue2 = resetValue2ToZeroOffset == 0
                    && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear();
            if (shouldResetValue2) {
                resetValue2ToZeroOffset = value - value1;
                System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate);
            }
        }

        int value2 = value - value1 - resetValue2ToZeroOffset;
        // System.out.println("value=" + value + ", value1=" + value1 + ", value2=" + value2);
        ordersPriceInCentsSrv1TimeSeries.add(dataItem.getPeriod(), value1);
        ordersPriceInCentsSrv2TimeSeries.add(dataItem.getPeriod(), value2);
    }

    TimeSeries orderItemsCountTimeSeries = new TimeSeries("shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrderItemsCount");

    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        RegularTimePeriod period = ordersPriceInCentsTimeSeries.getDataItem(i).getPeriod();
        int ordersPriceInCents1 = ordersPriceInCentsSrv1TimeSeries.getDataItem(i).getValue().intValue();
        int ordersPriceInCents2 = ordersPriceInCentsSrv2TimeSeries.getDataItem(i).getValue().intValue();

        int value1 = ordersPriceInCents1 / 600;
        int value2 = ordersPriceInCents2 / 600;

        orderItemsCountTimeSeries.add(period, value1 + value2);
        orderItemsCountSrv1TimeSeries.add(period, value1);
        orderItemsCountSrv2TimeSeries.add(period, value2);

    }

    exportMetrics(ordersPriceInCentsTimeSeries, ordersPriceInCentsSrv1TimeSeries,
            ordersPriceInCentsSrv2TimeSeries, ordersPriceInCentsTimeSeries, orderItemsCountTimeSeries,
            orderItemsCountSrv1TimeSeries, orderItemsCountSrv2TimeSeries);

    TimeSeries activeSrv1Visitors = new TimeSeries("srv1.visitors.currentActive");
    TimeSeries activeSrv2Visitors = new TimeSeries("srv1.visitors.currentActive");

}

From source file:org.jruby.ext.date.RubyDate.java

License:LGPL

private void adjustWithDayFraction(ThreadContext context, DateTime dt, final long[] rest) {
    final RubyFixnum zero = RubyFixnum.zero(context.runtime);
    int ival;/* ww w .  j  a va 2  s  .co  m*/

    ival = RubyDateTime.getHour(context, zero, rest);
    dt = dt.plusHours(ival);

    if (rest[0] != 0) {
        ival = RubyDateTime.getMinute(context, zero, rest);
        dt = dt.plusMinutes(ival);

        if (rest[0] != 0) {
            ival = RubyDateTime.getSecond(context, zero, rest);
            dt = dt.plusSeconds(ival);

            final long r0 = rest[0], r1 = rest[1];
            if (r0 != 0) {
                long millis = (1000 * r0) / r1;
                dt = dt.plusMillis((int) millis);

                subMillisNum = ((1000 * r0) - (millis * r1));
                subMillisDen = r1;
                normalizeSubMillis();
            }
        }
    }

    this.dt = dt;
}

From source file:org.kairosdb.util.Util.java

License:Apache License

/**
 Computes the duration of the sampling (value * unit) starting at timestamp.
        /*from ww  w.  j a va 2 s .c  o  m*/
 @param timestamp unix timestamp of the start time.
 @return the duration of the sampling in millisecond.
 */
public static long getSamplingDuration(long timestamp, Sampling sampling, DateTimeZone timeZone) {
    long ret = sampling.getValue();
    DateTime dt = new DateTime(timestamp, timeZone);
    switch (sampling.getUnit()) {
    case YEARS:
        ret = new org.joda.time.Duration(dt, dt.plusYears((int) sampling.getValue())).getMillis();
        break;
    case MONTHS:
        ret = new org.joda.time.Duration(dt, dt.plusMonths((int) sampling.getValue())).getMillis();
        break;
    case WEEKS:
        ret = new org.joda.time.Duration(dt, dt.plusWeeks((int) sampling.getValue())).getMillis();
        break;
    case DAYS:
        ret = new org.joda.time.Duration(dt, dt.plusDays((int) sampling.getValue())).getMillis();
        break;
    case HOURS:
        ret = new org.joda.time.Duration(dt, dt.plusHours((int) sampling.getValue())).getMillis();
        break;
    case MINUTES:
        ret = new org.joda.time.Duration(dt, dt.plusMinutes((int) sampling.getValue())).getMillis();
        break;
    case SECONDS:
        ret = new org.joda.time.Duration(dt, dt.plusSeconds((int) sampling.getValue())).getMillis();
        break;
    case MILLISECONDS:
        ret = (long) sampling.getValue();
        break;
    }
    return ret;
}

From source file:org.kitesdk.apps.spi.oozie.CronConverter.java

License:Apache License

public static Instant nextInstant(String cronSchedule, Instant current) {

    DateTime currentTime = new DateTime(current, DateTimeZone.UTC).withSecondOfMinute(0).withMillisOfSecond(0);

    validate(cronSchedule);/*from   w  w w . j a v a 2  s . com*/

    String[] splits = cronSchedule.split(" ");

    String minutePart = splits[0];
    String hourPart = splits[1];
    String dayPart = splits[2];

    // TODO: fold these together like the hour.
    if (isWildCard(minutePart)) {
        return currentTime.plusMinutes(1).toInstant();
    }

    if (isInterval(minutePart)) {

        // Roll minutes forward until we hit a start time
        // that matches the cron interval.
        int interval = getInterval(minutePart);

        DateTime next = currentTime.withSecondOfMinute(0).plusMinutes(1);

        while (!(next.getMinuteOfHour() % interval == 0)) {

            next = next.plusMinutes(1);
        }

        return next.toInstant();
    }

    assert (isConstant(minutePart));

    // The minute part must be a constant, so
    // simply get the value.
    int minute = Integer.parseInt(minutePart);

    // The schedule is based on hours.
    if (!isConstant(hourPart)) {

        int hourModulus = isWildCard(hourPart) ? 1 : getInterval(hourPart);

        DateTime next = currentTime.withMinuteOfHour(minute);

        while (next.isBefore(current) || !(next.getHourOfDay() % hourModulus == 0)) {

            next = next.plusHours(1);
        }

        return next.toInstant();
    }

    int hour = Integer.parseInt(hourPart);

    // The schedule is based on days, and therfore the day cannot
    // be a constant. This is is checked in validation as well.
    assert (!isConstant(dayPart));

    DateTime next = currentTime.withMinuteOfHour(minute).withHourOfDay(hour);

    while (next.isBefore(current)) {

        next = next.plusDays(1);
    }

    return next.toInstant();
}