Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package th.in.oneauth.servlet;
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.MultipartConfig;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.Part;
- import org.apache.commons.io.IOUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import th.in.oneauthen.object.SignatureProfileDB;
- import th.in.oneauthen.object.SystemConfigDB;
- import th.in.oneauthen.object.DAO.SignatureProfileDAO;
- import th.in.oneauthen.object.DAO.SystemConfigDAO;
- import th.in.oneauthen.pdf.PDFPage;
- import th.in.oneauthen.pdf.PDFPageRendering;
- import th.in.oneauthen.signing.SignatureProfile;
- import th.in.oneauthen.signing.SignatureUtil;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.io.BufferedWriter;
- import java.io.BufferedReader;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.InputStreamReader;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.text.SimpleDateFormat;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.methods.HttpPut;
- import org.apache.http.client.utils.URIBuilder;
- import org.apache.http.entity.ByteArrayEntity;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.impl.client.HttpClientBuilder;
- /**
- * Servlet implementation class SigningServlet
- */
- @WebServlet("/sign")
- @MultipartConfig
- public class SigningServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public static final String SIGNING_URL = "dashboard.jsp?reqp=signing";
- public static final String SESSION_ERR_MSG = "errMsg";
- public static final String SESSION_PDF_DATA = "pdfData";
- public static final String SESSION_PAGE_DATA = "pdfPageData";
- public static final String PARAM_DOCUMENT = "document";
- public static final String PARAM_ACTION = "action";
- public static final String PARAM_SIG_VIS = "";
- public static final String PARAM_PAGE = "currentPage";
- public static final String PARAM_SIG_LOCATION = "location";
- public static final String ACTION_UPLOAD = "upload";
- public static final String ACTION_SIGN = "signing";
- private static final String SYSTEM_PARAM_TIMESTAMP = "TIMESTAMP_URL";
- private static final String TIMESTAMP_URL = "http://203.154.52.180/signserver/process?workerName=TimeStampSigner";
- private static final int SYSTEM_DEFAULT_SIGNATURE_PROFILE = 1;
- private static final File Null = null;
- private static final String UPLOAD_FOLDER = "C:\\temp\\";
- private static final String SESSION_FILENAME = "";
- public static final String PARAM_FILE_LOCATION = "";
- /**
- * @see HttpServlet#HttpServlet()
- */
- public SigningServlet() {
- super();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String signAction = request.getParameter(PARAM_ACTION);
- if (ACTION_UPLOAD.equals(signAction)) {
- Part filePart = request.getPart(PARAM_DOCUMENT); // Retrieves <input type="file" name="file">
- String fileName_GET = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
- request.getSession().setAttribute(SESSION_FILENAME, fileName_GET);
- System.out.println(filePart.getName());
- System.out.println(fileName_GET);
- System.out.println(filePart.getContentType());
- InputStream fileContent = filePart.getInputStream();
- byte[] pdfData = IOUtils.toByteArray(fileContent);
- System.out.println(pdfData == null ? "Null UploadData" : pdfData.length);
- ArrayList<PDFPage> pageData = null;
- String errorMessage = "";
- try {
- pageData = new PDFPageRendering().extractPDF(pdfData);
- if (pageData == null || pageData.isEmpty()) {
- errorMessage = "INVALID PDF! PDF page cannot be rendered.";
- }
- } catch (InvalidPasswordException pwdEx) {
- errorMessage = "INVALID PDF! Password Protected PDF was not supported in this version.";
- } catch (IOException ioE) {
- ioE.printStackTrace();
- errorMessage = "INVALID PDF! PDF file cannot be opened.";
- }
- if (StringUtils.isEmpty(errorMessage)) {
- request.getSession().setAttribute(SESSION_PDF_DATA, pdfData);
- request.getSession().setAttribute(SESSION_PAGE_DATA, pageData);
- request.setAttribute(UtilityServlet.PARAM_PAGE, UtilityServlet.PAGE_SIGN_DOCUMENT);
- request.setAttribute(PARAM_PAGE, 0);
- } else {
- request.getSession().setAttribute(SESSION_ERR_MSG, errorMessage);
- }
- request.getRequestDispatcher(SIGNING_URL).forward(request, response);
- } else if (ACTION_SIGN.equals(signAction)) {
- byte[] pdfData = (byte[]) request.getSession().getAttribute(SESSION_PDF_DATA);
- String signatureLocation = request.getParameter(PARAM_SIG_LOCATION);
- String timestampURL = TIMESTAMP_URL;
- try {
- SystemConfigDB tsaConfig = new SystemConfigDAO().find(SYSTEM_PARAM_TIMESTAMP);
- if (tsaConfig != null)
- timestampURL = tsaConfig.getValue();
- } catch (Exception e) {
- e.printStackTrace();
- }
- SignatureProfile sessionSigProfile = null;
- try {
- SignatureProfileDB systemSigProfile = new SignatureProfileDAO().find(SYSTEM_DEFAULT_SIGNATURE_PROFILE);
- sessionSigProfile = new SignatureProfile(systemSigProfile);
- sessionSigProfile.setIsVisible(true);
- sessionSigProfile.setSignatureLocation(signatureLocation);
- System.out.println(Arrays.toString(sessionSigProfile.getSignatuerCoOrdinate()));
- SignatureUtil util = new SignatureUtil(sessionSigProfile, timestampURL);
- byte[] signPDF = util.SignTheDocument(pdfData);
- Date dNow = new Date( );
- SimpleDateFormat ft =
- new SimpleDateFormat ("yyyy-MM-dd_hh-mm-ss");
- // request.setCharacterEncoding("UTF-8");
- String pre_NAME = (String) request.getSession().getAttribute(SESSION_FILENAME);
- String[] pre_NAME_noPDF =pre_NAME.split("\\.");
- //String filename = pre_NAME_noPDF[0]+"_" + new Random().nextInt(100000) + ".pdf";
- // pre_NAME_noPDF[0] = java.net.URLEncoder.encode(pre_NAME_noPDF[0],"UTF-8");
- new String (pre_NAME_noPDF[0].getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
- String filename = pre_NAME_noPDF[0]+"_" + ft.format(dNow) + ".pdf";
- writeBytesToFileNio(signPDF, UPLOAD_FOLDER + filename);
- String Directory = UPLOAD_FOLDER + filename;
- request.getSession().setAttribute(PARAM_FILE_LOCATION, Directory);
- System.out.println(filename);
- // writeBytesToFileNio(signPDF, UPLOAD_FOLDER + "Signing.pdf");
- try {
- System.out.println(request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH));
- String RefectToken = null;
- try {
- String email = (String) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH);
- // String email = authToken.get("thai_email").getAsString();
- RefectToken = this.getToken(email );
- if (StringUtils.isEmpty(RefectToken))
- throw new NullPointerException("Cannot get refect tokent data or System error !! Please contact system administrator! ");
- } catch (Exception e) {
- e.printStackTrace();
- LogoutServlet.doLogout(request, response, e.getMessage());
- }
- BufferedReader br = null;
- String output;
- StringBuilder responseBuilder = null;
- HttpClient httpClient = HttpClientBuilder.create().build();
- URIBuilder uriBuilder = new URIBuilder("https://box.one.th/app/api/upload");
- HttpPost request1 = new HttpPost(uriBuilder.build());
- request1.addHeader("Authorization", RefectToken);
- // request.addHeader("Content-Type", "text/plain; charset=utf8");
- // HttpEntity entity = new
- // ByteArrayEntity(Files.readAllBytes(Paths.get("C:\\Users\\BallZaR5R5\\Desktop\\test.pdf")));
- HttpEntity entity = MultipartEntityBuilder.create().addTextBody("appkey", "EsignKeY")
- // .addBinaryBody("file", new File("C:\\temp\\Signing.pdf"))
- .addBinaryBody("file", new File(UPLOAD_FOLDER + filename)).build();
- request1.setEntity(entity);
- HttpResponse response1 = httpClient.execute(request1);
- int responseCode = response1.getStatusLine().getStatusCode();
- if (responseCode == 201 || responseCode == 200) {
- br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));
- responseBuilder = new StringBuilder();
- while ((output = br.readLine()) != null) {
- responseBuilder.append(output);
- }
- System.out.println(responseBuilder.toString());
- } else {
- System.out.println("value Byte :" + signPDF.length);
- System.out.println("Failed : HTTP error code : " + response1.getStatusLine().getStatusCode());
- }
- String Del = UPLOAD_FOLDER + filename;
- Files.delete(Paths.get(Del));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- LogoutServlet.doLogout(request, response,
- "client cannot parse the URL correctly!" + e.getMessage());
- } catch (IOException e) {
- e.printStackTrace();
- }
- // response.setContentType("application/pdf");
- // response.addHeader("Content-Disposition", "attachment;filename=signDocument.pdf");
- // response.setContentLength(signPDF.length);
- // response.getOutputStream().write(signPDF);
- // response.getOutputStream().write("upload to OneBox complete ".getBytes());
- request.getRequestDispatcher(SIGNING_URL).forward(request, response);
- } catch (Exception e) {
- e.printStackTrace();
- LogoutServlet.doLogout(request, response, "PDF Signing Error !" + e.getMessage());
- }
- } else {
- LogoutServlet.doLogout(request, response, "Invalid signing action!! Please login and try again.");
- }
- }
- private static void writeBytesToFileNio(byte[] bFile, String fileDest) {
- try {
- Path path = Paths.get(fileDest);
- Files.write(path, bFile);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private String getToken(String email ) throws Exception {
- // System.setProperty("javax.net.debug","all");
- BufferedReader br = null;
- String output;
- StringBuilder responseBuilder = null;
- HttpClient httpClient = HttpClientBuilder.create().build();
- URIBuilder uriBuilder = new URIBuilder("https://box.one.th/app/api/genAccessToken");
- HttpPost request = new HttpPost(uriBuilder.build());
- request.addHeader("Authorization",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBuYW1lIjoiZS1zaWduIn0.hjTLi2r-eKlTz9HafSCo5BSBsEdtK7cNUDGZnNOX4vY");
- HttpEntity entity = MultipartEntityBuilder.create().addTextBody("client_email", email)
- .addTextBody("service_name", "upload").build();
- request.setEntity(entity);
- HttpResponse response = httpClient.execute(request);
- int responseCode = response.getStatusLine().getStatusCode();
- if (responseCode == 201 || responseCode == 200) {
- br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
- responseBuilder = new StringBuilder();
- while ((output = br.readLine()) != null) {
- responseBuilder.append(output);
- }
- } else {
- System.out.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
- }
- System.out.println(responseBuilder.toString());
- String RefectToken = responseBuilder.toString();
- JsonObject jsonObject = new JsonParser().parse(RefectToken).getAsJsonObject();
- String token = jsonObject.get("data").getAsJsonObject().get("token").getAsString();
- return token;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment