Example usage for org.joda.time DateTime toString

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

Introduction

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

Prototype

@ToString
public String toString() 

Source Link

Document

Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ).

Usage

From source file:com.thinkbiganalytics.metadata.sla.api.core.FeedOnTimeArrivalMetricAssessor.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void assess(FeedOnTimeArrivalMetric metric, MetricAssessmentBuilder builder) {
    LOG.debug("Assessing metric: ", metric);

    builder.metric(metric);// w w w  .j  a  va2s.c  o  m

    String feedName = metric.getFeedName();
    DateTime lastFeedTime = feedProvider.getLastActiveTimeStamp(feedName);
    HashMap<String, String> data = new HashMap<>();
    data.put("feed", feedName);

    Long nowDiff = 0L;
    Period nowDiffPeriod = new Period(nowDiff.longValue());

    if (lastFeedTime != null) {
        nowDiff = DateTime.now().getMillis() - lastFeedTime.getMillis();
        nowDiffPeriod = new Period(nowDiff.longValue());
    }

    Long latePeriodMillis = metric.getLatePeriod().toStandardDuration().getMillis();
    Long duration = CronExpressionUtil.getCronInterval(metric.getExpectedExpression());
    Period acceptedPeriod = new Period(duration + latePeriodMillis);
    Date expectedDate = CronExpressionUtil.getPreviousFireTime(metric.getExpectedExpression());
    DateTime expectedTime = new DateTime(expectedDate);
    LOG.debug("Calculated the Expected Date to be {}  ", expectedTime);
    DateTime lateTime = expectedTime.plus(metric.getLatePeriod());
    LOG.debug("CurrentTime is: {}.  Comparing {} against the lateTime of {} ", DateTime.now(), lastFeedTime,
            lateTime);
    builder.compareWith(expectedDate, feedName);

    data.put("expectedTime", expectedTime.toString());
    data.put("expectedTimeMillis", expectedTime.getMillis() + "");

    data.put("lateTime", expectedTime.toString());
    data.put("lateTimeMillis", expectedTime.getMillis() + "");

    if (lastFeedTime != null) {
        data.put("lastFeedTime", lastFeedTime.toString());
        data.put("lastFeedTimeMillis", lastFeedTime.getMillis() + "");
    }
    builder.data(data);

    if (lastFeedTime == null) {
        LOG.debug("Feed with the specified name {} not found", feedName);
        builder.message("Feed with the specified name " + feedName + " not found ")
                .result(AssessmentResult.WARNING);
    } else if (lastFeedTime.isAfter(expectedTime) && lastFeedTime.isBefore(lateTime)) {
        LOG.debug("Data for feed {} arrived on {}, which was before late time: {}", feedName, lastFeedTime,
                lateTime);

        builder.message("Data for feed " + feedName + " arrived on " + lastFeedTime
                + ", which was before late time:  " + lateTime).result(AssessmentResult.SUCCESS);
    } else if (lastFeedTime.isAfter(lateTime)) {
        LOG.debug("Data for feed {} has not arrived before the late time: {} ", feedName, lateTime);
        builder.message("Data for feed " + feedName + " has not arrived before the late time: " + lateTime
                + "\n The last successful feed was on " + lastFeedTime).result(AssessmentResult.FAILURE);
    } else if (nowDiff <= (duration + latePeriodMillis)) {
        LOG.debug(
                "Data for feed {} has arrived before the late time: {}. The last successful feed was on {}.  It has been {} since data has arrived.  The allowed duration is {} ",
                feedName, lateTime, lastFeedTime, DateTimeUtil.formatPeriod(nowDiffPeriod),
                DateTimeUtil.formatPeriod(acceptedPeriod));
        builder.message(
                "Data for feed " + feedName + " has arrived on time.  \n The last successful feed was on "
                        + lastFeedTime + ". It has been " + DateTimeUtil.formatPeriod(nowDiffPeriod)
                        + " since data has arrived.  The allowed duration is "
                        + DateTimeUtil.formatPeriod(acceptedPeriod))
                .result(AssessmentResult.SUCCESS);
    } else if (nowDiff > (duration + latePeriodMillis)) {
        //error its been greater that the duration of the cron + lateTime
        LOG.debug(
                "Data for feed {} has not arrived before the late time: {}. The last successful feed was on {}.  It has been {} since data has arrived.  The allowed duration is {} ",
                feedName, lateTime, lastFeedTime, DateTimeUtil.formatPeriod(nowDiffPeriod),
                DateTimeUtil.formatPeriod(acceptedPeriod));
        builder.message(
                "Data for feed " + feedName + " has not arrived on time. \n The last successful feed was on "
                        + lastFeedTime + ".  It has been " + DateTimeUtil.formatPeriod(nowDiffPeriod)
                        + " since data has arrived. The allowed duration is "
                        + DateTimeUtil.formatPeriod(acceptedPeriod))
                .result(AssessmentResult.FAILURE);
    } else if (DateTime.now().isBefore(lateTime)) { //&& lastFeedTime.isBefore(expectedTime)
        LOG.debug("CurrentTime {} is before the lateTime of {}.  Not Assessing", DateTime.now(), lateTime);
        return;
    } else {
        LOG.debug("Data for feed {} has not arrived before the late time: {} ", feedName, lateTime);

        builder.message("Data for feed " + feedName + " has not arrived before the late time: " + lateTime
                + "\n The last successful feed was on " + lastFeedTime).result(AssessmentResult.FAILURE);
    }
}

From source file:com.threewks.thundr.json.DateTimeTypeConvertor.java

License:Apache License

@Override
public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
    return new JsonPrimitive(src.toString());
}

From source file:com.vangent.hieos.services.sts.transactions.SAML2TokenIssueHandler.java

License:Open Source License

/**
 *
 * @param assertion/*from   w  w w  . j av a  2 s  .  c  o m*/
 * @param creationDate
 * @param expirationDate
 * @return
 */
private OMElement getWSTrustResponse(OMElement assertion, DateTime creationDate, DateTime expirationDate) {
    OMFactory omfactory = OMAbstractFactory.getOMFactory();
    OMNamespace wstNs = omfactory.createOMNamespace(STSConstants.WSTRUST_NS, "wst");
    OMNamespace wsuNs = omfactory.createOMNamespace(STSConstants.WSSECURITY_UTILITY_NS, "wsu");
    OMElement rstResponseCollection = omfactory.createOMElement("RequestSecurityTokenResponseCollection",
            wstNs);
    OMElement rstResponse = omfactory.createOMElement("RequestSecurityTokenResponse", wstNs);
    OMElement requestedSecurityToken = omfactory.createOMElement("RequestedSecurityToken", wstNs);
    OMElement lifeTime = omfactory.createOMElement("Lifetime", wstNs);
    OMElement created = omfactory.createOMElement("Created", wsuNs);
    OMElement expires = omfactory.createOMElement("Expires", wsuNs);
    created.setText(creationDate.toString());
    expires.setText(expirationDate.toString());
    lifeTime.addChild(created);
    lifeTime.addChild(expires);

    OMElement tokenType = omfactory.createOMElement("TokenType", wstNs);
    tokenType.setText(STSConstants.SAML2_TOKEN_TYPE);

    // Wire things up in proper order.
    rstResponseCollection.addChild(rstResponse);
    rstResponse.addChild(tokenType);
    rstResponse.addChild(lifeTime);
    rstResponse.addChild(requestedSecurityToken);
    requestedSecurityToken.addChild(assertion);
    return rstResponseCollection;
}

From source file:com.viadeo.kasper.core.component.event.eventbus.EventBusMessageConverter.java

License:Open Source License

/**
 * Transform an axon event message to an amqp message
 *
 * @param object message to convert/*ww  w  . j a v  a 2s. c om*/
 * @param messageProperties spring message properties
 * @return converted message
 * @throws org.springframework.amqp.support.converter.MessageConversionException throws a MessageConversionException
 */
public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {

    EventMessage eventMessage = (EventMessage) object;

    checkNotNull(eventMessage);

    final SerializedObject<byte[]> payload = serializer.serializePayload(eventMessage, byte[].class);
    DateTime timestamp = checkNotNull(eventMessage.getTimestamp());
    String className = checkNotNull(eventMessage.getPayloadType().getName());
    MessageBuilderSupport<Message> builder = MessageBuilder.withBody(payload.getData())
            .setDeliveryMode(MessageDeliveryMode.PERSISTENT).setContentType("application/json")
            .setContentEncoding("UTF-8").setMessageId(checkNotNull(eventMessage.getIdentifier()))
            .setType(className).setTimestamp(new Date(eventMessage.getTimestamp().getMillis()))
            .setHeader(SERIALIZER_VERSION_KEY, "1.0").setHeader(EVENT_TIMESTAMP_KEY, timestamp.toString())
            .setHeader(PAYLOAD_REVISION_KEY, checkNotNull(payload.getType().getRevision()))
            .setHeader(PAYLOAD_TYPE_KEY, className)
            .setHeader(EVENT_TYPE_KEY, checkNotNull(EventMessageType.forMessage(eventMessage).getTypeByte()));

    if (eventMessage instanceof DomainEventMessage) {
        final DomainEventMessage domainEventMessage = (DomainEventMessage) eventMessage;
        final Object aggregateIdentifier = checkNotNull(domainEventMessage.getAggregateIdentifier());
        try {
            builder.setHeader(AGGREGATE_ID_KEY, objectMapper.writeValueAsString(aggregateIdentifier))
                    .setHeader(AGGREGATE_ID_TYPE_KEY, aggregateIdentifier.getClass().getName())
                    .setHeader(SEQUENCE_NUMBER_KEY, checkNotNull(domainEventMessage.getSequenceNumber()));
        } catch (JsonProcessingException e) {
            LOGGER.warn("Failed to specify properties of a domain event message", e);
        }
    }

    serializeMetadata(eventMessage, builder);

    Message message = builder.build();

    int bodyLength = message.getBody().length;
    Preconditions.checkState(MAX_PAYLOAD_SIZE > bodyLength, MAX_PAYLOAD_SIZE_MESSAGE, MAX_PAYLOAD_SIZE,
            className, bodyLength);

    return message;
}

From source file:com.viadeo.kasper.exposition.http.jetty.RequestLogHandler.java

License:Open Source License

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {

    final String correlationId = Objects.firstNonNull(baseRequest.getHeader("X-KASPER-REQUEST-CID"), "-");
    final String path = baseRequest.getRequestURI();
    final long timestamp = baseRequest.getTimeStamp();
    final DateTime time = new DateTime(timestamp);
    final String message = String.format("%s %s %s", time.toString(), path, correlationId);

    LOGGER.debug("BEFORE HANDLE: {}", message);
    final long tic = System.currentTimeMillis();

    try {/*from w ww .j ava2s  . c om*/
        super.handle(target, baseRequest, request, response);
    } finally {
        final long handleDuration = System.currentTimeMillis() - tic;
        LOGGER.debug("AFTER HANDLE ({} ms): {}", handleDuration, message);
    }

}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateValidator.java

License:Open Source License

@Override
public ValidationResult validate(AuthnRequestState t) {
    log.debug("Validating request {}", t);

    ValidationResult vr = null;/* www  . j a v a2s  . c  o  m*/

    try {
        Validate.notNull(t);

        HttpServletRequest httpRequest = t.getRequest();
        Validate.notNull(httpRequest);

        AuthnRequest request = t.getAuthnRequest();
        Validate.notNull(request);
        Validate.notNull(request.getIssuer());

        IdmAccessor accessor = t.getIdmAccessor();
        Validate.notNull(accessor);
        Validate.notNull(accessor.getTenant());

        // Validate assertion consumer service first, if that is valid, we can send SAML replies
        try {
            boolean validateACSWithMetadata = !this.isRequestSigned(t);
            String acsUrl = accessor.getAcsForRelyingParty(request.getIssuer().getValue(),
                    request.getAssertionConsumerServiceIndex(), request.getAssertionConsumerServiceURL(),
                    request.getProtocolBinding(), validateACSWithMetadata);

            t.setAcsUrl(acsUrl);
        } catch (IllegalStateException e) {
            // set validation result to 400
            log.debug("Caught illegal state exception while Validating {} returning 400", e.toString());
            vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
        }

        // Validate ID
        if (vr == null && request.getID() == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - Request ID is missing");
        }

        // Validate version
        if (vr == null) {
            SAMLVersion version = request.getVersion();
            if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                    || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                            && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
                // version too high
                vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH);
                log.debug("Validation FAILED - Version is too high");
            } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                    || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                            && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
                // version too low
                vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW);
                log.debug("Validation FAILED - Version is too low");
            }
        }

        // Validate IssueInstant only if this is a new request (i.e. it had not pass been validated)
        if (vr == null && !t.isExistingRequest()) {
            DateTime dtPlus = request.getIssueInstant();
            DateTime dtMinus = request.getIssueInstant();
            DateTime instant = new DateTime();
            long clockTolerance = accessor.getClockTolerance();
            if (dtPlus == null) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - Issue Instant is missing");
            } else {
                dtPlus = dtPlus.plus(clockTolerance);
                dtMinus = dtMinus.minus(clockTolerance);
                // dtPlus must be after now and dtMinus must be before now
                //   in order to satisfy clock tolerance
                if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) {
                    vr = new ValidationResult(OasisNames.REQUESTER);
                    log.debug("Validation FAILED - Issue Instant outside of clock tolerance");
                    log.debug("clockTolerance {}", clockTolerance);
                    log.debug("now {}", instant);
                    log.debug("dtPlus {}", dtPlus.toString());
                    log.debug("dtMinus {}", dtMinus.toString());
                }
            }
        }

        // Destination URL skipped, this is already done by OpenSAML when parsing

        // validate scoping if presenet
        if (vr == null) {
            vr = validateScoping(t);
        }

        // signature must NOT be included
        if (vr == null) {
            if (request.getSignature() != null) {
                log.debug("Validation FAILED - Signature MUST NOT be present");
                vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.REQUEST_UNSUPPORTED);
            }
        }

        // ensure that we don't accept unsigned requests if configuration requires signing
        if (vr == null) {

            try {
                boolean mustBeSigned = accessor
                        .getAuthnRequestsSignedForRelyingParty(request.getIssuer().getValue());
                this.validateSigning(mustBeSigned, t);
            } catch (IllegalStateException e) {
                // set validation result to request denied
                log.error("Validation FAILED - unsigned request detected, signing required");
                vr = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED);
            }
        }

        // validate NameIDPolicy if present
        if (vr == null) {
            NameIDPolicy policy = request.getNameIDPolicy();
            if (policy != null) {
                String format = policy.getFormat();
                if (format != null && !format.equals(OasisNames.PERSISTENT)
                        && !format.equals(OasisNames.EMAIL_ADDRESS)
                        && !format.equals(SAMLNames.IDFORMAT_VAL_UPN.toString())) {
                    log.error("Validation FAILED - unknown NameIDPolicy Format");
                    vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.INVALID_NAMEID_POLICY);
                }
            }
        }

        // validate conditions
        if (vr == null) {
            Conditions conditions = request.getConditions();
            if (conditions != null) {
                // notBefore processing
                DateTime notBefore = conditions.getNotBefore();
                if (notBefore != null) {
                    // no additional validation, we'll use whatever client wants
                    t.setStartTime(notBefore.toDate());
                }
                // delegable and renewable conditions
                for (Condition c : conditions.getConditions()) {
                    if (c == null) {
                        continue;
                    }
                    if (c instanceof RenewableType) {
                        t.setRenewable(true);
                    }
                    if (c instanceof DelegableType) {
                        t.setDelegable(true);
                    }
                }
            }
        }
        if (vr == null) {
            computeSupportedAuthnTypes(t, request);
        }

        // validation done
        if (vr == null) {
            log.info("Authentication request validation succeeded");
            vr = new ValidationResult(); // success

            // check if we need to convert a principal into emailAddress
            if (request.getNameIDPolicy() != null && request.getNameIDPolicy().getFormat() != null
                    && request.getNameIDPolicy().getFormat().equals(OasisNames.EMAIL_ADDRESS)) {
                t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_EMAIL_ADDRESS);
            } else {
                t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_UPN);
            }
        }

    } catch (Exception e) {
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        log.debug("Caught exception while Validating " + e.toString() + ", returning 400");
    }
    return vr;
}

From source file:com.vmware.identity.samlservice.impl.LogoutStateValidator.java

License:Open Source License

/**
 * Validate LogoutResponse/* w  ww .j  a va 2 s .c o  m*/
 *
 * @param vr
 * @param accessor
 * @param response
 * @return
 */
private com.vmware.identity.samlservice.SamlValidator.ValidationResult validateLogoutResponse(
        com.vmware.identity.samlservice.SamlValidator.ValidationResult vr, IdmAccessor accessor,
        LogoutResponse response, SessionManager sm) {
    Validate.notNull(response.getIssuer());

    // Validate single logout service first, if that is valid, we can send
    // SAML replies
    try {
        @SuppressWarnings("unused")
        String acsUrl = accessor.getSloForRelyingParty(response.getIssuer().getValue(),
                OasisNames.HTTP_REDIRECT);
    } catch (IllegalStateException e) {
        // set validation result to 400
        log.debug("Caught illegal state exception while Validating " + e.toString() + ", returning 400");
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
    }

    // Validate ID
    if (vr == null && response.getID() == null) {
        vr = new ValidationResult(OasisNames.REQUESTER);
        log.debug("Validation FAILED - Request ID is missing");
    }

    // Validate version
    if (vr == null) {
        SAMLVersion version = response.getVersion();
        if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                        && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
            // version too high
            vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH);
            log.debug("Validation FAILED - Version is too high");
        } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                        && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
            // version too low
            vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW);
            log.debug("Validation FAILED - Version is too low");
        }
    }

    // Validate IssueInstant
    if (vr == null) {
        DateTime dtPlus = response.getIssueInstant();
        DateTime dtMinus = response.getIssueInstant();
        DateTime instant = new DateTime();
        long clockTolerance = accessor.getClockTolerance();
        if (dtPlus == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - Issue Instant is missing");
        } else {
            dtPlus = dtPlus.plus(clockTolerance);
            dtMinus = dtMinus.minus(clockTolerance);
            // dtPlus must be after now and dtMinus must be before now
            // in order to satisfy clock tolerance
            if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - Issue Instant outside of clock tolerance");
                log.debug("clockTolerance {} ", clockTolerance);
                log.debug("now {}", instant);
                log.debug("dtPlus {}", dtPlus.toString());
                log.debug("dtMinus {}", dtMinus.toString());
            }
        }
    }

    // Destination URL skipped, this is already done by OpenSAML when
    // parsing

    // validate inResponseTo (which is the corresponding SLO request ID that
    // this response is targetting at)
    if (vr == null) {
        String inResponseTo = response.getInResponseTo();
        if (inResponseTo == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - inResponseTo is missing");
        } else {
            // try to find a session by LogoutRequest id that we have
            Session session = sm.getByLogoutRequestId(inResponseTo);
            if (session == null) {
                // No session found using the SLO request ID. This could
                // happen due to
                // fail-over (node switch). So here we ignore rather than
                // throw error at browser
                log.info(
                        "Unable to identify a session the SLO response is referring to. This could be caused by site-affinity switch.");
            }
        }
    }

    // check response status code
    if (vr == null) {
        Status status = null;
        StatusCode statusCode = null;
        if (vr == null) {
            // check LogoutResponse status code here
            status = response.getStatus();
            if (status == null) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - unable to find status code");
            }
        }
        if (vr == null) {
            statusCode = status.getStatusCode();
            if (statusCode == null) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - unable to find status code");
            }
        }
        if (vr == null) {
            String code = statusCode.getValue();
            if (!OasisNames.SUCCESS.equals(code)) {
                vr = new ValidationResult(OasisNames.SUCCESS, OasisNames.PARTIAL_LOGOUT);
                log.debug("Validation FAILED - partially logged out session");
            }
        }
    }

    // validation done
    if (vr == null) {
        vr = new ValidationResult(); // success
    }
    return vr;
}

From source file:com.vmware.identity.samlservice.impl.LogoutStateValidator.java

License:Open Source License

/**
 * Validate LogoutRequest//from  w  ww  .  java2s .  c o m
 *
 * @param vr
 * @param accessor
 * @param request
 * @return
 */
private ValidationResult validateLogoutRequest(ValidationResult vr, IdmAccessor accessor,
        LogoutRequest request) {
    Validate.notNull(request.getIssuer());

    // Validate single logout service first, if that is valid, we can send
    // SAML replies
    try {
        @SuppressWarnings("unused")
        String acsUrl = accessor.getSloForRelyingParty(request.getIssuer().getValue(),
                OasisNames.HTTP_REDIRECT);
    } catch (IllegalStateException e) {
        // set validation result to 400
        log.debug("Caught illegal state exception while Validating " + e.toString() + ", returning 400");
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
    }

    // Validate ID
    if (vr == null && request.getID() == null) {
        vr = new ValidationResult(OasisNames.REQUESTER);
        log.debug("Validation FAILED - Request ID is missing");
    }

    // Validate version
    if (vr == null) {
        SAMLVersion version = request.getVersion();
        if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                        && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
            // version too high
            vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH);
            log.debug("Validation FAILED - Version is too high");
        } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                        && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
            // version too low
            vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW);
            log.debug("Validation FAILED - Version is too low");
        }
    }

    // Validate IssueInstant
    if (vr == null) {
        DateTime dtPlus = request.getIssueInstant();
        DateTime dtMinus = request.getIssueInstant();
        DateTime instant = new DateTime();
        long clockTolerance = accessor.getClockTolerance();
        if (dtPlus == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - Issue Instant is missing");
        } else {
            dtPlus = dtPlus.plus(clockTolerance);
            dtMinus = dtMinus.minus(clockTolerance);
            // dtPlus must be after now and dtMinus must be before now
            // in order to satisfy clock tolerance
            if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - Issue Instant outside of clock tolerance");
                log.debug("clockTolerance {}", clockTolerance);
                log.debug("now {}", instant);
                log.debug("dtPlus {}", dtPlus.toString());
                log.debug("dtMinus {}", dtMinus.toString());
            }
        }
    }

    // Destination URL skipped, this is already done by OpenSAML when
    // parsing

    // Validate NotOnOrAfter
    if (vr == null) {
        DateTime notOnOrAfter = request.getNotOnOrAfter();
        if (notOnOrAfter != null) {
            DateTime instant = new DateTime();
            if (!instant.isBefore(notOnOrAfter)) {
                vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.REQUEST_DENIED);
                log.debug("Validation FAILED - NotOnOrAfter condition violated");
                log.debug("now {}", instant);
                log.debug("notOnOrAfter {}", notOnOrAfter.toString());
            }
        }
    }

    // validate NameID
    if (vr == null) {
        NameID nameID = request.getNameID();
        if (nameID == null || nameID.getFormat() == null || nameID.getValue() == null) {
            log.debug("Validation FAILED for NameID: node, format or value missing");
            vr = new ValidationResult(OasisNames.REQUESTER);
        }
    }

    // validate session index
    if (vr == null) {
        List<SessionIndex> sessionList = request.getSessionIndexes();
        if (sessionList == null || sessionList.size() == 0) {
            log.debug("Validation FAILED for session indices: at least one session index is required");
            vr = new ValidationResult(OasisNames.REQUESTER);
        }
    }

    // validation done
    if (vr == null) {
        vr = new ValidationResult(); // success
    }
    return vr;
}

From source file:com.wso2telco.dep.reportingservice.dao.BillingDAO.java

License:Open Source License

/**
 * Convert to local time.//from ww w  .ja v a 2 s  . c o m
 *
 * @param timeOffset the time offset
 * @param time the time
 * @return the string
 */
public String convertToLocalTime(String timeOffset, String time) {
    Integer offsetValue = Integer.parseInt(timeOffset);

    log.debug("Offset value = " + offsetValue);
    DateTimeZone systemTimeZone = DateTimeZone.getDefault();
    log.debug("system time zone " + systemTimeZone.toString());
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime systemDateTime = formatter.parseDateTime(time);
    log.debug("system date time " + systemDateTime.toString());
    systemDateTime = systemDateTime.withZoneRetainFields(systemTimeZone);
    log.debug("system date time after adding systemtimezone === " + systemDateTime.toString());

    int hours = -1 * offsetValue / 60;
    int minutes = offsetValue % 60;
    minutes = Math.abs(minutes);

    DateTimeZone localTimeZone = DateTimeZone.forOffsetHoursMinutes(hours, minutes);

    log.debug("Local time zone ==== " + localTimeZone.toString());

    DateTime convertedDateTime = systemDateTime.withZone(localTimeZone);

    String convertedDateTimeString = formatter.print(convertedDateTime);

    log.debug("converted time  :" + convertedDateTimeString);

    return convertedDateTimeString;

}

From source file:com.yahoo.bard.webservice.data.dimension.impl.KeyValueStoreDimension.java

License:Apache License

@Override
public void setLastUpdated(DateTime lastUpdated) {
    if (lastUpdated == null) {
        keyValueStore.remove(lastUpdatedKey);
    } else {//w  ww .  ja  va  2  s.c om
        keyValueStore.put(lastUpdatedKey, lastUpdated.toString());
    }
}