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.ojbc.util.validator.OJBSimpleWSPSamlTokenValidator.java

License:RPL License

/**
 * Check the Conditions of the Assertion.
 *//*from  w  ww .java  2s  . c o m*/
protected void checkConditions(SamlAssertionWrapper assertion) throws WSSecurityException {

    log.info("Entering OJB custom check conditions method.");

    DateTime validFrom = null;
    DateTime validTill = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)
            && assertion.getSaml2().getConditions() != null) {
        validFrom = assertion.getSaml2().getConditions().getNotBefore();
        validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
    } else if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_11)
            && assertion.getSaml1().getConditions() != null) {
        validFrom = assertion.getSaml1().getConditions().getNotBefore();
        validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
    }

    if (validFrom != null) {
        DateTime currentTime = new DateTime();

        //We hardcode future time to live at 60 here, it is configurable in the super class
        currentTime = currentTime.plusSeconds(60);
        if (validFrom.isAfter(currentTime)) {
            log.debug("SAML Token condition (Not Before) not met");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }
    }

    if (validTill != null && validTill.isBeforeNow()) {
        log.info(
                "SAML Token condition (Not On Or After) not met.  We catch this error and don't throw an exception");
        //throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity");
    }
}

From source file:org.opendatakit.common.android.utilities.DataUtil.java

License:Apache License

public Interval tryParseInterval(String input) {
    for (int i = 0; i < userPartialParsers.length; i++) {
        try {/*from w ww .  j ava 2 s.c o m*/
            DateTime start = userPartialParsers[i].parseDateTime(input);
            DateTime end = start.plusSeconds(USER_INTERVAL_DURATIONS[i]);
            return new Interval(start, end);
        } catch (IllegalArgumentException e) {
        }
    }
    if (!locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
        return null;
    }
    DateTime start = new DateMidnight().toDateTime();
    boolean match = false;
    if (input.equalsIgnoreCase("today")) {
        match = true;
    } else if (input.equalsIgnoreCase("yesterday")) {
        start = start.minusDays(1);
        match = true;
    } else if (input.equalsIgnoreCase("tomorrow") || input.equalsIgnoreCase("tmw")) {
        start = start.plusDays(1);
        match = true;
    }
    if (match) {
        DateTime end = start.plusDays(1);
        return new Interval(start, end);
    }
    return null;
}

From source file:org.opendatakit.utilities.DateUtils.java

License:Apache License

private Interval tryParseInterval(String input) {
    for (int i = 0; i < userPartialParsers.length; i++) {
        try {//from w ww. jav a2s  .c o  m
            DateTime start = userPartialParsers[i].parseDateTime(input);
            DateTime end = start.plusSeconds(USER_INTERVAL_DURATIONS[i]);
            return new Interval(start, end);
        } catch (IllegalArgumentException ignored) {
            // TODO
        }
    }
    if (!locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
        return null;
    }
    DateTime start = new DateTime().withTimeAtStartOfDay();
    boolean match = false;
    if ("today".equalsIgnoreCase(input)) {
        match = true;
    } else if ("yesterday".equalsIgnoreCase(input)) {
        start = start.minusDays(1);
        match = true;
    } else if ("tomorrow".equalsIgnoreCase(input) || "tmw".equalsIgnoreCase(input)) {
        start = start.plusDays(1);
        match = true;
    }
    if (match) {
        DateTime end = start.plusDays(1);
        return new Interval(start, end);
    }
    return null;
}

From source file:org.opensaml.common.binding.security.IssueInstantRule.java

License:Open Source License

/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext");
        return;/*from ww w  . j a  va  2  s .co  m*/
    }
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    if (samlMsgCtx.getInboundSAMLMessageIssueInstant() == null) {
        if (requiredRule) {
            log.warn("Inbound SAML message issue instant not present in message context");
            throw new SecurityPolicyException(
                    "Inbound SAML message issue instant not present in message context");
        } else {
            return;
        }
    }

    DateTime issueInstant = samlMsgCtx.getInboundSAMLMessageIssueInstant();
    DateTime now = new DateTime();
    DateTime latestValid = now.plusSeconds(clockSkew);
    DateTime expiration = issueInstant.plusSeconds(clockSkew + expires);

    // Check message wasn't issued in the future
    if (issueInstant.isAfter(latestValid)) {
        log.warn("Message was not yet valid: message time was {}, latest valid is: {}", issueInstant,
                latestValid);
        throw new SecurityPolicyException("Message was rejected because was issued in the future");
    }

    // Check message has not expired
    if (expiration.isBefore(now)) {
        log.warn("Message was expired: message issue time was '" + issueInstant + "', message expired at: '"
                + expiration + "', current time: '" + now + "'");
        throw new SecurityPolicyException("Message was rejected due to issue instant expiration");
    }

}

From source file:org.restcomm.connect.dao.entities.Registration.java

License:Open Source License

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

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

License:Educational Community License

public String generateJsonWebToken(String tool) {

    String token = null;//w  ww.j av a  2 s. co  m

    String userId = sessionManager.getCurrentSessionUserId();

    try {

        String siteId = toolManager.getCurrentPlacement().getContext();

        DateTime now = DateTime.now();

        JWTCreator.Builder jwtBuilder = JWT.create();
        jwtBuilder.withIssuer(JWT_ISSUER).withAudience(JWT_AUDIENCE).withSubject(userId)
                .withClaim(JWT_CUSTOM_CLAIM_TOOL_ID, tool)
                .withClaim(JWT_CUSTOM_CLAIM_SESSION_ID, sessionManager.getCurrentSession().getId())
                .withIssuedAt(now.toDate());
        int sessionTimeoutInSeconds = sessionManager.getCurrentSession().getMaxInactiveInterval();
        if (sessionTimeoutInSeconds > 0) {
            jwtBuilder.withExpiresAt(now.plusSeconds(sessionTimeoutInSeconds).toDate());
        } else {
            // if Sakai is configured for sessions to never timeout (negative value), we will set 30 minutes for
            // tokens - the rubrics service will check Sakai session validity if it receives an expired token.
            jwtBuilder.withExpiresAt(now.plusMinutes(30).toDate());
        }

        if (securityService.isSuperUser()) {
            jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES,
                    new String[] { RBCS_PERMISSIONS_EDITOR, RBCS_PERMISSIONS_ASSOCIATOR,
                            RBCS_PERMISSIONS_EVALUATOR, RBCS_PERMISSIONS_EVALUEE, RBCS_PERMISSIONS_SUPERUSER });

        } else {

            List<String> roles = new ArrayList<>();
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EDITOR, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_EDITOR);
            }
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_ASSOCIATOR, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_ASSOCIATOR);
            }
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUATOR, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_EVALUATOR);
            }
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUEE, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_EVALUEE);
            }
            jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES, roles.toArray(new String[] {}));
        }
        jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_ID, siteId);
        jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_TYPE, SITE_CONTEXT_TYPE);
        token = jwtBuilder.sign(Algorithm
                .HMAC256(serverConfigurationService.getString(RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY)));

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(String.format(
                "An error occurred while generating a JSON Web Token to "
                        + "authorize communication with the Rubrics service. Please verify the %s property is "
                        + "defined in the sakai.properties file.",
                RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY), e);
    }

    return token;
}

From source file:org.sakaiproject.rubrics.logic.RubricsServiceImpl.java

License:Educational Community License

public String generateJsonWebToken(String tool, String siteId) {

    String token = null;/*from   www. ja va2 s.c  om*/
    String userId = sessionManager.getCurrentSessionUserId();

    try {
        DateTime now = DateTime.now();

        JWTCreator.Builder jwtBuilder = JWT.create();
        jwtBuilder.withIssuer(JWT_ISSUER).withAudience(JWT_AUDIENCE).withSubject(userId)
                .withClaim(JWT_CUSTOM_CLAIM_TOOL_ID, tool)
                .withClaim(JWT_CUSTOM_CLAIM_SESSION_ID, sessionManager.getCurrentSession().getId())
                .withIssuedAt(now.toDate());
        int sessionTimeoutInSeconds = sessionManager.getCurrentSession().getMaxInactiveInterval();
        if (sessionTimeoutInSeconds > 0) {
            jwtBuilder.withExpiresAt(now.plusSeconds(sessionTimeoutInSeconds).toDate());
        } else {
            // if Sakai is configured for sessions to never timeout (negative value), we will set 30 minutes for
            // tokens - the rubrics service will check Sakai session validity if it receives an expired token.
            jwtBuilder.withExpiresAt(now.plusMinutes(30).toDate());
        }

        if (securityService.isSuperUser()) {
            jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES,
                    new String[] { RBCS_PERMISSIONS_EDITOR, RBCS_PERMISSIONS_ASSOCIATOR,
                            RBCS_PERMISSIONS_EVALUATOR, RBCS_PERMISSIONS_EVALUEE, RBCS_PERMISSIONS_SUPERUSER });
        } else {
            List<String> roles = new ArrayList<>();
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EDITOR, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_EDITOR);
            }
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_ASSOCIATOR, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_ASSOCIATOR);
            }
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUATOR, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_EVALUATOR);
            }
            if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUEE, "/site/" + siteId)) {
                roles.add(RBCS_PERMISSIONS_EVALUEE);
            }
            jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES, roles.toArray(new String[] {}));
        }
        jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_ID, siteId);
        jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_TYPE, SITE_CONTEXT_TYPE);
        token = jwtBuilder.sign(Algorithm
                .HMAC256(serverConfigurationService.getString(RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY)));

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(String.format(
                "An error occurred while generating a JSON Web Token to "
                        + "authorize communication with the Rubrics service. Please verify the %s property is "
                        + "defined in the sakai.properties file.",
                RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY), e);
    }

    return token;
}

From source file:org.smallmind.javafx.extras.instrument.TimeAxis.java

License:Open Source License

@Override
protected List<Long> calculateTickValues(double length, Object range) {

    LinkedList<Long> ticks = new LinkedList<Long>();
    DateTime origin = new DateTime(((EndPoints<Long>) range).getLow()).withMillisOfSecond(0);
    DateTime bound = new DateTime(((EndPoints<Long>) range).getHigh());
    int majorInterval;

    if ((majorInterval = (origin.getSecondOfMinute() / 15) + 1) < 4) {
        origin = origin.withSecondOfMinute(majorInterval * 15);
    } else {//www . j  a  va 2  s .  co  m
        origin = origin.plusMinutes(1).withSecondOfMinute(0);
    }

    while (origin.isBefore(bound)) {
        ticks.add(origin.getMillis());
        origin = origin.plusSeconds(15);
    }

    return ticks;
}

From source file:org.smallmind.javafx.extras.instrument.TimeAxis.java

License:Open Source License

@Override
protected List<Long> calculateMinorTickMarks() {

    LinkedList<Long> ticks = new LinkedList<Long>();
    Object range = getRange();/*from   w  ww.j  a va  2s .  com*/
    DateTime origin = new DateTime(((EndPoints<Long>) range).getLow()).withMillisOfSecond(0);
    DateTime bound = new DateTime(((EndPoints<Long>) range).getHigh());
    int minorInterval;

    if ((minorInterval = (origin.getSecondOfMinute() / 5) + 1) < 12) {
        origin = origin.withSecondOfMinute(minorInterval * 5);
    } else {
        origin = origin.plusMinutes(1).withSecondOfMinute(0);
    }

    while (origin.isBefore(bound)) {
        if ((origin.getSecondOfMinute() % 15) != 0) {
            ticks.add(origin.getMillis());
        }

        origin = origin.plusSeconds(5);
    }

    return ticks;
}

From source file:org.taverna.server.master.notification.RateLimitedDispatcher.java

/**
 * Test whether the rate limiter allows the given user to send a message.
 * /*from   w ww .  ja va2s.  c  o m*/
 * @param who
 *            Who wants to send the message?
 * @return <tt>true</tt> iff they are permitted.
 */
protected boolean isSendAllowed(String who) {
    DateTime now = new DateTime();
    synchronized (lastSend) {
        DateTime last = lastSend.get(who);
        if (last != null) {
            if (!now.isAfter(last.plusSeconds(cooldownSeconds)))
                return false;
        }
        lastSend.put(who, now);
    }
    return true;
}