Advertisement
ballchaichana

SigningSerlvet_bag

Sep 25th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.31 KB | None | 0 0
  1. package th.in.oneauthen.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.Locale;
  13. import java.util.Map;
  14. import java.util.Random;
  15.  
  16. import javax.servlet.ServletException;
  17. import javax.servlet.annotation.MultipartConfig;
  18. import javax.servlet.annotation.WebServlet;
  19. import javax.servlet.http.HttpServlet;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.http.HttpServletResponse;
  22. import javax.servlet.http.Part;
  23. import javax.swing.text.html.HTMLDocument;
  24. import javax.swing.text.html.HTMLEditorKit;
  25.  
  26. import org.apache.commons.io.IOUtils;
  27. import org.apache.commons.lang3.StringUtils;
  28. import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
  29.  
  30. import com.google.gson.JsonObject;
  31. import com.google.gson.JsonParser;
  32. import com.itextpdf.text.Rectangle;
  33. import com.itextpdf.text.pdf.PdfReader;
  34.  
  35. import th.in.oneauthen.object.DocumentDB;
  36. import th.in.oneauthen.object.SignatureProfileDB;
  37. import th.in.oneauthen.object.SystemConfigDB;
  38. import th.in.oneauthen.object.UserUidDB;
  39. import th.in.oneauthen.object.DAO.DocumentDAO;
  40. import th.in.oneauthen.object.DAO.SignatureProfileDAO;
  41. import th.in.oneauthen.object.DAO.SystemConfigDAO;
  42. import th.in.oneauthen.object.DAO.UserUidDAO;
  43. import th.in.oneauthen.pdf.PDFPage;
  44. import th.in.oneauthen.pdf.PDFPageRendering;
  45. import th.in.oneauthen.signing.SignatureProfile;
  46. import th.in.oneauthen.signing.SignatureUtil;
  47.  
  48. import java.io.BufferedReader;
  49. import java.io.DataOutputStream;
  50. import java.io.IOException;
  51. import java.io.InputStreamReader;
  52. import java.net.HttpURLConnection;
  53. import java.net.MalformedURLException;
  54. import java.net.URL;
  55. import java.net.URLConnection;
  56. import java.net.URLDecoder;
  57. import java.io.OutputStream;
  58. import java.io.OutputStreamWriter;
  59. import java.io.PrintWriter;
  60. import java.io.StringReader;
  61. import java.net.HttpURLConnection;
  62. import java.io.BufferedWriter;
  63. import java.io.BufferedReader;
  64.  
  65. import java.io.BufferedReader;
  66. import java.io.File;
  67. import java.io.FileOutputStream;
  68. import java.io.InputStreamReader;
  69. import java.nio.charset.Charset;
  70. import java.nio.charset.StandardCharsets;
  71. import java.nio.file.Files;
  72. import java.nio.file.Path;
  73. import java.nio.file.Paths;
  74. import java.text.SimpleDateFormat;
  75.  
  76. import org.apache.http.HttpEntity;
  77. import org.apache.http.HttpResponse;
  78. import org.apache.http.client.HttpClient;
  79. import org.apache.http.client.methods.HttpPost;
  80. import org.apache.http.client.methods.HttpPut;
  81. import org.apache.http.client.utils.URIBuilder;
  82. import org.apache.http.entity.ByteArrayEntity;
  83. import org.apache.http.entity.ContentType;
  84. import org.apache.http.entity.mime.MultipartEntityBuilder;
  85. import org.apache.http.impl.client.HttpClientBuilder;
  86.  
  87. /**
  88.  * Servlet implementation class SigningServlet
  89.  */
  90. @WebServlet("/sign")
  91. @MultipartConfig
  92. public class SigningServlet extends HttpServlet {
  93.     private static final long serialVersionUID = 1L;
  94.  
  95.     public static final String SIGNING_URL = "dashboard.jsp?reqp=signing";
  96.  
  97.     public static final String SESSION_ERR_MSG = "errMsg";
  98.     public static final String SESSION_PDF_DATA = "pdfData";
  99.     public static final String SESSION_PAGE_DATA = "pdfPageData";
  100.  
  101.     public static final String PARAM_DOCUMENT = "document";
  102.     public static final String PARAM_ACTION = "action";
  103.  
  104.     public static final String PARAM_SIG_VIS = "";
  105.     public static final String PARAM_PAGE = "currentPage";
  106.     public static final String PARAM_SIG_LOCATION = "location";
  107.  
  108.     public static final String ACTION_UPLOAD = "upload";
  109.     public static final String ACTION_SIGN = "signing";
  110.  
  111.     public static final String SYSTEM_PARAM_TIMESTAMP = "TIMESTAMP_URL";
  112.     public static final String TIMESTAMP_URL = "http://203.154.52.180/signserver/process?workerName=TimeStampSigner";
  113.     private static final int SYSTEM_DEFAULT_SIGNATURE_PROFILE = 1;
  114.  
  115.     private static final File Null = null;
  116.  
  117.     private static final String UPLOAD_FOLDER = "C:\\temp\\";
  118.     private static final String SESSION_FILENAME = "";
  119.     public static final String PARAM_FILE_LOCATION = "";
  120.    
  121.     public static final String PROFILE_NAME = "profilename";
  122.     public static  String Email = "email";
  123.    
  124.    
  125.    
  126.  
  127.    
  128.  
  129.     /**
  130.      * @see HttpServlet#HttpServlet()
  131.      */
  132.     public SigningServlet() {
  133.         super();
  134.         // TODO Auto-generated constructor stub
  135.     }
  136.  
  137.     /**
  138.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  139.      *      response)
  140.      */
  141.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  142.             throws ServletException, IOException {
  143.         String signAction = request.getParameter(PARAM_ACTION);
  144.         if (ACTION_UPLOAD.equals(signAction)) {
  145.             Part filePart = request.getPart(PARAM_DOCUMENT); // Retrieves <input type="file" name="file">
  146. //          String fileName_GET = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
  147.             String fileName_GET = new String(filePart.getSubmittedFileName().getBytes(), Charset.forName("UTF-8"));
  148.              String filename_DECODE = unescapeHtml3(fileName_GET);
  149.             request.getSession().setAttribute(SESSION_FILENAME, filename_DECODE);
  150. //          byte[] byte_utf16 = fileName_GET.getBytes(StandardCharsets.UTF_8);
  151. //         
  152. //                  String string = new String(byte_utf16, "UTF-8");
  153.             // String filename_DECODE = unescapeHtml3(fileName_GET);
  154.            
  155.             System.out.println(filePart.getName());
  156.             System.out.println("test : "+fileName_GET);
  157.             System.out.println(unescapeHtml3(fileName_GET));
  158.             System.out.println(filePart.getContentType());
  159.             InputStream fileContent = filePart.getInputStream();
  160.             byte[] pdfData = IOUtils.toByteArray(fileContent);
  161.             System.out.println(pdfData == null ? "Null UploadData" : pdfData.length);
  162.             ArrayList<PDFPage> pageData = null;
  163.             String errorMessage = "";
  164.             try {
  165.                 pageData = new PDFPageRendering().extractPDF(pdfData);
  166.                 if (pageData == null || pageData.isEmpty()) {
  167.                     errorMessage = "INVALID PDF! PDF page cannot be rendered.";
  168.                 }
  169.             } catch (InvalidPasswordException pwdEx) {
  170.                 errorMessage = "INVALID PDF! Password Protected PDF was not supported in this version.";
  171.             } catch (IOException ioE) {
  172.                 ioE.printStackTrace();
  173.                 errorMessage = "INVALID PDF! PDF file cannot be opened.";
  174.             }
  175.  
  176.             if (StringUtils.isEmpty(errorMessage)) {
  177.                 request.getSession().setAttribute(SESSION_PDF_DATA, pdfData);
  178.                 request.getSession().setAttribute(SESSION_PAGE_DATA, pageData);
  179.                 request.setAttribute(UtilityServlet.PARAM_PAGE, UtilityServlet.PAGE_SIGN_DOCUMENT);
  180.                 request.setAttribute(PARAM_PAGE, 0);
  181.             } else {
  182.                 request.getSession().setAttribute(SESSION_ERR_MSG, errorMessage);
  183.             }
  184.             request.getRequestDispatcher(SIGNING_URL).forward(request, response);
  185.         } else if (ACTION_SIGN.equals(signAction)) {
  186.             byte[] pdfData = (byte[]) request.getSession().getAttribute(SESSION_PDF_DATA);
  187.             String signatureLocation = request.getParameter(PARAM_SIG_LOCATION);
  188.  
  189.             String timestampURL = TIMESTAMP_URL;
  190.             try {
  191.                 SystemConfigDB tsaConfig = new SystemConfigDAO().find(SYSTEM_PARAM_TIMESTAMP);
  192.                 if (tsaConfig != null)
  193.                     timestampURL = tsaConfig.getValue();
  194.             } catch (Exception e) {
  195.                 e.printStackTrace();
  196.             }
  197.  
  198.             SignatureProfile sessionSigProfile = null;
  199.             UserUidDB userIdForProfile = (UserUidDB) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_USER);
  200.             int ownerId =userIdForProfile.getUserId();
  201.             String profileName = (String) request.getSession().getAttribute("profileName");
  202.             try {
  203.                 SignatureProfileDB systemSigProfile = new SignatureProfileDAO().findByNameAndUserUID(profileName, ownerId);
  204.  
  205.                 sessionSigProfile = new SignatureProfile(systemSigProfile);
  206.                 sessionSigProfile.setIsVisible(true);
  207.                 sessionSigProfile.setSignatureLocation(signatureLocation);
  208.                 System.out.println(Arrays.toString(sessionSigProfile.getSignatuerCoOrdinate()));
  209. /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  210.                 float[] CoOrdinate = sessionSigProfile.getSignatuerCoOrdinate();
  211.                
  212.                  for(int i= 0;i<CoOrdinate.length;i++)
  213.                      System.out.println(CoOrdinate[i]);
  214.                  String saveLocationDB = +CoOrdinate[0]+":"+CoOrdinate[1]+":"+CoOrdinate[2]+":"+CoOrdinate[3];
  215.                  System.out.println(saveLocationDB);
  216.                  
  217.                 systemSigProfile.setSigLocation(saveLocationDB);
  218.                  new SignatureProfileDAO().updateSignatureProfile(systemSigProfile);
  219.                
  220. ////////////////////////////////////////////////////////////////////////////////////////////////////               
  221.            
  222.                 SignatureUtil util = new SignatureUtil(sessionSigProfile, timestampURL);
  223.                 byte[] signPDF = util.SignTheDocument(pdfData);
  224.                
  225.                   Date dNow = new Date( );
  226.                   SimpleDateFormat ft =
  227.                   new SimpleDateFormat ("yyyy-MM-dd_hh-mm-ss");
  228.                  // request.setCharacterEncoding("UTF-8");
  229.                  
  230.                 String pre_NAME = (String) request.getSession().getAttribute(SESSION_FILENAME);
  231.                 String[] pre_NAME_noPDF =pre_NAME.split("\\.");
  232.                 //String filename = pre_NAME_noPDF[0]+"_" + new Random().nextInt(100000) + ".pdf";
  233. //              pre_NAME_noPDF[0] = java.net.URLEncoder.encode(pre_NAME_noPDF[0],"UTF-8");
  234.                 new String (pre_NAME_noPDF[0].getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
  235.                 String filename = pre_NAME_noPDF[0]+"_" + ft.format(dNow) + ".pdf";
  236.  
  237.                 writeBytesToFileNio(signPDF, UPLOAD_FOLDER + filename);
  238.                
  239.                 String Directory = UPLOAD_FOLDER + filename;              
  240.                 request.getSession().setAttribute(PARAM_FILE_LOCATION, Directory);// [B@6b96482d
  241.                
  242.                
  243.                 System.out.println(filename);
  244.                 String FilePDF = request.getSession(true).getAttribute(SigningServlet.SESSION_PDF_DATA).toString();
  245.                 // writeBytesToFileNio(signPDF, UPLOAD_FOLDER + "Signing.pdf");
  246.  
  247.  
  248.                 try {
  249.                    
  250.                     System.out.println(request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH));
  251.                     String RefectToken = null;
  252. //                  try {
  253.                    
  254.                         String email_person = (String) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH);
  255.                         String email_company = (String) request.getSession().getAttribute(LoginCompanyServlet.SESSION_PARAM_ONEID_AUTH);
  256.                         if(email_person == null) {
  257.                             Email = email_company;
  258.                         }
  259.                         else {
  260.                             Email = email_person;
  261.                         }
  262.                         RefectToken = this.getToken(Email);
  263.                         if (StringUtils.isEmpty(RefectToken))
  264.                             throw new NullPointerException("Cannot get refect tokent data or System error !! Please contact system administrator! ");
  265.  
  266.  
  267.                     BufferedReader br = null;
  268.                     String output;
  269.                     StringBuilder responseBuilder = null;
  270.  
  271.                     HttpClient httpClient = HttpClientBuilder.create().build();
  272.                     URIBuilder uriBuilder = new URIBuilder("https://box.one.th/app/api/upload");
  273.                     HttpPost request1 = new HttpPost(uriBuilder.build());
  274.                     request1.addHeader("Authorization", RefectToken);
  275.                     HttpEntity entity = MultipartEntityBuilder.create().addTextBody("appkey", "EsignKeY")
  276.                             .addBinaryBody("file", new File(UPLOAD_FOLDER + filename)).build();
  277.                     request1.setEntity(entity);
  278.                     HttpResponse response1 = httpClient.execute(request1);
  279.                     int responseCode = response1.getStatusLine().getStatusCode();
  280.                     if (responseCode == 201 || responseCode == 200) {
  281.                         br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));
  282.                         responseBuilder = new StringBuilder();
  283.                         while ((output = br.readLine()) != null) {
  284.                             responseBuilder.append(output);
  285.  
  286.                         }
  287.                         System.out.println(responseBuilder.toString());
  288.                     } else {
  289.                         System.out.println("value Byte :" + signPDF.length);
  290.                         System.out.println("Failed : HTTP error code : " + response1.getStatusLine().getStatusCode());
  291.  
  292.                     }
  293.                         String Del = UPLOAD_FOLDER + filename;
  294.                         Files.delete(Paths.get(Del));
  295.                        
  296.                 } catch (MalformedURLException e) {
  297.                     e.printStackTrace();
  298.                     LogoutServlet.doLogout(request, response,
  299.                             "client cannot parse the URL correctly!" + e.getMessage());
  300.  
  301.                 } catch (IOException e) {
  302.                     e.printStackTrace();
  303.  
  304.                 }
  305.                
  306.  
  307.  
  308.                
  309.                 // save in DB documentDB
  310.  
  311.                
  312.                 UserUidDB userID = (UserUidDB) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_USER);
  313.                 System.out.println("hhhhhhhhhhhhhhhhhhhhh"+userID);
  314.                 int user_id =userID.getUserId();
  315.                 DocumentDAO sessionLogDao = new DocumentDAO();
  316.                 DocumentDB sessionLog = new DocumentDB();
  317.                 sessionLog.setCreator(userID);
  318.                 sessionLog.setDocFile(signPDF);
  319.                 sessionLog.setRemainingSigner(1);
  320.                 sessionLog.setTimeSign(new Date( ));   
  321.                 String FILE_NAME = unescapeHtml3(pre_NAME);
  322.                 sessionLog.setFileName(FILE_NAME);
  323.                 sessionLog.setTypeApi("Web Application");
  324.                 sessionLog.setTotalDocument(1);
  325.                 sessionLog.setStatus("success");
  326.                
  327.                
  328.                 sessionLogDao.save(sessionLog);
  329.                
  330.                
  331.                
  332.                
  333.             ////session go to select
  334.                
  335.                 request.getSession().setAttribute("myPDF", signPDF);
  336.                 request.getRequestDispatcher(SIGNING_URL).forward(request, response);
  337.  
  338.             } catch (Exception e) {
  339.                 e.printStackTrace();
  340.                 LogoutServlet.doLogout(request, response, "PDF Signing Error !" + e.getMessage());
  341.                
  342.             }
  343.         } else {
  344.             LogoutServlet.doLogout(request, response, "Invalid signing action!! Please login and try again.");
  345.         }
  346.     }
  347.  
  348.     private static void writeBytesToFileNio(byte[] bFile, String fileDest) {
  349.  
  350.         try {
  351.             Path path = Paths.get(fileDest);
  352.             Files.write(path, bFile);
  353.         } catch (IOException e) {
  354.             e.printStackTrace();
  355.         }
  356.  
  357.     }
  358.  
  359.     private String getToken(String email ) throws Exception {
  360.         // System.setProperty("javax.net.debug","all");
  361.        
  362.  
  363.         BufferedReader br = null;
  364.         String output;
  365.         StringBuilder responseBuilder = null;
  366.  
  367.         HttpClient httpClient = HttpClientBuilder.create().build();
  368.         URIBuilder uriBuilder = new URIBuilder("https://box.one.th/app/api/genAccessToken");
  369.         HttpPost request = new HttpPost(uriBuilder.build());
  370.         request.addHeader("Authorization",
  371.                 "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBuYW1lIjoiZS1zaWduIn0.hjTLi2r-eKlTz9HafSCo5BSBsEdtK7cNUDGZnNOX4vY");
  372.  
  373.         HttpEntity entity = MultipartEntityBuilder.create().addTextBody("client_email", email)
  374.                 .addTextBody("service_name", "upload").build();
  375.         request.setEntity(entity);
  376.         HttpResponse response = httpClient.execute(request);
  377.         int responseCode = response.getStatusLine().getStatusCode();
  378.         if (responseCode == 201 || responseCode == 200) {
  379.             br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
  380.             responseBuilder = new StringBuilder();
  381.             while ((output = br.readLine()) != null) {
  382.                 responseBuilder.append(output);
  383.             }
  384.  
  385.         } else {
  386.             System.out.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
  387.         }
  388.         System.out.println(responseBuilder.toString());
  389.  
  390.         String RefectToken = responseBuilder.toString();
  391.  
  392.         JsonObject jsonObject = new JsonParser().parse(RefectToken).getAsJsonObject();
  393.  
  394.         String token = jsonObject.get("data").getAsJsonObject().get("token").getAsString();
  395.  
  396.         return token;
  397.  
  398.     }
  399.    
  400.     public static String unescapeHtml3( String str ) {
  401.         try {
  402.             HTMLDocument doc = new HTMLDocument();
  403.             new HTMLEditorKit().read( new StringReader( "<html><body>" + str ), doc, 0 );
  404.             return doc.getText( 1, doc.getLength() );
  405.         } catch( Exception ex ) {
  406.             return str;
  407.         }
  408.     }
  409.    
  410.  
  411.  
  412. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement