ballchaichana

SigningSerlvet

Aug 6th, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.64 KB | None | 0 0
  1. package th.in.oneauth.servlet;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.ArrayList;
  9. import java.util.Arrays;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import java.util.Random;
  14.  
  15. import javax.servlet.ServletException;
  16. import javax.servlet.annotation.MultipartConfig;
  17. import javax.servlet.annotation.WebServlet;
  18. import javax.servlet.http.HttpServlet;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import javax.servlet.http.Part;
  22.  
  23. import org.apache.commons.io.IOUtils;
  24. import org.apache.commons.lang3.StringUtils;
  25. import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
  26.  
  27. import com.google.gson.JsonObject;
  28. import com.google.gson.JsonParser;
  29.  
  30. import th.in.oneauthen.object.SignatureProfileDB;
  31. import th.in.oneauthen.object.SystemConfigDB;
  32. import th.in.oneauthen.object.DAO.SignatureProfileDAO;
  33. import th.in.oneauthen.object.DAO.SystemConfigDAO;
  34. import th.in.oneauthen.pdf.PDFPage;
  35. import th.in.oneauthen.pdf.PDFPageRendering;
  36. import th.in.oneauthen.signing.SignatureProfile;
  37. import th.in.oneauthen.signing.SignatureUtil;
  38.  
  39. import java.io.BufferedReader;
  40. import java.io.DataOutputStream;
  41. import java.io.IOException;
  42. import java.io.InputStreamReader;
  43. import java.net.HttpURLConnection;
  44. import java.net.MalformedURLException;
  45. import java.net.URL;
  46. import java.net.URLConnection;
  47.  
  48. import java.io.OutputStream;
  49. import java.io.OutputStreamWriter;
  50. import java.io.PrintWriter;
  51. import java.net.HttpURLConnection;
  52. import java.io.BufferedWriter;
  53. import java.io.BufferedReader;
  54.  
  55. import java.io.BufferedReader;
  56. import java.io.File;
  57. import java.io.FileOutputStream;
  58. import java.io.InputStreamReader;
  59. import java.nio.charset.StandardCharsets;
  60. import java.nio.file.Files;
  61. import java.nio.file.Path;
  62. import java.nio.file.Paths;
  63. import java.text.SimpleDateFormat;
  64.  
  65. import org.apache.http.HttpEntity;
  66. import org.apache.http.HttpResponse;
  67. import org.apache.http.client.HttpClient;
  68. import org.apache.http.client.methods.HttpPost;
  69. import org.apache.http.client.methods.HttpPut;
  70. import org.apache.http.client.utils.URIBuilder;
  71. import org.apache.http.entity.ByteArrayEntity;
  72. import org.apache.http.entity.ContentType;
  73. import org.apache.http.entity.mime.MultipartEntityBuilder;
  74. import org.apache.http.impl.client.HttpClientBuilder;
  75.  
  76. /**
  77.  * Servlet implementation class SigningServlet
  78.  */
  79. @WebServlet("/sign")
  80. @MultipartConfig
  81. public class SigningServlet extends HttpServlet {
  82.     private static final long serialVersionUID = 1L;
  83.  
  84.     public static final String SIGNING_URL = "dashboard.jsp?reqp=signing";
  85.  
  86.     public static final String SESSION_ERR_MSG = "errMsg";
  87.     public static final String SESSION_PDF_DATA = "pdfData";
  88.     public static final String SESSION_PAGE_DATA = "pdfPageData";
  89.  
  90.     public static final String PARAM_DOCUMENT = "document";
  91.     public static final String PARAM_ACTION = "action";
  92.  
  93.     public static final String PARAM_SIG_VIS = "";
  94.     public static final String PARAM_PAGE = "currentPage";
  95.     public static final String PARAM_SIG_LOCATION = "location";
  96.  
  97.     public static final String ACTION_UPLOAD = "upload";
  98.     public static final String ACTION_SIGN = "signing";
  99.  
  100.     private static final String SYSTEM_PARAM_TIMESTAMP = "TIMESTAMP_URL";
  101.     private static final String TIMESTAMP_URL = "http://203.154.52.180/signserver/process?workerName=TimeStampSigner";
  102.     private static final int SYSTEM_DEFAULT_SIGNATURE_PROFILE = 1;
  103.  
  104.     private static final File Null = null;
  105.  
  106.     private static final String UPLOAD_FOLDER = "C:\\temp\\";
  107.     private static final String SESSION_FILENAME = "";
  108.     public static final String PARAM_FILE_LOCATION = "";
  109.  
  110.     /**
  111.      * @see HttpServlet#HttpServlet()
  112.      */
  113.     public SigningServlet() {
  114.         super();
  115.         // TODO Auto-generated constructor stub
  116.     }
  117.  
  118.     /**
  119.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  120.      *      response)
  121.      */
  122.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  123.             throws ServletException, IOException {
  124.         String signAction = request.getParameter(PARAM_ACTION);
  125.         if (ACTION_UPLOAD.equals(signAction)) {
  126.             Part filePart = request.getPart(PARAM_DOCUMENT); // Retrieves <input type="file" name="file">
  127.             String fileName_GET = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
  128.             request.getSession().setAttribute(SESSION_FILENAME, fileName_GET);
  129.             System.out.println(filePart.getName());
  130.             System.out.println(fileName_GET);
  131.             System.out.println(filePart.getContentType());
  132.             InputStream fileContent = filePart.getInputStream();
  133.             byte[] pdfData = IOUtils.toByteArray(fileContent);
  134.             System.out.println(pdfData == null ? "Null UploadData" : pdfData.length);
  135.             ArrayList<PDFPage> pageData = null;
  136.             String errorMessage = "";
  137.             try {
  138.                 pageData = new PDFPageRendering().extractPDF(pdfData);
  139.                 if (pageData == null || pageData.isEmpty()) {
  140.                     errorMessage = "INVALID PDF! PDF page cannot be rendered.";
  141.                 }
  142.             } catch (InvalidPasswordException pwdEx) {
  143.                 errorMessage = "INVALID PDF! Password Protected PDF was not supported in this version.";
  144.             } catch (IOException ioE) {
  145.                 ioE.printStackTrace();
  146.                 errorMessage = "INVALID PDF! PDF file cannot be opened.";
  147.             }
  148.  
  149.             if (StringUtils.isEmpty(errorMessage)) {
  150.                 request.getSession().setAttribute(SESSION_PDF_DATA, pdfData);
  151.                 request.getSession().setAttribute(SESSION_PAGE_DATA, pageData);
  152.                 request.setAttribute(UtilityServlet.PARAM_PAGE, UtilityServlet.PAGE_SIGN_DOCUMENT);
  153.                 request.setAttribute(PARAM_PAGE, 0);
  154.             } else {
  155.                 request.getSession().setAttribute(SESSION_ERR_MSG, errorMessage);
  156.             }
  157.             request.getRequestDispatcher(SIGNING_URL).forward(request, response);
  158.         } else if (ACTION_SIGN.equals(signAction)) {
  159.             byte[] pdfData = (byte[]) request.getSession().getAttribute(SESSION_PDF_DATA);
  160.             String signatureLocation = request.getParameter(PARAM_SIG_LOCATION);
  161.  
  162.             String timestampURL = TIMESTAMP_URL;
  163.             try {
  164.                 SystemConfigDB tsaConfig = new SystemConfigDAO().find(SYSTEM_PARAM_TIMESTAMP);
  165.                 if (tsaConfig != null)
  166.                     timestampURL = tsaConfig.getValue();
  167.             } catch (Exception e) {
  168.                 e.printStackTrace();
  169.             }
  170.  
  171.             SignatureProfile sessionSigProfile = null;
  172.             try {
  173.                 SignatureProfileDB systemSigProfile = new SignatureProfileDAO().find(SYSTEM_DEFAULT_SIGNATURE_PROFILE);
  174.                 sessionSigProfile = new SignatureProfile(systemSigProfile);
  175.                 sessionSigProfile.setIsVisible(true);
  176.                 sessionSigProfile.setSignatureLocation(signatureLocation);
  177.                 System.out.println(Arrays.toString(sessionSigProfile.getSignatuerCoOrdinate()));
  178.                 SignatureUtil util = new SignatureUtil(sessionSigProfile, timestampURL);
  179.                 byte[] signPDF = util.SignTheDocument(pdfData);
  180.                
  181.                   Date dNow = new Date( );
  182.                   SimpleDateFormat ft =
  183.                   new SimpleDateFormat ("yyyy-MM-dd_hh-mm-ss");
  184.                  // request.setCharacterEncoding("UTF-8");
  185.                  
  186.                 String pre_NAME = (String) request.getSession().getAttribute(SESSION_FILENAME);
  187.                 String[] pre_NAME_noPDF =pre_NAME.split("\\.");
  188.                 //String filename = pre_NAME_noPDF[0]+"_" + new Random().nextInt(100000) + ".pdf";
  189. //              pre_NAME_noPDF[0] = java.net.URLEncoder.encode(pre_NAME_noPDF[0],"UTF-8");
  190.                 new String (pre_NAME_noPDF[0].getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
  191.                 String filename = pre_NAME_noPDF[0]+"_" + ft.format(dNow) + ".pdf";
  192.  
  193.                 writeBytesToFileNio(signPDF, UPLOAD_FOLDER + filename);
  194.                
  195.                 String Directory = UPLOAD_FOLDER + filename;              
  196.                 request.getSession().setAttribute(PARAM_FILE_LOCATION, Directory);
  197.                
  198.                 System.out.println(filename);
  199.                 // writeBytesToFileNio(signPDF, UPLOAD_FOLDER + "Signing.pdf");
  200.  
  201.  
  202.                 try {
  203.                    
  204.                     System.out.println(request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH));
  205.                     String RefectToken = null;
  206.                     try {
  207.                         String email = (String) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH);
  208.                         // String email = authToken.get("thai_email").getAsString();
  209.                         RefectToken = this.getToken(email );
  210.                         if (StringUtils.isEmpty(RefectToken))
  211.                             throw new NullPointerException("Cannot get refect tokent data or System error !! Please contact system administrator! ");
  212.                     } catch (Exception e) {
  213.                         e.printStackTrace();
  214.                         LogoutServlet.doLogout(request, response, e.getMessage());
  215.                     }
  216.  
  217.                     BufferedReader br = null;
  218.                     String output;
  219.                     StringBuilder responseBuilder = null;
  220.  
  221.                     HttpClient httpClient = HttpClientBuilder.create().build();
  222.                     URIBuilder uriBuilder = new URIBuilder("https://box.one.th/app/api/upload");
  223.                     HttpPost request1 = new HttpPost(uriBuilder.build());
  224.                     request1.addHeader("Authorization", RefectToken);
  225.                     // request.addHeader("Content-Type", "text/plain; charset=utf8");
  226.  
  227.                     // HttpEntity entity = new
  228.                     // ByteArrayEntity(Files.readAllBytes(Paths.get("C:\\Users\\BallZaR5R5\\Desktop\\test.pdf")));
  229.                     HttpEntity entity = MultipartEntityBuilder.create().addTextBody("appkey", "EsignKeY")
  230.                             // .addBinaryBody("file", new File("C:\\temp\\Signing.pdf"))
  231.                             .addBinaryBody("file", new File(UPLOAD_FOLDER + filename)).build();
  232.                     request1.setEntity(entity);
  233.                     HttpResponse response1 = httpClient.execute(request1);
  234.                     int responseCode = response1.getStatusLine().getStatusCode();
  235.                     if (responseCode == 201 || responseCode == 200) {
  236.                         br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));
  237.                         responseBuilder = new StringBuilder();
  238.                         while ((output = br.readLine()) != null) {
  239.                             responseBuilder.append(output);
  240.  
  241.                         }
  242.                         System.out.println(responseBuilder.toString());
  243.                     } else {
  244.                         System.out.println("value Byte :" + signPDF.length);
  245.                         System.out.println("Failed : HTTP error code : " + response1.getStatusLine().getStatusCode());
  246.  
  247.                     }
  248.                         String Del = UPLOAD_FOLDER + filename;
  249.                         Files.delete(Paths.get(Del));
  250.                        
  251.                 } catch (MalformedURLException e) {
  252.                     e.printStackTrace();
  253.                     LogoutServlet.doLogout(request, response,
  254.                             "client cannot parse the URL correctly!" + e.getMessage());
  255.  
  256.                 } catch (IOException e) {
  257.                     e.printStackTrace();
  258.  
  259.                 }
  260.  
  261. //               response.setContentType("application/pdf");
  262. //               response.addHeader("Content-Disposition", "attachment;filename=signDocument.pdf");
  263. //               response.setContentLength(signPDF.length);
  264. //               response.getOutputStream().write(signPDF);
  265. //              response.getOutputStream().write("upload to OneBox complete ".getBytes());
  266.                 request.getRequestDispatcher(SIGNING_URL).forward(request, response);
  267.  
  268.             } catch (Exception e) {
  269.                 e.printStackTrace();
  270.                 LogoutServlet.doLogout(request, response, "PDF Signing Error !" + e.getMessage());
  271.             }
  272.         } else {
  273.             LogoutServlet.doLogout(request, response, "Invalid signing action!! Please login and try again.");
  274.         }
  275.     }
  276.  
  277.     private static void writeBytesToFileNio(byte[] bFile, String fileDest) {
  278.  
  279.         try {
  280.             Path path = Paths.get(fileDest);
  281.             Files.write(path, bFile);
  282.         } catch (IOException e) {
  283.             e.printStackTrace();
  284.         }
  285.  
  286.     }
  287.  
  288.     private String getToken(String email ) throws Exception {
  289.         // System.setProperty("javax.net.debug","all");
  290.        
  291.  
  292.         BufferedReader br = null;
  293.         String output;
  294.         StringBuilder responseBuilder = null;
  295.  
  296.         HttpClient httpClient = HttpClientBuilder.create().build();
  297.         URIBuilder uriBuilder = new URIBuilder("https://box.one.th/app/api/genAccessToken");
  298.         HttpPost request = new HttpPost(uriBuilder.build());
  299.         request.addHeader("Authorization",
  300.                 "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBuYW1lIjoiZS1zaWduIn0.hjTLi2r-eKlTz9HafSCo5BSBsEdtK7cNUDGZnNOX4vY");
  301.  
  302.         HttpEntity entity = MultipartEntityBuilder.create().addTextBody("client_email", email)
  303.                 .addTextBody("service_name", "upload").build();
  304.         request.setEntity(entity);
  305.         HttpResponse response = httpClient.execute(request);
  306.         int responseCode = response.getStatusLine().getStatusCode();
  307.         if (responseCode == 201 || responseCode == 200) {
  308.             br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
  309.             responseBuilder = new StringBuilder();
  310.             while ((output = br.readLine()) != null) {
  311.                 responseBuilder.append(output);
  312.             }
  313.  
  314.         } else {
  315.             System.out.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
  316.         }
  317.         System.out.println(responseBuilder.toString());
  318.  
  319.         String RefectToken = responseBuilder.toString();
  320.  
  321.         JsonObject jsonObject = new JsonParser().parse(RefectToken).getAsJsonObject();
  322.  
  323.         String token = jsonObject.get("data").getAsJsonObject().get("token").getAsString();
  324.  
  325.         return token;
  326.  
  327.     }
  328.  
  329. }
Advertisement
Add Comment
Please, Sign In to add comment