Skip to content Skip to sidebar Skip to footer

Ionic File Upload With Soap Web Service Java

In this Java spider web services tutorial, we are going to discuss how MTOM (Message Transmission Optimization Mechanism) can exist used to optimize binary data transfer through web services with JAX-WS (Coffee API for XML-based Web Services). We will get from groundwork of MTOM and its usages to development of a simple spider web services application that can transfer large binary data (upload and download files) in the optimized style.

1. Why MTOM?

By default, binary data is converted to base64Binary or hexBinary XML data type within a SOAP envelope, pregnant that the raw bytes are encoded every bit a Cord using base64 technique. For example, the following XML snippet is content of such a Soap message:

<?xml version="1.0" ?> <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> 	<South:Body> 		<ns2:upload xmlns:ns2="http://server.mtom.ws.codejava.net/"> 			<arg0>binary.png</arg0> 			<arg1>iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoL...5CYII=</arg1> 		</ns2:upload> 	</South:Torso> </S:Envelope>

Look at the text inside the element <arg1> - it is the encoded form of the binary data in base64 format. Basically, the base64 encoding technique bloats the original data by a factor of ane.33x (with UTF-viii encoding) or 2.66x (with UTF-16), so it becomes very inefficient when dealing with a large amount of information. To overcome this drawback, MTOM is defined every bit a specification for optimizing the transmission of this kind of information type in Soap messages, and XOP (XML-binary Optimized Packaging) is the concrete implementation. The following example is content of a HTTP POST request which is generated past MTOM/XOP:

Mail service /codejava/fileService HTTP/ane.one Have: text/xml, multipart/related Content-Type: multipart/related;start="<rootpart*[email protected]>"; 	type="application/xop+xml";boundary="uuid:8b39dc38-7f35-437f-920f-b99b6b2c9888";start-info="text/xml" SOAPAction: "http://server.mtom.ws.codejava.net/FileTransfererImpl/uploadRequest" User-Agent: JAX-WS RI 2.ii.4-b01 Host: localhost:8787 Connection: go along-live Content-Length: 2154  --uuid:8b39dc38-7f35-437f-920f-b99b6b2c9888 Content-Id: <rootpart*[e-mail protected]> Content-Type: awarding/xop+xml;charset=utf-eight;type="text/xml" Content-Transfer-Encoding: binary  <?xml version="1.0" ?> <Southward:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> 	<S:Body> 		<ns2:upload xmlns:ns2="http://server.mtom.ws.codejava.net/"> 			<arg0>binary.png</arg0> 			<arg1> 				<xop:Include xmlns:xop="http://world wide web.w3.org/2004/08/xop/include"  					href="cid:[electronic mail protected]"> 				</xop:Include> 			</arg1> 		</ns2:upload> 	</South:Trunk> </Southward:Envelope>  --uuid:8b39dc38-7f35-437f-920f-b99b6b2c9888 Content-Id: <[email protected]> Content-Type: application/octet-stream Content-Transfer-Encoding: binary  [binary octet stream]

Here, the asking's content type becomes multipart/related in which the Soap message and the binary data are separated as individual parts of a MIME bulletin. The Soap message itself doesn't contain the binary information. Instead, it has a reference to the part that contains the actual binary information:

<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include"  	href="cid:[e-mail protected]"> </xop:Include>

And the binary information is attached to the request equally a MIME attachment which is outside the SOAP message.

2. Enabling MTOM in JAX-WS

In JAX-WS, it's easy to enable MTOM for a web service endpoint by using either the @MTOM or @BindingType annotations. At the client side, MTOM can be enabled either by passing a new example of MTOMFeature course when getting a reference to the spider web service endpoint (port), or by calling the SOAPBinding.setMTOMEnabled(true) method on the binding provider object. Here are the usages and examples in details.

Enabling MTOM for the web service endpoint

The following example illustrates a web service endpoint is annotated with the @MTOM annotation:

import javax.jws.WebMethod; import javax.jws.WebService; import javax.xml.ws.soap.MTOM;   @WebService @MTOM public course MyWebService { 	 	@WebMethod 	public void upload(byte[] information) { 		// implementation details...	 	} }

That enables MTOM support for the MyWebService endpoint. The @MTOM annotation has two optional parameters:

  • enabled : specifies whether MTOM characteristic is enabled (true) or disabled (faux).
  • threshold : specifies the size (in bytes) above which the binary data will be sent as attachment. This would be useful to enable MTOM only for data which is larger than a specified corporeality.

This example shows MTOM is used but disabled:

@WebService @MTOM(enabled = imitation) public course MyWebService { }

This instance shows MTOM is enabled just for binary data which is larger than 10KB (10240 bytes):

@WebService @MTOM(threshold = 10240) public class MyWebService { }

An alternative way is using the @BindingType notation with an appropriate value for the Soap version used. For instance:

  • Enabling MTOM with SOAP version 1.one:
    import javax.xml.ws.BindingType; import javax.xml.ws.soap.SOAPBinding;  @WebService @BindingType(value = SOAPBinding.SOAP11HTTP_MTOM_BINDING) public class MyWebService { }
  • Enabling MTOM with SOAP version 1.2:
    import javax.xml.ws.BindingType; import javax.xml.ws.soap.SOAPBinding;  @WebService @BindingType(value = SOAPBinding.SOAP12HTTP_MTOM_BINDING) public grade MyWebService { }

From the above examples, nosotros can come across that using the @MTOM notation is preferred equally its succinct and flexibility (enabled/disabled and threshold).

Enabling MTOM for the client

The following case shows how to enable MTOM at the client by passing a new instance of the MTOMFeature class when getting a proxy reference the spider web service endpoint:

import javax.xml.ws.soap.MTOMFeature;  MyWebServiceService service = new MyWebServiceService(); MyWebService port = service.getMyWebServicePort(new MTOMFeature());

Suppose that the MyWebServiceService and MyWebService classes are generated by the wsimport tool. And similar to the @MTOM annotation, nosotros tin also specify the enabled and threshold parameters in the MTOMFeature class' constructor like this:

boolean enabled = true; int threshold = 10240; MyWebService port = service.getMyWebServicePort(new MTOMFeature(enabled, threshold));

And here'due south an alternative style, calling the SOAPBinding.setMTOMEnabled(truthful) method:

MyWebServiceService service = new MyWebServiceService(); MyWebService port = service.getMyWebServicePort();  BindingProvider provider = (BindingProvider) port; SOAPBinding soapBinding = (SOAPBinding) provider.getBinding(); soapBinding.setMTOMEnabled(truthful);

So far we have understood the advantages of MTOM and how to apply it for a web service end point and client. Now, let's go through a complete sample application.

3. Code Java Web Service Endpoint

The following class is for a spider web service endpoint implementation that offers 2 operations for binary information transfer - files upload and download:

package net.codejava.ws.mtom.server;  import coffee.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import coffee.io.IOException;  import javax.jws.WebMethod; import javax.jws.WebService; import javax.xml.ws.WebServiceException; import javax.xml.ws.soap.MTOM;   /**  * A web service endpoint implementation that demonstrates the usage of  * MTOM (Message Transmission Optimization Machinery).  * @writer www.codejava.internet  *  */ @WebService @MTOM(enabled = true, threshold = 10240) public class FileTransferer { 	@WebMethod 	public void upload(String fileName, byte[] imageBytes) { 		 		Cord filePath = "east:/Examination/Server/Upload/" + fileName; 		 		try { 			FileOutputStream fos = new FileOutputStream(filePath); 			BufferedOutputStream outputStream = new BufferedOutputStream(fos); 			outputStream.write(imageBytes); 			outputStream.close(); 			 			Arrangement.out.println("Received file: " + filePath); 			 		} catch (IOException ex) { 			Arrangement.err.println(ex); 			throw new WebServiceException(ex); 		} 	} 	 	@WebMethod 	public byte[] download(String fileName) { 		String filePath = "due east:/Test/Server/Download/" + fileName; 		System.out.println("Sending file: " + filePath); 		 		endeavour { 			File file = new File(filePath); 			FileInputStream fis = new FileInputStream(file); 			BufferedInputStream inputStream = new BufferedInputStream(fis); 			byte[] fileBytes = new byte[(int) file.length()]; 			inputStream.read(fileBytes); 			inputStream.close(); 			 			return fileBytes; 		} catch (IOException ex) { 			System.err.println(ex); 			throw new WebServiceException(ex); 		}		 	} }

As nosotros can see, the @MTOM annotation is used to enable binary transfer optimization with the threshold of 10KB.

NOTE: You lot should prepare a file to be sent to the client and correct the file path according to your environment in the download() method.

4. Coding Java Server Program for Web Services

Write a simple server program (console awarding) that publishes the web services with the following code:

package net.codejava.ws.mtom.server;  import javax.xml.ws.Endpoint;  /**  * A uncomplicated web service server.  * @author www.codejava.net  *  */ public class WebServiceServer {  	public static void main(Cord[] args) { 		String bindingURI = "http://localhost:9898/codejava/fileService"; 		FileTransferer service = new FileTransferer(); 		Endpoint.publish(bindingURI, service); 		System.out.println("Server started at: " + bindingURI); 	} }

Run this program to start the server. We should encounter the post-obit output in the console:

Server started at: http://localhost:9898/codejava/fileService

v. Code Coffee Customer Program for Web Services

Utilize the wsimport tool to generate client lawmaking for the to a higher place web service endpoint (come across instructions included in the attached projection), and then write lawmaking for the application client program as follows:

package net.codejava.ws.mtom.client;  import java.io.BufferedInputStream; import coffee.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;  import javax.xml.ws.soap.MTOMFeature;  /**  * A client program that demonstrates how to utilise MTOM to optimize binary information  * transfer with JAX-WS web services.  * @author www.codejava.net  *  */ public class WebServiceAppClient {  	public static void master(Cord[] args) { 		// connects to the web service 		FileTransfererService service = new FileTransfererService(); 		FileTransferer port = service.getFileTransfererPort(new MTOMFeature(10240)); 		 		String fileName = "binary.png"; 		String filePath = "east:/Test/Client/Upload/" + fileName; 		File file = new File(filePath); 		 		// uploads a file 		attempt { 			FileInputStream fis = new FileInputStream(file); 			BufferedInputStream inputStream = new BufferedInputStream(fis); 			byte[] imageBytes = new byte[(int) file.length()]; 			inputStream.read(imageBytes); 			 			port.upload(file.getName(), imageBytes);  			inputStream.close(); 			System.out.println("File uploaded: " + filePath); 		} catch (IOException ex) { 			System.err.println(ex); 		}		 		 		// downloads another file 		fileName = "camera.png"; 		filePath = "Due east:/Examination/Client/Download/" + fileName; 		byte[] fileBytes = port.download(fileName); 		 		try { 			FileOutputStream fos = new FileOutputStream(filePath); 			BufferedOutputStream outputStream = new BufferedOutputStream(fos); 			outputStream.write(fileBytes); 			outputStream.close(); 			 			System.out.println("File downloaded: " + filePath); 		} grab (IOException ex) { 			System.err.println(ex); 		} 	} }

Every bit nosotros tin see, MTOM is enabled by passing an instance of the MTOMFeature grade with an integer indicates a threshold value. This program uploads a file past sending a chunk of bytes to the server, and downloads a file past receiving an assortment of bytes from the server.

NOTE: You should prepare a file to exist uploaded to the server and correct the file path according to your surround.

6. Test binary data transfer via web services and inspect SOAP Messages

Now, execute the awarding client program to test out the web service. Nosotros should see the following output at the client:

File uploaded: e:/Test/Client/Upload/binary.png File downloaded: Eastward:/Test/Client/Download/photographic camera.png

And output at the server:

Server started at: http://localhost:9898/codejava/fileService Received file: due east:/Exam/Server/Upload/binary.png Sending file: e:/Examination/Server/Download/camera.png

We inspect the Soap letters in details past using a monitoring tool such as TCP/IP Monitor in Eclipse IDE. Here's the summary (WSDL asking/response is omitted):

  • For upload operation:
    • Client Asking:
      Postal service /codejava/fileService HTTP/1.1 Accept: text/xml, multipart/related Content-Type: multipart/related;kickoff="<rootpart*[email protected]>"; 		type="application/xop+xml"; 		boundary="uuid:0d441e76-7247-40de-a6e5-d49c9bf4a172";outset-info="text/xml" SOAPAction: "http://server.mtom.ws.codejava.internet/FileTransferer/uploadRequest" User-Amanuensis: JAX-WS RI two.2.4-b01 Host: localhost:9898 Connection: keep-alive Content-Length: 2133  --uuid:0d441e76-7247-40de-a6e5-d49c9bf4a172 Content-Id: <rootpart*[email protected]> Content-Type: awarding/xop+xml;charset=utf-viii;type="text/xml" Content-Transfer-Encoding: binary  <?xml version="1.0" ?> <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> 	<Southward:Torso> 		<ns2:upload xmlns:ns2="http://server.mtom.ws.codejava.internet/"> 			<arg0>binary.png</arg0> 			<arg1> 				<Include xmlns="http://www.w3.org/2004/08/xop/include"  					href="cid:[email protected]"/> 			</arg1> 		</ns2:upload> 	</S:Body> </S:Envelope>  --uuid:0d441e76-7247-40de-a6e5-d49c9bf4a172 Content-Id: <[email protected]> Content-Type: application/octet-stream Content-Transfer-Encoding: binary  [binary octet stream]
    • Server Response:
      HTTP/one.1 200 OK Transfer-encoding: chunked Content-type: multipart/related;start="<rootpart*[electronic mail protected]>"; 	type="awarding/xop+xml"; 	boundary="uuid:e8611ccc-2442-4d56-8b17-d15eb6138c24";first-info="text/xml" Date: Fri, 29 Nov 2013 09:57:xiii GMT  --uuid:e8611ccc-2442-4d56-8b17-d15eb6138c24 Content-Id: <rootpart*[email protected]> Content-Type: awarding/xop+xml;charset=utf-eight;blazon="text/xml" Content-Transfer-Encoding: binary  <?xml version="1.0" ?> <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> 	<Southward:Body> 		<ns2:uploadResponse xmlns:ns2="http://server.mtom.ws.codejava.net/"></ns2:uploadResponse> 	</S:Body> </S:Envelope>  --uuid:e8611ccc-2442-4d56-8b17-d15eb6138c24--
  • For download operation:
    • Client Asking:
      Mail service /codejava/fileService HTTP/1.i Take: text/xml, multipart/related Content-Blazon: multipart/related;first="<rootpart*[email protected]>"; 	type="application/xop+xml"; 	boundary="uuid:95d74f1f-5c21-474b-9481-400785c18ae5";offset-info="text/xml" SOAPAction: "http://server.mtom.ws.codejava.cyberspace/FileTransferer/downloadRequest" User-Agent: JAX-WS RI ii.2.4-b01 Host: localhost:9898 Connectedness: keep-alive Content-Length: 493  --uuid:95d74f1f-5c21-474b-9481-400785c18ae5 Content-Id: <rootpart*[email protected]> Content-Type: application/xop+xml;charset=utf-8;type="text/xml" Content-Transfer-Encoding: binary  <?xml version="i.0" ?> <South:Envelope xmlns:S="http://schemas.xmlsoap.org/lather/envelope/"> 	<Due south:Trunk> 		<ns2:download xmlns:ns2="http://server.mtom.ws.codejava.net/"> 			<arg0>camera.png</arg0> 		</ns2:download> 	</Southward:Body> </S:Envelope>  --uuid:95d74f1f-5c21-474b-9481-400785c18ae5--
    • Server Response:
      HTTP/1.1 200 OK Transfer-encoding: chunked Content-blazon: multipart/related;start="<rootpart*[e-mail protected]>"; 	type="awarding/xop+xml"; 	purlieus="uuid:b581cf1e-507a-4b6a-b1c6-0bf16e1278c6";beginning-info="text/xml" Date: Fri, 29 Nov 2013 x:thirty:12 GMT  --uuid:b581cf1e-507a-4b6a-b1c6-0bf16e1278c6 Content-Id: <rootpart*[email protected]> Content-Type: application/xop+xml;charset=utf-8;type="text/xml" Content-Transfer-Encoding: binary  <?xml version="1.0" ?> <Due south:Envelope xmlns:Due south="http://schemas.xmlsoap.org/soap/envelope/"> 	<Southward:Trunk> 		<ns2:downloadResponse xmlns:ns2="http://server.mtom.ws.codejava.net/"> 			<render> 				<Include xmlns="http://world wide web.w3.org/2004/08/xop/include"  					href="cid:[electronic mail protected]"/> 			</return> 		</ns2:downloadResponse> 	</S:Torso> </S:Envelope>   --uuid:b581cf1e-507a-4b6a-b1c6-0bf16e1278c6 Content-Id: <[email protected]> Content-Type: application/octet-stream Content-Transfer-Encoding: binary  [binary octet stream]

And then far we accept finished discussing what MTOM is and how it is applied in JAX-WS in terms of optimization of binary data transfer via web services.

References:

  • MTOM Note Type
  • MTOMFeature class Javadoc
  • Enabling MTOM for JAX-WS Web services
  • Optimizing Binary Data Transmission Using MTOM/XOP
  • Lather Message Manual Optimization Mechanism
  • XML-binary Optimized Packaging

Other Java Web Services Tutorial:

  • Java Client Server Web Services (JAX-WS) Tutorial
  • Java Web Services Tutorial using Apache Axis2, Ant and Tomcat
  • Coffee Spider web Services Binary Data Transfer Example (base64 encoding)
  • How to monitor Lather Messages using TCP/IP Monitor in Eclipse
  • Java RESTful Spider web Services Tutorial for Beginner with Jersey and Tomcat
  • How to lawmaking and deploy Java XML Web Services (JAX-WS) on Tomcat
  • Java Crud RESTful Web Services Examples with Jersey and Tomcat

Well-nigh the Writer:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java ane.four and has been falling in love with Java since then. Make friend with him on Facebook and sentry his Java videos you YouTube.

Add comment

robinsonmameniecs.blogspot.com

Source: https://www.codejava.net/java-ee/web-services/using-mtom-to-optimize-binary-data-transfer-with-jax-ws-web-services

Postar um comentário for "Ionic File Upload With Soap Web Service Java"