ws-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From gi...@apache.org
Subject svn commit: r1172285 [33/48] - in /webservices/wss4j/branches/swssf: ./ cxf-integration/ cxf-integration/src/ cxf-integration/src/main/ cxf-integration/src/main/java/ cxf-integration/src/main/java/org/ cxf-integration/src/main/java/org/swssf/ cxf-integ...
Date Sun, 18 Sep 2011 13:51:36 GMT
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/AbstractTestBase.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/AbstractTestBase.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/AbstractTestBase.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/AbstractTestBase.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,838 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.swssf.test;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSSConfig;
+import org.apache.ws.security.WSSecurityEngineResult;
+import org.apache.ws.security.action.SignatureAction;
+import org.apache.ws.security.handler.RequestData;
+import org.apache.ws.security.handler.WSHandler;
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.handler.WSHandlerResult;
+import org.apache.ws.security.message.WSSecSignature;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.apache.xml.security.utils.XMLUtils;
+import org.swssf.WSSec;
+import org.swssf.ext.*;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.securityEvent.SecurityEventListener;
+import org.swssf.test.utils.StAX2DOM;
+import org.swssf.test.utils.XmlReaderToWriter;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.rpc.Call;
+import javax.xml.rpc.JAXRPCException;
+import javax.xml.rpc.handler.HandlerInfo;
+import javax.xml.rpc.handler.MessageContext;
+import javax.xml.rpc.handler.soap.SOAPMessageContext;
+import javax.xml.soap.*;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.Logger;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public abstract class AbstractTestBase {
+
+    //javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
+    //transformer.transform(new StreamSource(new ByteArrayInputStream(baos.toByteArray())), new StreamResult(System.out));
+
+    protected static final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
+    protected static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
+    protected DocumentBuilderFactory documentBuilderFactory;
+
+    protected static final String SECURED_DOCUMENT = "securedDocument";
+
+    static {
+        LogManager.getLogManager().addLogger(Logger.getLogger("org.jcp.xml.dsig.internal.dom"));
+        LogManager.getLogManager().getLogger("org.jcp.xml.dsig.internal.dom").setLevel(Level.FINE);
+    }
+
+    public AbstractTestBase() {
+        documentBuilderFactory = DocumentBuilderFactory.newInstance();
+        documentBuilderFactory.setNamespaceAware(true);
+        documentBuilderFactory.setIgnoringComments(false);
+        documentBuilderFactory.setCoalescing(false);
+        documentBuilderFactory.setIgnoringElementContentWhitespace(false);
+        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, false);
+        xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
+        //xmlInputFactory.setProperty(WstxInputProperties.P_MIN_TEXT_SEGMENT, new Integer(5 * 8192));
+    }
+
+    public Document doInboundSecurity(SecurityProperties securityProperties, InputStream inputStream) throws WSSecurityException, WSSConfigurationException, XMLStreamException, ParserConfigurationException {
+        return doInboundSecurity(securityProperties, xmlInputFactory.createXMLStreamReader(inputStream), null);
+    }
+
+    public Document doInboundSecurity(SecurityProperties securityProperties, InputStream inputStream, SecurityEventListener securityEventListener) throws WSSecurityException, WSSConfigurationException, XMLStreamException, ParserConfigurationException {
+        return doInboundSecurity(securityProperties, xmlInputFactory.createXMLStreamReader(inputStream), securityEventListener);
+    }
+
+    public Document doInboundSecurity(SecurityProperties securityProperties, XMLStreamReader xmlStreamReader) throws WSSecurityException, WSSConfigurationException, XMLStreamException, ParserConfigurationException {
+        return doInboundSecurity(securityProperties, xmlStreamReader, null);
+    }
+
+    public Document doInboundSecurity(SecurityProperties securityProperties, XMLStreamReader xmlStreamReader, SecurityEventListener securityEventListener) throws WSSecurityException, XMLStreamException, ParserConfigurationException {
+        InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+        XMLStreamReader outXmlStreamReader = wsSecIn.processInMessage(xmlStreamReader, new ArrayList<SecurityEvent>(), securityEventListener);
+        return StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), outXmlStreamReader);
+    }
+
+    protected ByteArrayOutputStream doOutboundSecurity(SecurityProperties securityProperties, InputStream sourceDocument) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+        XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
+        XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+        xmlStreamWriter.close();
+        return baos;
+    }
+
+    protected Document doOutboundSecurityWithWSS4J(InputStream sourceDocument, String action, Properties properties) throws org.apache.ws.security.WSSecurityException {
+        return doOutboundSecurityWithWSS4J(sourceDocument, action, properties, SOAPConstants.SOAP_1_1_PROTOCOL);
+    }
+
+    protected Document doOutboundSecurityWithWSS4J(InputStream sourceDocument, String action, Properties properties, String soapProtocol) throws org.apache.ws.security.WSSecurityException {
+        MessageContext messageContext = doOutboundSecurityWithWSS4J_1(sourceDocument, action, properties, soapProtocol);
+        return (Document) messageContext.getProperty(SECURED_DOCUMENT);
+    }
+
+    @SuppressWarnings("unchecked")
+    protected MessageContext doOutboundSecurityWithWSS4J_1(InputStream sourceDocument, String action, final Properties properties, String soapProtocol) throws org.apache.ws.security.WSSecurityException {
+        CustomWSS4JHandler wss4JHandler = new CustomWSS4JHandler();
+        HandlerInfo handlerInfo = new HandlerInfo();
+        wss4JHandler.init(handlerInfo);
+        final MessageContext messageContext = getMessageContext(sourceDocument, soapProtocol);
+        handlerInfo.getHandlerConfig().put(WSHandlerConstants.ACTION, action);
+        handlerInfo.getHandlerConfig().put(WSHandlerConstants.USER, "transmitter");
+        Properties sigProperties = new Properties();
+        sigProperties.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
+        sigProperties.setProperty("org.apache.ws.security.crypto.merlin.file", "transmitter.jks");
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.alias.password", "default");
+        sigProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "default");
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", "transmitter");
+        wss4JHandler.setPassword(messageContext, "default");
+        messageContext.setProperty(WSHandlerConstants.SIG_PROP_REF_ID, "" + sigProperties.hashCode());
+        messageContext.setProperty("" + sigProperties.hashCode(), sigProperties);
+
+        Properties encProperties = new Properties();
+        encProperties.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
+        encProperties.setProperty("org.apache.ws.security.crypto.merlin.file", "transmitter.jks");
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.alias.password", "default");
+        encProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "default");
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", "transmitter");
+        wss4JHandler.setPassword(messageContext, "default");
+        messageContext.setProperty(WSHandlerConstants.ENCRYPTION_USER, "receiver");
+        messageContext.setProperty(WSHandlerConstants.ENC_PROP_REF_ID, "" + encProperties.hashCode());
+        messageContext.setProperty("" + encProperties.hashCode(), encProperties);
+
+        Enumeration enumeration = properties.propertyNames();
+        while (enumeration.hasMoreElements()) {
+            String s = (String) enumeration.nextElement();
+            messageContext.setProperty(s, properties.get(s));
+        }
+
+        RequestData requestData = new RequestData();
+        requestData.setMsgContext(messageContext);
+        requestData.setNoSerialization(true);
+        requestData.setCallbackHandler(new WSS4JCallbackHandlerImpl());
+        WSSConfig wssConfig = WSSConfig.getNewInstance();
+        wssConfig.setAction(new Integer(WSConstants.SIGN), new SignatureAction() {
+            @Override
+            public void execute(WSHandler handler, int actionToDo, Document doc, RequestData reqData) throws org.apache.ws.security.WSSecurityException {
+
+                CallbackHandler callbackHandler = handler.getPasswordCallbackHandler(reqData);
+                org.apache.ws.security.WSPasswordCallback passwordCallback = handler.getPasswordCB(reqData.getSignatureUser(), actionToDo, callbackHandler, reqData);
+
+                WSSecSignature wsSign = new WSSecSignature();
+                wsSign.setWsConfig(reqData.getWssConfig());
+
+                if (reqData.getSigKeyId() != 0) {
+                    wsSign.setKeyIdentifierType(reqData.getSigKeyId());
+                }
+                if (reqData.getSigAlgorithm() != null) {
+                    wsSign.setSignatureAlgorithm(reqData.getSigAlgorithm());
+                }
+                if (reqData.getSigDigestAlgorithm() != null) {
+                    wsSign.setDigestAlgo(reqData.getSigDigestAlgorithm());
+                }
+                if (properties.getProperty("CanonicalizationAlgo") != null) {
+                    wsSign.setSigCanonicalization(properties.getProperty("CanonicalizationAlgo"));
+                }
+
+                wsSign.setUserInfo(reqData.getSignatureUser(), passwordCallback.getPassword());
+                if (reqData.getSignatureParts().size() > 0) {
+                    wsSign.setParts(reqData.getSignatureParts());
+                }
+
+                try {
+                    wsSign.build(doc, reqData.getSigCrypto(), reqData.getSecHeader());
+                    reqData.getSignatureValues().add(wsSign.getSignatureValue());
+                } catch (org.apache.ws.security.WSSecurityException e) {
+                    throw new org.apache.ws.security.WSSecurityException("Error during Signature: ", e);
+                }
+            }
+        });
+        requestData.setWssConfig(wssConfig);
+        wss4JHandler.doSender(messageContext, requestData, true);
+
+        return messageContext;
+    }
+
+    protected Document doInboundSecurityWithWSS4J(Document document, String action) throws Exception {
+        MessageContext messageContext = doInboundSecurityWithWSS4J_1(document, action);
+        return ((Document) messageContext.getProperty(SECURED_DOCUMENT));
+    }
+
+    protected MessageContext doInboundSecurityWithWSS4J_1(Document document, String action) throws Exception {
+        return doInboundSecurityWithWSS4J_1(document, action, SOAPConstants.SOAP_1_1_PROTOCOL);
+    }
+
+    protected MessageContext doInboundSecurityWithWSS4J_1(Document document, String action, String soapProtocol) throws Exception {
+        return doInboundSecurityWithWSS4J_1(document, action, SOAPConstants.SOAP_1_1_PROTOCOL, new Properties(), false);
+    }
+
+    @SuppressWarnings("unchecked")
+    protected MessageContext doInboundSecurityWithWSS4J_1(Document document, String action, String soapProtocol, Properties properties, boolean client) throws Exception {
+        CustomWSS4JHandler wss4JHandler = new CustomWSS4JHandler();
+        HandlerInfo handlerInfo = new HandlerInfo();
+        wss4JHandler.init(handlerInfo);
+        MessageContext messageContext = getMessageContext(document, soapProtocol);
+        handlerInfo.getHandlerConfig().put(WSHandlerConstants.ACTION, action);
+        if (client) {
+            handlerInfo.getHandlerConfig().put(WSHandlerConstants.USER, "transmitter");
+        } else {
+            handlerInfo.getHandlerConfig().put(WSHandlerConstants.USER, "receiver");
+        }
+        handlerInfo.getHandlerConfig().putAll(properties);
+        //handlerInfo.getHandlerConfig().put(WSHandlerConstants.ACTOR, "receiver");
+        Properties sigProperties = new Properties();
+        sigProperties.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
+        if (client) {
+            sigProperties.setProperty("org.apache.ws.security.crypto.merlin.file", "transmitter.jks");
+        } else {
+            sigProperties.setProperty("org.apache.ws.security.crypto.merlin.file", "receiver.jks");
+        }
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.alias.password", "default");
+        sigProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "default");
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", "transmitter");
+        wss4JHandler.setPassword(messageContext, "default");
+        messageContext.setProperty(WSHandlerConstants.SIG_PROP_REF_ID, "" + sigProperties.hashCode());
+        messageContext.setProperty("" + sigProperties.hashCode(), sigProperties);
+        if (properties.get(WSHandlerConstants.PW_CALLBACK_REF) != null) {
+            messageContext.setProperty(WSHandlerConstants.PW_CALLBACK_REF, properties.get(WSHandlerConstants.PW_CALLBACK_REF));
+        } else {
+            messageContext.setProperty(WSHandlerConstants.PW_CALLBACK_REF, new WSS4JCallbackHandlerImpl());
+        }
+
+        Properties decProperties = new Properties();
+        decProperties.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
+        if (client) {
+            decProperties.setProperty("org.apache.ws.security.crypto.merlin.file", "transmitter.jks");
+        } else {
+            decProperties.setProperty("org.apache.ws.security.crypto.merlin.file", "receiver.jks");
+        }
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.alias.password", "default");
+        decProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "default");
+        //sigProperties.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", "transmitter");
+        wss4JHandler.setPassword(messageContext, "default");
+        messageContext.setProperty(WSHandlerConstants.DEC_PROP_REF_ID, "" + decProperties.hashCode());
+        messageContext.setProperty("" + decProperties.hashCode(), decProperties);
+
+        Enumeration enumeration = properties.propertyNames();
+        while (enumeration.hasMoreElements()) {
+            String s = (String) enumeration.nextElement();
+            messageContext.setProperty(s, properties.get(s));
+        }
+
+        RequestData requestData = new RequestData();
+        requestData.setMsgContext(messageContext);
+        wss4JHandler.doReceiver(messageContext, requestData, false);
+
+        return messageContext;
+    }
+
+    private MessageContext getMessageContext(InputStream inputStream, String soapProtocol) {
+        return getMessageContext(new StreamSource(inputStream), soapProtocol);
+    }
+
+    private MessageContext getMessageContext(Document document, String soapProtocol) {
+        return getMessageContext(new DOMSource(document), soapProtocol);
+    }
+
+    @SuppressWarnings("unchecked")
+    private MessageContext getMessageContext(final Source inSource, final String soapProtocol) {
+        MessageContext messageContext = new SOAPMessageContext() {
+
+            private Map properties = new HashMap();
+
+            public void setProperty(String s, Object o) {
+                properties.put(s, o);
+            }
+
+            public Object getProperty(String s) {
+                return properties.get(s);
+            }
+
+            public void removeProperty(String s) {
+                properties.remove(s);
+            }
+
+            public boolean containsProperty(String s) {
+                return properties.containsKey(s);
+            }
+
+            public Iterator getPropertyNames() {
+                return properties.keySet().iterator();
+            }
+
+            public SOAPMessage getMessage() {
+                try {
+                    //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
+                    MessageFactory messageFactory = MessageFactory.newInstance(soapProtocol);
+                    SOAPMessage soapMessage = messageFactory.createMessage();
+                    soapMessage.getSOAPPart().setContent(inSource);
+                    setProperty(SECURED_DOCUMENT, soapMessage.getSOAPHeader().getOwnerDocument());
+                    return soapMessage;
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+            }
+
+            public void setMessage(SOAPMessage soapMessage) {
+                throw new UnsupportedOperationException();
+            }
+
+            public String[] getRoles() {
+                return new String[0];  //To change body of implemented methods use File | Settings | File Templates.
+            }
+        };
+        return messageContext;
+    }
+
+    protected XPathExpression getXPath(String expression) throws XPathExpressionException {
+        XPathFactory xPathFactory = XPathFactory.newInstance();
+        XPath xPath = xPathFactory.newXPath();
+        xPath.setNamespaceContext(
+                new NamespaceContext() {
+                    public String getNamespaceURI(String prefix) {
+                        if (org.swssf.ext.Constants.PREFIX_DSIG.equals(prefix)) {
+                            return org.swssf.ext.Constants.NS_DSIG;
+                        } else if (org.swssf.ext.Constants.PREFIX_SOAPENV.equals(prefix)) {
+                            return org.swssf.ext.Constants.NS_SOAP11;
+                        } else if (org.swssf.ext.Constants.PREFIX_WSSE.equals(prefix)) {
+                            return org.swssf.ext.Constants.NS_WSSE10;
+                        } else if (org.swssf.ext.Constants.PREFIX_WSU.equals(prefix)) {
+                            return org.swssf.ext.Constants.NS_WSU10;
+                        } else if (org.swssf.ext.Constants.PREFIX_XENC.equals(prefix)) {
+                            return org.swssf.ext.Constants.NS_XMLENC;
+                        } else {
+                            return null;
+                        }
+                    }
+
+                    public String getPrefix(String namespaceURI) {
+                        if (org.swssf.ext.Constants.NS_DSIG.equals(namespaceURI)) {
+                            return org.swssf.ext.Constants.PREFIX_DSIG;
+                        } else if (org.swssf.ext.Constants.NS_SOAP11.equals(namespaceURI)) {
+                            return org.swssf.ext.Constants.PREFIX_SOAPENV;
+                        } else if (org.swssf.ext.Constants.NS_WSSE10.equals(namespaceURI)) {
+                            return org.swssf.ext.Constants.PREFIX_WSSE;
+                        } else if (org.swssf.ext.Constants.NS_WSU10.equals(namespaceURI)) {
+                            return org.swssf.ext.Constants.PREFIX_WSU;
+                        } else if (org.swssf.ext.Constants.NS_XMLENC.equals(namespaceURI)) {
+                            return org.swssf.ext.Constants.PREFIX_XENC;
+                        } else {
+                            return null;
+                        }
+                    }
+
+                    public Iterator getPrefixes(String namespaceURI) {
+                        return null;
+                    }
+                }
+        );
+        return xPath.compile(expression);
+    }
+
+    @SuppressWarnings("unchecked")
+    class CustomWSS4JHandler extends WSHandler {
+
+        private final Log log = LogFactory.getLog(CustomWSS4JHandler.class.getName());
+        private final boolean doDebug = log.isDebugEnabled();
+        private HandlerInfo handlerInfo;
+
+        /**
+         * Initializes the instance of the handler.
+         */
+        public void init(HandlerInfo hi) {
+            handlerInfo = hi;
+        }
+
+        /**
+         * Handles incoming web service requests and outgoing responses
+         */
+        public boolean doSender(MessageContext mc, RequestData reqData, boolean isRequest) throws org.apache.ws.security.WSSecurityException {
+
+            reqData.getSignatureParts().clear();
+            reqData.getEncryptParts().clear();
+            reqData.setNoSerialization(true);
+            /*
+            * Get the action first.
+            */
+            Vector actions = new Vector();
+            String action = (String) getOption(WSHandlerConstants.ACTION);
+            if (action == null) {
+                action = (String) mc.getProperty(WSHandlerConstants.ACTION);
+            }
+            if (action == null) {
+                throw new JAXRPCException("WSS4JHandler: No action defined");
+            }
+            int doAction = WSSecurityUtil.decodeAction(action, actions);
+            if (doAction == WSConstants.NO_SECURITY) {
+                return true;
+            }
+
+            /*
+            * For every action we need a username, so get this now. The username
+            * defined in the deployment descriptor takes precedence.
+            */
+            reqData.setUsername((String) getOption(WSHandlerConstants.USER));
+            if (reqData.getUsername() == null || reqData.getUsername().equals("")) {
+                reqData.setUsername((String) mc.getProperty(WSHandlerConstants.USER));
+                mc.setProperty(WSHandlerConstants.USER, null);
+            }
+
+            /*
+            * Now we perform some set-up for UsernameToken and Signature
+            * functions. No need to do it for encryption only. Check if username
+            * is available and then get a password.
+            */
+            if (((doAction & (WSConstants.SIGN | WSConstants.UT | WSConstants.UT_SIGN)) != 0)
+                    && (reqData.getUsername() == null || reqData.getUsername().equals(""))) {
+                /*
+                * We need a username - if none throw an JAXRPCException. For encryption
+                * there is a specific parameter to get a username.
+                */
+                throw new JAXRPCException("WSS4JHandler: Empty username for specified action");
+            }
+            if (doDebug) {
+                log.debug("Action: " + doAction);
+                log.debug("Actor: " + reqData.getActor());
+            }
+            /*
+            * Now get the SOAP part from the request message and convert it into a
+            * Document.
+            *
+            * This forces Axis to serialize the SOAP request into FORM_STRING.
+            * This string is converted into a document.
+            *
+            * During the FORM_STRING serialization Axis performs multi-ref of
+            * complex data types (if requested), generates and inserts references
+            * for attachments and so on. The resulting Document MUST be the
+            * complete and final SOAP request as Axis would send it over the wire.
+            * Therefore this must shall be the last (or only) handler in a chain.
+            *
+            * Now we can perform our security operations on this request.
+            */
+            Document doc = null;
+            SOAPMessage message = ((SOAPMessageContext) mc).getMessage();
+            Boolean propFormOptimization = (Boolean) mc.getProperty("axis.form.optimization");
+            log.debug("Form optimization: " + propFormOptimization);
+            /*
+            * If the message context property contains a document then this is a
+            * chained handler.
+            */
+            SOAPPart sPart = message.getSOAPPart();
+            if ((doc = (Document) mc.getProperty(SECURED_DOCUMENT)) == null) {
+                try {
+                    doc = messageToDocument(message);
+                } catch (Exception e) {
+                    if (doDebug) {
+                        log.debug(e.getMessage(), e);
+                    }
+                    throw new JAXRPCException("WSS4JHandler: cannot get SOAP envlope from message", e);
+                }
+            }
+            if (doDebug) {
+                log.debug("WSS4JHandler: orginal SOAP request: ");
+                log.debug(org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc));
+            }
+            doSenderAction(doAction, doc, reqData, actions, isRequest);
+
+            /*
+            * If required convert the resulting document into a message first. The
+            * outputDOM() method performs the necessary c14n call. After that we
+            * extract it as a string for further processing.
+            *
+            * Set the resulting byte array as the new SOAP message.
+            *
+            * If noSerialization is false, this handler shall be the last (or only)
+            * one in a handler chain. If noSerialization is true, just set the
+            * processed Document in the transfer property. The next Axis WSS4J
+            * handler takes it and performs additional security processing steps.
+            *
+            */
+            if (reqData.isNoSerialization()) {
+                mc.setProperty(SECURED_DOCUMENT, doc);
+            } else {
+                ByteArrayOutputStream os = new ByteArrayOutputStream();
+                XMLUtils.outputDOM(doc, os, true);
+                if (doDebug) {
+                    String osStr = null;
+                    try {
+                        osStr = os.toString("UTF-8");
+                    } catch (UnsupportedEncodingException e) {
+                        if (doDebug) {
+                            log.debug(e.getMessage(), e);
+                        }
+                        osStr = os.toString();
+                    }
+                    log.debug("Send request:");
+                    log.debug(osStr);
+                }
+
+                try {
+                    sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray())));
+                } catch (SOAPException se) {
+                    if (doDebug) {
+                        log.debug(se.getMessage(), se);
+                    }
+                    throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se);
+                }
+                mc.setProperty(SECURED_DOCUMENT, null);
+            }
+            if (doDebug) {
+                log.debug("WSS4JHandler: exit invoke()");
+            }
+            return true;
+        }
+
+        @SuppressWarnings("unchecked")
+        public boolean doReceiver(MessageContext mc, RequestData reqData, boolean isRequest) throws org.apache.ws.security.WSSecurityException {
+            Vector actions = new Vector();
+            String action = (String) getOption(WSHandlerConstants.ACTION);
+            if (action == null) {
+                action = (String) mc.getProperty(WSHandlerConstants.ACTION);
+            }
+            if (action == null) {
+                throw new JAXRPCException("WSS4JHandler: No action defined");
+            }
+            int doAction = WSSecurityUtil.decodeAction(action, actions);
+
+            String actor = (String) getOption(WSHandlerConstants.ACTOR);
+
+            SOAPMessage message = ((SOAPMessageContext) mc).getMessage();
+            //SOAPPart sPart = message.getSOAPPart();
+
+            Document doc = null;
+            try {
+                doc = message.getSOAPHeader().getOwnerDocument();
+            } catch (SOAPException e) {
+                throw new JAXRPCException(e);
+            }
+
+            /*
+            * Check if it's a fault. Don't process faults.
+            *
+            */
+            org.apache.ws.security.SOAPConstants soapConstants =
+                    WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
+            if (WSSecurityUtil
+                    .findElement(doc.getDocumentElement(),
+                            "Fault",
+                            soapConstants.getEnvelopeURI())
+                    != null) {
+                return false;
+            }
+
+            /*
+            * To check a UsernameToken or to decrypt an encrypted message we need
+            * a password.
+            */
+
+            CallbackHandler cbHandler = null;
+            //if ((doAction & (WSConstants.ENCR | WSConstants.UT | WSConstants.UT_SIGN)) != 0) {
+            cbHandler = getPasswordCallbackHandler(reqData);
+            //}
+            reqData.setCallbackHandler(cbHandler);
+
+            /*
+            * Get and check the Signature specific parameters first because they
+            * may be used for encryption too.
+            */
+            doReceiverAction(doAction, reqData);
+
+            Element elem = WSSecurityUtil.getSecurityHeader(doc, actor);
+
+            List wsResult = null;
+            try {
+                wsResult =
+                        secEngine.processSecurityHeader(elem, reqData);
+            } catch (org.apache.ws.security.WSSecurityException ex) {
+                if (doDebug) {
+                    log.debug(ex.getMessage(), ex);
+                }
+                throw new JAXRPCException("WSS4JHandler: security processing failed",
+                        ex);
+            }
+            if (wsResult == null || wsResult.size() == 0) {         // no security header found
+                if (doAction == WSConstants.NO_SECURITY) {
+                    return true;
+                } else {
+                    throw new JAXRPCException("WSS4JHandler: Request does not contain required Security header");
+                }
+            }
+            if (reqData.getWssConfig().isEnableSignatureConfirmation() && !isRequest) {
+                checkSignatureConfirmation(reqData, wsResult);
+            }
+
+            if (doDebug) {
+                log.debug("Processed received SOAP request");
+            }
+
+            /*
+            * After setting the new current message, probably modified because
+            * of decryption, we need to locate the security header. That is,
+            * we force Axis (with getSOAPEnvelope()) to parse the string, build
+            * the new header. Then we examine, look up the security header
+            * and set the header as processed.
+            *
+            * Please note: find all header elements that contain the same
+            * actor that was given to processSecurityHeader(). Then
+            * check if there is a security header with this actor.
+            */
+
+            SOAPHeader sHeader = null;
+            try {
+                sHeader = message.getSOAPPart().getEnvelope().getHeader();
+            } catch (Exception ex) {
+                if (doDebug) {
+                    log.debug(ex.getMessage(), ex);
+                }
+                throw new JAXRPCException("WSS4JHandler: cannot get SOAP header after security processing", ex);
+            }
+
+            /*
+            * Now we can check the certificate used to sign the message.
+            * In the following implementation the certificate is only trusted
+            * if either it itself or the certificate of the issuer is installed
+            * in the keystore.
+            *
+            * Note: the method verifyTrust(X509Certificate) allows custom
+            * implementations with other validation algorithms for subclasses.
+            */
+
+            // Extract the signature action result from the action vector
+
+            WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.SIGN);
+
+/*
+            if (actionResult != null) {
+                X509Certificate returnCert =
+                        (X509Certificate) actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
+
+                if (returnCert != null && !verifyTrust(returnCert, reqData)) {
+                    throw new JAXRPCException("WSS4JHandler: The certificate used for the signature is not trusted");
+                }
+            }
+*/
+
+            /*
+            * Perform further checks on the timestamp that was transmitted in the header.
+            * In the following implementation the timestamp is valid if it was
+            * created after (now-ttl), where ttl is set on server side, not by the client.
+            *
+            * Note: the method verifyTimestamp(Timestamp) allows custom
+            * implementations with other validation algorithms for subclasses.
+            */
+
+            // Extract the timestamp action result from the action vector
+            actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS);
+
+/*
+            if (actionResult != null) {
+                Timestamp timestamp =
+                        (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
+
+                if (timestamp != null && reqData.getWssConfig().isTimeStampStrict()
+                        && !verifyTimestamp(timestamp, decodeTimeToLive(reqData))) {
+                    throw new JAXRPCException("WSS4JHandler: The timestamp could not be validated");
+                }
+            }
+*/
+
+            /*
+            * now check the security actions: do they match, in right order?
+            */
+            if (!checkReceiverResults(wsResult, actions)) {
+                throw new JAXRPCException("WSS4JHandler: security processing failed (actions mismatch)");
+            }
+
+            /*
+            * All ok up to this point. Now construct and setup the
+            * security result structure. The service may fetch this
+            * and check it.
+            */
+            Vector results = null;
+            if ((results = (Vector) mc.getProperty(WSHandlerConstants.RECV_RESULTS))
+                    == null) {
+                results = new Vector();
+                mc.setProperty(WSHandlerConstants.RECV_RESULTS, results);
+            }
+            WSHandlerResult rResult =
+                    new WSHandlerResult(actor,
+                            wsResult);
+            results.add(0, rResult);
+            if (doDebug) {
+                log.debug("WSS4JHandler: exit invoke()");
+            }
+
+            return true;
+        }
+
+        protected boolean checkReceiverResults(
+                List<WSSecurityEngineResult> wsResult, List<Integer> actions
+        ) {
+            List<WSSecurityEngineResult> wsSecurityEngineResults = new ArrayList<WSSecurityEngineResult>();
+            for (WSSecurityEngineResult result : wsResult) {
+                boolean found = false;
+                for (WSSecurityEngineResult res : wsSecurityEngineResults) {
+                    if (((Integer) result.get(WSSecurityEngineResult.TAG_ACTION)).equals((Integer) res.get(WSSecurityEngineResult.TAG_ACTION))) {
+                        found = true;
+                        break;
+                    }
+                }
+                if (!found) {
+                    wsSecurityEngineResults.add(result);
+                }
+            }
+            int size = actions.size();
+            int ai = 0;
+            for (WSSecurityEngineResult result : wsSecurityEngineResults) {
+                final Integer actInt = (Integer) result.get(WSSecurityEngineResult.TAG_ACTION);
+                int act = actInt.intValue();
+                if (act == WSConstants.SC || act == WSConstants.BST || act == WSConstants.DKT || act == WSConstants.SCT || act == WSConstants.UT_NOPASSWORD) {
+                    continue;
+                }
+
+                if (ai >= size || actions.get(ai++).intValue() != act) {
+                    return false;
+                }
+            }
+/*
+        if (ai != size) {
+            return false;
+        }
+*/
+            return true;
+        }
+
+        protected boolean checkReceiverResultsAnyOrder(
+                List<WSSecurityEngineResult> wsResult, List<Integer> actions
+        ) {
+            List<Integer> recordedActions = new ArrayList<Integer>(actions.size());
+            for (Integer action : actions) {
+                recordedActions.add(action);
+            }
+
+            for (WSSecurityEngineResult result : wsResult) {
+                final Integer actInt = (Integer) result.get(WSSecurityEngineResult.TAG_ACTION);
+                int act = actInt.intValue();
+                if (act == WSConstants.SC || act == WSConstants.BST) {
+                    continue;
+                }
+
+                if (!recordedActions.remove(actInt)) {
+                    if (actInt == 8192) {
+                        if (!recordedActions.remove(new Integer(1))) {
+                            return false;
+                        }
+                    } else {
+                        return false;
+                    }
+                }
+            }
+
+            return recordedActions.isEmpty();
+        }
+
+        /**
+         * Utility method to convert SOAPMessage to org.w3c.dom.Document
+         */
+        public Document messageToDocument(SOAPMessage message) {
+            try {
+                Source content = message.getSOAPPart().getContent();
+                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+                dbf.setNamespaceAware(true);
+                DocumentBuilder builder = dbf.newDocumentBuilder();
+                return builder.parse(org.apache.ws.security.util.XMLUtils.sourceToInputSource(content));
+            } catch (Exception ex) {
+                throw new JAXRPCException("messageToDocument: cannot convert SOAPMessage into Document", ex);
+            }
+        }
+
+        public Object getOption(String key) {
+            return handlerInfo.getHandlerConfig().get(key);
+        }
+
+        public Object getProperty(Object msgContext, String key) {
+            return ((MessageContext) msgContext).getProperty(key);
+        }
+
+        public void setProperty(Object msgContext, String key, Object value) {
+            ((MessageContext) msgContext).setProperty(key, value);
+        }
+
+        public String getPassword(Object msgContext) {
+            return (String) ((MessageContext) msgContext).getProperty(Call.PASSWORD_PROPERTY);
+        }
+
+        public void setPassword(Object msgContext, String password) {
+            ((MessageContext) msgContext).setProperty(Call.PASSWORD_PROPERTY, password);
+        }
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/AbstractTestBase.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/CallbackHandlerImpl.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/CallbackHandlerImpl.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/CallbackHandlerImpl.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/CallbackHandlerImpl.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,310 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.swssf.test;
+
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.message.WSSecEncryptedKey;
+import org.apache.ws.security.saml.ext.builder.SAML2Constants;
+import org.opensaml.common.SAMLVersion;
+import org.swssf.crypto.CryptoBase;
+import org.swssf.crypto.Merlin;
+import org.swssf.ext.WSPasswordCallback;
+import org.swssf.impl.saml.SAMLCallback;
+import org.swssf.impl.saml.bean.*;
+import org.swssf.impl.saml.builder.SAML1Constants;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.IOException;
+import java.security.KeyStore;
+import java.security.cert.X509Certificate;
+import java.util.Collections;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class CallbackHandlerImpl implements CallbackHandler {
+
+    private String username = "default";
+    private byte[] secret;
+
+    public enum Statement {
+        AUTHN, ATTR, AUTHZ
+    }
+
+    private String subjectName = "uid=joe,ou=people,ou=saml-demo,o=example.com";
+    private String subjectQualifier = "www.example.com";
+    private String confirmationMethod = SAML1Constants.CONF_SENDER_VOUCHES;
+    private X509Certificate[] certs;
+    private Statement statement = Statement.AUTHN;
+    private KeyInfoBean.CERT_IDENTIFIER certIdentifier = KeyInfoBean.CERT_IDENTIFIER.X509_CERT;
+    private byte[] ephemeralKey = null;
+    private String issuer = null;
+    private SAMLVersion samlVersion = SAMLVersion.VERSION_11;
+
+    private boolean signAssertion = true;
+
+    public CallbackHandlerImpl() {
+    }
+
+    public CallbackHandlerImpl(String username) {
+        if (username != null) {
+            this.username = username;
+        }
+    }
+
+    public CallbackHandlerImpl(byte[] secret) {
+        this.secret = secret;
+    }
+
+    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+        if (callbacks[0] instanceof WSPasswordCallback) {
+            WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
+
+            if (pc.getUsage() == WSPasswordCallback.Usage.DECRYPT
+                    || pc.getUsage() == WSPasswordCallback.Usage.SIGNATURE
+                    || pc.getUsage() == WSPasswordCallback.Usage.USERNAME_TOKEN
+                    || pc.getUsage() == WSPasswordCallback.Usage.USERNAME_TOKEN_UNKNOWN
+                    ) {
+                pc.setPassword(username);
+            } else if (pc.getUsage() == WSPasswordCallback.Usage.SECRET_KEY
+                    || pc.getUsage() == WSPasswordCallback.Usage.SECURITY_CONTEXT_TOKEN) {
+                pc.setKey(secret);
+            } else {
+                throw new UnsupportedCallbackException(pc, "Unrecognized CallbackHandlerImpl");
+            }
+        } else if (callbacks[0] instanceof SAMLCallback) {
+            try {
+                SAMLCallback samlCallback = (SAMLCallback) callbacks[0];
+                KeyStore keyStore = KeyStore.getInstance("jks");
+                keyStore.load(this.getClass().getClassLoader().getResourceAsStream("saml/issuer.jks"), "default".toCharArray());
+                CryptoBase crypto = new Merlin();
+                crypto.setKeyStore(keyStore);
+                samlCallback.setIssuerCrypto(crypto);
+                samlCallback.setIssuerKeyName("samlissuer");
+                samlCallback.setIssuerKeyPassword("default");
+                samlCallback.setSignAssertion(this.signAssertion);
+
+                if (getSamlVersion() == SAMLVersion.VERSION_11) {
+
+                    samlCallback.setSamlVersion(SAMLVersion.VERSION_11);
+                    samlCallback.setIssuer(issuer);
+                    SubjectBean subjectBean =
+                            new SubjectBean(
+                                    subjectName, subjectQualifier, confirmationMethod
+                            );
+                    if (SAML1Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
+                        try {
+                            KeyInfoBean keyInfo = createKeyInfo();
+                            subjectBean.setKeyInfo(keyInfo);
+                        } catch (Exception ex) {
+                            throw new IOException("Problem creating KeyInfo: " + ex.getMessage());
+                        }
+                    }
+                    samlCallback.setSubject(subjectBean);
+                    createAndSetStatement(subjectBean, samlCallback);
+                } else {
+                    samlCallback.setSamlVersion(SAMLVersion.VERSION_20);
+                    samlCallback.setIssuer(issuer);
+                    SubjectBean subjectBean =
+                            new SubjectBean(
+                                    subjectName, subjectQualifier, confirmationMethod
+                            );
+                    if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
+                        try {
+                            KeyInfoBean keyInfo = createKeyInfo();
+                            subjectBean.setKeyInfo(keyInfo);
+                        } catch (Exception ex) {
+                            throw new IOException("Problem creating KeyInfo: " + ex.getMessage());
+                        }
+                    }
+                    samlCallback.setSubject(subjectBean);
+                    createAndSetStatement(null, samlCallback);
+                }
+            } catch (Exception e) {
+                throw new IOException(e);
+            }
+        }
+    }
+
+    /**
+     * Note that the SubjectBean parameter should be null for SAML2.0
+     */
+    protected void createAndSetStatement(SubjectBean subjectBean, SAMLCallback callback) {
+        if (statement == Statement.AUTHN) {
+            AuthenticationStatementBean authBean = new AuthenticationStatementBean();
+            if (subjectBean != null) {
+                authBean.setSubject(subjectBean);
+            }
+            authBean.setAuthenticationMethod("Password");
+            callback.setAuthenticationStatementData(Collections.singletonList(authBean));
+        } else if (statement == Statement.ATTR) {
+            AttributeStatementBean attrBean = new AttributeStatementBean();
+            if (subjectBean != null) {
+                attrBean.setSubject(subjectBean);
+            }
+            AttributeBean attributeBean = new AttributeBean();
+            attributeBean.setSimpleName("role");
+            attributeBean.setAttributeValues(Collections.singletonList("user"));
+            attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
+            callback.setAttributeStatementData(Collections.singletonList(attrBean));
+        } else {
+            AuthDecisionStatementBean authzBean = new AuthDecisionStatementBean();
+            if (subjectBean != null) {
+                authzBean.setSubject(subjectBean);
+            }
+            ActionBean actionBean = new ActionBean();
+            actionBean.setContents("Read");
+            authzBean.setActions(Collections.singletonList(actionBean));
+            authzBean.setResource("endpoint");
+            authzBean.setDecision(AuthDecisionStatementBean.Decision.PERMIT);
+            callback.setAuthDecisionStatementData(Collections.singletonList(authzBean));
+        }
+    }
+
+    protected KeyInfoBean createKeyInfo() throws Exception {
+        KeyInfoBean keyInfo = new KeyInfoBean();
+        if (statement == Statement.AUTHN) {
+            keyInfo.setCertificate(certs[0]);
+            keyInfo.setCertIdentifer(certIdentifier);
+        } else if (statement == Statement.ATTR) {
+            // Build a new Document
+            DocumentBuilderFactory docBuilderFactory =
+                    DocumentBuilderFactory.newInstance();
+            docBuilderFactory.setNamespaceAware(true);
+            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
+            Document doc = docBuilder.newDocument();
+
+            // Create an Encrypted Key
+            WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
+            encrKey.setKeyIdentifierType(WSConstants.X509_KEY_IDENTIFIER);
+            encrKey.setUseThisCert(certs[0]);
+            encrKey.prepare(doc, null);
+            ephemeralKey = encrKey.getEphemeralKey();
+            Element encryptedKeyElement = encrKey.getEncryptedKeyElement();
+
+            // Append the EncryptedKey to a KeyInfo element
+            Element keyInfoElement =
+                    doc.createElementNS(
+                            WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":" + WSConstants.KEYINFO_LN
+                    );
+            keyInfoElement.setAttributeNS(
+                    WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
+            );
+            keyInfoElement.appendChild(encryptedKeyElement);
+
+            keyInfo.setElement(keyInfoElement);
+        }
+        return keyInfo;
+    }
+
+    public String getUsername() {
+        return username;
+    }
+
+    public void setUsername(String username) {
+        this.username = username;
+    }
+
+    public String getSubjectName() {
+        return subjectName;
+    }
+
+    public void setSubjectName(String subjectName) {
+        this.subjectName = subjectName;
+    }
+
+    public String getSubjectQualifier() {
+        return subjectQualifier;
+    }
+
+    public void setSubjectQualifier(String subjectQualifier) {
+        this.subjectQualifier = subjectQualifier;
+    }
+
+    public String getConfirmationMethod() {
+        return confirmationMethod;
+    }
+
+    public void setConfirmationMethod(String confirmationMethod) {
+        this.confirmationMethod = confirmationMethod;
+    }
+
+    public X509Certificate[] getCerts() {
+        return certs;
+    }
+
+    public void setCerts(X509Certificate[] certs) {
+        this.certs = certs;
+    }
+
+    public Statement getStatement() {
+        return statement;
+    }
+
+    public void setStatement(Statement statement) {
+        this.statement = statement;
+    }
+
+    public KeyInfoBean.CERT_IDENTIFIER getCertIdentifier() {
+        return certIdentifier;
+    }
+
+    public void setCertIdentifier(KeyInfoBean.CERT_IDENTIFIER certIdentifier) {
+        this.certIdentifier = certIdentifier;
+    }
+
+    public byte[] getEphemeralKey() {
+        return ephemeralKey;
+    }
+
+    public void setEphemeralKey(byte[] ephemeralKey) {
+        this.ephemeralKey = ephemeralKey;
+    }
+
+    public String getIssuer() {
+        return issuer;
+    }
+
+    public void setIssuer(String issuer) {
+        this.issuer = issuer;
+    }
+
+    public boolean isSignAssertion() {
+        return signAssertion;
+    }
+
+    public void setSignAssertion(boolean signAssertion) {
+        this.signAssertion = signAssertion;
+    }
+
+    public SAMLVersion getSamlVersion() {
+        return samlVersion;
+    }
+
+    public void setSamlVersion(SAMLVersion samlVersion) {
+        this.samlVersion = samlVersion;
+    }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/CallbackHandlerImpl.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer11Test.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer11Test.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer11Test.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer11Test.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,675 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.swssf.test;
+
+import org.swssf.impl.transformer.canonicalizer.Canonicalizer11_OmitCommentsTransformer;
+import org.swssf.impl.transformer.canonicalizer.Canonicalizer11_WithCommentsTransformer;
+import org.swssf.impl.transformer.canonicalizer.CanonicalizerBase;
+import org.swssf.test.utils.XMLEventNSAllocator;
+import org.testng.annotations.Test;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLResolver;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.XMLEvent;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+import static org.testng.Assert.*;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class Canonicalizer11Test {
+
+    private XMLInputFactory xmlInputFactory;
+
+    public Canonicalizer11Test() throws Exception {
+        this.xmlInputFactory = XMLInputFactory.newFactory();
+        this.xmlInputFactory.setEventAllocator(new XMLEventNSAllocator());
+        XMLResolver xmlResolver = new XMLResolver() {
+            public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException {
+                return this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/in/" + systemID);
+            }
+        };
+        this.xmlInputFactory.setXMLResolver(xmlResolver);
+    }
+
+    /**
+     * 3.1 PIs, Comments, and Outside of Document Element
+     */
+    @Test
+    public void test31withCommentsSubtree() throws Exception {
+
+        String descri =
+                "3.1: PIs, Comments, and Outside of Document Element. (commented)";
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_c14n-comments.xml");
+
+        c14nAndCompare(fileIn, fileRef, false);
+    }
+
+    /**
+     * 3.1 PIs, Comments, and Outside of Document Element
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-OutsideDoc">the example from the spec</A>
+     */
+    @Test
+    public void test31subtree() throws Exception {
+
+        String descri =
+                "3.1: PIs, Comments, and Outside of Document Element. (uncommented)";
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_c14n.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.2 Whitespace in Document Content
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-WhitespaceInContent">the example from the spec</A>
+     */
+    @Test
+    public void test32subtree() throws Exception {
+
+        String descri = "3.2 Whitespace in Document Content. (uncommented)";
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/32_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/32_c14n.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.3 Start and End Tags
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-SETags">the example from the spec</A>
+     */
+    @Test
+    public void test33subtree() throws Exception {
+
+        String descri = "3.3 Start and End Tags. (uncommented)";
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/33_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/33_c14n.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.4 Character Modifications and Character References
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-Chars">the example from the spec</A>
+     */
+    @Test
+    public void test34() throws Exception {
+
+        String descri =
+                "3.4 Character Modifications and Character References. (uncommented)";
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_c14n.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.4 Character Modifications and Character References (patched to run on validating Parsers)
+     * <p/>
+     * <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119"> The spec</A> states that:
+     * <p/>
+     * Note: The last element, normId, is well-formed but violates a validity
+     * constraint for attributes of type ID. For testing canonical XML
+     * implementations based on validating processors, remove the line
+     * containing this element from the input and canonical form. In general,
+     * XML consumers should be discouraged from using this feature of XML.
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-Chars">the example from the spec</A>
+     */
+    @Test
+    public void test34subtree() throws Exception {
+        //todo enable validation
+        String descri =
+                "3.4 Character Modifications and Character References. (uncommented, patched to run on validating Parsers)";
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_input_validatingParser.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_c14n_validatingParser.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.5 Entity References
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-Entities">the example from the spec</A>
+     */
+    @Test
+    public void test35subtree() throws Exception {
+        //todo enable validation
+        String descri = "3.5 Entity References. (uncommented)";
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/35_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/35_c14n.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.6 UTF-8 Encoding
+     *
+     * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-UTF8">the example from the spec</A>
+     */
+    @Test
+    public void test36subtree() throws Exception {
+
+        String descri = "3.6 UTF-8 Encoding. (uncommented)";
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/36_input.xml");
+        URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/36_c14n.xml");
+
+        c14nAndCompare(fileIn, fileRef, true);
+    }
+
+    /**
+     * 3.8 Document Subsets and XML Attributes (modified)
+     *
+     * @see <A HREF="http://www.w3.org/TR/2007/CR-xml-c14n11-20070621/#Example-DocSubsetsXMLAttrs">the example from the spec</A>
+     */
+    @Test
+    public void test38() throws Exception {
+        String descri = "3.6 UTF-8 Encoding. (uncommented)";
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        Canonicalizer11_OmitCommentsTransformer c = new Canonicalizer11_OmitCommentsTransformer(null, baos);
+        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+                this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/in/38_input.xml")
+        );
+
+        XMLEvent xmlEvent = null;
+        while (xmlEventReader.hasNext()) {
+            xmlEvent = xmlEventReader.nextEvent();
+            if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(new QName("http://www.ietf.org", "e1"))) {
+                break;
+            }
+        }
+        while (xmlEventReader.hasNext()) {
+
+            c.transform(xmlEvent);
+
+            if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(new QName("http://www.ietf.org", "e1"))) {
+                break;
+            }
+            xmlEvent = xmlEventReader.nextEvent();
+        }
+
+        byte[] reference = getBytesFromResource(this.getClass().getClassLoader().getResource("testdata/c14n/in/38_c14n.xml"));
+        boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
+
+        if (!equals) {
+            System.out.println("Expected:\n" + new String(reference, "UTF-8"));
+            System.out.println("");
+            System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+        }
+
+        assertTrue(equals);
+    }
+
+//   /**
+//    * 3.7 Document Subsets
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-DocSubsets">the example from the spec</A>
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void test37() throws Exception {
+//
+//      String descri = "3.7 Document Subsets. (uncommented)";
+//      String fileIn = prefix + "in/37_input.xml";
+//      String fileRef = prefix + "in/37_c14n.xml";
+//      String fileOut = prefix + "out/xpath_37_output.xml";
+//      String c14nURI = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
+//      boolean validating = true;
+//      Element xpath = null;
+//      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+//
+//      dfactory.setNamespaceAware(true);
+//
+//      DocumentBuilder db = dfactory.newDocumentBuilder();
+//      Document doc = db.newDocument();
+//
+//      xpath = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_XPATH);
+//
+//      xpath.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ietf", "http://www.ietf.org");
+//
+//      //J-
+//         String xpathFromSpec =
+//              "(//. | //@* | //namespace::*)"
+//            + "[ "
+//            + "self::ietf:e1 or "
+//            + "(parent::ietf:e1 and not(self::text() or self::e2)) or "
+//            + "count(id(\"E3\")|ancestor-or-self::node()) = count(ancestor-or-self::node()) "
+//            + "]";
+//
+//         //J+
+//      xpath.appendChild(doc.createTextNode(xpathFromSpec));
+//      assertTrue(descri,
+//                 c14nAndCompare(fileIn, fileRef, fileOut, c14nURI, validating,
+//                                xpath));
+//   }
+//
+
+    /**
+     * Note: This specification supports the recent XML plenary decision to
+     * deprecate relative namespace URIs as follows: implementations of XML
+     * canonicalization MUST report an operation failure on documents containing
+     * relative namespace URIs. XML canonicalization MUST NOT be implemented
+     * with an XML parser that converts relative URIs to absolute URIs.
+     * <p/>
+     * Implementations MUST report an operation failure on documents containing
+     * relative namespace URIs.
+     */
+    @Test
+    public void testRelativeNSbehaviour() throws Exception {
+
+        URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/relative-ns-behaviour.xml");
+
+        try {
+            c14nAndCompare(fileIn, fileIn, true);
+            fail();
+        } catch (XMLStreamException cex) {
+            assertTrue(cex != null);
+        }
+    }
+
+//   /**
+//    * The XPath data model represents data using UCS characters.
+//    * Implementations MUST use XML processors that support UTF-8 and UTF-16
+//    * and translate to the UCS character domain. For UTF-16, the leading byte
+//    * order mark is treated as an artifact of encoding and stripped from the
+//    * UCS character data (subsequent zero width non-breaking spaces appearing
+//    * within the UTF-16 data are not removed) [UTF-16, Section 3.2]. Support
+//    * for ISO-8859-1 encoding is RECOMMENDED, and all other character encodings
+//    * are OPTIONAL.
+//    *
+//    * $todo$ implement the test
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void testTranslationFromUTF16toUTF8() throws Exception {
+//
+//      String val =
+//         "<UTF16>The german &amp;auml (which is Unicode &amp;#xE4;):  &quot;&#xE4;&quot;</UTF16>";
+//      byte utf16[] = convertToUTF16(val.getBytes());
+//      Canonicalizer c14n =
+//         Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
+//      byte c14nBytes[] = c14n.canonicalize(utf16);
+//      org.xml.sax.EntityResolver resolver = new TestVectorResolver();
+//      InputStream refStream = resolver.resolveEntity(
+//         null,
+//            prefix + "/in/testTranslationFromUTF16toUTF8.xml")
+//               .getByteStream();
+//      byte refBytes[] = JavaUtils.getBytesFromStream(refStream);
+//      boolean equal = java.security.MessageDigest.isEqual(refBytes, c14nBytes);
+//
+//      assertTrue("Parser does not translate to UCS character domain", equal);
+//   }
+//
+//   /**
+//    * Method testXMLAttributes1
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void testXMLAttributes1() throws Exception {
+//      //J-
+//      String input = ""
+//         + "<included    xml:lang='de'>"
+//         + "<notIncluded xml:lang='de'>"
+//         + "<notIncluded xml:lang='uk'>"
+//         + "<included                 >"
+//         + "</included>"
+//         + "</notIncluded>"
+//         + "</notIncluded>"
+//         + "</included>";
+//
+//      String definedOutput = ""
+//         + "<included xml:lang=\"de\">"
+//         + "<included xml:lang=\"uk\">"
+//         + "</included>"
+//         + "</included>";
+//      //J+
+//      assertTrue(doTestXMLAttributes(input, definedOutput));
+//   }
+//
+//   /**
+//    * Method testXMLAttributes2
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void testXMLAttributes2() throws Exception {
+//      //J-
+//      String input = ""
+//         + "<included    xml:lang='uk'>"
+//         + "<notIncluded xml:lang='de'>"
+//         + "<notIncluded xml:lang='uk'>"
+//         + "<included                 >"
+//         + "</included>"
+//         + "</notIncluded>"
+//         + "</notIncluded>"
+//         + "</included>";
+//
+//      String definedOutput = ""
+//         + "<included xml:lang=\"uk\">"
+//         + "<included xml:lang=\"uk\">"
+//         + "</included>"
+//         + "</included>";
+//      //J+
+//      assertTrue(doTestXMLAttributes(input, definedOutput));
+//   }
+//
+//   /**
+//    * Method testXMLAttributes3
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void testXMLAttributes3() throws Exception {
+//      //J-
+//      String input = ""
+//         + "<included    xml:lang='de'>"
+//         + "<notIncluded xml:lang='de'>"
+//         + "<notIncluded xml:lang='uk'>"
+//         + "<included    xml:lang='de'>"
+//         + "</included>"
+//         + "</notIncluded>"
+//         + "</notIncluded>"
+//         + "</included>";
+//
+//      String definedOutput = ""
+//         + "<included xml:lang=\"de\">"
+//         + "<included xml:lang=\"de\">"
+//         + "</included>"
+//         + "</included>";
+//      //J+
+//      assertTrue(doTestXMLAttributes(input, definedOutput));
+//   }
+//
+//   /**
+//    * Method testXMLAttributes4
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void _testXMLAttributes4() throws Exception {
+//      //J-
+//      String input = ""
+//         + "<included    xml:lang='de'>"
+//         + "<included    xml:lang='de'>"
+//         + "<notIncluded xml:lang='uk'>"
+//         + "<included                 >"
+//         + "</included>"
+//         + "</notIncluded>"
+//         + "</included>"
+//         + "</included>";
+//
+//      String definedOutput = ""
+//         + "<included xml:lang=\"de\">"
+//         + "<included>"
+//         + "<included xml:lang=\"uk\">"
+//         + "</included>"
+//         + "</included>"
+//         + "</included>";
+//      //J+
+//      assertTrue(doTestXMLAttributes(input, definedOutput));
+//   }
+//
+//   /**
+//    * Method testXMLAttributes5
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void _testXMLAttributes5() throws Exception {
+//      //J-
+//      String input = ""
+//         + "<included                         xml:lang='de'>"
+//         + "<included                         xml:lang='de'>"
+//         + "<notIncluded xml:space='preserve' xml:lang='uk'>"
+//         + "<included                 >"
+//         + "</included>"
+//         + "</notIncluded>"
+//         + "</included>"
+//         + "</included>";
+//
+//      String definedOutput = ""
+//         + "<included xml:lang=\"de\">"
+//         + "<included>"
+//         + "<included xml:lang=\"uk\" xml:space=\"preserve\">"
+//         + "</included>"
+//         + "</included>"
+//         + "</included>";
+//      //J+
+//      assertTrue(doTestXMLAttributes(input, definedOutput));
+//   }
+//
+//   /**
+//    * Method testXMLAttributes6
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static void _testXMLAttributes6() throws Exception {
+//      //J-
+//      String input = ""
+//         + "<included   xml:space='preserve'  xml:lang='de'>"
+//         + "<included                         xml:lang='de'>"
+//         + "<notIncluded                      xml:lang='uk'>"
+//         + "<included>"
+//         + "</included>"
+//         + "</notIncluded>"
+//         + "</included>"
+//         + "</included>";
+//
+//      String definedOutput = ""
+//         + "<included xml:lang=\"de\" xml:space=\"preserve\">"
+//         + "<included>"
+//         + "<included xml:lang=\"uk\" xml:space=\"preserve\">"
+//         + "</included>"
+//         + "</included>"
+//         + "</included>";
+//      //J+
+//      assertTrue(doTestXMLAttributes(input, definedOutput));
+//   }
+//
+//   /**
+//    * Method doTestXMLAttributes
+//    *
+//    * @param input
+//    * @param definedOutput
+//    * @param writeResultsToFile
+//    *
+//    * @throws CanonicalizationException
+//    * @throws java.io.FileNotFoundException
+//    * @throws java.io.IOException
+//    * @throws InvalidCanonicalizerException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   private static boolean doTestXMLAttributes(
+//           String input, String definedOutput) throws Exception {
+//
+//      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+//
+//      dfactory.setNamespaceAware(true);
+//      dfactory.setValidating(true);
+//
+//      DocumentBuilder db = dfactory.newDocumentBuilder();
+//
+//      db.setErrorHandler(new org.apache.xml.security.utils
+//         .IgnoreAllErrorHandler());
+//
+//      Document doc = db.parse(new ByteArrayInputStream(input.getBytes()));
+//      Canonicalizer c14nizer =
+//         Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
+//      CachedXPathAPI xpathAPI = new CachedXPathAPI();
+//
+//      //XMLUtils.circumventBug2650(doc);
+//
+//      NodeList nodes =
+//         xpathAPI.selectNodeList(doc, "(//*[local-name()='included'] | //@*[parent::node()[local-name()='included']])");
+//      byte result[] = c14nizer.canonicalizeXPathNodeSet(nodes);
+//      byte defined[] = definedOutput.getBytes();
+//      assertEquals(definedOutput, new String(result));
+//      return java.security.MessageDigest.isEqual(defined, result);
+//   }
+
+    /**
+     * Method c14nAndCompare
+     */
+    private void c14nAndCompare(
+            URL fileIn, URL fileRef, boolean omitComments) throws Exception {
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+        CanonicalizerBase canonicalizerBase;
+        if (omitComments) {
+            canonicalizerBase = new Canonicalizer11_OmitCommentsTransformer(null, baos);
+        } else {
+            canonicalizerBase = new Canonicalizer11_WithCommentsTransformer(null, baos);
+        }
+
+        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(fileIn.openStream());
+        while (xmlEventReader.hasNext()) {
+            XMLEvent xmlEvent = xmlEventReader.nextEvent();
+            canonicalizerBase.transform(xmlEvent);
+        }
+
+        // org.xml.sax.InputSource refIs = resolver.resolveEntity(null, fileRef);
+        // byte refBytes[] = JavaUtils.getBytesFromStream(refIs.getByteStream());
+        byte refBytes[] = getBytesFromResource(fileRef);
+
+        // if everything is OK, result is true; we do a binary compare, byte by byte
+        boolean result = java.security.MessageDigest.isEqual(refBytes, baos.toByteArray());
+        if (!result) {
+            assertEquals(new String(baos.toByteArray()), new String(refBytes));
+        }
+        assertTrue(result);
+    }
+
+
+    public static byte[] getBytesFromResource(URL resource) throws IOException {
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        InputStream inputStream = resource.openStream();
+        try {
+            byte buf[] = new byte[1024];
+            int len;
+            while ((len = inputStream.read(buf)) > 0) {
+                baos.write(buf, 0, len);
+            }
+
+            return baos.toByteArray();
+        } finally {
+            inputStream.close();
+        }
+    }
+
+//   /**
+//    * This method takes the input bytes as XML Document and converts it to an
+//    * UTF-16 encoded XML document which is serialized to byte[] and returned.
+//    *
+//    * @param input
+//    *
+//    * @throws java.io.IOException
+//    * @throws javax.xml.parsers.ParserConfigurationException
+//    * @throws org.xml.sax.SAXException
+//    * @throws javax.xml.transform.TransformerConfigurationException
+//    * @throws javax.xml.transform.TransformerException
+//    */
+//   public static byte[] convertToUTF16(byte input[]) throws Exception {
+//
+//      //String ENCODING_ISO8859_1 = "ISO-8859-1";
+//      //String ENCODING_UTF8 = "UTF-8";
+//      String ENCODING_UTF16 = "UTF-16";
+//      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+//      DocumentBuilder db = dbf.newDocumentBuilder();
+//      Document doc = db.parse(new ByteArrayInputStream(input));
+//      TransformerFactory tFactory = TransformerFactory.newInstance();
+//      Transformer transformer = tFactory.newTransformer();
+//
+//      transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING_UTF16);
+//      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+//
+//      DOMSource source = new DOMSource(doc);
+//      ByteArrayOutputStream os = new ByteArrayOutputStream();
+//      StreamResult result = new StreamResult(os);
+//
+//      transformer.transform(source, result);
+//
+//      return os.toByteArray();
+//   }
+}

Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer11Test.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision



Mime
View raw message