ws-axis-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ruchi...@apache.org
Subject svn commit: r370083 - in /webservices/axis2/trunk/java/modules: saaj/ saaj/src/org/apache/axis2/saaj/ saaj/src/org/apache/axis2/saaj/util/ saaj/test-resources/ saaj/test/org/apache/axis2/saaj/ saaj/test/org/apache/axis2/saaj/integration/ xml/src/org/ap...
Date Wed, 18 Jan 2006 09:19:28 GMT
Author: ruchithf
Date: Wed Jan 18 01:18:53 2006
New Revision: 370083

URL: http://svn.apache.org/viewcvs?rev=370083&view=rev
Log:
Checking in the patch from Azeez

Added:
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/util/IDGenerator.java
    webservices/axis2/trunk/java/modules/saaj/test-resources/axis2.xml
    webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/SOAPConnectionTest.java
Removed:
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/util/SessionUtils2.java
Modified:
    webservices/axis2/trunk/java/modules/saaj/maven.xml
    webservices/axis2/trunk/java/modules/saaj/project.xml
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/NodeImplEx.java
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPConnectionImpl.java
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPElementImpl.java
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPEnvelopeImpl.java
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java
    webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/TextImplEx.java
    webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/AttachmentSerializationTest.java
    webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/EchoService.java
    webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/IntegrationTest.java
    webservices/axis2/trunk/java/modules/xml/src/org/apache/axis2/om/impl/MIMEOutputUtils.java

Modified: webservices/axis2/trunk/java/modules/saaj/maven.xml
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/maven.xml?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/maven.xml (original)
+++ webservices/axis2/trunk/java/modules/saaj/maven.xml Wed Jan 18 01:18:53 2006
@@ -3,15 +3,31 @@
 <!-- $Revision: 1.21 $ $Date: 2004-10-27 20:54:09 +0600 (Wed, 27 Oct 2004) $ -->
 
 <project default="jar"
-    xmlns:j="jelly:core"
-    xmlns:u="jelly:util"
-    xmlns:maven="jelly:maven"
-    xmlns:deploy="deploy"
-    xmlns:ant="jelly:ant">
-    <preGoal name="itest:compile">
+         xmlns:j="jelly:core"
+         xmlns:u="jelly:util"
+         xmlns:maven="jelly:maven"
+         xmlns:deploy="deploy"
+         xmlns:ant="jelly:ant">
+
+    <!-- <preGoal name="itest:compile">
         <u:file var="file" name="${maven.itest.src}"/>
         <j:if test="${!file.exists()}">
             <j:expr value="${context.setVariable('maven.itest.skip', 'true')}"/>
         </j:if>
+    </preGoal>-->
+
+    <preGoal name="test:compile">
+        <ant:property name="maven.class.path" refid="maven.dependency.classpath"/>
+        
+        <!-- copy the mars so that they are available on the test classpath -->
+        <copy file="../addressing/target/addressing.mar"
+            tofile="target/test-classes/modules/addressing.mar"/>
     </preGoal>
+
+    <postGoal name="test:compile">
+        <mkdir dir="target/test-resources/saaj-repo"/>
+        <ant:copy toDir="target/test-resources/saaj-repo">
+            <ant:fileset file="test-resources/axis2.xml"/>
+        </ant:copy>
+    </postGoal>
 </project>

Modified: webservices/axis2/trunk/java/modules/saaj/project.xml
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/project.xml?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/project.xml (original)
+++ webservices/axis2/trunk/java/modules/saaj/project.xml Wed Jan 18 01:18:53 2006
@@ -85,6 +85,11 @@
     <dependencies>
         <dependency>
             <groupId>axis2</groupId>
+            <artifactId>axis2-wsdl</artifactId>
+            <version>${pom.currentVersion}</version>
+        </dependency>
+        <dependency>
+            <groupId>axis2</groupId>
             <artifactId>axis2-xml</artifactId>
             <version>${pom.currentVersion}</version>
         </dependency>
@@ -151,6 +156,22 @@
         </dependency>
         <dependency>
             <groupId>geronimo-spec</groupId>
+            <artifactId>geronimo-spec-javamail</artifactId>
+            <version>${geronimo.spec.javamail.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
+        <dependency>
+            <groupId>geronimo-spec</groupId>
+            <artifactId>geronimo-spec-jms</artifactId>
+            <version>${geronimo.spec.jms.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
+        <dependency>
+            <groupId>geronimo-spec</groupId>
             <artifactId>geronimo-spec-activation</artifactId>
             <version>${geronimo.spec.activation.version}</version>
             <properties>
@@ -173,7 +194,47 @@
                 <module>true</module>
             </properties>
             <url>http://dist.codehaus.org/stax/jars/</url>
-        </dependency>        
+        </dependency>
+        <dependency>
+            <groupId>commons-httpclient</groupId>
+            <artifactId>commons-httpclient</artifactId>
+            <version>${commons.httpclient.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
+        <dependency>
+            <groupId>ws-commons</groupId>
+            <artifactId>ws-policy</artifactId>
+            <version>${ws_policy.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
+        <dependency>
+            <groupId>axis</groupId>
+            <artifactId>axis-wsdl4j</artifactId>
+            <version>${axis.wsdl4j.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
+        <dependency>
+            <groupId>commons-codec</groupId>
+            <artifactId>commons-codec</artifactId>
+            <version>${commons.codec.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
+        <dependency>
+            <groupId>annogen</groupId>
+            <artifactId>annogen</artifactId>
+            <version>${annogen.version}</version>
+            <properties>
+                <module>true</module>
+            </properties>
+        </dependency>
     </dependencies>
 
     <reports/>

Modified: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/NodeImplEx.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/NodeImplEx.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/NodeImplEx.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/NodeImplEx.java Wed Jan 18 01:18:53 2006
@@ -107,38 +107,6 @@
         this.parentElement = parent;
     }
 
-    /**
-     * If this is a Text node then this method will set its value, otherwise it
-     * sets the value of the immediate (Text) child of this node. The value of
-     * the immediate child of this node can be set only if, there is one child
-     * node and that node is a Text node, or if there are no children in which
-     * case a child Text node will be created.
-     *
-     * @param value the text to set
-     * @throws IllegalStateException if the node is not a Text  node and
-     *                               either has more than one child node or has a child node that
-     *                               is not a Text node
-     */
-    public void setValue(String value) {
-        if (this.getNodeType() == Node.TEXT_NODE) {
-            this.setNodeValue(value);
-        } else if (this.getNodeType() == Node.ELEMENT_NODE) {
-            OMElement elem = ((OMElement) this);
-            OMNode firstChild = elem.getFirstOMChild();
-            if (firstChild == null ||
-                (((Node) firstChild).getNodeType() == Node.TEXT_NODE &&
-                 firstChild.getNextOMSibling() == null)){//If there are no children OR
-                //the first child is a text node and the only child
-
-                ((OMElement) this).setText(value);
-            } else {
-                throw new IllegalStateException("This node is not a Text  node and " +
-                                                "either has more than one child node or has a child " +
-                                                "node that is not a Text node");
-            }
-        }
-    }
-
     public void setType(int nodeType) throws OMException {
         throw new UnsupportedOperationException("TODO");
     }

Modified: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPConnectionImpl.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPConnectionImpl.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPConnectionImpl.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPConnectionImpl.java Wed Jan 18 01:18:53 2006
@@ -17,35 +17,54 @@
 
 import org.apache.axis2.AxisFault;
 import org.apache.axis2.Constants;
+import org.apache.axis2.context.MessageContext;
 import org.apache.axis2.addressing.EndpointReference;
 import org.apache.axis2.client.Options;
 import org.apache.axis2.client.ServiceClient;
-import org.apache.axis2.context.MessageContext;
-import org.apache.axis2.om.DOOMAbstractFactory;
+import org.apache.axis2.client.OperationClient;
 import org.apache.axis2.om.OMAttribute;
 import org.apache.axis2.om.OMElement;
 import org.apache.axis2.om.OMNode;
 import org.apache.axis2.om.OMText;
-import org.apache.axis2.om.impl.dom.DocumentImpl;
-import org.apache.axis2.om.impl.dom.ElementImpl;
+import org.apache.axis2.om.impl.llom.OMTextImpl;
 import org.apache.axis2.saaj.util.SAAJUtil;
-import org.apache.axis2.saaj.util.SessionUtils2;
-import org.apache.axis2.soap.SOAP11Constants;
+import org.apache.axis2.saaj.util.IDGenerator;
+import org.apache.wsdl.WSDLConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 
 import javax.activation.DataHandler;
 import javax.xml.namespace.QName;
 import javax.xml.soap.AttachmentPart;
+import javax.xml.soap.MessageFactory;
+import javax.xml.soap.SOAPBody;
 import javax.xml.soap.SOAPConnection;
 import javax.xml.soap.SOAPException;
 import javax.xml.soap.SOAPMessage;
+import javax.xml.soap.SOAPPart;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
+import javax.xml.soap.SOAPElement;
+import javax.xml.stream.XMLStreamException;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.Iterator;
+import java.util.HashMap;
+import java.util.Map;
+import java.io.ByteArrayOutputStream;
 
 /**
  *
  */
 public class SOAPConnectionImpl extends SOAPConnection {
+
+    /**
+     * Attribute which keeps track of whether this connection has been closed
+     */
+    private boolean closed = false;
+
+    private Log log = LogFactory.getLog(getClass());
+
     /**
      * Sends the given message to the specified endpoint and
      * blocks until it has returned the response.
@@ -60,10 +79,15 @@
      *                 <code>javax.xml.messaging.URLEndpoint</code>
      * @return the <CODE>SOAPMessage</CODE> object that is the
      *         response to the message that was sent
-     * @throws javax.xml.soap.SOAPException if there is a SOAP error
+     * @throws javax.xml.soap.SOAPException if there is a SOAP error,
+     *                                      or this SOAPConnection is already closed
      */
     public SOAPMessage call(SOAPMessage request, Object endpoint) throws SOAPException {
 
+        if (closed) {
+            throw new SOAPException("SOAPConnection closed");
+        }
+
         // initialize URL
         URL url;
         try {
@@ -72,170 +96,234 @@
             throw new SOAPException(e);
         }
 
+        // initialize and set Options
+        Options options = new Options();
+        options.setTo(new EndpointReference(url.toString()));
+
+        // initialize the Sender
+        OperationClient opClient;
+        try {
+            opClient = new ServiceClient().createClient(ServiceClient.ANON_OUT_IN_OP);
+        } catch (AxisFault e) {
+            throw new SOAPException(e);
+        }
+        opClient.setOptions(options);
+
         if (request.countAttachments() != 0) { // SOAPMessage with attachments
-            return handleSOAPMessageWithAttachments(request, url);
+            opClient.getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
+            return handleSOAPMessage(request, opClient);
         } else { // simple SOAPMessage
-            return handleBasicSOAPMessage(request, url);
+            return handleSOAPMessage(request, opClient);
         }
     }
 
     /**
      * Closes this <CODE>SOAPConnection</CODE> object.
      *
-     * @throws javax.xml.soap.SOAPException if there is a SOAP error
+     * @throws javax.xml.soap.SOAPException if there is a SOAP error,
+     *                                      or this SOAPConnection is already closed
      */
     public void close() throws SOAPException {
-        //TODO: Method implementation
-
+        if (closed) {
+            throw new SOAPException("SOAPConnection Closed");
+        }
+        closed = true;
     }
 
-    private SOAPMessage handleSOAPMessageWithAttachments(SOAPMessage request,
-                                                         URL url) throws SOAPException {
-        SOAPMessage response = null;
+    private SOAPMessage handleSOAPMessage(SOAPMessage request,
+                                          OperationClient opClient) throws SOAPException {
 
-        // initialize the Sender
-        ServiceClient sender;
+        MessageContext requestMsgCtx = new MessageContext();
         try {
-            sender = new ServiceClient(null, null);  //TODO: create the config context properly
+            requestMsgCtx.setEnvelope(toOMSOAPEnvelope(request));
+            opClient.addMessageContext(requestMsgCtx);
+            opClient.execute(true);
+            return getSOAPMessage(opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).
+                    getEnvelope());
         } catch (AxisFault e) {
             throw new SOAPException(e);
         }
+    }
 
-        // initialize and set Options
-        Options options = new Options();
-        options.setProperty(MessageContext.CHARACTER_SET_ENCODING, "UTF-16");
-        options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
-        options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
-        options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
-        options.setTo(new EndpointReference(url.toString()));
-        sender.setOptions(options);
+    /**
+     * This method handles the conversion of an OM SOAP Envelope to a SAAJ SOAPMessage
+     *
+     * @param respOMSoapEnv
+     * @return the SAAJ SOAPMessage
+     * @throws SOAPException If an exception occurs during this conversion
+     */
+    private SOAPMessage getSOAPMessage(org.apache.axis2.soap.SOAPEnvelope respOMSoapEnv)
+            throws SOAPException {
+
+        // Create the basic SOAP Message
+        MessageFactory mf = MessageFactory.newInstance();
+        SOAPMessage response = mf.createMessage();
+        SOAPPart sPart = response.getSOAPPart();
+        javax.xml.soap.SOAPEnvelope env = sPart.getEnvelope();
+        SOAPBody body = env.getBody();
+        SOAPHeader header = env.getHeader();
+
+        //Convert all header blocks
+        for (Iterator hbIter = respOMSoapEnv.getHeader().examineAllHeaderBlocks();
+             hbIter.hasNext();) {
+
+            // Converting a single OM SOAP HeaderBlock to a SAAJ SOAP HeaderBlock
+            org.apache.axis2.soap.SOAPHeaderBlock hb =
+                    (org.apache.axis2.soap.SOAPHeaderBlock) hbIter.next();
+            final QName hbQName = hb.getQName();
+            final SOAPHeaderElement headerEle =
+                    header.addHeaderElement(env.createName(hbQName.getLocalPart(),
+                                                           hbQName.getPrefix(),
+                                                           hbQName.getNamespaceURI()));
+            for (Iterator attribIter = hb.getAllAttributes(); attribIter.hasNext();) {
+                OMAttribute attr = (OMAttribute) attribIter.next();
+                final QName attrQName = attr.getQName();
+                headerEle.addAttribute(env.createName(attrQName.getLocalPart(),
+                                                      attrQName.getPrefix(),
+                                                      attrQName.getNamespaceURI()),
+                                       attr.getAttributeValue());
+            }
+            final String role = hb.getRole();
+            if (role != null) {
+                headerEle.setActor(role);
+            }
+            headerEle.setMustUnderstand(hb.getMustUnderstand());
 
-        // process the attachments
-        final Iterator attachmentIter = request.getAttachments();
-        while (attachmentIter.hasNext()) {
-            System.err.println("########### Att=" + attachmentIter.next());
-            //TODO: process it
+            toSAAJElement(headerEle, hb, response);
         }
 
-        try {
-            OMElement result =
-                        sender.sendReceive(SAAJUtil.toOMSOAPEnvelope(request.getSOAPPart().getDocumentElement()));
+        // Convert the body
+        toSAAJElement(body, respOMSoapEnv.getBody(), response);
 
-            //-------------- Handle the response --------------------
-            SOAPEnvelopeImpl responseEnv =
-                    new SOAPEnvelopeImpl(SAAJUtil.toDOOMSOAPEnvelope((org.apache.axis2.soap.SOAPEnvelope) result));
+        return response;
+    }
 
-            response = new SOAPMessageImpl(responseEnv);
+    /**
+     * Converts an OMNode into a SAAJ SOAPElement
+     *
+     * @param saajEle
+     * @param omNode
+     * @param saajSOAPMsg
+     * @throws SOAPException If conversion fails
+     */
+    private void toSAAJElement(SOAPElement saajEle,
+                               OMNode omNode,
+                               javax.xml.soap.SOAPMessage saajSOAPMsg) throws SOAPException {
+
+        if (omNode instanceof OMText) {
+            return; // simply return since the text has already been added to saajEle
+        }
+
+        if (omNode instanceof OMElement) {
+            OMElement omEle = (OMElement) omNode;
+            for (Iterator childIter = omEle.getChildren(); childIter.hasNext();) {
+                OMNode omChildNode = (OMNode) childIter.next();
+                SOAPElement saajChildEle = null;
+
+                if (omChildNode instanceof OMText) {
+                    // check whether the omtext refers to an attachment
+
+                    final OMText omText = (OMText) omChildNode;
+                    if (omText.isOptimized()) { // is this an attachment?
+                        final DataHandler datahandler = (DataHandler) omText.getDataHandler();
+                        AttachmentPart attachment = saajSOAPMsg.createAttachmentPart(datahandler);
+                        final String sessionID = IDGenerator.generateID();
+                        attachment.setContentId(sessionID);
+                        attachment.setContentType(datahandler.getContentType());
+                        saajSOAPMsg.addAttachmentPart(attachment);
+
+                        saajEle.addAttribute(saajSOAPMsg.getSOAPPart().getEnvelope().createName("href"),
+                                             "cid:" + sessionID);
+                    } else {
+                        saajChildEle = saajEle.addTextNode(omText.getText());
+                    }
+                } else if (omChildNode instanceof OMElement) {
+                    OMElement omChildEle = (OMElement) omChildNode;
+                    final QName omChildQName = omChildEle.getQName();
+                    saajChildEle =
+                            saajEle.addChildElement(omChildQName.getLocalPart(),
+                                                    omChildQName.getPrefix(),
+                                                    omChildQName.getNamespaceURI());
+                    for (Iterator attribIter = omChildEle.getAllAttributes();
+                         attribIter.hasNext();) {
+                        OMAttribute attr = (OMAttribute) attribIter.next();
+                        final QName attrQName = attr.getQName();
+                        saajChildEle.addAttribute(saajSOAPMsg.getSOAPPart().getEnvelope().
+                                createName(attrQName.getLocalPart(),
+                                           attrQName.getPrefix(),
+                                           attrQName.getNamespaceURI()),
+                                                  attr.getAttributeValue());
+                    }
+                }
 
-            //TODO: process the attachments in result and add in those as attachments of response
-        } catch (AxisFault e) {
-            throw new SOAPException(e);
+                // go down the tree adding child elements, till u reach a leaf(i.e. text element)
+                toSAAJElement(saajChildEle, omChildNode, saajSOAPMsg);
+            }
         }
-
-        return response;
     }
 
-    private SOAPMessage handleBasicSOAPMessage(SOAPMessage request, URL url) throws SOAPException {
-        SOAPMessage response = null;
+    /**
+     * Converts a SAAJ SOAPMessage to an OM SOAPEnvelope
+     * 
+     * @param saajSOAPMsg
+     * @return
+     * @throws SOAPException
+     */
+    protected org.apache.axis2.soap.SOAPEnvelope toOMSOAPEnvelope(SOAPMessage saajSOAPMsg)
+            throws SOAPException {
+
+        final org.apache.axis2.soap.SOAPEnvelope omSOAPEnv =
+                SAAJUtil.toOMSOAPEnvelope(saajSOAPMsg.getSOAPPart().getDocumentElement());
 
-        // initialize the Sender
-        ServiceClient sender;
-        try {
-            sender = new ServiceClient();
-        } catch (AxisFault e) {
-            throw new SOAPException(e);
+        Map attachmentMap = new HashMap();
+        final Iterator attachments = saajSOAPMsg.getAttachments();
+        while (attachments.hasNext()) {
+            final AttachmentPart attachment = (AttachmentPart) attachments.next();
+            if (attachment.getContentId() == null || attachment.getContentId().trim().length() == 0)
+            {
+                throw new SOAPException("Attachment with NULL or Empty contend ID");
+            }
+            if (attachment.getDataHandler() == null) {
+                throw new SOAPException("Attachment with NULL DataHandler");
+            }
+            attachmentMap.put(attachment.getContentId(), attachment);
         }
 
-        // initialize and set Options
-        Options options = new Options();
-        options.setProperty(MessageContext.CHARACTER_SET_ENCODING, "UTF-8");
-        options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
-        options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
-        options.setTo(new EndpointReference(url.toString()));
-        sender.setOptions(options);
+        insertAttachmentNodes(attachmentMap, omSOAPEnv);
 
-        try {
-            OMElement result =
-                    sender.sendReceive(SAAJUtil.toOMSOAPEnvelope(request.getSOAPPart().getDocumentElement()));
-            SOAPEnvelopeImpl responseEnv =
-                    new SOAPEnvelopeImpl(SAAJUtil.toDOOMSOAPEnvelope((org.apache.axis2.soap.SOAPEnvelope) result));
+        printOMSOAPEnvelope(omSOAPEnv);
 
-            response = new SOAPMessageImpl(responseEnv);
-        } catch (AxisFault e) {
-            throw new SOAPException(e);
-        }
-        return response;
+        return omSOAPEnv;
     }
 
     /**
-     * This method recursively stuffs the OMElement with appropriate OMText nodes
-     * that are prepared out of attachment contents whereever those attachments are referenced
+     * Inserts the attachments in the proper places
      *
+     * @param attachments
      * @param omEnvelope
-     * @param soapMsg
+     * @throws SOAPException
      */
-    private void insertAttachmentNodes(OMElement omEnvelope, SOAPMessage soapMsg) throws SOAPException {
-//    private void insertAttachmentNodes(org.apache.axis2.soap.SOAPEnvelope omEnvelope,
-//                                       SOAPMessage soapMsg) throws SOAPException {
+    private void insertAttachmentNodes(Map attachments,
+                                       OMElement omEnvelope) throws SOAPException {
 
         Iterator childIter = omEnvelope.getChildElements();
         while (childIter.hasNext()) {
             OMElement child = (OMElement) childIter.next();
-            //check if there is an href attribute
-            OMAttribute hrefAttr = child.getAttribute(new QName("href"));
-            String hrefContentId = validateHref(hrefAttr);
+            final OMAttribute hrefAttr = child.getAttribute(new QName("href"));
+            String contentID = getContentID(hrefAttr);
 
-            System.err.println("########## hrefContentId=" + hrefContentId);
-            if (hrefContentId != null) {//This is an omEnvelope referencing an attachment!
+            if (contentID != null) {//This is an omEnvelope referencing an attachment
                 child.build();
-                OMText omText = getOMTextForReferencedAttachment(hrefContentId,
-                                                                 soapMsg,
-                                                                 (DocumentImpl) ((ElementImpl) child).getOwnerDocument());
-
-                child.removeAttribute(hrefAttr); //y did SAAJ1 implementors remove the attribute???
-                child.addChild(omText);
-            } else { //possibly there can be references in the children of this omEnvelope
-                //so recurse through.
-                insertAttachmentNodes(child, soapMsg);
-            }
-        }
-    }
-
-    /**
-     * The method recursively looks for the binary text nodes and adds them as attachment
-     * to soapMessage at the same time removing them from soapEnv and putting appropriate
-     * contentId
-     *
-     * @param element
-     * @param soapMsg
-     */
-    private void extractAttachmentNodes(OMElement element, SOAPMessage soapMsg) {
-        Iterator childIter = element.getChildren();
-        while (childIter.hasNext()) {
-            OMNode child = (OMNode) childIter.next();
-            if (child instanceof OMText) {
-                OMText binaryNode = (OMText) child;
-                DataHandler actualDH = (DataHandler) binaryNode.getDataHandler();
-                if (actualDH != null) {
-                    AttachmentPart ap = soapMsg.createAttachmentPart(actualDH);
-                    String contentId = SessionUtils2.generateSessionId();
-                    ap.setContentId(contentId);
-                    ap.setContentType(actualDH.getContentType());
-                    OMElement parent = (OMElement) child.getParent();
-                    OMAttribute attr =
-                            DOOMAbstractFactory.getOMFactory().createOMAttribute("href",
-                                                                                 null,
-                                                                                 "cid:" + contentId);
-
-                    parent.addAttribute(attr);
-                    binaryNode.detach();
-                    soapMsg.addAttachmentPart(ap);
-                }
+                OMText text =
+                        new OMTextImpl(((AttachmentPart) attachments.get(contentID.trim())).getDataHandler(),
+                                       true);
+                child.removeAttribute(hrefAttr);
+                child.addChild(text);
             } else {
-                if (child instanceof OMElement) {
-                    OMElement childElement = (OMElement) child;
-                    extractAttachmentNodes(childElement, soapMsg);
-                }
+
+                //possibly there can be references in the children of this omEnvelope
+                //so recurse through.
+                insertAttachmentNodes(attachments, child);
             }
         }
     }
@@ -245,8 +333,10 @@
      * returns the contentID (with cid: prefix stripped off) or else returns null.
      * A null return value can be assumed that this attribute is not an attachment
      * referencing attribute
+     *
+     * @return the ContentID
      */
-    private String validateHref(OMAttribute attr) {
+    private String getContentID(OMAttribute attr) {
         String contentId;
         if (attr != null) {
             contentId = attr.getAttributeValue();
@@ -261,29 +351,15 @@
         return null;
     }
 
-    /**
-     * This method looks up the attachment part corresponding to the given contentId and
-     * returns the OMText node thta has the content of the attachment.
-     *
-     * @param contentId
-     * @param soapMsg
-     * @return OMText
-     */
-    private OMText getOMTextForReferencedAttachment(String contentId,
-                                                    SOAPMessage soapMsg,
-                                                    DocumentImpl doc) throws SOAPException {
-
-        Iterator attachIter = soapMsg.getAttachments();
-        while (attachIter.hasNext()) {
-            AttachmentPart attachment = (AttachmentPart) attachIter.next();
-            if (attachment.getContentId().equals(contentId)) {
-                try {
-                    return ((AttachmentPartImpl) attachment).getText(doc);
-                } catch (Exception e) {
-                    throw new SOAPException(e);
-                }
-            }
+    private void printOMSOAPEnvelope(final org.apache.axis2.soap.SOAPEnvelope omSOAPEnv) {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        try {
+            omSOAPEnv.serialize(baos);
+            log.info("---------------------------------------------------------------------------");
+            log.info(baos);
+            log.info("---------------------------------------------------------------------------");
+        } catch (XMLStreamException e) {
+            e.printStackTrace();
         }
-        throw new SOAPException("No attachment found with the given contentID");
     }
 }

Modified: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPElementImpl.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPElementImpl.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPElementImpl.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPElementImpl.java Wed Jan 18 01:18:53 2006
@@ -20,6 +20,7 @@
 import org.apache.axis2.om.OMException;
 import org.apache.axis2.om.OMNamespace;
 import org.apache.axis2.om.OMNode;
+import org.apache.axis2.om.OMElement;
 import org.apache.axis2.om.impl.OMOutputImpl;
 import org.apache.axis2.om.impl.dom.DocumentImpl;
 import org.apache.axis2.om.impl.dom.ElementImpl;
@@ -354,8 +355,9 @@
 
         while (childIter.hasNext()) {
             Object o = childIter.next();
-            if (o instanceof org.apache.axis2.om.OMNode)
+            if (o instanceof org.apache.axis2.om.OMNode) {
                 ((org.apache.axis2.om.OMNode) o).detach();
+            }
         }
     }
 
@@ -551,7 +553,7 @@
             final OMNode firstOMChild = element.getFirstOMChild();
             if (firstOMChild instanceof TextImpl) {
                 return ((TextImpl) firstOMChild).getData();
-            } else {
+            } else if(firstOMChild instanceof SOAPElementImpl) {
                 return ((SOAPElementImpl) firstOMChild).getValue();
             }
         }
@@ -589,5 +591,34 @@
 
     public boolean hasChildNodes() {
         return this.element.hasChildNodes();
+    }
+
+    /**
+     * If this is a Text node then this method will set its value, otherwise it
+     * sets the value of the immediate (Text) child of this node. The value of
+     * the immediate child of this node can be set only if, there is one child
+     * node and that node is a Text node, or if there are no children in which
+     * case a child Text node will be created.
+     *
+     * @param value the text to set
+     * @throws IllegalStateException if the node is not a Text  node and
+     *                               either has more than one child node or has a child node that
+     *                               is not a Text node
+     */
+    public void setValue(String value) {
+        OMNode firstChild = element.getFirstOMChild();
+        if (firstChild == null ||
+            (((javax.xml.soap.Node) firstChild).getNodeType() == javax.xml.soap.Node.TEXT_NODE &&
+             firstChild.getNextOMSibling() == null)) {
+
+            //If there are no children OR
+            //the first child is a text node and the only child
+
+            element.setText(value);
+        } else {
+            throw new IllegalStateException("This node is not a Text  node and " +
+                                            "either has more than one child node or has a child " +
+                                            "node that is not a Text node");
+        }
     }
 }

Modified: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPEnvelopeImpl.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPEnvelopeImpl.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPEnvelopeImpl.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPEnvelopeImpl.java Wed Jan 18 01:18:53 2006
@@ -160,11 +160,10 @@
         org.apache.axis2.soap.SOAPHeader header = omSOAPEnvelope.getHeader();
         if (header == null) {
             header = new SOAP11HeaderImpl(omSOAPEnvelope);
-            omSOAPEnvelope.addChild(header);
             return (new SOAPHeaderImpl(header));
         } else {
             throw new SOAPException("Header already present, can't set header again without " +
-                                    "deleting the existing header.");
+                                    "deleting the existing header. Use getHeader() method instead.");
         }
     }
 
@@ -186,11 +185,10 @@
         org.apache.axis2.soap.SOAPBody body = omSOAPEnvelope.getBody();
         if (body == null) {
             body = new SOAP11BodyImpl(omSOAPEnvelope);
-            omSOAPEnvelope.addChild(body);
             return (new SOAPBodyImpl(body));
         } else {
             throw new SOAPException("Body already present, can't set body again without " +
-                                    "deleting the existing body.");
+                                    "deleting the existing body. Use getBody() method instead.");
         }
     }
 

Modified: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/SOAPPartImpl.java Wed Jan 18 01:18:53 2006
@@ -15,7 +15,7 @@
  */
 package org.apache.axis2.saaj;
 
-import org.apache.axis2.saaj.util.SessionUtils2;
+import org.apache.axis2.saaj.util.IDGenerator;
 import org.apache.axis2.soap.impl.dom.soap11.SOAP11Factory;
 import org.apache.axis2.soap.impl.llom.builder.StAXSOAPModelBuilder;
 import org.apache.axis2.transport.http.HTTPConstants;
@@ -57,7 +57,7 @@
     public SOAPPartImpl(SOAPMessageImpl parentSoapMsg,
                         SOAPEnvelopeImpl soapEnvelope) {
 
-        setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils2.generateSessionId());
+        setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, IDGenerator.generateID());
         setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, "text/xml");
 
         soapMessage = parentSoapMsg;
@@ -68,7 +68,7 @@
     public SOAPPartImpl(SOAPMessageImpl parentSoapMsg,
                         InputStream inputStream) throws SOAPException {
 
-        setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils2.generateSessionId());
+        setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, IDGenerator.generateID());
         setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, "text/xml");
 
         soapMessage = parentSoapMsg;

Modified: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/TextImplEx.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/TextImplEx.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/TextImplEx.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/TextImplEx.java Wed Jan 18 01:18:53 2006
@@ -34,29 +34,7 @@
     public TextImplEx(String data) {
         textNode = (TextImpl) DOOMAbstractFactory.getOMFactory().createText(data);
     }
-    /*public TextImplEx(SOAPElementImpl parent, String s) throws SOAPException {
-        //super();
-        //super.setParentElement(parent);
-        OMElement par = parent.getOMElement();
-        omNode =
-        omText =
-                org.apache.axis2.om.OMAbstractFactory.getOMFactory()
-                        .createText(par, s);
-    }
-
-    public TextImplEx(org.w3c.dom.CharacterData data) {
-        if (data == null) {
-            throw new IllegalArgumentException("Text value may not be null.");
-        }
-        omText =
-                org.apache.axis2.om.OMAbstractFactory.getOMFactory()
-                        .createText(data.getData());
-    }
-
-    public TextImplEx(OMText omText) {
-        omNode = this.omText = omText;
-    }*/
-
+    
     /**
      * Retrieves whether this <CODE>Text</CODE> object
      * represents a comment.
@@ -271,7 +249,25 @@
         return textNode.getData();
     }
 
+    /**
+     * If this is a Text node then this method will set its value, otherwise it
+     * sets the value of the immediate (Text) child of this node. The value of
+     * the immediate child of this node can be set only if, there is one child
+     * node and that node is a Text node, or if there are no children in which
+     * case a child Text node will be created.
+     *
+     * @param value the text to set
+     * @throws IllegalStateException if the node is not a Text  node and
+     *                               either has more than one child node or has a child node that
+     *                               is not a Text node
+     */
+    public void setValue(String value) {
+        textNode.setData(value);
+    }
+
     public String toString() {
         return getValue();
     }
+
+
 }

Added: webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/util/IDGenerator.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/util/IDGenerator.java?rev=370083&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/util/IDGenerator.java (added)
+++ webservices/axis2/trunk/java/modules/saaj/src/org/apache/axis2/saaj/util/IDGenerator.java Wed Jan 18 01:18:53 2006
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.apache.axis2.saaj.util;
+
+import java.util.Random;
+
+/**
+ * Code borrowed from AuthenticatorBase.java for generating a secure id's.
+ */
+public class IDGenerator {
+
+    /**
+     * The number of random bytes to include when generating a
+     * session identifier.
+     */
+    protected static final int SESSION_ID_BYTES = 16;
+
+    /**
+     * A random number generator to use when generating session identifiers.
+     */
+    protected static Random random = null;
+
+    /**
+     * The Java class name of the random number generator class to be used
+     * when generating session identifiers.
+     */
+    protected static String randomClass = "java.security.SecureRandom";
+
+    /**
+     * Generate and return a new session identifier.
+     *
+     * @return a new session id
+     */
+    public static synchronized String generateID() {
+        // Generate a byte array containing a session identifier
+        byte bytes[] = new byte[SESSION_ID_BYTES];
+
+        getRandom().nextBytes(bytes);
+
+        // Render the result as a String of hexadecimal digits
+        StringBuffer result = new StringBuffer();
+
+        for (int i = 0; i < bytes.length; i++) {
+            byte b1 = (byte) ((bytes[i] & 0xf0) >> 4);
+            byte b2 = (byte) (bytes[i] & 0x0f);
+
+            if (b1 < 10) {
+                result.append((char) ('0' + b1));
+            } else {
+                result.append((char) ('A' + (b1 - 10)));
+            }
+            if (b2 < 10) {
+                result.append((char) ('0' + b2));
+            } else {
+                result.append((char) ('A' + (b2 - 10)));
+            }
+        }
+        return (result.toString());
+    }
+
+    /**
+     * Return the random number generator instance we should use for
+     * generating session identifiers.  If there is no such generator
+     * currently defined, construct and seed a new one.
+     *
+     * @return Random object
+     */
+    private static synchronized Random getRandom() {
+        if (random == null) {
+            try {
+                Class clazz = Class.forName(randomClass);
+                random = (Random) clazz.newInstance();
+            } catch (Exception e) {
+                random = new java.util.Random();
+            }
+        }
+        return (random);
+    }
+
+}
+

Added: webservices/axis2/trunk/java/modules/saaj/test-resources/axis2.xml
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/test-resources/axis2.xml?rev=370083&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/test-resources/axis2.xml (added)
+++ webservices/axis2/trunk/java/modules/saaj/test-resources/axis2.xml Wed Jan 18 01:18:53 2006
@@ -0,0 +1,125 @@
+<axisconfig name="AxisJava2.0">
+    <!-- ================================================= -->
+    <!-- Parameters -->
+    <!-- ================================================= -->
+    <parameter name="hotdeployment" locked="false">true</parameter>
+    <parameter name="hotupdate" locked="false">false</parameter>
+    <parameter name="enableMTOM" locked="false">true</parameter>
+    <parameter name="cacheAttachments" locked="false">false</parameter>
+    <!-- Uncomment this to enable REST support -->
+    <!--    <parameter name="eanbleREST" locked="false">true</parameter>-->
+
+
+    <parameter name="userName" locked="false">admin</parameter>
+    <parameter name="password" locked="false">axis2</parameter>
+
+
+
+    <!-- ================================================= -->
+    <!-- Message Receivers -->
+    <!-- ================================================= -->
+    <!-- This is the Deafult Message Receiver for the Request Response style Operations -->
+    <messageReceiver mep="INOUT" class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
+
+    <!-- ================================================= -->
+    <!-- Transport Ins -->
+    <!-- ================================================= -->
+    <transportReceiver name="http" class="org.apache.axis2.transport.http.SimpleHTTPServer">
+        <parameter name="port" locked="false">6060</parameter>
+    </transportReceiver>
+
+    <!-- Uncomment this one with the appropriate papameters to enable the SMTP transport Receiver
+    <transportReceiver name="mail" class="org.apache.axis2.transport.mail.SimpleMailListener">
+          <parameter name="transport.mail.pop3.host" locked="false">127.0.0.1</parameter>
+          <parameter name="transport.mail.pop3.user" locked="false">axis2</parameter>
+          <parameter name="transport.mail.pop3.password" locked="false">axis2</parameter>
+          <parameter name="transport.mail.pop3.port" locked="false">110</parameter>
+          <parameter name="transport.mail.replyToAddress" locked="false">axis2@127.0.0.1</parameter>
+      </transportReceiver> -->
+
+    <transportReceiver name="tcp" class="org.apache.axis2.transport.tcp.TCPServer">
+        <parameter name="port" locked="false">6060</parameter>
+    </transportReceiver>
+
+    <!-- ================================================= -->
+    <!-- Transport Outs -->
+    <!-- ================================================= -->
+
+  <transportSender name="http" class="org.apache.axis2.transport.http.CommonsHTTPTransportSender">
+            <parameter name="PROTOCOL" locked="false">HTTP/1.1</parameter>
+    </transportSender>
+    <transportSender name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportSender"/>
+    <transportSender name="local" class="org.apache.axis2.transport.local.LocalTransportSender"/>
+    <transportSender name="jms" class="org.apache.axis2.transport.jms.JMSSender"/>
+
+    <!-- Uncomment this one with the appropriate papameters to enable the SMTP transport Receiver
+   <transportSender name="mail" class="org.apache.axis2.transport.mail.MailTransportSender">
+       <parameter name="transport.mail.smtp.host" locked="false">127.0.0.1</parameter>
+       <parameter name="transport.mail.smtp.user" locked="false">axis2</parameter>
+       <parameter name="transport.mail.smtp.password" locked="false">axis2</parameter>
+       <parameter name="transport.mail.smtp.port" locked="false">25</parameter>
+   </transportSender>
+   -->
+
+    <!-- ================================================= -->
+    <!-- Global Modules  -->
+    <!-- ================================================= -->
+    <!-- Uncomment this to enable Addressing
+    <module ref="addressing"/> -->
+
+    <!-- ================================================= -->
+    <!-- Phases  -->
+    <!-- ================================================= -->
+    <phaseOrder type="inflow">
+        <!--  System pre defined phases       -->
+        <phase name="TransportIn"/>
+        <phase name="PreDispatch"/>
+        <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
+            <handler name="AddressingBasedDispatcher"
+                     class="org.apache.axis2.engine.AddressingBasedDispatcher">
+                <order phase="Dispatch"/>
+            </handler>
+
+            <handler name="RequestURIBasedDispatcher"
+                     class="org.apache.axis2.engine.RequestURIBasedDispatcher">
+                <order phase="Dispatch"/>
+            </handler>
+
+            <handler name="SOAPActionBasedDispatcher"
+                     class="org.apache.axis2.engine.SOAPActionBasedDispatcher">
+                <order phase="Dispatch"/>
+            </handler>
+
+            <handler name="SOAPMessageBodyBasedDispatcher"
+                     class="org.apache.axis2.engine.SOAPMessageBodyBasedDispatcher">
+                <order phase="Dispatch"/>
+            </handler>
+            <handler name="InstanceDispatcher"
+                     class="org.apache.axis2.engine.InstanceDispatcher">
+                <order phase="PostDispatch"/>
+            </handler>
+        </phase>
+        <!--  System pre defined phases       -->
+        <!--   After Postdispatch phase module author or or service author can add any phase he want      -->
+        <phase name="userphase1"/>
+    </phaseOrder>
+    <phaseOrder type="outflow">
+        <!--      user can add his own phases to this area  -->
+        <phase name="userphase1"/>
+        <!--system predefined phase-->
+        <!--these phase will run irrespective of the service-->
+        <phase name="PolicyDetermination"/>
+        <phase name="MessageOut"/>
+    </phaseOrder>
+    <phaseOrder type="INfaultflow">
+        <!--      user can add his own phases to this area  -->
+        <phase name="userphase1"/>
+    </phaseOrder>
+    <phaseOrder type="Outfaultflow">
+        <!--      user can add his own phases to this area  -->
+        <phase name="userphase1"/>
+        <phase name="PolicyDetermination"/>
+        <phase name="MessageOut"/>
+    </phaseOrder>
+</axisconfig>
+

Modified: webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/AttachmentSerializationTest.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/AttachmentSerializationTest.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/AttachmentSerializationTest.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/AttachmentSerializationTest.java Wed Jan 18 01:18:53 2006
@@ -16,6 +16,7 @@
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.Iterator;
@@ -31,11 +32,6 @@
         super(name);
     }
 
-    public static void main(String args[]) throws Exception {
-        AttachmentSerializationTest tester = new AttachmentSerializationTest("tester");
-        tester.testAttachments();
-    }
-
     public void testAttachments() throws Exception {
         try {
             ByteArrayOutputStream bais = new ByteArrayOutputStream();
@@ -66,7 +62,7 @@
         el2.addTextNode("bodyvalue3a");
         el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
         el2.addTextNode("bodyvalue3b");
-        el2 = el.addChildElement("datefield", NS_PREFIX);
+        el.addChildElement("datefield", NS_PREFIX);
 
         // First Attachment
         AttachmentPart ap = msg.createAttachmentPart();
@@ -75,7 +71,7 @@
         msg.addAttachmentPart(ap);
 
         // Second attachment
-        String jpgfilename = "./test-resources/axis.jpg";
+        String jpgfilename = "test-resources/axis.jpg";
         File myfile = new File(jpgfilename);
         FileDataSource fds = new FileDataSource(myfile);
         DataHandler dh = new DataHandler(fds);
@@ -88,19 +84,23 @@
         String [] contentType = headers.getHeader("Content-Type");
         assertTrue(contentType != null);
 
+        int i = 0;
         for (Iterator iter = msg.getAttachments(); iter.hasNext();) {
             AttachmentPart attachmentPart = (AttachmentPart) iter.next();
             final Object content = attachmentPart.getDataHandler().getContent();
             if (content instanceof String) {
                 assertEquals(testText, (String) content);
             } else if (content instanceof FileInputStream) {
-            	//TODO : Complete this
-                // try to write to a File and check whether it is ok
-                // final FileInputStream fis = (FileInputStream) content;
-                /*File file = new File("output-file.jpg");
-                file.createNewFile();
 
-                fis.read(new byte[(int)file.length()])*/
+                // try to write to a File and check whether it is ok
+                final FileInputStream fis = (FileInputStream) content;
+                byte[] b = new byte[15000];
+                final int lengthRead = fis.read(b);
+                FileOutputStream fos =
+                        new FileOutputStream(new File("target/test-resources/atts-op" + (i++) + ".jpg"));
+                fos.write(b, 0, lengthRead);
+                fos.flush();
+                fos.close();
             }
         }
 

Added: webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/SOAPConnectionTest.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/SOAPConnectionTest.java?rev=370083&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/SOAPConnectionTest.java (added)
+++ webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/SOAPConnectionTest.java Wed Jan 18 01:18:53 2006
@@ -0,0 +1,84 @@
+/*                                                                             
+ * Copyright 2004,2005 The Apache Software Foundation.                         
+ *                                                                             
+ * Licensed 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.apache.axis2.saaj;
+
+import junit.framework.TestCase;
+
+import javax.xml.soap.SOAPConnection;
+import javax.xml.soap.SOAPConnectionFactory;
+import javax.xml.soap.SOAPException;
+
+/**
+ * 
+ */
+public class SOAPConnectionTest extends TestCase {
+    public void testClose() {
+        try {
+            SOAPConnection sCon = SOAPConnectionFactory.newInstance().createConnection();
+            sCon.close();
+        } catch (SOAPException e) {
+            fail("Unexpected Exception " + e);
+        }
+    }
+
+    public void testCloseTwice() {
+        SOAPConnectionFactory soapConnectionFactory = null;
+        try {
+            soapConnectionFactory = SOAPConnectionFactory.newInstance();
+        } catch (SOAPException e) {
+            fail("Unexpected Exception " + e);
+        }
+
+        SOAPConnection sCon = null;
+        try {
+            sCon = soapConnectionFactory.createConnection();
+            sCon.close();
+        } catch (SOAPException e) {
+            fail("Unexpected Exception " + e);
+        }
+
+        try {
+            sCon.close();
+            fail("Expected Exception did not occur");
+        } catch (SOAPException e) {
+            assertTrue(true);
+        }
+    }
+
+    public void testCallOnCloseConnection(){
+        SOAPConnectionFactory soapConnectionFactory = null;
+        try {
+            soapConnectionFactory = SOAPConnectionFactory.newInstance();
+        } catch (SOAPException e) {
+            fail("Unexpected Exception " + e);
+        }
+
+        SOAPConnection sCon = null;
+        try {
+            sCon = soapConnectionFactory.createConnection();
+            sCon.close();
+        } catch (SOAPException e) {
+            fail("Unexpected Exception " + e);
+        }
+
+        try {
+            sCon.call(null, new Object());
+            fail("Expected Exception did not occur");
+        } catch (SOAPException e) {
+            assertTrue(true);
+        }
+    }
+}

Modified: webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/EchoService.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/EchoService.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/EchoService.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/EchoService.java Wed Jan 18 01:18:53 2006
@@ -16,21 +16,33 @@
 package org.apache.axis2.saaj.integration;
 
 import org.apache.axis2.om.OMElement;
+import org.apache.axis2.om.OMAttribute;
+import org.apache.axis2.om.OMText;
+import org.apache.axis2.om.impl.MTOMConstants;
+import org.apache.axis2.om.impl.llom.OMTextImpl;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.attachments.MIMEHelper;
 
 import javax.xml.stream.XMLStreamException;
+import javax.xml.namespace.QName;
+import javax.activation.DataHandler;
 
 /**
  * 
  */
 public class EchoService {
-    public OMElement echo(OMElement element) throws XMLStreamException {
+     public OMElement echo(OMElement element) throws XMLStreamException {
+        System.err.println("################ Echo Service was called, Element=" + element);
+
         //Praparing the OMElement so that it can be attached to another OM Tree.
-        //First the OMElement should be completely build in case it is not fully built and still
+        //First the OMElement should be completely built in case it is not fully built and still
         //some of the xml is in the stream.
         element.build();
         //Secondly the OMElement should be detached from the current OMTree so that it can be attached
         //some other OM Tree. Once detached the OmTree will remove its connections to this OMElement.
-        element.detach();
+//        element.detach();
         return element;
     }
+
+
 }

Modified: webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/IntegrationTest.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/IntegrationTest.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/IntegrationTest.java (original)
+++ webservices/axis2/trunk/java/modules/saaj/test/org/apache/axis2/saaj/integration/IntegrationTest.java Wed Jan 18 01:18:53 2006
@@ -2,6 +2,8 @@
 
 import junit.framework.TestCase;
 import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.util.Utils;
 
 import javax.activation.DataHandler;
 import javax.activation.FileDataSource;
@@ -16,45 +18,50 @@
 import javax.xml.soap.SOAPElement;
 import javax.xml.soap.SOAPEnvelope;
 import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
 import javax.xml.soap.SOAPMessage;
 import javax.xml.soap.SOAPPart;
+import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
+import java.util.Iterator;
 
 public class IntegrationTest extends TestCase {
 
-    public static final EndpointReference TARGET_EPR =
-            new EndpointReference("http://127.0.0.1:" +
-                                  (UtilServer.TESTING_PORT)
-                                  + "/axis2/services/EchoService/echo");
+    private static final String ADDRESS = "http://127.0.0.1:" +
+                                          (UtilServer.TESTING_PORT) +
+                                          "/axis2/services/Echo";
+//    private static final String ADDRESS = "http://127.0.0.1:8081" +
+//                                          "/axis2/services/Echo";
+    public static final EndpointReference TARGET_EPR = new EndpointReference(ADDRESS);
 
-    public static final QName SERVICE_NAME = new QName("EchoService");
+    public static final QName SERVICE_NAME = new QName("Echo");
     public static final QName OPERATION_NAME = new QName("echo");
 
+    public static final String SAAJ_REPO = "target/test-resources/saaj-repo";
+
     public IntegrationTest(String name) {
         super(name);
     }
 
     protected void setUp() throws Exception {
-      /*  UtilServer.start(Constants.TESTING_PATH + "saaj-repo");
-        service = Utils.createSimpleService(SERVICE_NAME,
-                                            EchoService.class.getName(),
-                                            OPERATION_NAME);
-        UtilServer.deployService(service);*/
+        UtilServer.start(SAAJ_REPO);
+        final AxisService service = Utils.createSimpleService(SERVICE_NAME,
+                                                              EchoService.class.getName(),
+                                                              OPERATION_NAME);
+        UtilServer.deployService(service);
     }
 
     protected void tearDown() throws Exception {
-      /*  UtilServer.unDeployService(SERVICE_NAME);
+        UtilServer.unDeployService(SERVICE_NAME);
         UtilServer.stop();
-        UtilServer.unDeployClientService();*/
-    }
-
-    public void testOK(){
-
+        UtilServer.unDeployClientService();
     }
 
-    public void _testSendReceiveSimpleSOAPMessage() {
+    public void testSendReceiveSimpleSOAPMessage() {
         try {
             MessageFactory mf = MessageFactory.newInstance();
             SOAPMessage request = mf.createMessage();
@@ -62,70 +69,109 @@
             createSimpleSOAPPart(request);
 
             SOAPConnection sCon = SOAPConnectionFactory.newInstance().createConnection();
-            SOAPMessage response = sCon.call(request, "http://localhost:8081/axis2/services/Echo"); //TODO: change this service
+            SOAPMessage response = sCon.call(request, ADDRESS);
             assertFalse(response.getAttachments().hasNext());
             assertEquals(0, response.countAttachments());
 
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            response.writeTo(baos);
-
-            System.out.println(new String(baos.toByteArray()));
+            String responseStr = printResponse(response);
+            assertTrue(responseStr.indexOf("echo") != -1);
         } catch (SOAPException e) {
-            fail("Unexpected Exception while running test");
+            e.printStackTrace();
+            fail("Unexpected Exception while running test: " + e);
         } catch (IOException e) {
-            fail("Unexpected Exception while running test");
+            fail("Unexpected Exception while running test: " + e);
         }
     }
 
-    public void _testSendReceiveMessageWithAttachment() throws Exception {
+    private String printResponse(final SOAPMessage response) throws SOAPException, IOException {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        response.writeTo(baos);
+        String responseStr = baos.toString();
+
+        System.out.println("\n\n----------------------Response-------------------------\n" +
+                           responseStr);
+        System.out.println("-------------------------------------------------------\n\n");
+        assertTrue(responseStr.indexOf("This is some text") != -1);
+        return responseStr;
+    }
+
+    public void testSendReceiveMessageWithAttachment() throws Exception {
         MessageFactory mf = MessageFactory.newInstance();
-        SOAPMessage message = mf.createMessage();
+        SOAPMessage request = mf.createMessage();
 
         //create the SOAPPart
-        createSOAPPart(message);
+        createSOAPPart(request);
 
-        //Attach a text/plain object with the SOAP message
+        //Attach a text/plain object with the SOAP request
         String sampleMessage = "Sample Message: Hello World!";
-        AttachmentPart textAttach = message.createAttachmentPart(sampleMessage, "text/plain");
+        AttachmentPart textAttach = request.createAttachmentPart(sampleMessage, "text/plain");
         textAttach.addMimeHeader("Content-Transfer-Encoding", "binary");
         textAttach.setContentId("submitSampleText@apache.org");
-        message.addAttachmentPart(textAttach);
+        request.addAttachmentPart(textAttach);
 
-        //Attach a java.awt.Image object to the SOAP message
-        String jpgfilename = "./test-resources/axis.jpg";
+        //Attach a java.awt.Image object to the SOAP request
+        String jpgfilename = "test-resources/axis.jpg";
         File myfile = new File(jpgfilename);
         FileDataSource fds = new FileDataSource(myfile);
         DataHandler imageDH = new DataHandler(fds);
-        AttachmentPart jpegAttach = message.createAttachmentPart(imageDH);
+        AttachmentPart jpegAttach = request.createAttachmentPart(imageDH);
         jpegAttach.addMimeHeader("Content-Transfer-Encoding", "binary");
         jpegAttach.setContentId("submitSampleImage@apache.org");
         jpegAttach.setContentType("image/jpg");
-        message.addAttachmentPart(jpegAttach);
+        request.addAttachmentPart(jpegAttach);
 
         SOAPConnection sCon = SOAPConnectionFactory.newInstance().createConnection();
 
-        SOAPMessage sMsg = sCon.call(message, "http://localhost:8081/axis2/services/Echo");
-        int attachmentCount = sMsg.countAttachments();
+        SOAPMessage response = sCon.call(request, ADDRESS);
+
+        int attachmentCount = response.countAttachments();
         assertTrue(attachmentCount == 2);
 
-//		Iterator attachIter = sMsg.getAttachments();
+        Iterator attachIter = response.getAttachments();
 
-        //Of the two attachments first should be of type text/plain and
-        //second of content-type image/jpeg
+        int i = 0;
+        while (attachIter.hasNext()) {
+            AttachmentPart attachment = (AttachmentPart) attachIter.next();
+            final Object content = attachment.getDataHandler().getContent();
+            if (content instanceof String) {
+                assertEquals(sampleMessage, (String) content);
+            } else if (content instanceof ByteArrayInputStream) {
+                ByteArrayInputStream bais = (ByteArrayInputStream) content;
+                byte[] b = new byte[15000];
+                final int lengthRead = bais.read(b);
+                FileOutputStream fos =
+                        new FileOutputStream(new File("target/test-resources/result" + (i++) + ".jpg"));
+                fos.write(b, 0, lengthRead);
+                fos.flush();
+                fos.close();
+
+                assertTrue(attachment.getContentType().equals("image/jpeg")
+                           || attachment.getContentType().equals("text/plain"));
+            }
+        }
 
-        //Underlying MTOM is converting all contentTypes to application/octet-stream
-        //Thats something to be fixed, I guess. Till then commenting out
-        //these two asserts
-        /*
-          AttachmentPart ap1 = (AttachmentPart)attachIter.next();
-          assertTrue(ap1.getContentType().equals("text/plain"));
-          AttachmentPart ap2 = (AttachmentPart)attachIter.next();
-          assertTrue(ap2.getContentType().equals("image/jpeg"));
-          */
-    }
+        /*final SOAPBody respBody = response.getSOAPPart().getEnvelope().getBody();
+        System.out.println("------------------------------------");
+        for (Iterator childEleIter = respBody.getChildElements(); childEleIter.hasNext();) {
+            SOAPElement o = (SOAPElement) childEleIter.next();
+            System.out.println("@@@@@@@@@ o.tn=" + o.getTagName());
+            System.out.println("------------------------------------------");
+            for (Iterator iter = o.getChildElements(); iter.hasNext();) {
+                SOAPElement p = (SOAPElement) iter.next();
+                System.out.println("@@@@@@@@@ p.o=" + p);
+                System.out.println("@@@@@@@@@ p.pre=" + p.getPrefix());
+                System.out.println("@@@@@@@@@ p.ln=" + p.getLocalName());
+                System.out.println("@@@@@@@@@ p.tn=" + p.getTagName());
+                System.out.println("@@@@@@@@@ p.ns URI=" + p.getNamespaceURI());
+                System.out.println("@@@@@@@@@ p.Val=" + p.getValue());
+            }
+        }
+        System.out.println("------------------------------------");*/
 
-    public void addAttachments() {
+//        response.getSOAPPart().getEnvelope().getHeader().extractAllHeaderElements();
+//        sCon.call(response, ADDRESS);
 
+//        printResponse(response);
     }
 
     private void createSOAPPart(SOAPMessage message) throws SOAPException {
@@ -133,17 +179,41 @@
         SOAPEnvelope env = sPart.getEnvelope();
         SOAPBody body = env.getBody();
 
+        final SOAPHeader soapHeader = env.getHeader();
+        soapHeader.addHeaderElement(env.createName("TestHeader1", "swa", "http://fakeNamespace.org"));
+        soapHeader.addHeaderElement(env.createName("TestHeader2", "swa", "http://fakeNamespace.org"));
+        final SOAPHeaderElement headerEle3 =
+                soapHeader.addHeaderElement(env.createName("TestHeader3", "swa", "http://fakeNamespace.org"));
+        final SOAPElement ch1 = headerEle3.addChildElement("he3", "swa");
+        ch1.addTextNode("Im Header Element of header3");
+
         Name ns = env.createName("echo", "swa", "http://fakeNamespace.org");
         SOAPBodyElement bodyElement = body.addBodyElement(ns);
 
+        Name nameMain = env.createName("internal");
+        SOAPElement mainChildEle = bodyElement.addChildElement(nameMain);
+
         Name ns2 = env.createName("text");
-        SOAPElement textReference = bodyElement.addChildElement(ns2);
+        SOAPElement textReference = mainChildEle.addChildElement(ns2);
         Name hrefAttr = env.createName("href");
         textReference.addAttribute(hrefAttr, "cid:submitSampleText@apache.org");
 
         Name ns3 = env.createName("image");
-        SOAPElement imageReference = bodyElement.addChildElement(ns3);
-        imageReference.addAttribute(hrefAttr, "cid:submitSampleImage@apache.org");
+        SOAPElement imageReference = mainChildEle.addChildElement(ns3);
+        Name ns31 = env.createName("inner");
+        final SOAPElement img = imageReference.addChildElement(ns31);
+        img.addAttribute(hrefAttr, "cid:submitSampleImage@apache.org");
+
+        Name ns4 = env.createName("plaintxt");
+        SOAPElement plainTxt = mainChildEle.addChildElement(ns4);
+        plainTxt.addTextNode("This is simple plain text");
+
+        Name ns5 = env.createName("nested");
+        SOAPElement nested = mainChildEle.addChildElement(ns5);
+        nested.addTextNode("Nested1 Plain Text");
+        Name ns6 = env.createName("nested2");
+        SOAPElement nested2 = nested.addChildElement(ns6);
+        nested2.addTextNode("Nested2 Plain Text");
     }
 
     private void createSimpleSOAPPart(SOAPMessage message) throws SOAPException {
@@ -151,7 +221,16 @@
         SOAPEnvelope env = sPart.getEnvelope();
         SOAPBody body = env.getBody();
 
-        Name ns = env.createName("echo", "swa", "http://fakeNamespace.org");
-        body.addBodyElement(ns);
+        Name ns = env.createName("echo", "swa2", "http://fakeNamespace2.org");
+        final SOAPBodyElement bodyElement = body.addBodyElement(ns);
+        Name ns2 = env.createName("something");
+        final SOAPElement ele1 = bodyElement.addChildElement(ns2);
+        ele1.addTextNode("This is some text");
+
+        Name ns3 = env.createName("ping", "swa3", "http://fakeNamespace3.org");
+        final SOAPBodyElement bodyElement2 = body.addBodyElement(ns3);
+        Name ns4 = env.createName("another");
+        final SOAPElement ele2 = bodyElement2.addChildElement(ns4);
+        ele2.addTextNode("This is another text");
     }
 }

Modified: webservices/axis2/trunk/java/modules/xml/src/org/apache/axis2/om/impl/MIMEOutputUtils.java
URL: http://svn.apache.org/viewcvs/webservices/axis2/trunk/java/modules/xml/src/org/apache/axis2/om/impl/MIMEOutputUtils.java?rev=370083&r1=370082&r2=370083&view=diff
==============================================================================
--- webservices/axis2/trunk/java/modules/xml/src/org/apache/axis2/om/impl/MIMEOutputUtils.java (original)
+++ webservices/axis2/trunk/java/modules/xml/src/org/apache/axis2/om/impl/MIMEOutputUtils.java Wed Jan 18 01:18:53 2006
@@ -21,6 +21,7 @@
 
 import javax.mail.MessagingException;
 import javax.mail.internet.MimeBodyPart;
+import javax.activation.DataHandler;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.StringWriter;
@@ -67,9 +68,10 @@
     public static MimeBodyPart createMimeBodyPart(OMText node)
             throws MessagingException {
         MimeBodyPart mimeBodyPart = new MimeBodyPart();
-        mimeBodyPart.setDataHandler((javax.activation.DataHandler)node.getDataHandler());
+        final DataHandler dataHandler = (DataHandler) node.getDataHandler();
+        mimeBodyPart.setDataHandler(dataHandler);
         mimeBodyPart.addHeader("content-id", "<"+node.getContentID()+">");
-        mimeBodyPart.addHeader("content-type", "application/octet-stream");
+        mimeBodyPart.addHeader("content-type", dataHandler.getContentType());
         mimeBodyPart.addHeader("content-transfer-encoding", "binary");
         return mimeBodyPart;
 



Mime
View raw message