1. 程式人生 > >cxf web service 程式碼片段,儲存遠端上傳的檔案到資料庫

cxf web service 程式碼片段,儲存遠端上傳的檔案到資料庫

<pre name="code" class="java">/**
 * 
 */
package com.paxsz.tms.webservice.deploy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.paxsz.common.util.SpringContextUtil;
import com.paxsz.tms.deploy.model.PubFileData;
import com.paxsz.tms.deploy.model.PubFileInfo;
import com.paxsz.tms.deploy.model.PubPackage;
import com.paxsz.tms.deploy.model.PubPackageDeploy;
import com.paxsz.tms.deploy.model.PubPackageFile;
import com.paxsz.tms.deploy.service.PubFileDataService;
import com.paxsz.tms.deploy.service.PubFileInfoService;
import com.paxsz.tms.deploy.service.PubPackageDeployService;
import com.paxsz.tms.deploy.service.PubPackageFileService;
import com.paxsz.tms.deploy.service.PubPackageService;
import com.paxsz.tms.deploy.web.form.QueryPackageForm;
import com.paxsz.tms.webservice.utils.BaseResponse;
import com.paxsz.tms.webservice.utils.ConstantsUtil;
import com.paxsz.tms.webservice.utils.FileInfo;
import com.paxsz.tms.webservice.utils.Page;

/**
 * @author Dai.L
 * @date 2014-10-23
 */
@Service("deployWebService")
public class DeployWebServiceImpl implements DeployWebService {
	
	private static final String MANIFEST = "manifest.xml";

	@Autowired
	@Qualifier("pubPackageService")
	private PubPackageService pubPackageService;

	@Autowired
	@Qualifier("pubPackageFileService")
	private PubPackageFileService pubPackageFileService;

	@Autowired
	@Qualifier("pubPackageDeployService")
	private PubPackageDeployService pubPackageDeployService;

	@Autowired
	@Qualifier("pubFileDataService")
	private PubFileDataService pubFileDataService;
	
	@Autowired
	@Qualifier("pubFileInfoService")
	private PubFileInfoService pubFileInfoService;

	@Override
	public BaseResponse addPackageWS(byte[] inputByte, String name, String type) {
		BaseResponse response = new BaseResponse();
		if ((!StringUtils.equalsIgnoreCase("zip", type) && !StringUtils.equalsIgnoreCase("aip", type))
				|| StringUtils.isEmpty(name) || null == inputByte || inputByte.length == 0) {
			response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
			response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
			return response;
		}
		// get Zip file content
		Map<String, byte[]> resultMap = null;
		try {
			resultMap = getPackageFiles(inputByte);
		} catch (Exception e1) {
			response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
			response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
			return response;
		}
		
		// file id List
		List<Long> fileIdList = new ArrayList<Long>();
		// create a temp class to save file info and data
		List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
		// check package and read manifest.xml, package files
		Document doc = null;
		SAXReader reader = new SAXReader();
		
		
		try {
			byte[] manifestByte = resultMap.get(MANIFEST);
			if (manifestByte == null || manifestByte.length == 0) {			
				response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
				response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
				return response;
			}
			InputStream manifestInputStream = new ByteArrayInputStream(manifestByte);
			doc = reader.read(manifestInputStream);
			Element root = doc.getRootElement();
			String packageType = root.attributeValue("type");
			if((!"application".equalsIgnoreCase(packageType) && !"firmware".equalsIgnoreCase(packageType)) || !StringUtils.equalsIgnoreCase(root.getName(), "manifest") ){
				response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
				response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
				return response;
			}
	
			fileInfoList.add(getFileInfo("manifest", "", "", manifestByte, true));
			
			@SuppressWarnings("unchecked")
			List<Element> fileElements = root.element("files").elements("file");
			if(resultMap.size() - 1 != fileElements.size()){
				response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
				response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
				return response;
			}
			for (Element e: fileElements) {
				String fileName = e.attributeValue("path") == null ? "" : (e
						.attributeValue("path").startsWith("./") ? e
						.attributeValue("path").replaceFirst("./", "") : e
						.attributeValue("path"));
				String fileVersion = e.attributeValue("version");
				String md5 = e.attributeValue("md5");
				byte[] fileData = resultMap.get(fileName);
				if (fileData == null) {
					response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
					response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
					return response;
				}
				fileInfoList.add(getFileInfo(fileName, fileVersion, md5, fileData, false));
			}
			
			PubFileData packageFileData = savePubFileData(inputByte);
			PubFileInfo packageFileInfo = savePubFileInfo(packageFileData.getId(), name, packageFileData.getSize(), "", "");
			PubPackage pubPackage = null;
			for(FileInfo fileInfo : fileInfoList){
				PubFileData pubfileData = savePubFileData(fileInfo.getData());
				PubFileInfo pubfileInfo = savePubFileInfo(pubfileData.getId(), fileInfo.getName(), pubfileData.getSize(), fileInfo.getMd5(), fileInfo.getVersion());
				if(fileInfo.isManifest()){
					pubPackage = savePubPackage(name, packageType, root.element(packageType).attributeValue("version"), packageFileData.getId(), pubfileData.getId());
				}else{
					fileIdList.add(pubfileData.getId());
				}
			}
			for (Long id : fileIdList) {
				PubPackageFile pubPackageFile = new PubPackageFile();
				pubPackageFile.setPackage_id(pubPackage.getId());
				pubPackageFile.setFile_id(id);
				this.pubPackageFileService.save(pubPackageFile);
			}
		} catch (Exception e) {
			response.setResponseCode(ConstantsUtil.RESPONSECODE_FORMATINVALID);
			response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_FORMATINVALID);
			return response;
		}
	
		response.setResponseCode(ConstantsUtil.RESPONSECODE_SUCCESS);
		response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_SUCCESS);
		return response;
	}
	
	public FileInfo getFileInfo(String name, String version, String md5, byte[] data, boolean isManifest){
		FileInfo fileInfo = new FileInfo();
		fileInfo.setName(name);
		fileInfo.setVersion(version);
		fileInfo.setMd5(md5);
		fileInfo.setData(data);
		fileInfo.setManifest(isManifest);
		return fileInfo;
	}
	
	public PubFileData savePubFileData(byte[] buffer){
		PubFileData fileDate = new PubFileData();
		try {
			fileDate.setData(convertByteToBlob(buffer));
		} catch (Exception e) {
			e.printStackTrace();
		}
		fileDate.setSize(Long.parseLong(buffer.length + ""));
		return this.pubFileDataService.save(fileDate);
	}
	
	public PubFileInfo savePubFileInfo(Long id, String name, Long size, String md5, String version){
		UUID uuid = UUID.randomUUID();
		PubFileInfo fileInfo = new PubFileInfo();
		fileInfo.setId(id);
		fileInfo.setUuid(uuid.toString());
		fileInfo.setName(name);
		fileInfo.setSize(size);
		fileInfo.setMd5(md5);
		fileInfo.setVersion(version);
		return this.pubFileInfoService.save(fileInfo);
	}
	
	public PubPackage savePubPackage(String name, String type, String version, Long file_id, Long manifest_id){
		UUID uuid = UUID.randomUUID();
		PubPackage pubPackage = new PubPackage();
		pubPackage.setUuid(uuid.toString());
		pubPackage.setName(name);
		pubPackage.setType(type);
		pubPackage.setVersion(version);
		pubPackage.setDateAdded(new Date());
		pubPackage.setFile_id(file_id);
		pubPackage.setManifest_id(manifest_id);		
		return this.pubPackageService.save(pubPackage);
	}
	
	public Blob convertByteToBlob(byte[] buffer) throws Exception {
		SessionFactory sessionFactory = SpringContextUtil.getBean("sessionFactory");
		Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(buffer);
		return blob;
	}
	
	public Map<String, byte[]> getPackageFiles(byte[] inputByte) throws Exception {
		InputStream inputStream = new ByteArrayInputStream(inputByte);
		Map<String, byte[]> resultMap = new HashMap<String, byte[]>();

		ZipInputStream zipInputStream = new ZipInputStream(inputStream);
		ZipEntry entry;
		byte[] content = new byte[1024];
		while ((entry = zipInputStream.getNextEntry()) != null) {
			if(entry.isDirectory()){
				continue;
			}
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			int len = 0;
			while ((len = zipInputStream.read(content)) > 0) {
				output.write(content, 0, len);					
			}
			resultMap.put(entry.getName().startsWith("./") ? entry.getName().replaceFirst("./", "") : entry.getName(), output.toByteArray());
			output.flush();
			output.close();
		}
		return resultMap;
		
	}

	@Override
	public BaseResponse deployPackageWS(List<String> tsnList, String uuid, Date deployTime) {
		BaseResponse response = new BaseResponse();
		List<PubPackage> pubPackages = this.pubPackageService.getPubPackagesByUuid(uuid);
		if(pubPackages.size() < 1){
			response.setResponseCode(ConstantsUtil.RESPONSECODE_GETPACKAGEUUIDRROR);
			response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_GETPACKAGEUUIDRROR);
			return response;
		}
		PubPackage pubPackage = pubPackages.get(0);
		for (String tsn : tsnList) {
			PubPackageDeploy deploy = new PubPackageDeploy();
			deploy.setPackage_id(pubPackage.getId());
			deploy.setTsn(tsn);
			deploy.setSchedule_time(deployTime);
			deploy.setStatus("P");
			this.pubPackageDeployService.save(deploy);
		}
		response.setResponseCode(ConstantsUtil.RESPONSECODE_SUCCESS);
		response.setResponseMessage(ConstantsUtil.RESPONSEMESSAGE_SUCCESS);
		return response;
	}

	@Override
	public Page<PubPackage> listPackages(QueryPackageForm command) {
		return this.pubPackageService.query(command);
	}
	
	@Override
	public List<PubPackage> getPackages(){
		return this.pubPackageService.listAll();
	}
	
	@Override
	public PubPackage getPackage(Long id) {
		return this.pubPackageService.get(id);
	}
}

/** * */package com.paxsz.tms.webservice.deploy;import java.util.Date;import java.util.List;import javax.jws.WebParam;import javax.jws.WebService;import com.paxsz.tms.deploy.model.PubPackage;import com.paxsz.tms.deploy.web.form.QueryPackageForm;import com.paxsz.tms.webservice.utils.BaseResponse;import com.paxsz.tms.webservice.utils.Page;/** * @author Dai.L * @date 2014-10-23 */@WebService(serviceName = "DeployWebService", targetNamespace="http://webservice.paxsz.com/")public interface DeployWebService {// public String addPackage(InputStream is, String name, String type);/** * Description: save the package to database * @param inputByte : package content * @param name : package name * @param type : package type * @return success/false */public BaseResponse addPackageWS(@WebParam(name="inputByte") byte[] inputByte, @WebParam(name="name") String name, @WebParam(name="type") String type);/** * Description: deploy the terminals with the given uuid's package * @param tsnList: terminal SN list * @param uuid : package uuid * @return success or false */public BaseResponse deployPackageWS(@WebParam(name="tsnList") List<String> tsnList, @WebParam(name="uuid") String uuid, @WebParam(name="deployTime") Date deployTime);/** * description: get page contains current page, page size, total count and package items * @param command : query package form * @return Page :pagination page */public Page<PubPackage> listPackages(@WebParam(name="command") QueryPackageForm command);/** * description: get package list * @return list of package */public List<PubPackage> getPackages();/** * description: get package by package id * @return list of package */public PubPackage getPackage(Long id);}