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:com.aionemu.gameserver.utils.gametime.DateTimeUtil.java

License:Open Source License

public static DateTime getDateTime() {
    DateTime dt = new DateTime();
    if (canApplyZoneChange) {
        return dt.withZoneRetainFields(DateTimeZone.forID(GSConfig.TIME_ZONE_ID));
    }/*  www. j  a  v a 2s  .com*/
    return dt;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.logout.LogoutProfile.java

License:Open Source License

private LogoutRequest buildLogoutRequest(String sID, IUser user, String reason, String sDestination,
        String sSessionIndex) throws OAException {
    LogoutRequestBuilder lrBuilder = (LogoutRequestBuilder) _builderFactory
            .getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);

    LogoutRequest logoutRequest = lrBuilder.buildObject();

    logoutRequest.setID(sID);//from  w  w  w. j  ava2 s.c o m

    String sNameIDFormat = null;
    String sNameQualifier = null;

    if (user instanceof SAMLRemoteUser) {
        SAMLRemoteUser userSAML = (SAMLRemoteUser) user;
        sNameIDFormat = userSAML.getFormat();

        //add session index to request
        SessionIndexBuilder sessionIndexBuilder = (SessionIndexBuilder) _builderFactory
                .getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
        SessionIndex sessionIndex = sessionIndexBuilder.buildObject();
        sessionIndex.setSessionIndex(sSessionIndex);
        logoutRequest.getSessionIndexes().add(sessionIndex);

        //the namequalifier that was returned by the remote SAML 
        //organization is set as the organization of the remote 
        //SAML user; this way the organization is set as name qualifier
        sNameQualifier = userSAML.getOrganization();
    } else
        sNameQualifier = _entityDescriptor.getEntityID();

    NameID nid = buildNameID(user.getID(), sNameIDFormat, sNameQualifier);
    logoutRequest.setNameID(nid);

    if (reason != null) {
        logoutRequest.setReason(reason);
    }

    logoutRequest.setVersion(SAMLVersion.VERSION_20);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setIssuer(buildIssuer());
    if (sDestination != null)
        logoutRequest.setDestination(sDestination);

    if (_signingEnabled) {
        signSAMLObject(logoutRequest);
    }

    return logoutRequest;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.sso.WebBrowserSSOProfile.java

License:Open Source License

/**
 * Creates and sends the SAML2 AuthnRequest to the supplied IdP.
 *  // ww  w.  j  a  v a2s.c o m
 * @param servletRequest Servlet Request
 * @param servletResponse Selvet Response
 * @param session AuthN session
 * @param organization Target IdP
 * @return User Event
 * @throws OAException If authnrequest could not be send
 */
protected UserEvent createAuthNRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        ISession session, SAML2IDP organization) throws OAException {
    try {
        IDPSSODescriptor descriptor = getIdPDescriptor(organization);
        String sSupportedBinding = getSupportedBinding(descriptor);
        if (sSupportedBinding == null) {
            _logger.error("Authentication request could not be formed, since no suitable binding can be found");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
        _logger.debug("Using binding: " + sSupportedBinding);

        String sDestination = null;

        for (SingleSignOnService service : descriptor.getSingleSignOnServices()) {
            if (service.getBinding().equals(sSupportedBinding)) {
                sDestination = service.getLocation();
            }
        }

        AuthnRequest request = buildAuthnRequest();

        ISessionAttributes sessionAttributes = session.getAttributes();
        String requestID = generateRequestID(session.getId(), sessionAttributes);
        request.setID(requestID);

        //Add AssertionConsumerService

        if (_spSSODescriptor != null) {
            AssertionConsumerService acs = _spSSODescriptor.getDefaultAssertionConsumerService();
            if (acs != null) {
                Integer intIndex = acs.getIndex();
                String sLocation = acs.getLocation();
                String sBinding = acs.getBinding();
                if (intIndex != null && organization.useACSIndex() != null && organization.useACSIndex()) {
                    request.setAssertionConsumerServiceIndex(intIndex);
                } else if (sLocation != null && sBinding != null) {//If the AssertionConsumerServiceIndex can't be set, the following info should be set:
                    request.setAssertionConsumerServiceURL(sLocation);
                    request.setProtocolBinding(sBinding);
                }
            }
        }

        request.setDestination(sDestination);
        request.setIssueInstant(new DateTime());

        Issuer issuer = buildIssuer();
        request.setIssuer(issuer);

        //NameIDPolicy
        if (organization.useNameIDPolicy() != null && organization.useNameIDPolicy()) {
            NameIDPolicy nidp = buildNameIDPolicy(session, descriptor, organization.useAllowCreate(),
                    organization.getNameIDFormat());
            if (nidp != null)
                request.setNameIDPolicy(nidp);
        }

        IUser user = session.getUser();
        String sRequestUID = session.getForcedUserID();
        if (user != null)
            sRequestUID = user.getID();

        if (sRequestUID != null) {
            String sNameQualifier = _entityDescriptor.getEntityID();
            String sNameIDFormat = NameIDType.UNSPECIFIED;
            if (user instanceof SAMLRemoteUser) {
                SAMLRemoteUser samlUser = ((SAMLRemoteUser) user);
                sNameIDFormat = samlUser.getFormat();

                //the namequalifier that was returned by the remote SAML 
                //organization is set as the organization of the remote 
                //SAML user; this way the organization is set as name qualifier
                sNameQualifier = samlUser.getOrganization();
            } else {
                String sProxyNameID = (String) sessionAttributes.get(ProxyAttributes.class,
                        ProxyAttributes.SUBJECT_NAMEID);
                if (sProxyNameID != null && sProxyNameID.equals(session.getForcedUserID())) {//Check if the force user id is supplied by the requestor (SAML2) 

                    String sProxyNameIDFormat = (String) sessionAttributes.get(ProxyAttributes.class,
                            ProxyAttributes.SUBJECT_NAME_FORMAT);
                    if (sProxyNameIDFormat != null)
                        sNameIDFormat = sProxyNameIDFormat;

                    String sProxyNameQualifier = (String) sessionAttributes.get(ProxyAttributes.class,
                            ProxyAttributes.SUBJECT_NAME_QUALIFIER);
                    if (sProxyNameQualifier != null)
                        sNameQualifier = sProxyNameQualifier;
                }
            }

            Subject subject = buildSubject(sRequestUID, sNameIDFormat, sNameQualifier,
                    organization.avoidSubjectConfirmations());
            if (subject != null)
                request.setSubject(subject);
        }

        //Scoping
        if (organization.useScoping() != null && organization.useScoping()) {
            Scoping scop = buildScoping(sessionAttributes, session.getRequestorId());
            if (scop != null)
                request.setScoping(scop);
        }

        //TODO is the forceAuthN parameter for the session also valid for remote authNs? 
        request.setForceAuthn(session.isForcedAuthentication());

        String sProviderName = (String) sessionAttributes.get(ProxyAttributes.class,
                ProxyAttributes.PROVIDERNAME);
        if (sProviderName != null) {
            request.setProviderName(sProviderName);
        } else {//DD set ProviderName with requestor name if not supplied in AuthnRequest
            IRequestor requestor = _requestorPoolFactory.getRequestor(session.getRequestorId());
            if (requestor != null) {
                String sFriendlyName = requestor.getFriendlyName();
                if (sFriendlyName != null && sFriendlyName.length() > 0)
                    request.setProviderName(sFriendlyName);
            }
        }

        //DD proxy the optionally available authncontext
        RequestedAuthnContext requestedAuthnContext = buildRequestedAuthnContext(sessionAttributes);
        if (requestedAuthnContext != null)
            request.setRequestedAuthnContext(requestedAuthnContext);

        AbstractEncodingFactory encFactory = AbstractEncodingFactory.createInstance(servletRequest,
                servletResponse, sSupportedBinding,
                SAML2Exchange.getSPSSOBindingProperties(_sLinkedIDPProfile));

        if (encFactory == null) {
            _logger.error("No encoding factory available for request");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = createEncodingContext(
                servletRequest, servletResponse);

        context.setInboundMessageIssuer(organization.getID());
        context.setOutboundMessageIssuer(_entityDescriptor.getEntityID());
        context.setLocalEntityId(_entityDescriptor.getEntityID());
        context.setLocalEntityMetadata(_entityDescriptor);
        context.setLocalEntityRoleMetadata(_entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
        context.setMetadataProvider(organization.getMetadataProvider());

        context.setOutboundSAMLMessage(request);

        Endpoint endPoint = buildMetadataEndpoint(AssertionConsumerService.DEFAULT_ELEMENT_NAME,
                sSupportedBinding, sDestination, null);
        context.setPeerEntityEndpoint(endPoint);

        if (_signingEnabled) {
            Credential credentials = SAML2CryptoUtils.retrieveMySigningCredentials(_crypto,
                    _entityDescriptor.getEntityID());
            context.setOutboundSAMLMessageSigningCredential(credentials);
        } else if (_spSSODescriptor.isAuthnRequestsSigned() || descriptor.getWantAuthnRequestsSigned()) {
            _logger.warn("Could not sign AuthnRequest: no private key available");
        }

        SAMLMessageEncoder encoder = encFactory.getEncoder();

        //session must be persisted before sending the request.
        session.persist();

        encoder.encode(context);

        if (_logger.isDebugEnabled()) {
            XMLObject xmlObject = context.getOutboundSAMLMessage();
            if (xmlObject != null)
                logXML(xmlObject);
        }

        return UserEvent.AUTHN_METHOD_IN_PROGRESS;
    } catch (OAException e) {
        throw e;
    } catch (MessageEncodingException e) {
        _logger.error("Encoding of authentication request failed", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.util.RemoteIDPListEntry.java

License:Open Source License

/**
 * Retrieves the list.//  www. ja v  a 2  s .  c  o m
 * 
 * @return The IDPList xml resource.
 * @throws ResourceException When list could not be fetched or is malformed.
 */
public IDPList getList() throws ResourceException {
    if (getLastModifiedTime().compareTo(new DateTime()) < 0 && _list != null) {
        //not modified lately
        _logger.debug("Resource not modified lately");
        return _list;
    }

    _logger.debug("Retrieving resource from URL " + getLocation());

    GetMethod m = super.getResource();

    try {
        _client.executeMethod(m);
        if (m.getStatusCode() == HttpStatus.SC_OK) {
            _list = unmarshall(m.getResponseBodyAsStream());
            _logger.debug("Resource successfully retrieved from URL " + getLocation());
            return _list;
        }

        StringBuffer buf = new StringBuffer("Retrieval of IDPList returned wrong HTTP status: ");
        buf.append(m.getStatusCode());
        throw new ResourceException(buf.toString());
    } catch (HttpException e) {
        throw new ResourceException("HTTP Error occurred", e);
    } catch (IOException e) {
        throw new ResourceException("I/O error occurred", e);
    }
}

From source file:com.alfaariss.oa.profile.saml2.listener.slo.SynchronousSingleLogout.java

License:Open Source License

private LogoutRequest buildLogoutRequest(String sID, IUser user, String reason, ITGTAttributes attributes,
        String sSessionIndex, String tgtID, String requestorID) throws OAException, SecurityException {
    LogoutRequestBuilder lrBuilder = (LogoutRequestBuilder) _builderFactory
            .getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);

    LogoutRequest logoutRequest = lrBuilder.buildObject();

    logoutRequest.setID(sID);/*from w  w w .  j av  a2 s  . c o  m*/

    //TODO add support for multiple session indexes
    SessionIndexBuilder sessionIndexBuilder = (SessionIndexBuilder) _builderFactory
            .getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
    SessionIndex sessionIndex = sessionIndexBuilder.buildObject();
    sessionIndex.setSessionIndex(sSessionIndex);
    logoutRequest.getSessionIndexes().add(sessionIndex);

    String sNameQualifier = _entityDescriptor.getEntityID();

    String sNameIDFormat = (String) attributes.get(WebBrowserSSO.class, WebBrowserSSO.TGT_REQUEST_NAMEIDFORMAT);

    String sSPNameQualifier = (String) attributes.get(WebBrowserSSO.class,
            WebBrowserSSO.TGT_REQUEST_SPNAMEQUALIFIER);

    String sNameID = _nameIDFormatter.resolve(sNameIDFormat, requestorID, tgtID);
    if (sNameID == null) {
        StringBuffer sbDebug = new StringBuffer("No NameID found with format '");
        sbDebug.append(sNameIDFormat);
        sbDebug.append("' for requestor: ");
        sbDebug.append(requestorID);
        _logger.debug(sbDebug.toString());
        sNameID = user.getID();
        sNameIDFormat = null;
    }

    NameID nid = buildNameID(sNameID, sNameIDFormat, sNameQualifier, sSPNameQualifier);
    logoutRequest.setNameID(nid);

    logoutRequest.setReason(reason);
    logoutRequest.setVersion(SAMLVersion.VERSION_20);
    logoutRequest.setIssueInstant(new DateTime());

    Issuer issuer = buildIssuer(null, _entityDescriptor.getEntityID());
    logoutRequest.setIssuer(issuer);

    if (_cryptoManager.getPrivateKey() != null) {
        Signature signature = createSignature();
        logoutRequest.setSignature(signature);

        //update digest algorithm
        SAMLObjectContentReference contentReference = ((SAMLObjectContentReference) signature
                .getContentReferences().get(0));
        contentReference
                .setDigestAlgorithm(SAML2CryptoUtils.getXMLDigestMethodURI(_cryptoManager.getMessageDigest()));

        signXMLObject(logoutRequest, signature);
    }

    return logoutRequest;
}

From source file:com.alfaariss.oa.profile.saml2.profile.sso.protocol.AuthenticationRequestProtocol.java

License:Open Source License

private Assertion buildAssertion(ITGT tgt, List<String> authnContextTypes, IAttributes attributes,
        String sAttributeNameFormat, Hashtable<String, String> htAttributeNameFormatMapper,
        String sSessionIndex, long lExpirationOffset, List<String> listAuthenticatingAuthorities)
        throws OAException {
    Assertion assertion = null;//w  w  w .  j ava2 s.  c o m
    try {
        AssertionBuilder builder = (AssertionBuilder) _builderFactory
                .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);

        // Create the assertion
        assertion = builder.buildObject();
        assertion.setVersion(SAMLVersion.VERSION_20);
        assertion.setID(sSessionIndex);
        assertion.setIssueInstant(new DateTime());

        Issuer issuer;
        if (_sShadowedEntityId != null) {
            issuer = buildIssuer(null, _sShadowedEntityId);
        } else {
            issuer = buildIssuer(null, _sEntityID);
        }
        assertion.setIssuer(issuer);

        DateTime dtNotOnOrAfter = new DateTime(System.currentTimeMillis() + lExpirationOffset);

        String sTGTID = null;
        if (tgt != null)
            sTGTID = tgt.getId();

        String sNameID = _nameIDFormatter.format(_session.getUser(), _sNameIDFormat, _session.getRequestorId(),
                sTGTID);
        Subject subject = buildSubject(sNameID, dtNotOnOrAfter);
        assertion.setSubject(subject);

        DateTime dtAuthnStatementNotOnOrAfter = dtNotOnOrAfter;
        if (tgt != null)
            dtAuthnStatementNotOnOrAfter = new DateTime(tgt.getTgtExpTime());

        for (String authnContextType : authnContextTypes) {
            AuthnStatement authnStatement = buildAuthnStatement(sSessionIndex, dtAuthnStatementNotOnOrAfter,
                    authnContextType, listAuthenticatingAuthorities);
            assertion.getAuthnStatements().add(authnStatement);
        }

        if (attributes.size() > 0) {
            AttributeStatement attributeStatement = buildAttributeStatement(attributes, sAttributeNameFormat,
                    htAttributeNameFormatMapper);
            assertion.getAttributeStatements().add(attributeStatement);
        }

        Conditions conditions = buildConditions(dtNotOnOrAfter);
        assertion.setConditions(conditions);
    } catch (OAException e) {
        throw e;
    }

    return assertion;
}

From source file:com.alfaariss.oa.profile.saml2.profile.sso.protocol.AuthenticationRequestProtocol.java

License:Open Source License

private Conditions buildConditions(DateTime dtNotOnOrAfter) {
    AudienceRestrictionBuilder audienceRestrictionBuilder = (AudienceRestrictionBuilder) _builderFactory
            .getBuilder(AudienceRestriction.DEFAULT_ELEMENT_NAME);
    AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
    AudienceBuilder audienceBuilder = (AudienceBuilder) _builderFactory
            .getBuilder(Audience.DEFAULT_ELEMENT_NAME);
    Audience audience = audienceBuilder.buildObject();
    audience.setAudienceURI(_session.getRequestorId());
    audienceRestriction.getAudiences().add(audience);

    ConditionsBuilder conditionsBuilder = (ConditionsBuilder) _builderFactory
            .getBuilder(Conditions.DEFAULT_ELEMENT_NAME);
    Conditions conditions = conditionsBuilder.buildObject();
    conditions.getAudienceRestrictions().add(audienceRestriction);

    conditions.setNotBefore(new DateTime());
    conditions.setNotOnOrAfter(new DateTime(dtNotOnOrAfter));

    return conditions;
}

From source file:com.alfaariss.oa.profile.saml2.profile.sso.protocol.AuthenticationRequestProtocol.java

License:Open Source License

private AuthnStatement buildAuthnStatement(String sSessionIndex, DateTime dtSessionNotOnOrAfter,
        String authnContextType, List<String> listAuthenticatingAuthorities) {
    //Create the AuthnStatement
    AuthnStatementBuilder authnStatemenBuilder = (AuthnStatementBuilder) _builderFactory
            .getBuilder(AuthnStatement.DEFAULT_ELEMENT_NAME);
    AuthnStatement authnStatement = authnStatemenBuilder.buildObject();
    authnStatement.setAuthnInstant(new DateTime());
    authnStatement.setSessionIndex(sSessionIndex);
    authnStatement.setSessionNotOnOrAfter(dtSessionNotOnOrAfter);

    AuthnContextBuilder authnContextBuilder = (AuthnContextBuilder) _builderFactory
            .getBuilder(AuthnContext.DEFAULT_ELEMENT_NAME);
    AuthnContext authnContext = authnContextBuilder.buildObject();

    AuthnContextClassRefBuilder authnContextClassRefBuilder = (AuthnContextClassRefBuilder) _builderFactory
            .getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject();
    authnContextClassRef.setAuthnContextClassRef(authnContextType);
    authnContext.setAuthnContextClassRef(authnContextClassRef);

    if (listAuthenticatingAuthorities != null) {//DD set the authenticating authority
        for (String sAuthorityURI : listAuthenticatingAuthorities) {
            AuthenticatingAuthorityBuilder authenticatingAuthorityBuilder = (AuthenticatingAuthorityBuilder) _builderFactory
                    .getBuilder(AuthenticatingAuthority.DEFAULT_ELEMENT_NAME);
            AuthenticatingAuthority authnticatingAuthority = authenticatingAuthorityBuilder.buildObject();
            authnticatingAuthority.setURI(sAuthorityURI);
            authnContext.getAuthenticatingAuthorities().add(authnticatingAuthority);
        }//from   w ww . j a  v  a 2s  .c  o m
    }

    authnStatement.setAuthnContext(authnContext);

    return authnStatement;
}

From source file:com.alfaariss.oa.util.saml2.binding.artifact.ImplementedHTTPArtifactDecoder.java

License:Open Source License

/**
 * @see org.opensaml.saml2.binding.decoding.HTTPArtifactDecoder#processArtifact(org.opensaml.common.binding.SAMLMessageContext)
 *//*from w w  w.ja va  2 s. c o m*/
@SuppressWarnings("unchecked")
protected void processArtifact(SAMLMessageContext samlMsgCtx) throws MessageDecodingException {
    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    String encodedArtifact = DatatypeHelper.safeTrimOrNullString(inTransport.getParameterValue("SAMLart"));
    if (encodedArtifact == null) {
        _logger.error("URL SAMLart parameter was missing or did not contain a value");
        throw new MessageDecodingException("URL TARGET parameter was missing or did not contain a value");
    }

    ArtifactBuilder artifactBuilder = (ArtifactBuilder) _builderFactory
            .getBuilder(Artifact.DEFAULT_ELEMENT_NAME);
    Artifact artifact = artifactBuilder.buildObject();
    artifact.setArtifact(encodedArtifact);

    ArtifactResolveBuilder artifactResolveBuilder = (ArtifactResolveBuilder) _builderFactory
            .getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME);
    ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject();

    SecureRandomIdentifierGenerator idgen = null;
    try {
        idgen = new SecureRandomIdentifierGenerator();
    } catch (NoSuchAlgorithmException e) {
        String msg = "Could not generate ID for artifact resolve request";
        _logger.debug(msg);
        throw new MessageDecodingException(msg, e);
    }

    String id = idgen.generateIdentifier();

    artifactResolve.setID(id);
    artifactResolve.setVersion(SAMLVersion.VERSION_20);
    artifactResolve.setIssueInstant(new DateTime());
    artifactResolve.setArtifact(artifact);

    IssuerBuilder issuerBuilder = (IssuerBuilder) _builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(samlMsgCtx.getOutboundMessageIssuer());

    artifactResolve.setIssuer(issuer);

    MetadataProvider mp = samlMsgCtx.getMetadataProvider();
    if (mp == null) {
        _logger.debug("No MetadataProvider available in message context");
        throw new MessageDecodingException("No MetadataProvider available in message context");
    }

    String entID = samlMsgCtx.getInboundMessageIssuer();
    String endpoint = null;

    try {
        SSODescriptor rd = null;
        if (_sSSODescriptor != null) {
            if ("sp".equalsIgnoreCase(_sSSODescriptor)) {
                rd = (SPSSODescriptor) mp.getRole(entID, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
                        SAMLConstants.SAML20P_NS);
            } else if ("idp".equalsIgnoreCase(_sSSODescriptor)) {
                rd = (IDPSSODescriptor) mp.getRole(entID, IDPSSODescriptor.DEFAULT_ELEMENT_NAME,
                        SAMLConstants.SAML20P_NS);
            } else {
                StringBuffer sbDebug = new StringBuffer("Unknown SSODescriptor configured '");
                sbDebug.append(_sSSODescriptor);
                sbDebug.append("'; using IDPSSODescriptor");
                _logger.debug(sbDebug.toString());
            }
        }

        if (rd == null) {//default use IDP role
            rd = (IDPSSODescriptor) mp.getRole(entID, IDPSSODescriptor.DEFAULT_ELEMENT_NAME,
                    SAMLConstants.SAML20P_NS);
        }

        if (rd != null) {
            SAML2ArtifactType0004 b = null;
            SAML2ArtifactType0004Builder bf = new SAML2ArtifactType0004Builder();
            b = bf.buildArtifact(Base64.decode(encodedArtifact));

            String defaultEndpoint = null;
            String indexedEndpoint = null;
            String firstEndpoint = null;

            for (ArtifactResolutionService ars : rd.getArtifactResolutionServices()) {
                if (firstEndpoint == null)
                    firstEndpoint = ars.getLocation();
                if (ars.isDefault())
                    defaultEndpoint = ars.getLocation();

                int i = 0;
                byte[] ba = b.getEndpointIndex();

                for (int ia = ba.length - 1; ia >= 0; ia--) {
                    i = i + (ba[ia] * Byte.SIZE);
                }

                if (ars.getIndex() == i) {
                    indexedEndpoint = ars.getLocation();
                }
            }

            //choose right endpoint:
            if (indexedEndpoint != null)
                endpoint = indexedEndpoint;
            else if (defaultEndpoint != null)
                endpoint = defaultEndpoint;
            else
                endpoint = firstEndpoint;
        }
    } catch (MetadataProviderException e1) {
        String msg = "Exception while fetching metadata for requestor while decoding artifact";
        _logger.debug(msg);
        throw new MessageDecodingException(msg, e1);
    }

    if (endpoint == null) {
        String msg = "Could not fetch endpoint for requestor while decoding artifact";
        _logger.debug(msg);
        throw new MessageDecodingException(msg);
    }

    BodyBuilder bodyBuilder = (BodyBuilder) _builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
    Body body = bodyBuilder.buildObject();
    body.getUnknownXMLObjects().add(artifactResolve);

    EnvelopeBuilder envelopeBuilder = (EnvelopeBuilder) _builderFactory
            .getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    Envelope env = envelopeBuilder.buildObject();
    env.setBody(body);

    BasicSOAPMessageContext soapContext = new BasicSOAPMessageContext();
    soapContext.setOutboundMessage(env);

    HttpClientBuilder clientBuilder = new HttpClientBuilder();
    clientBuilder.setConnectionTimeout(5000);

    HttpSOAPClient soapClient = new HttpSOAPClient(clientBuilder.buildClient(), super.getParserPool());

    if (_logger.isDebugEnabled())
        logXML(env);

    try {
        soapClient.send(endpoint, soapContext);
    } catch (Exception e) {
        String msg = "Could not resolve artifact";
        _logger.debug(msg, e);
        throw new MessageDecodingException(msg, e);
    }

    Envelope envelope = (Envelope) soapContext.getInboundMessage();

    if (_logger.isDebugEnabled())
        logXML(envelope);

    XMLObject samlResponseMessage = null;
    XMLObject responseMessage = soapContext.getInboundMessage();
    if (responseMessage != null && responseMessage instanceof Envelope) {
        Envelope responseEnvelope = (Envelope) responseMessage;
        Body responseBody = responseEnvelope.getBody();
        if (responseBody != null) {
            samlResponseMessage = responseBody.getUnknownXMLObjects().get(0);
        } else {
            _logger.debug("No body in response message");
        }
    } else {
        _logger.debug("No envelope in response message");
    }

    if (samlResponseMessage != null && samlResponseMessage instanceof ArtifactResponse) {
        ArtifactResponse artResp = (ArtifactResponse) samlResponseMessage;
        SAMLObject message = artResp.getMessage();
        if (message != null)
            samlMsgCtx.setInboundSAMLMessage(message);
        else
            _logger.debug("No message found in artifact: " + artResp);
    } else {
        _logger.debug("Response doesn't contain an ArtifactResponse object");
    }
}

From source file:com.alfaariss.oa.util.saml2.protocol.AbstractSAML2Protocol.java

License:Open Source License

/**
 * Populate a <code>Response</code>.
 *
 * Set the basic properties ID, version and issueInstant of a response.
* 
 * If no ID is supplied, an ID is generated.
 * @param response Empty response./*from  w w  w  .ja v  a2  s  .c o  m*/
 * @param id The optional message ID, 
 * @throws UnsupportedEncodingException If base64 encoding fails.
 */
protected void populateResponse(StatusResponseType response, String id) throws UnsupportedEncodingException {
    //DD Identifier is generated by crypto provider, uniqueness depends on provider implementation [saml-core r323]
    if (id == null) {
        //If no ID supplied generate one
        byte[] baId = new byte[REPONSE_ID_LENGTH];
        _random.nextBytes(baId);
        id = ModifiedBase64.encode(baId);
    }
    response.setID("_" + id);
    response.setIssueInstant(new DateTime());
    response.setVersion(SAMLVersion.VERSION_20);
}