Example usage for org.joda.time DateTime DateTime

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

Introduction

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

Prototype

public DateTime() 

Source Link

Document

Constructs an instance set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:be.fedict.eid.idp.sp.protocol.saml2.AbstractAuthenticationResponseProcessor.java

License:Open Source License

/**
 * Process the incoming SAML v2.0 response.
 * //from  ww  w.jav  a2s  .co  m
 * @param requestId
 *            AuthnRequest.ID, should match response's InResponseTo
 * @param audience
 *            expected audience
 * @param recipient
 *            recipient, should match response's
 *            Subject.SubjectConfirmation.Recipient
 * @param relayState
 *            optional expected relay state
 * @param requiresResponseSignature
 *            do we expect a signature on the response or not, or
 *            <code>null</code> if to be retrieved from the
 *            {@link AuthenticationResponseService}.
 * @param request
 *            the HTTP servlet request that holds the SAML2 response.
 * @return the SAML2 {@link AuthenticationResponse}
 * @throws AuthenticationResponseProcessorException
 *             case something went wrong
 */
public AuthenticationResponse process(String requestId, String audience, String recipient, String relayState,
        Boolean requiresResponseSignature, HttpServletRequest request)
        throws AuthenticationResponseProcessorException {

    Response samlResponse = getSamlResponse(request);
    DateTime now = new DateTime();
    SecretKey secretKey = null;
    PrivateKey privateKey = null;
    int maxOffset = 5;
    boolean expectResponseSigned = null != requiresResponseSignature ? requiresResponseSignature : false;

    AuthenticationResponseService service = getAuthenticationResponseService();
    if (null != service) {
        secretKey = service.getAttributeSecretKey();
        privateKey = service.getAttributePrivateKey();
        maxOffset = service.getMaximumTimeOffset();
        expectResponseSigned = service.requiresResponseSignature();
    }

    // validate InResponseTo
    if (!samlResponse.getInResponseTo().equals(requestId)) {

        throw new AuthenticationResponseProcessorException("SAML Response not belonging to AuthnRequest!");
    }

    // validate status
    Status status = samlResponse.getStatus();
    StatusCode statusCode = status.getStatusCode();
    String statusValue = statusCode.getValue();
    if (!StatusCode.SUCCESS_URI.equals(statusValue)) {
        throw new AuthenticationResponseProcessorException("no successful SAML response");
    }

    List<Assertion> assertions = samlResponse.getAssertions();
    if (assertions.isEmpty()) {
        throw new AuthenticationResponseProcessorException("missing SAML assertions");
    }

    Assertion assertion = assertions.get(0);

    AuthenticationResponse authenticationResponse;
    try {
        authenticationResponse = Saml2Util.validateAssertion(assertion, now, maxOffset, audience, recipient,
                requestId, secretKey, privateKey);
    } catch (AssertionValidationException e) {
        throw new AuthenticationResponseProcessorException(e);
    }

    // check if SP expects a signature and if there is one
    if (null == samlResponse.getSignature() && expectResponseSigned) {
        throw new AuthenticationResponseProcessorException("Expected a signed response but was not so! ");
    }

    // get signature cert.chain if any and pass along to service
    {
        if (null != samlResponse.getSignature()) {

            try {
                List<X509Certificate> certChain = KeyInfoHelper
                        .getCertificates(samlResponse.getSignature().getKeyInfo());

                if (null != service) {
                    service.validateServiceCertificate(authenticationResponse.getAuthenticationPolicy(),
                            certChain);
                }
            } catch (CertificateException e) {
                throw new AuthenticationResponseProcessorException(e);
            } catch (Exception e) {

                if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                    Exception exception;
                    try {
                        Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                                new Class[] {});
                        exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                    } catch (Exception e2) {
                        LOG.debug("error: " + e.getMessage(), e);
                        throw new AuthenticationResponseProcessorException(
                                "error retrieving the root cause: " + e2.getMessage());
                    }

                    throw new AuthenticationResponseProcessorException("Validation exception: "
                            + (null != exception ? exception.getMessage() : e.getMessage()));
                }

                throw new AuthenticationResponseProcessorException(e);
            }
        }
    }

    // validate optional relaystate
    String returnedRelayState = request.getParameter(RELAY_STATE_PARAM);
    if (null != relayState) {
        if (!relayState.equals(returnedRelayState)) {
            throw new AuthenticationResponseProcessorException(
                    "Returned RelayState does not match original RelayState");
        }
    } else {
        if (null != returnedRelayState) {
            throw new AuthenticationResponseProcessorException("Did not expect RelayState to be returned.");
        }
    }
    authenticationResponse.setRelayState(relayState);

    return authenticationResponse;
}

From source file:be.fedict.eid.idp.sp.protocol.saml2.AuthenticationRequestUtil.java

License:Open Source License

/**
 * Generates a SAML v2.0 Authentication Request and performs a browser POST
 * to the specified idpDestination./*from   ww  w .ja  v a  2s.  co m*/
 * 
 * @param issuerName
 *            issuer of the SAML v2.0 AuthnRequest
 * @param idpDestination
 *            required eID IdP destination
 * @param spDestination
 *            Service Provider landing URL where the IdP will post the SAML2
 *            Response to.
 * @param relayState
 *            optional relay state
 * @param spIdentity
 *            optional Service Provider Identity. If specified the
 *            authentication request will be signed.
 * @param response
 *            response used for posting the request to the IdP
 * @param language
 *            optional language hint
 * @return the SAML v2.0 AuthnRequest just sent over.
 * @throws ServletException
 *             something went wrong.
 */
@SuppressWarnings("unchecked")
public static AuthnRequest sendRequest(String issuerName, String idpDestination, String spDestination,
        String relayState, KeyStore.PrivateKeyEntry spIdentity, HttpServletResponse response, String language)
        throws ServletException {

    if (null == idpDestination) {
        throw new ServletException("No IdP Destination specified");
    }
    if (null == spDestination) {
        throw new ServletException("No SP Destination specified");
    }

    LOG.debug("Issuer: " + issuerName);
    LOG.debug("IdP destination: " + idpDestination);
    LOG.debug("SP destination: " + spDestination);
    LOG.debug("relay state: " + relayState);
    LOG.debug("SP identity: " + spIdentity);

    String idpEndpoint = idpDestination;
    if (null != language) {
        idpEndpoint += "?language=" + language;
    }

    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SAMLObjectBuilder<AuthnRequest> requestBuilder = (SAMLObjectBuilder<AuthnRequest>) builderFactory
            .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    AuthnRequest authnRequest = requestBuilder.buildObject();
    authnRequest.setID("authn-request-" + UUID.randomUUID().toString());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setDestination(idpDestination);
    authnRequest.setAssertionConsumerServiceURL(spDestination);
    authnRequest.setForceAuthn(true);
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);

    SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) builderFactory
            .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerName);
    authnRequest.setIssuer(issuer);

    SAMLObjectBuilder<Endpoint> endpointBuilder = (SAMLObjectBuilder<Endpoint>) builderFactory
            .getBuilder(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    Endpoint samlEndpoint = endpointBuilder.buildObject();
    samlEndpoint.setLocation(idpEndpoint);
    samlEndpoint.setResponseLocation(spDestination);

    OutTransport outTransport = new HttpServletResponseAdapter(response, true);

    BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();
    messageContext.setOutboundMessageTransport(outTransport);
    messageContext.setPeerEntityEndpoint(samlEndpoint);
    messageContext.setOutboundSAMLMessage(authnRequest);
    messageContext.setRelayState(relayState);

    // sign request if a SP identity is specified
    if (null != spIdentity) {

        List<X509Certificate> certChain = new LinkedList<X509Certificate>();
        for (Certificate certificate : spIdentity.getCertificateChain()) {
            certChain.add((X509Certificate) certificate);
        }

        BasicX509Credential credential = new BasicX509Credential();
        credential.setPrivateKey(spIdentity.getPrivateKey());
        credential.setEntityCertificateChain(certChain);

        // enable adding the cert.chain as KeyInfo
        X509KeyInfoGeneratorFactory factory = (X509KeyInfoGeneratorFactory) org.opensaml.xml.Configuration
                .getGlobalSecurityConfiguration().getKeyInfoGeneratorManager().getDefaultManager()
                .getFactory(credential);
        factory.setEmitEntityCertificateChain(true);

        messageContext.setOutboundSAMLMessageSigningCredential(credential);
    }

    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, Log4JLogChute.class.getName());
    try {
        velocityEngine.init();
    } catch (Exception e) {
        throw new ServletException("velocity engine init error: " + e.getMessage(), e);
    }
    HTTPPostEncoder encoder = new HTTPPostEncoder(velocityEngine, "/templates/saml2-post-binding.vm");
    try {
        encoder.encode(messageContext);
    } catch (MessageEncodingException e) {
        throw new ServletException("SAML encoding error: " + e.getMessage(), e);
    }

    return authnRequest;
}

From source file:be.fedict.eid.idp.sp.protocol.ws_federation.AuthenticationResponseProcessor.java

License:Open Source License

/**
 * Process the incoming WS-Federation response.
 * /*from ww  w.ja v  a 2  s.c  o m*/
 * @param recipient
 *            recipient, should match SAML v2.0 assertions's
 *            AudienceRestriction
 * @param context
 *            optional expected context
 * @param requiresResponseSignature
 *            do we expect a signature on the response or not, or
 *            <code>null</code> if to be retrieved from the
 *            {@link AuthenticationResponseService}.
 * @param request
 *            the HTTP servlet request that holds the SAML2 response.
 * @return the {@link be.fedict.eid.idp.common.saml2.AuthenticationResponse}
 * @throws AuthenticationResponseProcessorException
 *             case something went wrong
 */
public AuthenticationResponse process(String recipient, String context, Boolean requiresResponseSignature,
        HttpServletRequest request) throws AuthenticationResponseProcessorException {

    DateTime now = new DateTime();
    SecretKey secretKey = null;
    PrivateKey privateKey = null;
    int maxOffset = 5;
    boolean expectAssertionSigned = null != requiresResponseSignature ? requiresResponseSignature : false;
    ValidationService validationService = null;

    if (null != this.service) {
        secretKey = this.service.getAttributeSecretKey();
        privateKey = this.service.getAttributePrivateKey();
        maxOffset = this.service.getMaximumTimeOffset();
        expectAssertionSigned = this.service.requiresResponseSignature();
        validationService = this.service.getValidationService();
    }

    // force UTF8 encoding!
    try {
        request.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationResponseProcessorException(e);
    }

    // check wa
    String wa = request.getParameter("wa");
    if (null == wa) {
        throw new AuthenticationResponseProcessorException("Missing \"wa\" param.");
    }
    if (!wa.equals("wsignin1.0")) {
        throw new AuthenticationResponseProcessorException("Unexpected value for \"wa\" param.");
    }

    // validate optional ctx
    validateContext(context, request.getParameter("wctx"));

    // get wresult
    String wresult = request.getParameter("wresult");
    LOG.debug("wresult=\"" + wresult + "\"");

    if (null == wresult) {
        throw new AuthenticationResponseProcessorException("Missing \"wresult\" param.");
    }
    Document responseDocument = Saml2Util.parseDocument(wresult);
    RequestSecurityTokenResponseCollection rstCollections = Saml2Util
            .unmarshall(responseDocument.getDocumentElement());

    if (rstCollections.getRequestSecurityTokenResponses().size() != 1) {
        throw new AuthenticationResponseProcessorException("Expected exactly 1 RequestSecurityTokenResponse");
    }

    RequestSecurityTokenResponse rstResponse = rstCollections.getRequestSecurityTokenResponses().get(0);

    // context
    validateContext(context, rstResponse.getContext());

    // tokentype
    validateTokenType(rstResponse);

    // requesttype
    validateRequestType(rstResponse);

    // keytype
    validateKeyType(rstResponse);

    // validate security token
    Assertion assertion = validateSecurityToken(rstResponse);

    // validate assertion
    AuthenticationResponse authenticationResponse;
    try {
        authenticationResponse = Saml2Util.validateAssertion(assertion, now, maxOffset, recipient, recipient,
                null, secretKey, privateKey);
    } catch (AssertionValidationException e) {
        throw new AuthenticationResponseProcessorException(e);
    }

    // check if SP expects a signature and if there is one
    if (null == assertion.getSignature() && expectAssertionSigned) {
        throw new AuthenticationResponseProcessorException("Expected a signed assertion but was not so! ");
    }

    // validate assertion's signature if any
    if (null != assertion.getSignature()) {
        try {
            // fix for recent versions of Apache xmlsec
            assertion.getDOM().setIdAttribute("ID", true);

            List<X509Certificate> certificateChain = Saml2Util.validateSignature(assertion.getSignature());

            if (null != validationService) {
                // have to reparse the document here
                NodeList assertionNodeList = Saml2Util.parseDocument(wresult)
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion");
                LOG.debug("number of SAML2 assertions: " + assertionNodeList.getLength());
                if (1 != assertionNodeList.getLength()) {
                    throw new AuthenticationResponseProcessorException("missing SAML2 Assertion");
                }
                Element assertionElement = (Element) assertionNodeList.item(0);

                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document tokenDocument = documentBuilder.newDocument();
                Node assertionTokenNode = tokenDocument.importNode(assertionElement, true);
                tokenDocument.appendChild(assertionTokenNode);

                String validationServiceLocation = validationService.getLocation();
                String expectedAudience = validationService.getExpectedAudience();
                SecurityTokenServiceClient securityTokenServiceClient = new SecurityTokenServiceClient(
                        validationServiceLocation);
                securityTokenServiceClient.validateToken(tokenDocument.getDocumentElement(), expectedAudience);
            }
            if (null != this.service) {
                this.service.validateServiceCertificate(authenticationResponse.getAuthenticationPolicy(),
                        certificateChain);
            }

        } catch (CertificateException e) {
            throw new AuthenticationResponseProcessorException(e);
        } catch (ValidationException e) {
            throw new AuthenticationResponseProcessorException(e);
        } catch (Exception e) {

            if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                Exception exception;
                try {
                    Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                            new Class[] {});
                    exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                } catch (Exception e2) {
                    LOG.debug("error: " + e.getMessage(), e);
                    throw new AuthenticationResponseProcessorException(
                            "error retrieving the root cause: " + e2.getMessage());
                }

                throw new AuthenticationResponseProcessorException("Validation exception: "
                        + (null != exception ? exception.getMessage() : e.getMessage()));
            }

            throw new AuthenticationResponseProcessorException(e);
        }
    }

    return authenticationResponse;
}

From source file:be.kdg.repaircafemodel.dom.repairs.Bid.java

public Bid(double price) {
    bidId = bidCounter++;
    this.price = price;
    timestamp = new DateTime();
}

From source file:be.kdg.repaircafemodel.dom.repairs.RepairDetails.java

public RepairDetails() {
    this.submitDate = new DateTime();
    this.dueDate = new DateTime().plusWeeks(2);
    this.rating = Rating.NotSet;
    this.status = Status.Broken;
}

From source file:be.kdg.repaircafemodel.dom.repairs.RepairDetails.java

/**
 * How much time is left for bidding on this repair
 *
 * @return Period. Represents time period
 *///from ww  w. jav a2 s.  co m
public Period getExpirationTime() {
    return new Period(new DateTime(), dueDate);
}

From source file:be.roots.taconic.pricingguide.service.ReportServiceImpl.java

License:Open Source License

@Override
public void report(Contact contact, List<String> modelIds) throws IOException {

    final CSVFormat csvFileFormat = CSVFormat.DEFAULT;
    final FileWriter fileWriter = new FileWriter(getFileNameFor(new DateTime()), true);
    final CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

    final List<String> record = new ArrayList<>();

    record.add(new DateTime().toString(DefaultUtil.FORMAT_TIMESTAMP));

    record.add(contact.getHsId());//ww  w . j  a  va 2 s  .c o  m
    record.add(contact.getSalutation());
    record.add(contact.getFirstName());
    record.add(contact.getLastName());
    record.add(contact.getEmail());
    record.add(contact.getCompany());
    record.add(contact.getCountry());
    record.add(contact.getPersona());
    if (contact.getJobRole() != null) {
        record.add(contact.getJobRole().getDescription());
    } else {
        record.add(null);
    }
    if (contact.getCurrency() != null) {
        record.add(contact.getCurrency().name());
        record.add(contact.getCurrency().getDescription());
    } else {
        record.add(null);
        record.add(null);
    }

    record.addAll(modelIds);

    csvFilePrinter.printRecord(record);
    csvFilePrinter.close();

}

From source file:be.roots.taconic.pricingguide.service.ReportServiceImpl.java

License:Open Source License

@Override
public DateTime getLastMonth() {
    return new DateTime().minusMonths(1);
}

From source file:bear.core.SessionContext.java

License:Apache License

private void logLevel(String s, String level, Object[] params) {
    // and here's how to get the String representation

    if (!s.endsWith("%n") && !s.endsWith("\n")) {
        s += "\n";
    }//from   w w w .ja  va  2 s  . co  m

    System.out.printf(new DateTime().toString(TIME_FORMATTER) + " " + level + " " + s, params);
}

From source file:bear.task.TaskExecutionContext.java

License:Apache License

public long getDuration() {
    //        Optional<ExecContext> firstEntry = getFirstEntry();
    ////w ww  . j  av a 2  s .c  o m
    //        if (!firstEntry.isPresent() || !firstEntry.get().hasStarted()) {
    //            return 0;
    //        }
    //
    //        Optional<ExecContext> lastEntry = getLastEntry();
    //
    //        DateTime finishedAt = lastEntry.isPresent() ? null : lastEntry.get().getFinishedAt();

    DateTime finishedAt = this.finishedAt == null ? new DateTime() : this.finishedAt;

    return finishedAt.getMillis() - getStartedAt().getMillis();
}