Example usage for org.joda.time Seconds secondsBetween

List of usage examples for org.joda.time Seconds secondsBetween

Introduction

In this page you can find the example usage for org.joda.time Seconds secondsBetween.

Prototype

public static Seconds secondsBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Seconds representing the number of whole seconds between the two specified partial datetimes.

Usage

From source file:com.rapidminer.operator.GenerateDateSeries.java

License:Open Source License

private long calculateNumberOfExample(DateTime startTime, DateTime endTime) {
    // TODO Auto-generated method stub
    long valuetoReturn = 0;
    try {/*from   w w w  .  j a va  2  s.  co m*/

        //getParameterAsString(key)

        switch (getParameterAsString(PARAMETER_INTERVALTYPE)) {

        case "YEAR":
            Years year = Years.yearsBetween(startTime, endTime);
            valuetoReturn = year.getYears() / getParameterAsInt(INTERVAL);
            break;
        case "MONTH":
            Months month = Months.monthsBetween(startTime, endTime);
            valuetoReturn = month.getMonths() / getParameterAsInt(INTERVAL);
            break;

        case "DAY":
            Days days = Days.daysBetween(startTime, endTime);
            valuetoReturn = days.getDays() / getParameterAsInt(INTERVAL);

            break;

        case "HOUR":
            Hours hours = Hours.hoursBetween(startTime, endTime);
            valuetoReturn = hours.getHours() / getParameterAsInt(INTERVAL);
            break;

        case "MINUTE":
            Minutes minute = Minutes.minutesBetween(startTime, endTime);
            valuetoReturn = minute.getMinutes() / getParameterAsInt(INTERVAL);
            break;
        case "SECOND":
            Seconds second = Seconds.secondsBetween(startTime, endTime);
            valuetoReturn = second.getSeconds() / getParameterAsInt(INTERVAL);
            break;
        case "MILLISECOND":
            // Milliseconds millisecond = milli
            long milli = endTime.getMillis() - startTime.getMillis();
            valuetoReturn = milli / getParameterAsInt(INTERVAL);

            break;
        default:
            valuetoReturn = 0;
        }

    } catch (Exception e) {
        valuetoReturn = 0;
    }

    return valuetoReturn;
}

From source file:com.sonicle.webtop.core.bol.model.SessionInfo.java

License:Open Source License

public SessionInfo(DateTime now, Session session, UserProfileId profileId, int pushSessionsCount) {
    this.sessionId = session.getId().toString();
    this.timeout = (session.getTimeout() < 0) ? -1 : (int) session.getTimeout() / 1000;
    this.creationTime = new DateTime(session.getStartTimestamp());
    this.lastAccessTime = new DateTime(session.getLastAccessTime());
    this.usedTime = Math.abs(Seconds.secondsBetween(creationTime, now).getSeconds());
    this.ttl = (timeout < 0) ? -1
            : timeout - Math.abs(Seconds.secondsBetween(lastAccessTime, now).getSeconds());
    this.profileId = profileId.toString();
    this.pushSessionsCount = pushSessionsCount;
}

From source file:com.sonicle.webtop.core.xmpp.XMPPClient.java

License:Open Source License

private boolean joinMuc(final MultiUserChat muc, final DateTime lastSeenActivity) {
    try {/*w  w  w  .j  a  v a  2s .  c  om*/
        logger.debug("Joining group chat [{}, {}]", muc.getRoom().toString(), lastSeenActivity);
        DiscussionHistory mucHistory = new DiscussionHistory();
        if (lastSeenActivity != null) {
            DateTime now = new DateTime(DateTimeZone.UTC);
            Seconds seconds = Seconds.secondsBetween(lastSeenActivity.withZone(DateTimeZone.UTC), now);
            mucHistory.setSeconds(Math.abs(seconds.getSeconds()));
        }
        muc.join(userNickname, null, mucHistory, SmackConfiguration.getDefaultReplyTimeout());
        return true;

    } catch (SmackException | XMPPException | InterruptedException ex) {
        logger.error("Error joining group chat", ex);
        return false;
    }
}

From source file:com.spotify.reaper.service.SegmentRunner.java

License:Apache License

private void runRepair() {
    LOG.debug("Run repair for segment #{}", segmentId);
    final RepairSegment segment = context.storage.getRepairSegment(segmentId).get();
    try (JmxProxy coordinator = context.jmxConnectionFactory.connectAny(Optional.<RepairStatusHandler>of(this),
            potentialCoordinators)) {//from  ww  w . ja v a  2  s  .c o  m

        if (segmentRunners.containsKey(segmentId)) {
            LOG.error("SegmentRunner already exists for segment with ID: " + segmentId);
            throw new ReaperException("SegmentRunner already exists for segment with ID: " + segmentId);
        }
        segmentRunners.put(segmentId, this);

        RepairUnit repairUnit = context.storage.getRepairUnit(segment.getRepairUnitId()).get();
        String keyspace = repairUnit.getKeyspaceName();

        if (!canRepair(segment, keyspace, coordinator)) {
            postponeCurrentSegment();
            return;
        }

        LOG.debug("Enter synchronized section with segment ID {}", segmentId);
        synchronized (condition) {
            commandId = coordinator.triggerRepair(segment.getStartToken(), segment.getEndToken(), keyspace,
                    validationParallelism, repairUnit.getColumnFamilies());

            if (commandId == 0) {
                // From cassandra source in "forceRepairAsync":
                //if (ranges.isEmpty() || Keyspace.open(keyspace).getReplicationStrategy().getReplicationFactor() < 2)
                //  return 0;
                LOG.info("Nothing to repair for keyspace {}", keyspace);
                context.storage.updateRepairSegment(segment.with().coordinatorHost(coordinator.getHost())
                        .state(RepairSegment.State.DONE).build(segmentId));
                segmentRunners.remove(segment.getId());
                return;
            }

            LOG.debug("Triggered repair with command id {}", commandId);
            context.storage.updateRepairSegment(segment.with().coordinatorHost(coordinator.getHost())
                    .repairCommandId(commandId).build(segmentId));
            String eventMsg = String.format("Triggered repair of segment %d via host %s", segment.getId(),
                    coordinator.getHost());
            repairRunner.updateLastEvent(eventMsg);
            LOG.info("Repair for segment {} started, status wait will timeout in {} millis", segmentId,
                    timeoutMillis);
            try {
                condition.await(timeoutMillis, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                LOG.warn("Repair command {} on segment {} interrupted", commandId, segmentId);
            } finally {
                RepairSegment resultingSegment = context.storage.getRepairSegment(segmentId).get();
                LOG.info("Repair command {} on segment {} returned with state {}", commandId, segmentId,
                        resultingSegment.getState());
                if (resultingSegment.getState() == RepairSegment.State.RUNNING) {
                    LOG.info("Repair command {} on segment {} has been cancelled while running", commandId,
                            segmentId);
                    abort(resultingSegment, coordinator);
                } else if (resultingSegment.getState() == RepairSegment.State.DONE) {
                    LOG.debug("Repair segment with id '{}' was repaired in {} seconds",
                            resultingSegment.getId(), Seconds.secondsBetween(resultingSegment.getStartTime(),
                                    resultingSegment.getEndTime()).getSeconds());
                    segmentRunners.remove(resultingSegment.getId());
                }
            }
        }
    } catch (ReaperException e) {
        LOG.warn("Failed to connect to a coordinator node for segment {}", segmentId);
        String msg = "Postponed a segment because no coordinator was reachable";
        repairRunner.updateLastEvent(msg);
        postponeCurrentSegment();
        LOG.warn("Open files amount for process: " + getOpenFilesAmount());
    }
    LOG.debug("Exiting synchronized section with segment ID {}", segmentId);
}

From source file:com.stormpath.sdk.servlet.filter.account.CookieAuthenticationResultSaver.java

License:Apache License

private int getMaxAge(String token, byte[] clientSecret, CookieConfig cookieConfig) {
    // non-zero indicates override from cookie config
    if (cookieConfig.getMaxAge() != 0) {
        return cookieConfig.getMaxAge();
    }/*from  ww w . j a va  2  s  .c  o m*/

    // otherwise, use the claims in the JWT to determine maxAge
    Jws<Claims> claimsJws = Jwts.parser().setSigningKey(clientSecret).parseClaimsJws(token);
    DateTime issueAt = new DateTime(claimsJws.getBody().getIssuedAt());
    DateTime expiration = new DateTime(claimsJws.getBody().getExpiration());

    return Seconds.secondsBetween(issueAt, expiration).getSeconds()
            - Seconds.secondsBetween(issueAt, DateTime.now()).getSeconds();
}

From source file:com.tdclighthouse.prototype.scheduler.Scheduler.java

License:Apache License

protected long getInitialDelayInMilliseconds(Configuration configuration) {
    DateTime dateTime = new DateTime(configuration.getTime(START_TIME_PROPERTY, getMidnight()));
    Seconds secondsBetween = Seconds.secondsBetween(new DateTime(), dateTime);
    return TimeUnit.SECONDS.toMillis((long) secondsBetween.getSeconds() + 30);
}

From source file:com.wadpam.guja.oauth2.api.OAuth2AuthorizationResource.java

License:Open Source License

/**
 * Validate an access_token./*from  w  w  w.  j  a v a  2 s  .  c  o  m*/
 * The Oauth2 specification does not specify how this should be done. Do similar to what Google does
 *
 * @param access_token access token to validate. Be careful about using url safe tokens or use url encoding.
 * @return http 200 if success and some basic info about the access_token
 */
@GET
@Path("tokeninfo")
public Response validate(@QueryParam("access_token") String access_token) {
    checkNotNull(access_token);

    DConnection connection = connectionDao.findByAccessToken(access_token);
    LOGGER.debug("Connection {}", connection);
    if (null == connection || hasAccessTokenExpired(connection)) {
        throw new BadRequestRestException("Invalid access_token");
    }

    return Response.ok(ImmutableMap
            .builder().put("user_id", connection.getUserId()).put("expires_in", Seconds
                    .secondsBetween(DateTime.now(), new DateTime(connection.getExpireTime())).getSeconds())
            .build()).build();

}

From source file:cz.muni.neural.network.util.OHLCReader.java

public static List<LabeledPoint> read(String file, int numberOfFeatures, int numberOfPoints,
        boolean skipWeekends, int period) throws IOException {

    BufferedReader br = null;/*from w ww  .ja  v  a 2s  .c o m*/
    String line = "";
    List<Double> values = new ArrayList<Double>();
    List<Integer> weekendIndices = new ArrayList<Integer>();
    DateTime prevDate = null;
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy.MM.dd HH:mm");

    int lineCount = 0;

    try {
        br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {

            String[] lineValues = line.split(",");
            int length = lineValues.length;

            if (length != 7) {
                throw new IOException("File has wrong format!");
            }

            //6th column is closing value
            values.add(Double.parseDouble(lineValues[5]));
            if (skipWeekends) {
                DateTime newDate = DateTime.parse(lineValues[0] + " " + lineValues[1], dtf);
                if (prevDate != null && Seconds.secondsBetween(prevDate, newDate).getSeconds() > period) {
                    weekendIndices.add(lineCount - 1);
                }
                prevDate = newDate;
            }
            lineCount++;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    Object[] doubleVals = values.toArray();

    int finalLength = doubleVals.length - numberOfFeatures - 1;

    List<LabeledPoint> labeledPoints = new ArrayList<>();
    for (int i = 0; i < finalLength && labeledPoints.size() < numberOfPoints; i++) {
        //check if period contains weekend
        if (skipWeekends) {
            boolean skip = false;
            for (int j = i; j < i + numberOfFeatures - 1; j++) {
                if (weekendIndices.contains(j)) {
                    skip = true;
                    break;
                }
            }
            if (skip) {
                continue;
            }
        }

        double[] features = new double[numberOfFeatures];
        for (int j = 0; j < numberOfFeatures; j++) {
            features[j] = (double) doubleVals[i + j];
        }
        labeledPoints.add(new LabeledPoint((double) doubleVals[i + numberOfFeatures + 1], features));
    }

    System.out.println("Read " + labeledPoints.size() + " points.");

    return labeledPoints;
}

From source file:de.dekstop.cosm.Coverage.java

License:Open Source License

static int getDistance(CoverageType type, DateTime start, DateTime end) {
    switch (type) {
    case SECOND:/*from www .j av a 2  s.  co m*/
        return Seconds.secondsBetween(start, end).getSeconds();
    case MINUTE:
        return Minutes.minutesBetween(start, end).getMinutes();
    case HOUR:
        return Hours.hoursBetween(start, end).getHours();
    case DAY:
        return Days.daysBetween(start, end).getDays();
    }
    throw new IllegalArgumentException("Unknown type: " + type);
}

From source file:de.fhdo.collaboration.helper.LoginHelper.java

License:Apache License

public boolean activate(String hash) {
    Session hb_session = HibernateUtil.getSessionFactory().openSession();
    hb_session.getTransaction().begin();

    org.hibernate.Query q = hb_session.createQuery("from Collaborationuser WHERE activation_md5=:p_hash");
    q.setString("p_hash", hash);

    java.util.List<Collaborationuser> userList = (java.util.List<Collaborationuser>) q.list();

    if (userList.size() == 1) {
        Collaborationuser user = userList.get(0);
        DateTime now = DateTime.now();/*w  w  w  .j  a v a2 s .c  om*/
        DateTime origin = new DateTime(user.getActivationTime());
        Seconds seconds = Seconds.secondsBetween(origin, now);
        int sec = seconds.getSeconds();
        if (seconds.getSeconds() < activationTimespan) {

            user.setEnabled(true);
            user.setActivated(true);
            user.setActivationMd5("");

            hb_session.merge(user);

            hb_session.getTransaction().commit();
            hb_session.close();

            return true;
        } else {
            return false;
        }
    }

    hb_session.close();

    return false;
}