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:org.locationtech.geomesa.examples.KafkaQuickStart.java

License:Open Source License

public static void addSimpleFeatures(SimpleFeatureType sft, FeatureStore producerFS)
        throws InterruptedException, IOException {
    final int MIN_X = -180;
    final int MAX_X = 180;
    final int MIN_Y = -90;
    final int MAX_Y = 90;
    final int DX = 2;
    final int DY = 1;
    final String[] PEOPLE_NAMES = { "James", "John", "Peter", "Hannah", "Claire", "Gabriel" };
    final long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L;
    final Random random = new Random();
    final DateTime MIN_DATE = new DateTime(2015, 1, 1, 0, 0, 0, DateTimeZone.forID("UTC"));

    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    // creates and updates two SimpleFeatures.
    // the first time this for loop runs the two SimpleFeatures are created.
    // in the subsequent iterations of the for loop, the two SimpleFeatures are updated.
    int numFeatures = (MAX_X - MIN_X) / DX;
    for (int i = 1; i <= numFeatures; i++) {
        builder.add(PEOPLE_NAMES[i % PEOPLE_NAMES.length]); // name
        builder.add((int) Math.round(random.nextDouble() * 110)); // age
        builder.add(MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR)).toDate()); // dtg
        builder.add(WKTUtils$.MODULE$.read("POINT(" + (MIN_X + DX * i) + " " + (MIN_Y + DY * i) + ")")); // geom
        SimpleFeature feature1 = builder.buildFeature("1");

        builder.add(PEOPLE_NAMES[(i + 1) % PEOPLE_NAMES.length]); // name
        builder.add((int) Math.round(random.nextDouble() * 110)); // age
        builder.add(MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR)).toDate()); // dtg
        builder.add(WKTUtils$.MODULE$.read("POINT(" + (MIN_X + DX * i) + " " + (MAX_Y - DY * i) + ")")); // geom
        SimpleFeature feature2 = builder.buildFeature("2");

        // write the SimpleFeatures to Kafka
        featureCollection.add(feature1);
        featureCollection.add(feature2);
        producerFS.addFeatures(featureCollection);
        featureCollection.clear();//from w  w  w . j a  va  2  s  . co  m

        // wait 200 ms in between updating SimpleFeatures to simulate a stream of data
        Thread.sleep(200);
    }
}

From source file:org.mobicents.servlet.restcomm.entities.Registration.java

License:Open Source License

public Registration setTimeToLive(final int timeToLive) {
    final DateTime now = DateTime.now();
    return new Registration(sid, dateCreated, now, now.plusSeconds(timeToLive), addressOfRecord, displayName,
            userName, userAgent, timeToLive, location, webrtc);
}

From source file:org.mobicents.servlet.restcomm.telephony.proxy.ProxyManager.java

License:Open Source License

private void refresh() {
    final GatewaysDao gateways = storage.getGatewaysDao();
    final List<Gateway> results = gateways.getGateways();
    for (final Gateway result : results) {
        final DateTime lastUpdate = result.getDateUpdated();
        final DateTime expires = lastUpdate.plusSeconds(result.getTimeToLive());
        if (expires.isBeforeNow() || expires.isEqualNow()) {
            register(result);//w ww  .ja  v a 2 s. co  m
        }
    }
}

From source file:org.n52.iceland.util.DateTimeHelper.java

License:Open Source License

/**
 * Set the time object to the end values (seconds, minutes, hours, days,..)
 * if the time Object has not all values
 *
 * @param dateTime//from  www  .ja v a2s . c o m
 *            Time object
 * @param isoTimeLength
 *            Length of the time object
 * @return Modified time object.
 */
public static DateTime setDateTime2EndOfMostPreciseUnit4RequestedEndPosition(final DateTime dateTime,
        final int isoTimeLength) {
    switch (isoTimeLength) {
    // year
    case YEAR:
        return dateTime.plusYears(ONE_VALUE).minusMillis(ONE_VALUE);
    // year, month
    case YEAR_MONTH:
        return dateTime.plusMonths(ONE_VALUE).minusMillis(ONE_VALUE);
    // year, month, day
    case YEAR_MONTH_DAY:
        return dateTime.plusDays(ONE_VALUE).minusMillis(ONE_VALUE);
    // year, month, day, hour
    case YEAR_MONTH_DAY_HOUR:
        return dateTime.plusHours(ONE_VALUE).minusMillis(ONE_VALUE);
    // year, month, day, hour, minute
    case YEAR_MONTH_DAY_HOUR_MINUTE:
        return dateTime.plusMinutes(ONE_VALUE).minusMillis(ONE_VALUE);
    // year, month, day, hour, minute, second
    case YEAR_MONTH_DAY_HOUR_MINUTE_SECOND:
        return dateTime.plusSeconds(ONE_VALUE).minusMillis(ONE_VALUE);
    default:
        return dateTime;
    }
}

From source file:org.n52.shetland.util.DateTimeHelper.java

License:Apache License

/**
 * Set the time object to the end values (seconds, minutes, hours, days,..)
 * if the time Object has not all values
 *
 * @param dateTime//w w w.  j av a2  s.c o  m
 *            Time object
 * @param isoTimeLength
 *            Length of the time object
 * @return Modified time object.
 */
public static DateTime setDateTime2EndOfMostPreciseUnit4RequestedEndPosition(DateTime dateTime,
        int isoTimeLength) {
    switch (isoTimeLength) {
    case YEAR:
        return dateTime.plusYears(1).minusMillis(1);
    case YEAR_MONTH:
        return dateTime.plusMonths(1).minusMillis(1);
    case YEAR_MONTH_DAY:
        return dateTime.plusDays(1).minusMillis(1);
    case YEAR_MONTH_DAY_HOUR:
        return dateTime.plusHours(1).minusMillis(1);
    case YEAR_MONTH_DAY_HOUR_MINUTE:
        return dateTime.plusMinutes(1).minusMillis(1);
    case YEAR_MONTH_DAY_HOUR_MINUTE_SECOND:
        return dateTime.plusSeconds(1).minusMillis(1);
    default:
        return dateTime;
    }
}

From source file:org.nfsdb.examples.append.MergeAppendUnordered.java

License:Apache License

/**
 * For cases where incoming data feed is not in chronological order but you would like your journal to be in chronological order.
 * This is a lossy way to append data as journal would only be merging a slice of data as specified by "lag" attribute.
 *
 * @param args factory directory// w  ww.j  a v a2 s .  c  o  m
 * @throws JournalException
 */
public static void main(String[] args) throws JournalException {

    if (args.length != 1) {
        System.out.println("Usage: " + MergeAppendUnordered.class.getName() + " <path>");
        System.exit(1);
    }

    String journalLocation = args[0];

    try (JournalFactory factory = new JournalFactory(new JournalConfigurationBuilder() {
        {
            $(Quote.class).location("quote-lag").lag(24, TimeUnit.HOURS) // enable lag
                    .$ts() // tell factory that Quote has "timestamp" column. If column is called differently you can pass its name
            ;
        }
    }.build(journalLocation))) {

        // delete existing quote journal
        Files.delete(new File(factory.getConfiguration().getJournalBase(), "quote-lag"));

        try (JournalWriter<Quote> writer = factory.writer(Quote.class)) {

            final String symbols[] = { "AGK.L", "BP.L", "TLW.L", "ABF.L", "LLOY.L", "BT-A.L", "WTB.L", "RRS.L",
                    "ADM.L", "GKN.L", "HSBA.L" };
            final Random r = new Random(System.currentTimeMillis());

            // 20 batches of 50,000 quotes, total 1,000,000
            final int batchCount = 20;
            final int batchSize = 50000;
            final ArrayList<Quote> batch = new ArrayList<>(batchSize);
            // have pre-initialized array to reduce GC overhead
            for (int i = 0; i < batchSize; i++) {
                batch.add(new Quote());
            }

            DateTime utc = Dates.utc();

            long t = System.nanoTime();
            for (int i = 0; i < batchCount; i++) {

                // populate batch in-memory
                for (int k = 0; k < batchSize; k++) {
                    Quote q = batch.get(k);
                    q.clear();
                    // generate some data
                    q.setSym(symbols[Math.abs(r.nextInt() % (symbols.length - 1))]);
                    q.setAsk(Math.abs(r.nextDouble()));
                    q.setBid(Math.abs(r.nextDouble()));
                    q.setAskSize(Math.abs(r.nextInt() % 10000));
                    q.setBidSize(Math.abs(r.nextInt() % 10000));
                    q.setEx("LXE");
                    q.setMode("Fast trading");
                    long timestamp = utc.plusSeconds(i * batchSize + (batchSize - k)).getMillis();
                    // make batches overlap (subtract 10 seconds)
                    timestamp -= 100000000L;
                    q.setTimestamp(timestamp);
                }

                // batch must be sorted before being presented to writer
                Collections.sort(batch, writer.getTimestampComparator());

                // append batch and have journal merge data
                writer.mergeAppend(batch);
            }

            // commit is necessary
            writer.commit();
            System.out.println("Journal size: " + writer.size());
            System.out.println("Generated " + batchCount * batchSize + " objects in "
                    + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t) + "ms.");
        }
    }
}

From source file:org.nimbustools.messaging.query.security.QueryAuthenticationFilter.java

License:Apache License

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    final String accessId = getAtMostOneParameter(request, this.accessIdParameter);
    if (accessId == null || accessId.length() == 0) {
        throw new QueryException(QueryError.MissingClientTokenId);
    }/* w  w w  . ja va2s  . c o  m*/

    final String signature = getExactlyOneParameter(request, this.signatureParameter);
    final String signatureVersion = getExactlyOneParameter(request, this.signatureVersionParameter);

    // Note that signature version 1 has known vulnerabilities when used across plain
    // HTTP. This interface should only be offered over SSL.
    // see http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1928
    //
    // if another version comes along, this library will need to be updated

    if (!(SIGNATURE_VERSION_2.equals(signatureVersion) || SIGNATURE_VERSION_1.equals(signatureVersion))) {
        throw new QueryException(QueryError.InvalidParameterValue,
                "Only signature versions 1 and 2 are supported");
    }

    String signatureMethod = getAtMostOneParameter(request, this.signatureMethodParameter);
    if (signatureMethod != null) {
        if (!(signatureMethod.equals(HMACSHA256) || signatureMethod.equals(HMACSHA1))) {
            throw new QueryException(QueryError.InvalidParameterValue,
                    "Only " + HMACSHA256 + " or " + HMACSHA1 + " are supported signature methods");
        }
    } else {
        signatureMethod = HMACSHA1;
    }

    final String timestamp = getAtMostOneParameter(request, this.timestampParameter);
    final String expires = getAtMostOneParameter(request, this.expiresParameter);

    final boolean hasTimestamp = timestamp != null;
    final boolean hasExpires = expires != null;
    if (hasTimestamp == hasExpires) {
        throw new QueryException(QueryError.InvalidArgument,
                "Request must have timestamp or expiration, but not both");
    }

    final QueryUser user;
    try {
        user = userDetailsService.loadUserByUsername(accessId);
    } catch (UsernameNotFoundException e) {
        throw new QueryException(QueryError.InvalidClientTokenId, e);
    } catch (DataAccessException e) {
        throw new QueryException(QueryError.InternalError,
                "Failed to retrieve user token for provided accessID", e);
    }
    final String secret = user.getSecret();

    final String stringToSign;
    if (SIGNATURE_VERSION_2.equals(signatureVersion)) {
        stringToSign = getStringToSign_v2(request);
    } else {
        stringToSign = getStringToSign_v1(request);
    }

    final String checkSig = createSignature(stringToSign, secret, signatureMethod);

    // Note that this comparison will succeed if both inputs are null.
    // (But checkSig can't be null in this implementation)

    if (!QueryUtils.safeStringEquals(signature, checkSig)) {
        logger.warn("Signature check failed on request for accessID: " + accessId);
        throw new QueryException(QueryError.SignatureDoesNotMatch, "Signature check failed!");
    }

    // check for expiration of request-- replay attack prevention
    final DateTime expireTime;
    try {
        if (hasTimestamp) {

            // boto doesn't include the 'Z' in its timestamp
            // we force parsing to assume UTC

            final DateTime stamp = new DateTime(timestamp, DateTimeZone.UTC);
            expireTime = stamp.plusSeconds(this.expirationSeconds);
        } else {
            expireTime = new DateTime(expires, DateTimeZone.UTC);
        }
    } catch (IllegalArgumentException e) {
        throw new QueryException(QueryError.InvalidParameterValue, "Failed to parse "
                + (hasTimestamp ? "timestamp" : "expiration") + ". Must be in ISO8601 format.", e);
    }

    if (expireTime.isBeforeNow()) {
        throw new QueryException(QueryError.RequestExpired, "Request is expired");
    }

    final QueryAuthenticationToken auth = new QueryAuthenticationToken(user, true);

    // okay we have an authenticated request. set token on the SecurityContext
    SecurityContextHolder.getContext().setAuthentication(auth);

    // and continue along chain
    chain.doFilter(request, response);
}

From source file:org.nuxeo.elasticsearch.aggregate.DateHelper.java

License:Apache License

private static DateTime plusDurationAsExpression(DateTime origin, String duration) {
    int k = getFactor(duration);
    switch (duration.substring(duration.length() - 1, duration.length())) {
    case "s":
        return origin.plusSeconds(k);
    case "m":
        return origin.plusMinutes(k);
    case "h":
        return origin.plusHours(k);
    case "d":
        return origin.plusDays(k);
    case "w":
        return origin.plusWeeks(k);
    case "M":
        return origin.plusMonths(k);
    case "y":
        return origin.plusYears(k);
    }/*from   ww  w  . j  av a 2s. co  m*/
    return invalid(duration);
}

From source file:org.nuxeo.elasticsearch.aggregate.DateHelper.java

License:Apache License

private static DateTime plusDurationAsNoun(DateTime origin, String duration) {
    switch (duration.toLowerCase()) {
    case "second":
        return origin.plusSeconds(1);
    case "minute":
        return origin.plusMinutes(1);
    case "hour":
        return origin.plusHours(1);
    case "day":
        return origin.plusDays(1);
    case "week":
        return origin.plusWeeks(1);
    case "month":
        return origin.plusMonths(1);
    case "quarter":
        return origin.plusMonths(3);
    case "year":
        return origin.plusYears(1);
    }// ww  w .jav  a  2s .  com
    return invalid(duration);
}

From source file:org.ojbc.bundles.adapters.staticmock.samplegen.AbstractSampleGenerator.java

License:RPL License

/**
 * Generates a random, uniformly distributed time between the two specified date/times.
 * //from  w  ww  .j  a v  a2 s. co m
 * @param d1
 *            the first datetime
 * @param d2
 *            the second datetime
 * @return a random datetime between the two
 */
protected final DateTime generateUniformRandomTimeBetween(DateTime d1, DateTime d2) {
    DateTime start = d1;
    DateTime end = d2;
    if (d1.isAfter(d2)) {
        start = d2;
        end = d1;
    }
    int secondsBetween = Seconds.secondsBetween(start, end).getSeconds();
    int r = randomGenerator.nextInt(0, secondsBetween);
    return start.plusSeconds(r);
}