GP Coder

Trang chia sẻ kiến thức lập trình Java

  • Java Core
    • Basic Java
    • OOP
    • Exception Handling
    • Multi-Thread
    • Java I/O
    • Networking
    • Reflection
    • Collection
    • Java 8
  • Design pattern
    • Creational Pattern
    • Structuaral Pattern
    • Behavior Pattern
  • Web Service
    • SOAP
    • REST
  • JPA
  • Java library
    • Report
    • Json
    • Unit Test
  • Message Queue
    • ActiveMQ
    • RabbitMQ
  • All
Trang chủ Java Webservice SOAP SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS

SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS

Đăng vào 06/06/2019 . Được đăng bởi GP Coder . 3418 Lượt xem . Toàn màn hình

Trong bài này chúng ta sẽ cùng tìm hiểu cách sử dụng Message Transmission Optimization Mechanism (MTOM) và XML-Binary Optimized Packaging (XOP) để upload file lên Server và download file từ Server về Client.

Nội dung

  • 1 Tạo WebService Server
  • 2 Tạo Client truy cập WS

Tạo WebService Server

DocumentService.java


package com.gpcoder.ws.document;

import javax.activation.DataHandler;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style = Style.RPC)
public interface DocumentService {

	@WebMethod
	DataHandler download(String name);

	@WebMethod
	String upload(DataHandler data);
}

DocumentServiceImpl.java


package com.gpcoder.ws.document;

import javax.activation.DataHandler;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;

@MTOM
@WebService(endpointInterface = "com.gpcoder.ws.document.DocumentService")
public class DocumentServiceImpl implements DocumentService {

	public static final String UPLOADED_FOLDER = "data/upload/";

	@Override
	public DataHandler download(String name) {
		return DocumentUtils.getFileAsDataHandler("data/" + name);
	}

	@Override
	public String upload(DataHandler dataHandler) {
		if (dataHandler != null) {
			String fileName = UPLOADED_FOLDER + "upload-" + System.currentTimeMillis() + ".docx";
			DocumentUtils.storeDataToFile(dataHandler, fileName);
			return "Uploaded Successful with name " + fileName;
		}
		throw new WebServiceException("Upload Failed!");
	}
}

Trong phần cài đặt trên, tôi sử dụng:
Sử dụng @MTOM : để enable sử dụng MTOM cho Web service.
DataHandler để có thể nhận được nhiều loại source, format từ Client gửi lên và tối ưu hơn về performance.

Lớp tiện ích hỗ trợ đọc/ ghi file từ DataHandler:
DocumentUtils.java


package com.gpcoder.ws.document;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class DocumentUtils {

	private DocumentUtils() {
		super();
	}

	public static void storeDataToFile(DataHandler dataHandler, String fileName) {
		try {
			File file = new File(fileName);
			OutputStream os = new FileOutputStream(file);
			dataHandler.writeTo(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static DataHandler getFileAsDataHandler(String fileName) {
		FileDataSource dataSource = new FileDataSource(fileName);
		return new DataHandler(dataSource);
	}
}

DocumentPublisher.java


package com.gpcoder.ws.document;

import javax.xml.ws.Endpoint;

public class DocumentPublisher {

	public static final String WS_URL = "http://localhost:8080/ws/document";

	public static void main(String[] args) {
		Endpoint.publish(WS_URL, new DocumentServiceImpl());
		System.out.println("Server is published!");
	}
}

Chạy chương trình DocumentPublisher.

Tạo Client truy cập WS

Chúng ta cần chuẩn bị một số resource để hỗ trợ upload/ download file theo cấu trúc thư mục sau:

Ứng dụng Client, truy xuất WS upload file

DocumentClientDownload.java


package com.gpcoder.ws.document;

import java.net.URL;

import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;

public class DocumentClientUpload {

	public static void main(String[] args) throws Exception {

		// Create URL of .wsdl file
		URL url = new URL(DocumentPublisher.WS_URL + "?wsdl");

		// Create a QName using targetNamespace and name
		QName qname = new QName("http://document.ws.gpcoder.com/", "DocumentServiceImplService");

		// Creates a Service instance with the specified WSDL document location and
		// service qualified name
		Service service = Service.create(url, qname);

		// We need to pass interface and model beans to client
		DocumentService imageServer = service.getPort(DocumentService.class);

		// Enable MTOM in client
		BindingProvider bp = (BindingProvider) imageServer;
		SOAPBinding binding = (SOAPBinding) bp.getBinding();
		binding.setMTOMEnabled(true);

		// Prepare document for upload
		DataHandler dataHandler = DocumentUtils.getFileAsDataHandler("data/test.docx");

		// Perform upload document
		String status = imageServer.upload(dataHandler);
		System.out.println("upload() : " + status);
	}
}

Chạy chương trình trên, chúng ta có kết quả như sau:


upload() : Uploaded Successful with name data/upload/upload-1559229879163.docx

Ứng dụng Client, truy xuất WS download file


package com.gpcoder.ws.document;

import java.net.URL;

import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class DocumentClientDownload {

	public static final String DOWNLOADED_FOLDER = "data/download/";

	public static void main(String[] args) throws Exception {

		// Create URL of .wsdl file
		URL url = new URL(DocumentPublisher.WS_URL + "?wsdl");

		// Create a QName using targetNamespace and name
		QName qname = new QName("http://document.ws.gpcoder.com/", "DocumentServiceImplService");

		// Creates a Service instance with the specified WSDL document location and
		// service qualified name
		Service service = Service.create(url, qname);

		// We need to pass interface and model beans to client
		DocumentService imageServer = service.getPort(DocumentService.class);

		// Perform download document
		DataHandler dataHandler = imageServer.download("test.docx");

		// Save the result to file
		String fileName = DOWNLOADED_FOLDER + "dowload-" + System.currentTimeMillis() + ".docx";
		DocumentUtils.storeDataToFile(dataHandler, fileName);
		System.out.println("download() : Downloaded Successful with name " + fileName);
	}
}

Chạy chương trình trên, chúng ta có kết quả như sau:


download() : Downloaded Successful with name data/download/dowload-1559229893344.docx

5.0
04
Nếu bạn thấy hay thì hãy chia sẻ bài viết cho mọi người nhé! Và Donate tác giả

Shares

Chuyên mục: Java Webservice, SOAP Được gắn thẻ: SOAP, Webservice

SOAP Web service: Authentication trong JAX-WS
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman

Có thể bạn muốn xem:

  • REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x (21/06/2019)
  • Làm thế nào để Test Jersey Rest API với JUnit? (22/08/2019)
  • Java Web Services – JAX-WS – SOAP (27/05/2019)
  • Tìm hiểu về xác thực và phân quyền trong ứng dụng (01/07/2019)
  • SOAP Web service: Authentication trong JAX-WS (03/06/2019)

Bình luận

bình luận

Tìm kiếm

Bài viết mới

  • Clean code 13/01/2024
  • Giới thiệu CloudAMQP – Một RabbitMQ server trên Cloud 02/10/2020
  • Kết nối RabbitMQ sử dụng Web STOMP Plugin 19/06/2020
  • Sử dụng publisher confirm trong RabbitMQ 16/06/2020
  • Sử dụng Dead Letter Exchange trong RabbitMQ 13/06/2020

Xem nhiều

  • Hướng dẫn Java Design Pattern – Factory Method (98066 lượt xem)
  • Hướng dẫn Java Design Pattern – Singleton (97706 lượt xem)
  • Giới thiệu Design Patterns (87777 lượt xem)
  • Lập trình đa luồng trong Java (Java Multi-threading) (86446 lượt xem)
  • Giới thiệu về Stream API trong Java 8 (83842 lượt xem)

Nội dung bài viết

  • 1 Tạo WebService Server
  • 2 Tạo Client truy cập WS

Lưu trữ

Thẻ đánh dấu

Annotation Authentication Basic Java Behavior Pattern Collection Creational Design Pattern Cấu trúc điều khiển Database Dependency Injection Design pattern Eclipse Exception Executor Service Google Guice Gson Hibernate How to Interceptor IO Jackson Java 8 Java Core JDBC JDK Jersey JMS JPA json JUnit JWT Message Queue Mockito Multithreading OOP PowerMockito RabbitMQ Reflection Report REST SOAP Structuaral Pattern Swagger Thread Pool Unit Test Webservice

Liên kết

  • Clean Code
  • JavaTpoint
  • Refactoring Guru
  • Source Making
  • TutorialsPoint
  • W3Schools Online Web Tutorials

Giới thiệu

GP Coder là trang web cá nhân, được thành lập với mục đích lưu trữ, chia sẽ kiến thức đã học và làm việc của tôi. Các bài viết trên trang này chủ yếu về ngôn ngữ Java và các công nghệ có liên quan đến Java như: Spring, JSF, Web Services, Unit Test, Hibernate, SQL, ...
Hi vọng góp được chút ít công sức cho sự phát triển cộng đồng Coder Việt.

Donate tác giả

Tìm kiếm các bài viết của GP Coder với Google Search

Liên hệ

Các bạn có thể liên hệ với tôi thông qua:
  • Trang liên hệ
  • Linkedin: gpcoder
  • Email: contact@gpcoder.com
  • Skype: ptgiang56it

Follow me

Copyright 2025 © GP Coder · All Rights Reserved · Giới thiệu · Chính sách · Điều khoản · Liên hệ ·

Share

Blogger
Delicious
Digg
Email
Facebook
Facebook messenger
Flipboard
Google
Hacker News
Line
LinkedIn
Mastodon
Mix
Odnoklassniki
PDF
Pinterest
Pocket
Print
Reddit
Renren
Short link
SMS
Skype
Telegram
Tumblr
Twitter
VKontakte
wechat
Weibo
WhatsApp
X
Xing
Yahoo! Mail

Copy short link

Copy link