You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-dev@axis.apache.org by ri...@apache.org on 2002/08/03 23:52:06 UTC

cvs commit: xml-axis/java/src/org/apache/axis/attachments AttachmentsImpl.java ManagedMemoryDataSource.java

rineholt    2002/08/03 14:52:06

  Modified:    java/samples/attachments EchoAttachmentsService.java
                        attachdeploy.wsdd deployit.cmd
               java/src/org/apache/axis/attachments AttachmentsImpl.java
                        ManagedMemoryDataSource.java
  Added:       java/samples/attachments TestRef.java testref.wsdd
  Log:
   An example of sending an attachment via messages.
   The main purpose is to validate the different types of attachment references
   by content Id, content location both absolute and relative.
  
   Creates 5 separate attachments referenced  differently by a SOAP document.
   Each attachment contains a string that is assembled and tested to see if
   if the attachments are correctly sent and referenced.  Each attachment also
   contains a mime header indicating its position and validated on the server
   to see if mime headers are correctly sent with attachments.
  
   Sends the same message again however the second attachments are placed in the
   stream in reverse to see if they are still referenced ok.
  
   The return SOAP document references a single attachment which is the a Java
   serialized vector holding strings to the individual attachments sent.
  
   Demos using attachments directly.
  
  Revision  Changes    Path
  1.4       +125 -1    xml-axis/java/samples/attachments/EchoAttachmentsService.java
  
  Index: EchoAttachmentsService.java
  ===================================================================
  RCS file: /home/cvs/xml-axis/java/samples/attachments/EchoAttachmentsService.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- EchoAttachmentsService.java	1 Jul 2002 02:46:27 -0000	1.3
  +++ EchoAttachmentsService.java	3 Aug 2002 21:52:05 -0000	1.4
  @@ -55,6 +55,7 @@
   
   package samples.attachments;
   import javax.activation.DataHandler;
  +import org.w3c.dom.*;
   
   
   /**
  @@ -66,7 +67,6 @@
    * This class has a main method that beside the standard arguments
    * allows you to specify an attachment that will be sent to a 
    * service which will then send it back.
  - *  WORK IN PROGRESS!
    *  
    */
   public class EchoAttachmentsService {
  @@ -115,6 +115,130 @@
           return attachments;
       }
   
  +    public Document attachments( Document xml)
  +      throws org.apache.axis.AxisFault,java.io.IOException, org.xml.sax.SAXException,
  +      java.awt.datatransfer.UnsupportedFlavorException,javax.xml.parsers.ParserConfigurationException,
  +      java.lang.ClassNotFoundException,javax.xml.soap.SOAPException  {
  +      System.err.println("In message handling attachments directly.");
  +      org.apache.axis.MessageContext msgContext= org.apache.axis.MessageContext.getCurrentContext(); 
  +
  +      org.apache.axis.Message reqMsg= msgContext.getRequestMessage();
  +
  +      org.apache.axis.attachments.Attachments attachments=reqMsg.getAttachmentsImpl();  
  +
  +      if(null == attachments){
  +         throw new org.apache.axis.AxisFault("No support for attachments" );
  +      }
  +
  +      Element rootEl= xml.getDocumentElement();
  +
  +      Element caEl= getNextFirstChildElement(rootEl);
  +      StringBuffer fullmsg= new StringBuffer();
  +      java.util.Vector reply= new java.util.Vector();
  +
  +
  +      for(int count=1 ;caEl != null; caEl= getNextSiblingElement(caEl), ++count){
  +        String href= caEl.getAttribute("href");
  +        org.apache.axis.Part p= attachments.getAttachmentByReference(href);
  +        if(null == p)
  +         throw new org.apache.axis.AxisFault("Attachment for ref='"+href+"' not found." );
  +         String ordinalStr =getOrdinalHeaders(p);
  +         if( null == ordinalStr || ordinalStr.trim().length()==0)
  +           throw new org.apache.axis.AxisFault("Ordinal for attachment  ref='"+href+"' not found." );
  +         int ordinal= Integer.parseInt(ordinalStr);
  +         if(count != ordinal)
  +           throw new org.apache.axis.AxisFault("Ordinal for attachment  ref='"+href+"' excpected" + count + " got " + ordinal +"." );
  +
  +          //check content type.
  +          if(!"text/plain".equals(p.getContentType()))
  +             throw new org.apache.axis.AxisFault("Attachment  ref='"+href+"' bad content-type:'"+p.getContentType()+"'." );
  +
  +         //now get at the data...
  +          DataHandler dh= ((org.apache.axis.attachments.AttachmentPart)p).getDataHandler();
  +          String pmsg=(String )dh.getContent();
  +          fullmsg.append(pmsg);
  +          reply.add(pmsg);
  +      }
  +      if(!(samples.attachments.TestRef .TheKey.equals(fullmsg.toString())))
  +        throw new org.apache.axis.AxisFault("Fullmsg not correct'"+fullmsg +"'." );
  +      System.out.println(fullmsg.toString());
  +
  +      //Now lets Java serialize the reply...
  +      java.io.ByteArrayOutputStream byteStream = new java.io.ByteArrayOutputStream();
  +      java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(byteStream);
  +      oos.writeObject(reply);
  +      oos.close();
  +      byte[] replyJavaSerialized= byteStream.toByteArray();
  +      byteStream=null; oos= null;
  +
  +      org.apache.axis.attachments.AttachmentPart replyPart= new 
  +          org.apache.axis.attachments.AttachmentPart(
  +        new DataHandler( new MemoryOnlyDataSource(replyJavaSerialized,
  +         java.awt.datatransfer.DataFlavor.javaSerializedObjectMimeType+"; class=\"" 
  +          + reply.getClass().getName()+"\"")));
  +
  +      //Now lets add the attachment to the response message.
  +      org.apache.axis.Message rspMsg= msgContext.getResponseMessage();
  +      rspMsg.addAttachmentPart(replyPart);
  +
  +      //Iterate over the attachments... not by reference.
  +      String ordinalPattern=""; 
  +      for(java.util.Iterator ai=reqMsg.getAttachments(); ai.hasNext();){
  +        org.apache.axis.Part p= (org.apache.axis.Part) ai.next();
  +        ordinalPattern += getOrdinalHeaders(p);
  +      }
  +
  +      //Now build the return document in a string buffer... 
  +      StringBuffer msgBody = new StringBuffer("\n<attachments xmlns=\"");
  +          msgBody.append(rootEl.getNamespaceURI())
  +          .append("\">\n")
  +          .append("\t<attachment href=\"")
  +          .append(replyPart.getContentIdRef())
  +          .append("\" ordinalPattern=\"")
  +          .append(ordinalPattern)
  +          .append("\"/>\n")
  +          .append("</attachments>\n");
  +
  +      //Convert the string buffer to an XML document and return it.
  +      return 
  +        org.apache.axis.utils.XMLUtils.newDocument(
  +          new org.xml.sax.InputSource(new java.io.ByteArrayInputStream(
  +            msgBody.toString().getBytes())));
  +    }
  +    Element getNextFirstChildElement(Node n) {
  +        if(n== null) return null;
  +        n= n.getFirstChild();
  +        for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
  +        return (Element)n;
  +    }
  +
  +    Element getNextSiblingElement(Node n) {
  +        if(n== null) return null;
  +        n= n.getNextSibling();
  +        for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
  +        return (Element)n;
  +    }
  +    String getOrdinalHeaders( org.apache.axis.Part p){
  +      StringBuffer ret= new StringBuffer();
  +      for(java.util.Iterator i= p.getMatchingMimeHeaders( new String[]{samples.attachments.TestRef.positionHTTPHeader});
  +          i.hasNext();){
  +          javax.xml.soap.MimeHeader mh= (javax.xml.soap.MimeHeader) i.next();
  +          String v= mh.getValue();  
  +          if(v != null) ret.append(v.trim());
  +      }
  +      return ret.toString();
  +    }
  +
  +    /**This class should store all attachment data in memory */
  +    static class MemoryOnlyDataSource extends org.apache.axis.attachments.ManagedMemoryDataSource{
  +    
  +       MemoryOnlyDataSource( byte [] in, String contentType) throws java.io.IOException{
  +         super( new java.io.ByteArrayInputStream( in) , Integer.MAX_VALUE -2, contentType, true); 
  +       }
  +       MemoryOnlyDataSource( String in, String contentType)throws java.io.IOException{
  +         this( in.getBytes() ,  contentType); 
  +       }
  +    }
   
   }
   
  
  
  
  1.8       +2 -1      xml-axis/java/samples/attachments/attachdeploy.wsdd
  
  Index: attachdeploy.wsdd
  ===================================================================
  RCS file: /home/cvs/xml-axis/java/samples/attachments/attachdeploy.wsdd,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- attachdeploy.wsdd	3 Jul 2002 20:21:43 -0000	1.7
  +++ attachdeploy.wsdd	3 Aug 2002 21:52:05 -0000	1.8
  @@ -1,6 +1,7 @@
   <!-- This file can be used to deploy the echoAttachments sample -->
   <!-- using this command: java org.apache.axis.client.AdminClient attachdeploy.wsdd -->
   
  +<!-- This deploys the echo attachment service.  -->
   <deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java" xmlns:ns1="urn:EchoAttachmentsService" >
     <service name="urn:EchoAttachmentsService" provider="java:RPC" >
       <parameter name="className" value="samples.attachments.EchoAttachmentsService"/>
  @@ -14,6 +15,6 @@
       serializer="org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory" 
       encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
        />
  -
     </service>
  +
   </deployment>
  
  
  
  1.3       +2 -0      xml-axis/java/samples/attachments/deployit.cmd
  
  Index: deployit.cmd
  ===================================================================
  RCS file: /home/cvs/xml-axis/java/samples/attachments/deployit.cmd,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- deployit.cmd	11 Dec 2001 13:23:56 -0000	1.2
  +++ deployit.cmd	3 Aug 2002 21:52:05 -0000	1.3
  @@ -1,3 +1,5 @@
   rem this assumes webserver is running on port 8080
   @echo off 
   java org.apache.axis.client.AdminClient %* attachdeploy.wsdd 
  +java org.apache.axis.client.AdminClient %* testref.wsdd 
  +rem java org.apache.axis.client.AdminClient list 
  
  
  
  1.1                  xml-axis/java/samples/attachments/TestRef.java
  
  Index: TestRef.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package samples.attachments;
  
  
  import org.apache.axis.AxisFault;
  import org.apache.axis.client.Call;
  import org.apache.axis.client.Service;
  import org.apache.axis.MessageContext;
  import org.apache.axis.transport.http.HTTPConstants;
  import org.apache.axis.encoding.XMLType;
  import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;
  import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
  import org.apache.axis.utils.Options;
  import org.apache.axis.attachments.AttachmentPart;
  import org.apache.axis.message.SOAPBodyElement;
  import javax.activation.DataHandler;
  import javax.activation.FileDataSource;
  import javax.xml.rpc.ParameterMode;
  import javax.xml.namespace.QName;
  import javax.activation.DataHandler;
  
  import java.net.URL;
  import java.util.Hashtable;
  import java.util.Vector;
  import java.io.ByteArrayInputStream;
  import java.io.File;
  import org.w3c.dom.*;
  
  
  /**
   *
   * @author Rick Rineholt 
   */
  
  /**
   * An example of sending an attachment via messages.
   *  The main purpose is to validate the different types of attachment references
   *  by content Id, content location both absolute and relative.
   * 
   *  Creates 5 separate attachments referenced  differently by a SOAP document.
   *  Each attachment contains a string that is assembled and tested to see if
   *  if the attachments are correctly sent and referenced.  Each attachment also
   *  contains a mime header indicating its position and validated on the server
   *  to see if mime headers are correctly sent with attachments.
   *
   *  Sends the same message again however the second attachments are placed in the
   *  stream in reverse to see if they are still referenced ok.
   *
   *
   *  The return SOAP document references a single attachment which is the a Java
   *  serialized vector holding strings to the individual attachments sent.
   *
   *  Demos using attachments directly.
   *  
   */
  public class TestRef {
  
      Options opts = null;
      public static final String positionHTTPHeader="Ordinal";
      public static final String TheKey= "Now is the time for all good men to come to the aid of their country.";
  
  
      public TestRef( Options opts) {
          this.opts = opts;
      }
  
  
      /**
       * This method sends all the files in a directory. 
       *  @param The directory that is the source to send.
       *  @return True if sent and compared.
       */
      public boolean testit() throws Exception {
          boolean rc = true;
          String baseLoc= "http://axis.org/attachTest";
          Vector refs= new Vector();  //holds a string of references to attachments.
  
          Service  service = new Service(); //A new axis Service.
  
          Call     call    = (Call) service.createCall(); //Create a call to the service.
  
          /*Un comment the below statement to do HTTP/1.1 protocol*/
        //call.setScopedProperty(MessageContext.HTTP_TRANSPORT_VERSION,HTTPConstants.HEADER_PROTOCOL_V11);
          Hashtable myhttp= new Hashtable();
          myhttp.put(HTTPConstants.HEADER_CONTENT_LOCATION, baseLoc);     //Send extra soap headers
  
          /*Un comment the below to do http chunking to avoid the need to calculate content-length. (Needs HTTP/1.1)*/
        //myhttp.put(HTTPConstants.HEADER_TRANSFER_ENCODING, HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED);
  
          /*Un comment the below to force a 100-Continue... This will cause  httpsender to wait for
           * this response on a post.  If HTTP 1.1 and this is not set, *SOME* servers *MAY* reply with this anyway.
           *  Currently httpsender won't handle this situation, this will require the resp. which it will handle.
           */
        //myhttp.put(HTTPConstants.HEADER_EXPECT, HTTPConstants.HEADER_EXPECT_100_Continue);
          call.setScopedProperty(HTTPConstants.REQUEST_HEADERS,myhttp);
  
          call.setTargetEndpointAddress( new URL(opts.getURL()) ); //Set the target service host and service location, 
  
          java.util.Stack rev= new java.util.Stack();
          //Create an attachment referenced by a generated contentId.
          AttachmentPart ap= new AttachmentPart(new javax.activation.DataHandler(
            "Now is the time", "text/plain" ));
           refs.add(ap.getContentIdRef()); //reference the attachment by contentId.
           ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
          call.addAttachmentPart(ap);
          rev.push(ap);
  
          //Create an attachment referenced by a set contentId.
          String setContentId="rick_did_this";
          ap= new AttachmentPart(new DataHandler(" for all good", "text/plain" ));
            //new MemoryOnlyDataSource(
           ap.setContentId(setContentId);  
           refs.add("cid:" + setContentId); //reference the attachment by contentId.
           ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
          call.addAttachmentPart(ap);
          rev.push(ap);
  
          //Create an attachment referenced by a absolute contentLocation.
          ap= new AttachmentPart(new DataHandler( " men to", "text/plain" ));
            //new MemoryOnlyDataSource( " men to", "text/plain" )));
          ap.setContentLocation(baseLoc+ "/firstLoc");  
           refs.add(baseLoc+ "/firstLoc"); //reference the attachment by contentId.
           ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
          call.addAttachmentPart(ap);
          rev.push(ap);
  
          //Create an attachment referenced by relative location to a absolute location. 
          ap= new AttachmentPart(new DataHandler( " come to", "text/plain" ));
            // new MemoryOnlyDataSource( " come to", "text/plain" )));
          ap.setContentLocation(baseLoc+ "/secondLoc");  
          refs.add("secondLoc"); //reference the attachment by contentId.
          ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
          call.addAttachmentPart(ap);
          rev.push(ap);
  
          //Create an attachment referenced by relative location to a relative location. 
          ap= new AttachmentPart(new DataHandler( " the aid of their country.", "text/plain" ));
            // new MemoryOnlyDataSource( " the aid of their country.", "text/plain" )));
          ap.setContentLocation("thirdLoc");  
          refs.add("thirdLoc"); //reference the attachment by contentId.
          ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
          call.addAttachmentPart(ap);
          rev.push(ap);
  
  
          //Now build the message....
          String namespace="urn:attachmentsTestRef"; //needs to match name of service. 
  
          StringBuffer msg = new StringBuffer("\n<attachments xmlns=\"" +namespace +"\">\n");
          for (java.util.Iterator i = refs.iterator(); i.hasNext() ; )
            msg.append("    <attachment href=\"" + (String) i.next()  + "\"/>\n");
  
          msg.append(  "</attachments>");
  
          call.setUsername( opts.getUser());
  
          call.setPassword( opts.getPassword() );
  
          call.setOperationStyle(org.apache.axis.enum.Style.DOCUMENT_STR);
  
          //Now do the call....
          Object ret = call.invoke(new Object[]{
             new SOAPBodyElement(new ByteArrayInputStream(msg.toString().getBytes("UTF-8"))) } ); 
  
          validate(ret, call, "12345");   
  
          //Note: that even though the attachments are sent in reverse they are still
          // retreived by reference so the ordinal will still match.
          int revc=1;
          for( ap= (AttachmentPart)rev.pop(); ap!=null ;ap= rev.empty()? null :  (AttachmentPart)rev.pop()){
            call.addAttachmentPart(ap);
          }
  
          //Now do the call....
          ret = call.invoke(new Object[]{
             new SOAPBodyElement(new ByteArrayInputStream(msg.toString().getBytes("UTF-8"))) } ); 
  
          validate(ret, call, "54321");   
  
  
          return rc;
      }
  
      void validate(Object ret, Call call, final String expOrdPattern) throws Exception{   
          if (null == ret) {
              System.out.println("Received null ");
              throw new AxisFault("", "Received null", null, null);
          }
  
          if (ret instanceof String) {
              System.out.println("Received problem response from server: " + ret);
              throw new AxisFault("", (String) ret, null, null);
          }
  
          Vector vret= (Vector) ret;
  
          if (!(ret instanceof java.util.Vector )) {
              //The wrong type of object that what was expected.
              System.out.println("Received unexpected type :" +
                  ret.getClass().getName());
              throw new AxisFault("", "Received unexpected type:" +
                      ret.getClass().getName(), null, null);
  
          }
  
          org.apache.axis.message.RPCElement retrpc= (org.apache.axis.message.RPCElement )
            ((Vector)ret).elementAt(0);
  
          Document retDoc= org.apache.axis.utils.XMLUtils.newDocument(
            new org.xml.sax.InputSource(new java.io.ByteArrayInputStream(
              retrpc.toString().getBytes())));
  
          //get at the attachments.    
          org.apache.axis.attachments.Attachments attachments= 
            call.getResponseMessage().getAttachmentsImpl();
  
          //Still here, so far so good.
          Element rootEl= retDoc.getDocumentElement();
  
          Element caEl= getNextFirstChildElement(rootEl);
          //this should be the only child element with the ref to our attachment
          // response.
          String href= caEl.getAttribute("href");
          org.apache.axis.Part p= attachments.getAttachmentByReference(href);
          if(null == p)
           throw new org.apache.axis.AxisFault("Attachment for ref='"+href+"' not found." );
  
           //Check to see the the attachment were sent in order
          String ordPattern= caEl.getAttribute("ordinalPattern");
          if(!expOrdPattern.equals(ordPattern))
            throw new org.apache.axis.AxisFault(
             "Attachments sent out of order expected:'" +expOrdPattern + "', got:'"+ordPattern+"'."  );
  
           //now get at the data...
           DataHandler dh= ((org.apache.axis.attachments.AttachmentPart)p).getDataHandler();
           System.err.println("content-type:" + dh.getContentType());
  
         java.util.Vector rspVector= null;
         Object rspObject =  dh.getContent();//This SHOULD just return the vector but reality strikes...
         if(rspObject == null)
             throw new AxisFault("", "Received unexpected object:null", null, null);
         else if(rspObject instanceof java.util.Vector) rspVector= (java.util.Vector)rspObject;
         else if(rspObject instanceof java.io.InputStream)
            rspVector= (java.util.Vector)
             new java.io.ObjectInputStream((java.io.InputStream)rspObject ).readObject();
         else    
             throw new AxisFault("", "Received unexpected object:" +
                      rspObject.getClass().getName(), null, null);
  
        StringBuffer fullmsg= new StringBuffer();
        for(java.util.Iterator ri= rspVector.iterator(); ri.hasNext();){
          String part= (String)ri.next();
          fullmsg.append(part);
          System.out.print(part);
        }
        System.out.println("");
  
        if(!(TheKey.equals (fullmsg.toString())))
          throw new org.apache.axis.AxisFault("Fullmsg not correct'"+fullmsg +"'." );
      }
  
      Element getNextFirstChildElement(Node n) {
          if(n== null) return null;
          n= n.getFirstChild();
          for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
          return (Element)n;
      }
  
      Element getNextSiblingElement(Node n) {
          if(n== null) return null;
          n= n.getNextSibling();
          for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
          return (Element)n;
      }
  
      /**
       * Give a single file to send or name a directory
       * to send an array of attachments of the files in
       * that directory.
       */
      public static void main(String args[]) {
          try {
  
              Options opts = new Options(args);
              TestRef echoattachment = new TestRef(opts);
  
              args = opts.getRemainingArgs();
              int argpos=0;
  
              if (echoattachment.testit()) {
                  System.out.println("Attachments sent and received ok!");
                  System.exit(0);
              }
          }
          catch ( Exception e ) {
              System.err.println(e);
               e.printStackTrace();
          }
          System.exit(18);
      }
  
  
      /**
       *  Return an array of datahandlers for each file in the dir. 
       *  @param the name of the directory
       *  @return return an array of datahandlers.
       */
  
      protected DataHandler[] getAttachmentsFromDir(String dirName) {
          java.util.LinkedList retList = new java.util.LinkedList();
          DataHandler[] ret = new DataHandler[0];// empty
  
          java.io.File sourceDir = new java.io.File(dirName);
  
          java.io.File[] files = sourceDir.listFiles();
  
          for ( int i = files.length - 1; i >= 0; --i) {
              java.io.File cf = files[i];
  
              if (cf.isFile() && cf.canRead()) {
                  String fname = null;
  
                  try {
                      fname = cf.getAbsoluteFile().getCanonicalPath();
                  }
                  catch ( java.io.IOException e) {
                      System.err.println("Couldn't get file \"" + fname + "\" skipping...");
                      continue;
                  }
                  retList.add( new DataHandler( new FileDataSource( fname )));
              }
          }
          if (!retList.isEmpty()) {
              ret = new DataHandler[ retList.size()];
              ret = (DataHandler[]) retList.toArray(ret);
          }
  
          return ret;
      }
  
      /**This class should store all attachment data in memory */
      static class MemoryOnlyDataSource extends org.apache.axis.attachments.ManagedMemoryDataSource{
      
         MemoryOnlyDataSource( byte [] in, String contentType) throws java.io.IOException{
           super( new java.io.ByteArrayInputStream( in) , Integer.MAX_VALUE -2, contentType, true); 
         }
         MemoryOnlyDataSource( String in, String contentType)throws java.io.IOException{
           this( in.getBytes() ,  contentType); 
         }
      }
  }
  
  
  
  1.1                  xml-axis/java/samples/attachments/testref.wsdd
  
  Index: testref.wsdd
  ===================================================================
  <!-- This file can be used to deploy the echoAttachments sample -->
  <!-- using this command: java org.apache.axis.client.AdminClient attachdeploy.wsdd -->
  
  <!-- This deploys the echo attachment service.  -->
  <deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java" xmlns:ns1="urn:EchoAttachmentsService" >
    <service name="urn:attachmentsTestRef" provider="java:MSG">
      <parameter value="samples.attachments.EchoAttachmentsService" name="className"/>
      <parameter value="attachments" name="allowedMethods"/>
    </service>
  </deployment>
  
  
  
  1.29      +3 -4      xml-axis/java/src/org/apache/axis/attachments/AttachmentsImpl.java
  
  Index: AttachmentsImpl.java
  ===================================================================
  RCS file: /home/cvs/xml-axis/java/src/org/apache/axis/attachments/AttachmentsImpl.java,v
  retrieving revision 1.28
  retrieving revision 1.29
  diff -u -r1.28 -r1.29
  --- AttachmentsImpl.java	15 Jul 2002 18:01:21 -0000	1.28
  +++ AttachmentsImpl.java	3 Aug 2002 21:52:06 -0000	1.29
  @@ -193,7 +193,8 @@
           if (mpartStream != null) {
               Collection atts = mpartStream.getAttachments();
   
  -            contentLocation= mpartStream.getContentLocation();
  +            if(contentLocation == null)
  +                contentLocation= mpartStream.getContentLocation();
   
               mpartStream = null;
   
  @@ -340,7 +341,6 @@
       public Part getAttachmentByReference(String reference)
               throws org.apache.axis.AxisFault {
   
  -
           if (null == reference) {
               return null;
           }
  @@ -359,9 +359,8 @@
           Part ret = (Part) attachments.get(reference);
           if( null != ret) return ret;
   
  -        String referenceLC = reference.toLowerCase();
   
  -        if (!referenceLC.startsWith(Attachments.CIDprefix) && (null != contentLocation)) {
  +        if (!reference.startsWith(Attachments.CIDprefix) && (null != contentLocation)) {
               //Not a content-id check to see if its a relative location id.
   
                   String fqreference = contentLocation;
  
  
  
  1.18      +2 -1      xml-axis/java/src/org/apache/axis/attachments/ManagedMemoryDataSource.java
  
  Index: ManagedMemoryDataSource.java
  ===================================================================
  RCS file: /home/cvs/xml-axis/java/src/org/apache/axis/attachments/ManagedMemoryDataSource.java,v
  retrieving revision 1.17
  retrieving revision 1.18
  diff -u -r1.17 -r1.18
  --- ManagedMemoryDataSource.java	3 Jul 2002 17:50:24 -0000	1.17
  +++ ManagedMemoryDataSource.java	3 Aug 2002 21:52:06 -0000	1.18
  @@ -476,6 +476,8 @@
   
           deleted = true;
   
  +        memorybuflist = null;
  +
           if (diskCacheFile != null) {
               if (cachediskstream != null) {
                   try {
  @@ -517,7 +519,6 @@
               }
           }
   
  -        memorybuflist = null;
   
           return ret;
       }