/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. licenses this file to you under the Apache License,
*  Version 2.0 (the "License"); you may not use this file except
*  in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.sts.passive.processors;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.util.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.RahasConstants;
import org.apache.rahas.RahasData;
import org.apache.rahas.TrustException;
import org.apache.rahas.impl.SAMLPassiveTokenIssuer;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSSecurityEngineResult;
import org.apache.ws.security.WSUsernameTokenPrincipal;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.handler.WSHandlerResult;
import org.wso2.carbon.identity.sts.passive.ClaimDTO;
import org.wso2.carbon.identity.sts.passive.PassiveSTSService;
import org.wso2.carbon.identity.sts.passive.RequestToken;
import org.wso2.carbon.identity.sts.passive.ResponseToken;

import javax.xml.stream.XMLStreamException;
import java.util.Vector;

public class SigningRequestProcessor extends RequestProcessor {
    private static final Log log = LogFactory.getLog(SigningRequestProcessor.class);

    public ResponseToken process(RequestToken request) throws TrustException {

        MessageContext context = MessageContext.getCurrentMessageContext();
        SAMLPassiveTokenIssuer issuer = null;
        WSHandlerResult handlerResults = null;
        WSSecurityEngineResult engineResult = null;
        WSUsernameTokenPrincipal principal = null;
        Vector<WSSecurityEngineResult> wsResults = null;
        ResponseToken reponseToken = null;
        Vector<WSHandlerResult> handlerResultsVector = null;
        OMElement rstr = null;

        principal = new WSUsernameTokenPrincipal(request.getUserName(), false);

        engineResult = new WSSecurityEngineResult(WSConstants.UT, principal, null, null, null);

        wsResults = new Vector<WSSecurityEngineResult>();
        wsResults.add(engineResult);

        handlerResults = new WSHandlerResult("", wsResults);

        handlerResultsVector = new Vector<WSHandlerResult>();
        handlerResultsVector.add(handlerResults);

        MessageContext.getCurrentMessageContext().setProperty(WSHandlerConstants.RECV_RESULTS,
                handlerResultsVector);

        // no claim attributes are requested, not included in request. So add the default claim
        // attributes if they are available for the realm in request. The request may contain realm or wreply value,
        // so extract the realm value from wreply. In registry we have a mapping of realms to claims.
        // Claims are stored as comma separated values.
        if (request.getAttributes() == null || request.getAttributes().length() == 0) {
            String realm = request.getRealm();
            if (realm == null) {
                log.warn("Realm is not set in request token.");
                String replyTo = request.getReplyTo();
                URL url = new URL(replyTo);
                realm = url.getHost();
            }
            if (realm != null) {
                try {
                    ClaimDTO claimDTO = new PassiveSTSService().getTrustedServiceClaims(realm);
                    StringBuffer claims = new StringBuffer();
                    request.setDialect(claimDTO.getClaimDialect());
                    if (claimDTO.getDefaultClaims() != null) {
                        for (String claim : claimDTO.getDefaultClaims()) {
                            claims.append(claim).append(",");
                        }
                        request.setAttributes(claims.toString());
                        log.debug("Default claims were added to request.");
                    }
                } catch (Exception e) {
                    log.error("Failed to get default claims for trusted service realm " + realm, e);
                }
            }
        }


        try {
            MessageContext.getCurrentMessageContext().setProperty(RahasConstants.PASSIVE_STS_RST,
                    getRST(request.getRealm(), request.getAttributes(), request.getDialect()));
        } catch (Exception e) {
            log.error("Failed to get RST element.", e);
            throw new TrustException("errorWhileProcessingSigninRequest", e);
        }

        SAMLTokenIssuerConfig samlTokenIssuerConfig = null;
        try {
            samlTokenIssuerConfig = getSAMLTokenIssuerConfig(MessageContext.getCurrentMessageContext()
                    .getAxisService(), true);
        } catch (Exception e) {
            log.error("Failed to get saml token issuer config.", e);
            throw new TrustException("errorWhileProcessingSigninRequest", e);
        }

        rahasData = new RahasData(context);
        issuer = new SAMLPassiveTokenIssuer();
        issuer.setAudienceRestrictionCondition(request.getRealm());
        issuer.setConfig(samlTokenIssuerConfig);

        rstr = issuer.issuePassiveRSTR(rahasData);
        reponseToken = new ResponseToken();
        if (rstr != null) {
            try {
                reponseToken.setResults(rstr.toStringWithConsume());
            } catch (XMLStreamException e) {
                log.error(e.getMessage(), e);
                throw new TrustException("errorWhileProcessingSigninRequest", e);
            }
        }
        return reponseToken;
    }

}

@@ -809,42 +809,8 @@
 xt;%0A
-import org.apache.axis2.util.URL;%0A
 impo
@@ -844,16 +844,16 @@
 ng.Log;%0A
+
 import o
@@ -1380,125 +1380,8 @@
 lt;%0A
-import org.wso2.carbon.identity.sts.passive.ClaimDTO;%0Aimport org.wso2.carbon.identity.sts.passive.PassiveSTSService;%0A
 impo
@@ -2803,16 +2803,16 @@
 ESULTS,%0A
+
         
@@ -2847,1618 +2847,8 @@
 );%0A%0A
-        // no claim attributes are requested, not included in request. So add the default claim%0A        // attributes if they are available for the realm in request. The request may contain realm or wreply value,%0A        // so extract the realm value from wreply. In registry we have a mapping of realms to claims.%0A        // Claims are stored as comma separated values.%0A        if (request.getAttributes() == null %7C%7C request.getAttributes().length() == 0) %7B%0A            String realm = request.getRealm();%0A            if (realm == null) %7B%0A                log.warn(%22Realm is not set in request token.%22);%0A                String replyTo = request.getReplyTo();%0A                URL url = new URL(replyTo);%0A                realm = url.getHost();%0A            %7D%0A            if (realm != null) %7B%0A                try %7B%0A                    ClaimDTO claimDTO = new PassiveSTSService().getTrustedServiceClaims(realm);%0A                    StringBuffer claims = new StringBuffer();%0A                    request.setDialect(claimDTO.getClaimDialect());%0A                    if (claimDTO.getDefaultClaims() != null) %7B%0A                        for (String claim : claimDTO.getDefaultClaims()) %7B%0A                            claims.append(claim).append(%22,%22);%0A                        %7D%0A                        request.setAttributes(claims.toString());%0A                        log.debug(%22Default claims were added to request.%22);%0A                    %7D%0A                %7D catch (Exception e) %7B%0A                    log.error(%22Failed to get default claims for trusted service realm %22 + realm, e);%0A                %7D%0A            %7D%0A        %7D%0A%0A
 %0A   

Remove registry accessing to get claim