PKIX path building failed

来自ling
跳转至: 导航搜索

run jetty run https

http://blog.csdn.net/dahaidao/article/details/71011

cd javahome/bin
keytool -genkey -alias User(keystore的别名) -keyalg RSA -validity 7 -keystore keystore

http://blog.csdn.net/zziamalei/article/details/46520797

解决办法:

1、导入证书到本地证书库

2、信任所有SSL证书

最好的解决办法或许是信任所有SSL证书,因为某些时候不能每次都手动的导入证书非常麻烦。现在封装了个方法,在连接openConnection的时候忽略掉证书就行了。

SslUtils.ignoreSsl();

SslUtils

package com.deloitte.filemanager.view;

import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SslUtils {
	private static void trustAllHttpsCertificates() throws Exception {
		TrustManager[] trustAllCerts = new TrustManager[1];
		TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	}

	static class miTM implements TrustManager, X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(X509Certificate[] certs, String authType)
				throws CertificateException {
			return;
		}

		public void checkClientTrusted(X509Certificate[] certs, String authType)
				throws CertificateException {
			return;
		}
	}

	/**
	 * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
	 * 
	 * @throws Exception
	 */
	public static void ignoreSsl() throws Exception {
		HostnameVerifier hv = new HostnameVerifier() {
			public boolean verify(String urlHostName, SSLSession session) {
				System.out.println("Warning: URL Host: " + urlHostName
						+ " vs. " + session.getPeerHost());
				return true;
			}
		};
		trustAllHttpsCertificates();
		HttpsURLConnection.setDefaultHostnameVerifier(hv);
	}

	public static void closeConnection(URLConnection connection) {
		if (connection instanceof HttpURLConnection) {
			HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.disconnect();
		} else if (connection instanceof HttpsURLConnection) {
			HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
			httpsURLConnection.disconnect();
		}
	}
}

SslTest

import java.io.OutputStreamWriter;  
import java.net.URL;  
import java.net.URLConnection;  
import org.apache.commons.io.IOUtils;  
   
public class SslTest {  
       
    public String getRequest(String url,int timeOut) throws Exception{  
        URL u = new URL(url);  
        if("https".equalsIgnoreCase(u.getProtocol())){  
            SslUtils.ignoreSsl();  
        }  
        URLConnection conn = u.openConnection();  
        conn.setConnectTimeout(timeOut);  
        conn.setReadTimeout(timeOut);  
        return IOUtils.toString(conn.getInputStream());  
    }  
       
    public String postRequest(String urlAddress,String args,int timeOut) throws Exception{  
        URL url = new URL(urlAddress);  
        if("https".equalsIgnoreCase(url.getProtocol())){  
            SslUtils.ignoreSsl();  
        }  
        URLConnection u = url.openConnection();  
        u.setDoInput(true);  
        u.setDoOutput(true);  
        u.setConnectTimeout(timeOut);  
        u.setReadTimeout(timeOut);  
        OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(), "UTF-8");  
        osw.write(args);  
        osw.flush();  
        osw.close();  
        u.getOutputStream();  
        return IOUtils.toString(u.getInputStream());  
    }  
       
    public static void main(String[] args) {  
        try {  
            SslTest st = new SslTest();  
            String a = st.getRequest("https://xxx.com/login.action", 3000);  
            System.out.println(a);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
   
}

OnlyOfficeCallBackController

package com.deloitte.filemanager.view;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Scanner;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deloitte.filemanager.model.FileItem;
import com.deloitte.filemanager.model.FileItemChangeHis;
import com.deloitte.filemanager.service.FileItemService;
import com.ling2.attachment.model.Attachment;
import com.ling2.attachment.service.FileManager;
import com.ling2.core.commons.utils.FileUtils;
import com.ling2.core.commons.utils.SslUtils;
import com.ling2.core.controller.IController;
import com.ling2.file.service.AttachmentRootFolderService;
import com.ling2.file.service.SystemRootFolderService;

@Component
public class OnlyOfficeCallBackController implements IController {
	public static String GROUP_HIS="FMMANAGER_HIS";
	public static String FMMANAGER_HIS_DETAIL="FMMANAGER_HIS_DETAIL";
	public static final String SEPARATOR = File.separator;

	@Resource
	AttachmentRootFolderService attachmentRootFolderService;
	@Resource
	FileItemService fileItemService;

	@Override
	public boolean anonymousAccess() {
		return true;
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		processRequest(request, response);
	}

	@Override
	public String getUrl() {
		return "/onlyofficecallback";
	}

	@Override
	public boolean isDisabled() {
		return false;
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
//		DocumentManager.Init(request, response);
		PrintWriter writer = response.getWriter();

		String itemId = request.getParameter("itemId");
		FileItem item=(FileItem)fileItemService.get(FileItem.class, Long.parseLong(itemId));
//		String storagePath = "c:/upload/test/" + itemId+FileUtils.getFileType(item.getFileName());

		String body = "";

		try {
			Scanner scanner = new Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			body = scanner.hasNext() ? scanner.next() : "";
			scanner.close();
		} catch (Exception ex) {
			writer.write("get request.getInputStream error:" + ex.getMessage());
			ex.printStackTrace();
			return;
		}
//		System.out.println(body);
		if (body.isEmpty()) {
			writer.write("empty request.getInputStream");
			return;
		}
		JSONObject jsonObj;

		try {
			jsonObj = JSONObject.parseObject(body);
		} catch (Exception ex) {
			writer.write("JSONParser.parse error:" + ex.getMessage());
			return;
		}

		Integer status = Integer.parseInt(jsonObj.get("status").toString());
		int saved = 0;
		if (status == 2 || status == 3 || status==6)// MustSave, Corrupted || status==6
		{
			try {
				Attachment changeResult = processChangeResult(item,jsonObj);
				Attachment changeDetail = processChangeDetail(item,jsonObj);
				/**
				 * 保存变更历史
				 */
				FileItemChangeHis his=new FileItemChangeHis();
				his.setFileId(changeResult.getId());
				his.setFileItemId(item.getId());
				his.setVersion(item.getVersion()+1);
				JSONObject history=jsonObj.getJSONObject("history");
				JSONArray changes=(JSONArray)history.get("changes");
				JSONObject change=changes.getJSONObject(0);
				JSONObject user=change.getJSONObject("user");
				String userId=user.getString("id");
				String name=user.getString("name");
				his.setChangeUserCode(userId);
				his.setChangeUserName(name);
				his.setServerVersion(history.getString("serverVersion"));
				his.setChangeDate(new Date());
				fileItemService.save(his);
				
				/**
				 * 更新item的version
				 */
				item.setVersion(item.getVersion()+1);
				item.setCurrentVersionFileId(changeResult.getId());
				item.setModifiedby(userId);
				item.setLastModifyTime(new Date());
				fileItemService.update(item);
			} catch (Exception ex) {
				ex.printStackTrace();
				saved = 1;
			}finally{
				
			}
		}

		writer.write("{\"error\":" + saved + "}");
	}

	private Attachment processChangeDetail(FileItem item,
			JSONObject jsonObj) throws Exception,
			FileNotFoundException {
		/**
		 * 保存附件
		 */
		String relationId=item.getId().toString();
		String groupId=FMMANAGER_HIS_DETAIL;
			
		Attachment filebean=new Attachment();
		filebean.setRelationId(relationId);
		filebean.setGroupId(groupId);
		/**
		 * xlsm onlyoffice下载后打不开
		 */
		String name="changes.zip";
		
		filebean.setFileName(name);
		filebean.setFilePath("");
		filebean.setFileTime(new Date());
//		filebean.setFileType(attachment.getFileType());
		
		filebean.setFlag("1");
		fileItemService.save(filebean);
		String rootFolder=attachmentRootFolderService.getRootPath(SystemRootFolderService.ATTACHMENT);
		
		String fileFolder=rootFolder+SEPARATOR+groupId;
		
		String fileName=filebean.getId()+filebean.getFileName();

		String realpath=fileFolder+SEPARATOR+fileName;
		
		String relativePath=groupId+SEPARATOR+fileName;
		
		File uploadfile= new File(realpath);
		FileUtils.ensureExistence(uploadfile);
		
		String downloadUri = (String) jsonObj.get("url");
		writeContent(downloadUri,uploadfile);
		
		filebean.setFileSize(uploadfile.length());
		filebean.setStoreType(FileManager.STORE_DISK);
		filebean.setRelativePath(relativePath);
		fileItemService.update(filebean);
		return filebean;
	}
	private Attachment processChangeResult(FileItem item,
			JSONObject jsonObj) throws Exception,
			FileNotFoundException {

		/**
		 * 保存附件
		 */
		String relationId=item.getId().toString();
		String groupId=GROUP_HIS;
			
			
		Attachment attachment=(Attachment)fileItemService.get(Attachment.class, item.getFileId());
		Attachment filebean=new Attachment();
		filebean.setRelationId(relationId);
		filebean.setGroupId(groupId);
		/**
		 * xlsm onlyoffice下载后打不开
		 */
		String name=attachment.getFileName();
		name=name.replace(".xlsm", ".xlsx");
		
		filebean.setFileName(name);
		filebean.setFilePath("");
		filebean.setFileTime(new Date());
		filebean.setFileType(attachment.getFileType());
		
		filebean.setFlag("1");
		fileItemService.save(filebean);
		String rootFolder=attachmentRootFolderService.getRootPath(SystemRootFolderService.ATTACHMENT);
		
		String fileFolder=rootFolder+SEPARATOR+groupId;
		
		String fileName=filebean.getId()+filebean.getFileName();

		String realpath=fileFolder+SEPARATOR+fileName;
		
		String relativePath=groupId+SEPARATOR+fileName;
		
		File uploadfile= new File(realpath);
		FileUtils.ensureExistence(uploadfile);
		
		String downloadUri = (String) jsonObj.get("changesurl");
		writeContent(downloadUri,uploadfile);

		
		filebean.setFileSize(uploadfile.length());
		filebean.setStoreType(FileManager.STORE_DISK);
		filebean.setRelativePath(relativePath);
		fileItemService.update(filebean);
		return filebean;
	}

	private void writeContent(String downloadUri,File uploadfile) throws Exception {
		
		URL url = new URL(downloadUri);
		if("https".equalsIgnoreCase(url.getProtocol())){  
            SslUtils.ignoreSsl();  
        }  
		URLConnection connection = url.openConnection();
		InputStream stream = connection.getInputStream();

		if (stream == null) {
			throw new Exception("Stream is null");
		}	
		
		FileOutputStream out=null;;
		try  {
			out = new FileOutputStream(uploadfile);
			int read;
			final byte[] bytes = new byte[1024];
			while ((read = stream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			out.flush();
		}catch(Exception e){
			
		}finally{
			try {
				out.close();
			} catch (Exception e2) {
				
			}
			try {
				SslUtils.closeConnection(connection);
			} catch (Exception e2) {
				
			}
		}
	}

}