Thứ Ba, 29 tháng 9, 2020

Zip file Java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipFiles {

	public static void main(String[] args) throws Exception {
    	// zip single file
		String fileContent = "Test zip files";
		String fileName = "Test.txt";
        String zipFileName = "toan.zip"
		zipSingleFile(zipFileName, fileName, fileContent);
        
        // zip many files
        String fileContent1 = "Content file 1";
		String fileContent2 = "Content file 2";
		String zipFileName2 = "manyZip.zip";
		zipFiles(zipFileName2, fileContent1, fileContent2);

	}
    
	public static void zipSingleFile(String zipFileName, String fileName, String fileContent) {
		File file = new File(zipFileName);
		try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file))) {
			ZipEntry zipEntry = new ZipEntry(fileName);
			zos.putNextEntry(zipEntry);

			byte[] data = fileContent.getBytes();
			zos.write(data, 0, data.length);
			zos.closeEntry();

		} catch (IOException e) {
			System.out.println("error while zipping file " + zipFileName);
		}
	}

	public static void zipFiles(String zipFileName, String fileContent1, String fileContent2) {
		File file = new File(zipFileName);
		try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file), StandardCharsets.UTF_8)) {
			zipFileEntry("file1.txt", fileContent1, zos);
			zipFileEntry("file2.txt", fileContent2, zos);
		} catch (IOException e) {
			System.out.println("error while zipping file " + zipFileName);
		}
	}

	public static void zipFileEntry(String fileName, String fileContent, ZipOutputStream zos)
			throws IOException {
		ZipEntry zipEntry = new ZipEntry(fileName);
		zos.putNextEntry(zipEntry);

		byte[] data = fileContent.getBytes("UTF-8");
		zos.write(data, 0, data.length);
		zos.closeEntry();
	}

}


Encode base 64

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

public class TestUtils {

	public static String encoderBase64(String filePath) {
        String base64File = "";
        File file = new File(filePath);
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte fileData[] = new byte[(int) file.length()];
            imageInFile.read(fileData);
            base64File = Base64.encodeBase64String(fileData);
        } catch (FileNotFoundException e) {
            System.out.println("File not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while reading the file " + ioe);
        }
        return base64File;
    }

}

Jar : commons-codec-1.6.jar

Phát sinh code Java từ WSDL

Ta có thể dùng lệnh wsimport để tạo ra mã nguồn Java cho dịch vụ web Soap từ một tập tin wsdl như sau :

$ wsimport -keep ToanService.wsdl

Nếu tập tin wsdl phụ thuộc vào một vài tập tin xml(xsd), ta có thể gọi thêm các tập tin ấy khi phát sinh code như sau :
$ wsimport -extension -keep -b Toan1_binding.xml -b Toan2_binding.xml ToanService.wsdl

Chương trình wsimport nằm trong thư mục bin của Java cài đặt trên máy, chẳng hạn :
C:\Java\jdk1.7.0_80\bin\wsimport.exe

Kiểm tra phiên phản của JAX-WS :
$ "C:\Java\jdk1.7.0_80\bin\wsimport.exe" -version

Thông thường với wsimport là ta đủ để phát sinh mã nguồn Java từ một WSDL, tuy nhiên phiên bản mới của wsimport không còn hỗ trợ một vài cấu trúc quá cũ, chẳng hạn như rpc/encoded :
parsing WSDL...
[ERROR] "Use of SOAP Encoding is not supported.
SOAP extension element on line 44 in file ToanService.wsdl has use="encoded" "

Dòng bị báo lỗi có định nghĩa như sau :
<wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ToanService/" use="encoded"/>

Không còn dịch vụ web hiện đại nào còn dùng đến cấu trúc rpc/encoded cổ lỗ này nữa, giờ đa phần sử dụng document/literal

Tuy nhiên Apache Axis v1 vẫn có thể giúp ta phát sinh code Java cho các dịch vụ web dùng cấu trúc rpc/encoded này nếu cần. Ta phải tải về axis-1.4.jar và các jars mà nó phụ thuộc để phát sinh code Java bằng lệnh sau :

$ java -cp axis-1.4.jar;commons-logging-1.1.jar;jaxrpc-api-1.1.jar;commons-discovery-0.2.jar;saaj-1.1.jar;wsdl4j-1.4.jar;activation-1.1.jar;mail-1.4.jar org.apache.axis.wsdl.WSDL2Java ToanService.wsdl


Khi dùng Apache Axis, có thể gọi client web như sau :
ToanServiceServiceLocator service = new ToanServiceServiceLocator();
ToanServiceSoapBindingStub soapClient = new ToanServiceSoapBindingStub(new URL(service.getToanServiceAddress()), service);
soapClient.getVersion();

Ta có thể xem soap request, response và lỗi trả về nếu có như sau :
String soapRequest = _call.getMessageContext().getRequestMessage().getSOAPPartAsString();
String soapResponse = _call.getMessageContext().getResponseMessage().getSOAPPartAsString();
if (_call.getResponseMessage().getSOAPPart().getEnvelope().getBody().getFault() != null) {
responseFault = _call.getResponseMessage().getSOAPPart().getEnvelope().getBody().getFault().getFaultCode();
}