Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package th.in.oneauthen.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.Locale;
- 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 javax.swing.text.html.HTMLDocument;
- import javax.swing.text.html.HTMLEditorKit;
- 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 com.itextpdf.text.Rectangle;
- import com.itextpdf.text.pdf.PdfReader;
- import th.in.oneauthen.object.DocumentDB;
- import th.in.oneauthen.object.SignatureProfileDB;
- import th.in.oneauthen.object.SystemConfigDB;
- import th.in.oneauthen.object.UserUidDB;
- import th.in.oneauthen.object.DAO.DocumentDAO;
- import th.in.oneauthen.object.DAO.SignatureProfileDAO;
- import th.in.oneauthen.object.DAO.SystemConfigDAO;
- import th.in.oneauthen.object.DAO.UserUidDAO;
- 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.net.URLDecoder;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.io.StringReader;
- 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.Charset;
- 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";
- public static final String SYSTEM_PARAM_TIMESTAMP = "TIMESTAMP_URL";
- public 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 = "";
- public static final String PROFILE_NAME = "profilename";
- public static String Email = "email";
- /**
- * @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();
- String fileName_GET = new String(filePart.getSubmittedFileName().getBytes(), Charset.forName("UTF-8"));
- String filename_DECODE = unescapeHtml3(fileName_GET);
- request.getSession().setAttribute(SESSION_FILENAME, filename_DECODE);
- // byte[] byte_utf16 = fileName_GET.getBytes(StandardCharsets.UTF_8);
- //
- // String string = new String(byte_utf16, "UTF-8");
- // String filename_DECODE = unescapeHtml3(fileName_GET);
- System.out.println(filePart.getName());
- System.out.println("test : "+fileName_GET);
- System.out.println(unescapeHtml3(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;
- UserUidDB userIdForProfile = (UserUidDB) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_USER);
- int ownerId =userIdForProfile.getUserId();
- String profileName = (String) request.getSession().getAttribute("profileName");
- try {
- SignatureProfileDB systemSigProfile = new SignatureProfileDAO().findByNameAndUserUID(profileName, ownerId);
- sessionSigProfile = new SignatureProfile(systemSigProfile);
- sessionSigProfile.setIsVisible(true);
- sessionSigProfile.setSignatureLocation(signatureLocation);
- System.out.println(Arrays.toString(sessionSigProfile.getSignatuerCoOrdinate()));
- /////////////////////////////////////////////////////////////////////////////////////////////////////////////
- float[] CoOrdinate = sessionSigProfile.getSignatuerCoOrdinate();
- for(int i= 0;i<CoOrdinate.length;i++)
- System.out.println(CoOrdinate[i]);
- String saveLocationDB = +CoOrdinate[0]+":"+CoOrdinate[1]+":"+CoOrdinate[2]+":"+CoOrdinate[3];
- System.out.println(saveLocationDB);
- systemSigProfile.setSigLocation(saveLocationDB);
- new SignatureProfileDAO().updateSignatureProfile(systemSigProfile);
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- 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);// [B@6b96482d
- System.out.println(filename);
- String FilePDF = request.getSession(true).getAttribute(SigningServlet.SESSION_PDF_DATA).toString();
- // writeBytesToFileNio(signPDF, UPLOAD_FOLDER + "Signing.pdf");
- try {
- System.out.println(request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH));
- String RefectToken = null;
- // try {
- String email_person = (String) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_ONEID_AUTH);
- String email_company = (String) request.getSession().getAttribute(LoginCompanyServlet.SESSION_PARAM_ONEID_AUTH);
- if(email_person == null) {
- Email = email_company;
- }
- else {
- Email = email_person;
- }
- RefectToken = this.getToken(Email);
- if (StringUtils.isEmpty(RefectToken))
- throw new NullPointerException("Cannot get refect tokent data or System error !! Please contact system administrator! ");
- 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);
- HttpEntity entity = MultipartEntityBuilder.create().addTextBody("appkey", "EsignKeY")
- .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();
- }
- // save in DB documentDB
- UserUidDB userID = (UserUidDB) request.getSession().getAttribute(LoginServlet.SESSION_PARAM_USER);
- System.out.println("hhhhhhhhhhhhhhhhhhhhh"+userID);
- int user_id =userID.getUserId();
- DocumentDAO sessionLogDao = new DocumentDAO();
- DocumentDB sessionLog = new DocumentDB();
- sessionLog.setCreator(userID);
- sessionLog.setDocFile(signPDF);
- sessionLog.setRemainingSigner(1);
- sessionLog.setTimeSign(new Date( ));
- String FILE_NAME = unescapeHtml3(pre_NAME);
- sessionLog.setFileName(FILE_NAME);
- sessionLog.setTypeApi("Web Application");
- sessionLog.setTotalDocument(1);
- sessionLog.setStatus("success");
- sessionLogDao.save(sessionLog);
- ////session go to select
- request.getSession().setAttribute("myPDF", signPDF);
- 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;
- }
- public static String unescapeHtml3( String str ) {
- try {
- HTMLDocument doc = new HTMLDocument();
- new HTMLEditorKit().read( new StringReader( "<html><body>" + str ), doc, 0 );
- return doc.getText( 1, doc.getLength() );
- } catch( Exception ex ) {
- return str;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement