Example usage for org.joda.time DateTime plusSeconds

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

Introduction

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

Prototype

public DateTime plusSeconds(int seconds) 

Source Link

Document

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

Usage

From source file:com.mapcode.services.implementation.RootResourceImpl.java

License:Apache License

private static void waitForResponse(@Nonnull final TestAsyncResponse asyncResponse)
        throws InterruptedException {
    final int sleepMillis = 100; // No more than 10 reqs/sec.
    final DateTime now = UTCTime.now();
    final DateTime until = now.plusSeconds(10); // Wait at most 10 seconds.
    while (now.isBefore(until)) {
        if (asyncResponse.isReady()) {
            if (asyncResponse.getResponse() != null) { // If the object is null, retry.

                // All OK.
                return;
            }/* w w  w  . ja  va2 s  . c  o m*/
        }
        //noinspection BusyWait
        Thread.sleep(sleepMillis);
    }
    throw new IllegalStateException("Did not receive a response");
}

From source file:com.mycompany.alarmdatasimulator.simulation.SimulationCore.java

public boolean simulate(Map<Alarm, Map<Alarm, CausalRelation>> relations) {
    for (Map.Entry<Alarm, Map<Alarm, CausalRelation>> entry : relations.entrySet()) {
        Alarm alarm = entry.getKey();/* w  w  w .  ja  va 2 s  . c o m*/
        Map<Alarm, CausalRelation> relation = entry.getValue();
        Float probability = alarm.getOcourrenceProbability();
        Long duration = alarm.getDuration();
        Long erro = alarm.getError();
        for (int i = 0; i < period.getStandardSeconds(); i++) {
            Float pvalue = (float) random(100, 0);
            if (probability >= pvalue) {
                double p = random(2, 1);
                Long realDuration = duration + Math.round(p * erro);
                DateTime initOcourr = initial.plusSeconds(i);
                registrarOcourrence(alarm.getName(), initOcourr, realDuration);

                for (Map.Entry<Alarm, CausalRelation> entry1 : relation.entrySet()) {
                    Alarm alarm1 = entry1.getKey();
                    CausalRelation causal = entry1.getValue();
                    Float causalProbability = causal.getProbability();
                    Long duration1 = alarm1.getDuration();
                    Long erro1 = alarm1.getError();
                    pvalue = (float) random(100, 0);
                    if (causalProbability >= pvalue) {
                        Long lag = causal.getLag();
                        Long lagErro = causal.getErro();
                        p = random(2, 1);
                        Long realLag = lag + Math.round(p * lagErro);
                        p = random(2, 1);
                        realDuration = duration1 + Math.round(p * erro1);
                        registrarOcourrence(alarm1.getName(), initOcourr.plusSeconds(realLag.intValue()),
                                realDuration);
                    }
                }
                i = i + realDuration.intValue();
            }
        }
    }
    return true;
}

From source file:com.mycompany.alarmdatasimulator.simulation.SimulationCore.java

private void registrarOcourrence(String name, DateTime init, Long duration) {
    String format = "dd-MM-yyyy HH:mm:ss.SSS";
    String initStr = init.toString(format);
    String endStr = init.plusSeconds(duration.intValue()).toString(format);
    String durationStr = duration.toString();
    table.addOcourrence(name, initStr, endStr, durationStr);
}

From source file:com.ning.arecibo.collector.persistent.TimelineLoadGenerator.java

License:Apache License

/**
 * This method simulates adding a ton of timelines, in more-or-less the way they would be added in real life.
 *///w w w.ja  va2  s .c  o  m
private void insertManyTimelines() throws Exception {
    final List<TimelineChunk> timelineChunkList = new ArrayList<TimelineChunk>();
    DateTime startTime = new DateTime().minusDays(1);
    DateTime endTime = startTime.plusHours(1);
    final int sampleCount = 120; // 1 hours worth
    for (int i = 0; i < 12; i++) {
        for (int hostId : hostIds) {
            for (int categoryId : categoriesForHostId.get(hostId)) {
                final List<DateTime> dateTimes = new ArrayList<DateTime>(sampleCount);
                for (int sc = 0; sc < sampleCount; sc++) {
                    dateTimes.add(startTime.plusSeconds(sc * 30));
                }
                final byte[] timeBytes = timelineCoder.compressDateTimes(dateTimes);
                for (int sampleKindId : categorySampleKindIds.get(categoryId)) {
                    final TimelineChunk timelineChunk = makeTimelineChunk(hostId, sampleKindId, startTime,
                            endTime, timeBytes, sampleCount);
                    addChunkAndMaybeSave(timelineChunkList, timelineChunk);

                }
            }
        }
        if (timelineChunkList.size() > 0) {
            defaultTimelineDAO.bulkInsertTimelineChunks(timelineChunkList);
        }
        log.info("After hour %d, inserted %d TimelineChunk rows", i, timelineChunkIdCounter.get());
        startTime = endTime;
        endTime = endTime.plusHours(1);
    }
}

From source file:com.ning.billing.meter.timeline.TimelineLoadGenerator.java

License:Apache License

/**
 * This method simulates adding a ton of timelines, in more-or-less the way they would be added in real life.
 *//*from w ww  . j  av a2s .c om*/
private void insertManyTimelines() throws Exception {
    final List<TimelineChunk> timelineChunkList = new ArrayList<TimelineChunk>();
    DateTime startTime = new DateTime().minusDays(1);
    DateTime endTime = startTime.plusHours(1);
    final int sampleCount = 120; // 1 hours worth
    for (int i = 0; i < 12; i++) {
        for (final int hostId : hostIds) {
            for (final int categoryId : categoriesForHostId.get(hostId)) {
                final List<DateTime> dateTimes = new ArrayList<DateTime>(sampleCount);
                for (int sc = 0; sc < sampleCount; sc++) {
                    dateTimes.add(startTime.plusSeconds(sc * 30));
                }
                final byte[] timeBytes = timelineCoder.compressDateTimes(dateTimes);
                for (final int sampleKindId : categorySampleKindIds.get(categoryId)) {
                    final TimelineChunk timelineChunk = makeTimelineChunk(hostId, sampleKindId, startTime,
                            endTime, timeBytes, sampleCount);
                    addChunkAndMaybeSave(timelineChunkList, timelineChunk);

                }
            }
        }
        if (timelineChunkList.size() > 0) {
            defaultTimelineDAO.bulkInsertTimelineChunks(timelineChunkList, internalCallContext);
        }
        log.info("After hour %d, inserted %d TimelineChunk rows", i, timelineChunkIdCounter.get());
        startTime = endTime;
        endTime = endTime.plusHours(1);
    }
}

From source file:com.onboard.service.account.impl.InvitationManager.java

License:Apache License

public boolean isInvitationExpired(Invitation invitation) {
    DateTime created = new DateTime(invitation.getCreated());
    return created.plusSeconds(configurer.getTokenExpired()).isBeforeNow();
}

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

License:Apache License

public static DateTime addSeconds(DateTime date, int seconds) {
    if (Objects.nonNull(date)) {
        return date.plusSeconds(seconds);
    } else {/*from   www.  j a  va2 s.  c  o m*/
        return null;
    }
}

From source file:com.precioustech.fxtrading.oanda.restapi.marketdata.historic.OandaHistoricMarketDataProvider.java

License:Apache License

@Override
public List<CandleStick<String>> getCandleSticks(TradeableInstrument<String> instrument,
        CandleStickGranularity granularity, DateTime from, DateTime to) {
    try {//from   w w  w . j  av  a 2  s.  c om
        return getCandleSticks(instrument, getFromToUrl(instrument, granularity, from, to), granularity);
    } catch (OandaLimitExceededException leex) {
        try {
            List<CandleStick<String>> allCandles = Lists.newArrayList();
            allCandles = getCandleSticks(instrument,
                    getFromCountUrl(instrument, granularity, from, MAX_CANDLES_COUNT), granularity);
            DateTime lastDate = allCandles.get(allCandles.size() - 1).getEventDate();
            long batchesReqd = (to.getMillis() - lastDate.getMillis())
                    / (lastDate.getMillis() - from.getMillis()) + 1;

            DateTime start = lastDate.plusSeconds((int) granularity.getGranularityInSeconds());

            for (long batch = 1; batch <= batchesReqd; batch++) {
                List<CandleStick<String>> batchCandles = null;
                if (batch == batchesReqd && start.isBefore(to)) {
                    batchCandles = getCandleSticks(instrument, getFromToUrl(instrument, granularity, start, to),
                            granularity);
                } else {
                    batchCandles = getCandleSticks(instrument,
                            getFromCountUrl(instrument, granularity, start, MAX_CANDLES_COUNT), granularity);
                }
                if (batchCandles == null || batchCandles.isEmpty()) {
                    break;
                }
                start = batchCandles.get(batchCandles.size() - 1).getEventDate()
                        .plusSeconds((int) granularity.getGranularityInSeconds());
                allCandles.addAll(batchCandles);
            }

            return allCandles;
        } catch (OandaLimitExceededException e) {
            LOG.error("limit exceedeed error encountered again", e);
        }
        return Collections.emptyList();
    }
}

From source file:com.quinsoft.zeidon.domains.DateTimeDomain.java

License:Open Source License

private Object addWithContext(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef,
        Object currentValue, Object operand, String contextName) {
    assert !StringUtils.isBlank(contextName);

    if (operand instanceof AttributeInstance)
        operand = ((AttributeInstance) operand).getValue();

    if (!(operand instanceof Integer) && !(operand instanceof Long)) {
        throw new ZeidonException(
                "When adding to DateTime with a context, operand must be integer or long value.  "
                        + "Type of operand = %s",
                operand.getClass().getName()).prependAttributeDef(attributeDef);
    }//from  w  w  w  .j  ava 2  s  . c  om

    int value = ((Number) operand).intValue();
    DateTime dt = (DateTime) currentValue;

    switch (contextName.toLowerCase()) {
    case "day":
    case "days":
        return dt.plusDays(value);

    case "hour":
    case "hours":
        return dt.plusHours(value);

    case "minute":
    case "minutes":
        return dt.plusMinutes(value);

    case "milli":
    case "millis":
    case "millisecond":
    case "milliseconds":
        return dt.plus(((Number) operand).longValue());

    case "month":
    case "months":
        return dt.plusMonths(value);

    case "second":
    case "seconds":
        return dt.plusSeconds(value);

    case "week":
    case "weeks":
        return dt.plusWeeks(value);

    case "year":
    case "years":
        return dt.plusYears(value);
    }

    // TODO Auto-generated method stub
    throw new ZeidonException("Unknown context name '%s' for DateTime domain", contextName)
            .prependAttributeDef(attributeDef);
}

From source file:com.talvish.tales.contracts.services.http.HttpResult.java

License:Apache License

/**
 * A convenience method that sets the to enable caching up to a particular date 
 * and a particular set of options./*from   www .  j  a v  a 2 s.  c  om*/
 * @param theMaxAge the maximum age of the result in seconds
 * @param theOptions the options to use for the caching
 * @return returns itself so that calls can be chained together
 */
@SuppressWarnings("unchecked")
public T setCachingEnabled(int theMaxAge, String[] theOptions) {
    Preconditions.checkArgument(theMaxAge >= 0, "need a max-age greater than or equal to zero");

    DateTime dateTimeNow = new DateTime(DateTimeZone.UTC);
    DateTime dateTimeExpired = dateTimeNow.plusSeconds(theMaxAge);

    StringBuilder value = new StringBuilder(HeaderConstants.CACHE_CONTROL_MAX_AGE_DIRECTIVE);
    value.append("=");
    value.append(theMaxAge);
    for (String option : theOptions) {
        value.append(", ");
        value.append(option);
    }

    // we put the date header so relative time can be calculated and as outlined
    // for origin-servers according to RFC2616
    headers.put(HeaderConstants.DATE_HEADER, RFC_1123_DATE_FORMATTER.print(dateTimeNow));
    // now we put in HTTP 1.1 headers
    headers.put(HeaderConstants.CACHE_CONTROL, value.toString());
    // and then the older HTTP 1.0 header, just in case
    headers.put(HeaderConstants.EXPIRES, RFC_1123_DATE_FORMATTER.print(dateTimeExpired));
    // and remove pragma, to ensure no conflict
    headers.remove(HeaderConstants.PRAGMA);
    return (T) this;
}