Hi,

Jay SenSharma

Jay SenSharma

Based on the comment/query of one of our subscriber “Mauriciohttp://middlewaremagic.com/weblogic/?page_id=131#comment-4208 , Here we are going to see a very simple demonstration of using the SOAP Attachment on JAXWS Style of WebServices. Using following sample we can upoad an attachment on WebLogic DOMAIN_HOME directory (or in any other location defined in our WebService class).

Step1). Create a Directory somewhere in your file system like “C:\SOAP_Attachment”

Step2). Now create a directory with name “src” inside “C:\SOAP_Attachment”

Step3). Write the following kind of WebService “AttachmentService_Impl.java” inside “C:\SOAP_Attachment\src”

package ws;
import java.io.*;
import java.util.*;
import javax.activation.*;   //DataHandler, FileDataSource

//XML Related APIs
import javax.xml.transform.*;   // Source, Transformer, TransformerFactory
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

//WebService APIs
import javax.jws.*;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

public class AttachmentService_Impl
	{
	   public DataHandler dataHandler=null;
       public String attachAnyFile(DataHandler dataHandler, String file)
		   {
		          String filename="";
             try {
				    //DataHandler dataHandler=new DataHandler(fileDataSource);
					File f=new File(file);
					filename=f.getName();
                    System.out.println("\n\t Writing to File /" + filename);
                    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(filename));
                    BufferedInputStream bin = new BufferedInputStream(dataHandler.getInputStream());

		            byte[] buffer = new byte[256];
				    while (true)
					{
						int bytesRead = bin.read(buffer);
		                if (bytesRead == -1)
				            break;
						bout.write(buffer, 0, bytesRead);
					}
		            bin.close();
				    bout.close();
		        }
			   catch (Exception e)
				{
					System.out.println("\n\t [AttachmentService_Impl] Exception Occured While Writing in File : "+e);
					return e.toString();
				}
               return ("\n\t File Attachment Completed Succesfully " + filename + "\t at " + new Date());
            }
}

Step4). Now write the WebService Client program inorder to send the Attachment to WebService. “Client.java” inside “C:\SOAP_Attachment\src”

package client;
import javax.activation.DataHandler;
import javax.activation.*;
import java.io.*;
public class Client
{
	public static void main(String[] ar) throws Exception
	{
		System.out.println("\n\tstart client");
		AttachmentServiceImplService service=new AttachmentServiceImplService();
		AttachmentServiceImpl port=service.getAttachmentServiceImplPort();

        String fileName_WithPath=ar[0];
		long length=new java.io.File(ar[0]).length();
		FileDataSource fileDataSource = new FileDataSource(fileName_WithPath);
        DataHandler dataHandler = new DataHandler(fileDataSource);
        System.out.println("\n\tCalling service to send a file from a customer...");

  	    BufferedInputStream bin = new BufferedInputStream(dataHandler.getInputStream());
		byte b[]=new byte[(int)length];
		bin.read(b);
        String result = port.attachAnyFile(b,fileName_WithPath);
        System.out.println("\n\t Result From Service: "+result);
        System.out.println("\n\tend client");
	}
}

Step5). Now we will write the following ANT Sctipt to completely Build, Deploy and Run the Client. “build.xml” inside “C:\SOAP_Attachment” directory.

<project name="DwAttach" default="all">
 <!-- set global properties for this build -->
 <property name="wls.username" value="weblogic" />
 <property name="wls.password" value="weblogic" />
 <property name="wls.hostname" value="localhost" />
 <property name="wls.port" value="7001" />
 <property name="wls.server.name" value="AdminServer" />

 <property name="ear.deploy.name" value="SOAP_JAXWS_AttachmentEar" />
 <property name="client-output" value="output" />
 <property name="tempjar-dir" value="${client-output}/tempjardir" />
 <property name="ear.dir" value="${client-output}/SOAP_JAXWS_AttachmentEar" />
 <property name="clientclass-dir" value="${client-output}/clientclasses" />

 <path id="client.class.path">
    <pathelement path="${clientclass-dir}"/>
    <pathelement path="${java.class.path}"/>
  <pathelement path="src"/>
 </path>

 <taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" />
 <taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />

 <target name="all" depends="clean,build-service,deploy-attach,client,run" />
 <target name="clean" depends="undeploy-attach">
	 <delete dir="${client-output}"/>
 </target>

 <target name="build-service">
	  <javac srcdir="src" destdir="src" classpath="${client.class.path}" includes="*Attach*.java"/>
	  <jwsc srcdir="src" destdir="${ear.dir}" debug="true" classpathref="client.class.path">
	       <jws file="AttachmentService_Impl.java" type="JAXWS" />
	  </jwsc>
 </target>

 <target name="deploy-attach">
  <wldeploy action="deploy" name="${ear.deploy.name}"   source="${ear.dir}"
            user="${wls.username}"  password="${wls.password}"
            verbose="true"   adminurl="t3://${wls.hostname}:${wls.port}"
            targets="${wls.server.name}" />
  </target>

 <target name="undeploy-attach">
 <wldeploy action="undeploy" name="${ear.deploy.name}"   failonerror="false"
           user="${wls.username}" password="${wls.password}" verbose="true"
           adminurl="t3://${wls.hostname}:${wls.port}"  targets="${wls.server.name}" />
 </target>

 <target name="client">
    <clientgen  wsdl="http://${wls.hostname}:${wls.port}/AttachmentService_Impl/AttachmentService_ImplService?WSDL"
                destDir="${clientclass-dir}"  packageName="client" type="JAXWS"/>
             <javac   debug="true"  srcdir="${clientclass-dir}" destdir="${clientclass-dir}" includes="**/*.java"/>
             <!-- <javac  debug="true"  srcdir="client" destdir="${clientclass-dir}" includes="client/**/*.java"/>  -->
 </target>

 <target name="run">
      <javac srcdir="src" destdir="${clientclass-dir}" classpath="${client.class.path}" includes="Client.java"/>
      <java classname="client.Client"   fork="true"  failonerror="true">
               <classpath refid="client.class.path"/>
			   <jvmarg value="-Xmx512m" />
               <arg line="Cant_Stop_Dancing.mp3" /> <!-- Name of the file for SOAP Attachment -->
      </java>
 </target>
</project>

Step6). Open a command prompt and then run “. ./setWLSEnv.sh” to set the Environment (classpath/path) , then run the ant script to build, Deploy and run the WebService Client. like following


C:\SOAP_Attachment>ant
Buildfile: build.xml

undeploy-attach:
 [wldeploy] weblogic.Deployer -verbose -noexit -name SOAP_JAXWS_AttachmentEar -targets AdminServer -adminurl t3://localhost:7001 -user weblo
gic -password ******** -undeploy
 [wldeploy] weblogic.Deployer invoked with options:  -verbose -noexit -name SOAP_JAXWS_AttachmentEar -targets AdminServer -adminurl t3://loc
alhost:7001 -user weblogic -undeploy
 [wldeploy] <Jun 12, 2011 4:47:27 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating undeploy operation for application, SOAP_JAX
WS_AttachmentEar [archive: null], to AdminServer .>
 [wldeploy] Task 8 initiated: [Deployer:149026]remove application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Task 8 completed: [Deployer:149026]remove application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Target state: undeploy completed on Server AdminServer
 [wldeploy]

clean:
   [delete] Deleting directory C:\SOAP_Attachment\output

build-service:
    [javac] Compiling 1 source file to C:\SOAP_Attachment\src
     [jwsc] JWS: processing module /AttachmentService_Impl
     [jwsc] Parsing source files
     [jwsc] Parsing source files
     [jwsc] 1 JWS files being processed for module /AttachmentService_Impl
     [jwsc] JWS: C:\SOAP_Attachment\src\AttachmentService_Impl.java Validated.
     [jwsc] Processing 1 JAX-WS web services...
     [jwsc] warning: Annotation types without processors: [javax.xml.bind.annotation.XmlRootElement, javax.xml.bind.annotation.XmlAccessorTy
pe, javax.xml.bind.annotation.XmlType, javax.xml.bind.annotation.XmlElement]
     [jwsc] 1 warning
     [jwsc] Compiling 3 source files to C:\DOCUME~1\DELLUS~1\LOCALS~1\Temp\_6vmlr8
     [jwsc] Building jar: C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar\AttachmentService_Impl.war
     [jwsc] Created JWS deployment outputFile: C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar\AttachmentService_Impl.war
     [jwsc] [EarFile] Application File : C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar\META-INF\application.xml
[AntUtil.deleteDir] Deleting directory C:\DOCUME~1\DELLUS~1\LOCALS~1\Temp\_6vmlr8

deploy-attach:
 [wldeploy] weblogic.Deployer -verbose -noexit -name SOAP_JAXWS_AttachmentEar -source C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar -ta
rgets AdminServer -adminurl t3://localhost:7001 -user weblogic -password ******** -deploy
 [wldeploy] weblogic.Deployer invoked with options:  -verbose -noexit -name SOAP_JAXWS_AttachmentEar -source C:\SOAP_Attachment\output\SOAP_
JAXWS_AttachmentEar -targets AdminServer -adminurl t3://localhost:7001 -user weblogic -deploy
 [wldeploy] <Jun 12, 2011 4:47:33 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, SOAP_JAXWS
_AttachmentEar [archive: C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar], to AdminServer .>
 [wldeploy] Task 9 initiated: [Deployer:149026]deploy application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Task 9 completed: [Deployer:149026]deploy application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Target state: deploy completed on Server AdminServer
 [wldeploy]
 [wldeploy] Target Assignments:
 [wldeploy] + SOAP_JAXWS_AttachmentEar  AdminServer

client:
[clientgen]
[clientgen] *********** jax-ws clientgen attribute settings ***************
[clientgen]
[clientgen] wsdlURI: http://localhost:7001/AttachmentService_Impl/AttachmentService_ImplService?WSDL
[clientgen] packageName : client
[clientgen] destDir : C:\SOAP_Attachment\output\clientclasses
[clientgen]
[clientgen] *********** jax-ws clientgen attribute settings end ***************
[clientgen] Consider using <depends>/<produces> so that wsimport won't do unnecessary compilation
[clientgen] parsing WSDL...

[clientgen] generating code...

[clientgen] compiling code...

[clientgen] Note: C:\SOAP_Attachment\output\clientclasses\client\AttachmentServiceImplService.java uses unchecked or unsafe operations.
[clientgen] Note: Recompile with -Xlint:unchecked for details.

run:
    [javac] Compiling 1 source file to C:\SOAP_Attachment\output\clientclasses

     [java]     start client

     [java]     Calling service to send a file from a customer...

     [java]      Result From Service:
     [java]      File Attachment Completed Succesfully Cant_Stop_Dancing.mp3     at Sun Jun 12 16:47:40 IST 2011

     [java]     end client

all:

BUILD SUCCESSFUL
Total time: 14 seconds
C:\SOAP_Attachment>

Step7). NOTE: as soon as you will run the above sample …you will find that the Attachment is created inside the $DOMAIN_HOME of your WebLogic Server. The Path of Attachement creation on the server side can be defined in the WebService program in the following line:

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(filename));
Example:
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(“/home/userone/”+filename));
OR
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(“C:/Attachements/”+filename));
.
.
Thanks
Jay SenSharma