Example usage for org.joda.time Instant compareTo

List of usage examples for org.joda.time Instant compareTo

Introduction

In this page you can find the example usage for org.joda.time Instant compareTo.

Prototype

public int compareTo(ReadableInstant other) 

Source Link

Document

Compares this object with the specified object for ascending millisecond instant order.

Usage

From source file:com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsAndCombineDoFn.java

License:Apache License

@Override
public void processElement(ProcessContext c) throws Exception {
    final K key = c.element().getKey();
    Iterator<WindowedValue<InputT>> iterator = c.element().getValue().iterator();

    final PriorityQueue<W> liveWindows = new PriorityQueue<>(11, new Comparator<BoundedWindow>() {
        @Override/*from w  w w .j  av  a  2  s .  com*/
        public int compare(BoundedWindow w1, BoundedWindow w2) {
            return Long.signum(w1.maxTimestamp().getMillis() - w2.maxTimestamp().getMillis());
        }
    });

    final Map<W, AccumT> accumulators = Maps.newHashMap();
    final Map<W, Instant> minTimestamps = Maps.newHashMap();

    WindowFn<Object, W>.MergeContext mergeContext = new CombiningMergeContext() {
        @Override
        public Collection<W> windows() {
            return liveWindows;
        }

        @Override
        public void merge(Collection<W> toBeMerged, W mergeResult) throws Exception {
            List<AccumT> accumsToBeMerged = new ArrayList<>(toBeMerged.size());
            Instant minTimestamp = null;
            for (W window : toBeMerged) {
                accumsToBeMerged.add(accumulators.remove(window));

                Instant timestampToBeMerged = minTimestamps.remove(window);
                if (minTimestamp == null
                        || (timestampToBeMerged != null && timestampToBeMerged.isBefore(minTimestamp))) {
                    minTimestamp = timestampToBeMerged;
                }
            }
            liveWindows.removeAll(toBeMerged);

            minTimestamps.put(mergeResult, minTimestamp);
            liveWindows.add(mergeResult);
            accumulators.put(mergeResult, combineFn.mergeAccumulators(key, accumsToBeMerged));
        }
    };

    while (iterator.hasNext()) {
        WindowedValue<InputT> e = iterator.next();

        @SuppressWarnings("unchecked")
        Collection<W> windows = (Collection<W>) e.getWindows();
        for (W w : windows) {
            Instant timestamp = minTimestamps.get(w);
            if (timestamp == null || timestamp.compareTo(e.getTimestamp()) > 0) {
                minTimestamps.put(w, e.getTimestamp());
            } else {
                minTimestamps.put(w, timestamp);
            }

            AccumT accum = accumulators.get(w);
            checkState((timestamp == null && accum == null) || (timestamp != null && accum != null));
            if (accum == null) {
                accum = combineFn.createAccumulator(key);
                liveWindows.add(w);
            }
            accum = combineFn.addInput(key, accum, e.getValue());
            accumulators.put(w, accum);
        }

        windowFn.mergeWindows(mergeContext);

        while (!liveWindows.isEmpty() && liveWindows.peek().maxTimestamp().isBefore(e.getTimestamp())) {
            closeWindow(key, liveWindows.poll(), accumulators, minTimestamps, c);
        }
    }

    // To have gotten here, we've either not had any elements added, or we've only run merge
    // and then closed windows. We don't need to retry merging.
    while (!liveWindows.isEmpty()) {
        closeWindow(key, liveWindows.poll(), accumulators, minTimestamps, c);
    }
}

From source file:com.mailrest.maildal.secur.DefaultTokenManager.java

License:Apache License

@Override
public T fromJwt(String jwt) {

    if (jwt == null || jwt.isEmpty()) {
        throw new IllegalArgumentException("empty token");
    }//ww  w.  ja  va  2 s  .  c o m

    JsonToken jsonToken;
    try {
        jsonToken = parser.verifyAndDeserialize(jwt);
    } catch (IllegalStateException | JsonParseException | SignatureException e) {
        throw new InvalidTokenException("wrong token format", e);
    }

    JsonObject payload = jsonToken.getPayloadAsJsonObject();

    // System.out.println(payload);

    String issuer = payload.getAsJsonPrimitive("iss").getAsString();
    if (!ISSUER.equals(issuer)) {
        throw new InvalidTokenException("invalid issuer");
    }

    Instant currentTime = new Instant(System.currentTimeMillis());

    Instant issuedTime = jsonToken.getIssuedAt();
    Instant expiresTime = jsonToken.getExpiration();

    if (issuedTime == null) {
        throw new InvalidTokenException("empty issuedTime");
    }

    if (expiresTime == null) {
        throw new InvalidTokenException("empty expiresTime");
    }

    if (currentTime.compareTo(issuedTime) >= 0 && currentTime.compareTo(expiresTime) <= 0) {

        T tokenObj = instance.newInstance();
        tokenObj.readJson(payload);

        String error = tokenObj.verifyObj();
        if (error != null) {
            throw new InvalidTokenException("token validation failed: " + error);
        }

        return tokenObj;

    } else {
        throw new InvalidTokenException("expired token");
    }

}

From source file:io.coala.time.Duration.java

License:Apache License

/**
 * @param i1/*from   w  ww . ja  va 2  s  .c o m*/
 * @param i2
 * @return the absolute distance/duration between two {@link Instant}s
 */
public static Duration between(final Instant i1, final Instant i2) {
    return i1.compareTo(i2) > 0 ? i1.subtract(i2) : i2.subtract(i1);
}

From source file:org.joda.example.time.Examples.java

License:Apache License

private void runInstant() {
    System.out.println("Instant");
    System.out.println("=======");
    System.out/*  w  w  w .j  av a2  s. com*/
            .println("Instant stores a point in the datetime continuum as millisecs from 1970-01-01T00:00:00Z");
    System.out.println("Instant is immutable and thread-safe");
    System.out.println("                      in = new Instant()");
    Instant in = new Instant();
    System.out.println("Millisecond time:     in.getMillis():           " + in.getMillis());
    System.out.println("ISO string version:   in.toString():            " + in.toString());
    System.out.println("ISO chronology:       in.getChronology():       " + in.getChronology());
    System.out.println("UTC time zone:        in.getDateTimeZone():     " + in.getZone());
    System.out.println("Change millis:        in.withMillis(0):         " + in.withMillis(0L));
    System.out.println("");
    System.out.println("Convert to Instant:   in.toInstant():           " + in.toInstant());
    System.out.println("Convert to DateTime:  in.toDateTime():          " + in.toDateTime());
    System.out.println("Convert to MutableDT: in.toMutableDateTime():   " + in.toMutableDateTime());
    System.out.println("Convert to Date:      in.toDate():              " + in.toDate());
    System.out.println("");
    System.out.println("                      in2 = new Instant(in.getMillis() + 10)");
    Instant in2 = new Instant(in.getMillis() + 10);
    System.out.println("Equals ms and chrono: in.equals(in2):           " + in.equals(in2));
    System.out.println("Compare millisecond:  in.compareTo(in2):        " + in.compareTo(in2));
    System.out.println("Compare millisecond:  in.isEqual(in2):          " + in.isEqual(in2));
    System.out.println("Compare millisecond:  in.isAfter(in2):          " + in.isAfter(in2));
    System.out.println("Compare millisecond:  in.isBefore(in2):         " + in.isBefore(in2));
}