ballchaichana

servicetipppppp

Sep 4th, 2018
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.16 KB | None | 0 0
  1. package th.in.oneauthen.client;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.FileReader;
  9. import java.io.FileWriter;
  10. import java.io.IOException;
  11. import java.io.InputStreamReader;
  12. import java.io.PrintStream;
  13. import java.io.PrintWriter;
  14. import java.net.URISyntaxException;
  15. import java.nio.file.Files;
  16. import java.nio.file.Paths;
  17. import java.nio.file.StandardOpenOption;
  18. import java.text.SimpleDateFormat;
  19. import java.util.Base64;
  20. import java.util.Date;
  21. import java.util.Locale;
  22.  
  23. import org.apache.http.HttpResponse;
  24. import org.apache.http.client.HttpClient;
  25. import org.apache.http.client.methods.HttpPost;
  26. import org.apache.http.client.utils.URIBuilder;
  27. import org.apache.http.entity.StringEntity;
  28. import org.apache.http.impl.client.HttpClientBuilder;
  29. import org.boris.winrun4j.AbstractService;
  30. import org.boris.winrun4j.ServiceException;
  31.  
  32. import com.google.gson.Gson;
  33. import com.google.gson.JsonObject;
  34. import com.google.gson.JsonParser;
  35. import com.google.gson.stream.JsonReader;
  36.  
  37. public class FolderMonitoring extends AbstractService {
  38.     public static final String CONFIG_FILE = "config.json";
  39.  
  40.     private volatile boolean shutdown = false;
  41.  
  42.     public int doRequest(int request) throws ServiceException {
  43.         switch (request) {
  44.         case SERVICE_CONTROL_STOP:
  45.         case SERVICE_CONTROL_SHUTDOWN:
  46.             shutdown = true;
  47.             break;
  48.         }
  49.         return 0;
  50.     }
  51.  
  52.     public int getControlsAccepted() {
  53.         return 0;
  54.     }
  55.  
  56.     public String getName() {
  57.         return "One Authen Signing Application Client";
  58.     }
  59.  
  60.     public String getDescription() {
  61.         return "One Authen Signing Application Client.";
  62.     }
  63.  
  64.     public static void main(String[] args) {
  65.         try {
  66.             new FolderMonitoring().serviceMain(args);
  67.         } catch (Exception e) {
  68.             e.printStackTrace();
  69.         }
  70.     }
  71.  
  72.     @Override
  73.     public int serviceMain(String[] args) throws ServiceException {
  74.         ServiceConfiguration serviceConfig = new ServiceConfiguration();
  75.  
  76.         File monitorFolder = null;
  77.         File logFile = null;
  78.         try {
  79.             Gson gsonUtil = new Gson();
  80.             JsonReader reader = new JsonReader(new FileReader(new File(CONFIG_FILE)));
  81.  
  82.             serviceConfig = gsonUtil.fromJson(reader, ServiceConfiguration.class);
  83.             if (serviceConfig == null)
  84.                 throw new Exception("Invalid service configuration");
  85.  
  86.             monitorFolder = new File(serviceConfig.getMonitoringFolder());
  87.             if ((!monitorFolder.exists()) || (!monitorFolder.isDirectory())) {
  88.                 throw new Exception("Invalid monitoring folder configuration:" + monitorFolder.getAbsolutePath());
  89.             }
  90.  
  91.             if (!new File(serviceConfig.getLogFolder()).exists()) {
  92.                 throw new Exception("Invalid log folder configuration");
  93.             } else {
  94.                 logFile = new File(serviceConfig.getLogFolder(), "service.log");
  95.             }
  96.         } catch (Exception e) {
  97.             e.printStackTrace();
  98.             return -1;
  99.         }
  100.  
  101.         System.out.println(serviceConfig.getMonitoringFolder());
  102.         while (!shutdown) {
  103.             // at this step, monitoring folder already validate that it is exist and it is a
  104.             // folder.
  105.             // do file list inside folder
  106.             // System.out.println(serviceConfig.getOutputFolder());
  107.             File[] fileList = monitorFolder.listFiles();
  108.             long start = System.currentTimeMillis();
  109.             // System.out.println(serviceConfig.getMonitoringFolder());
  110.             if (fileList.length > 0) {
  111.                 // System.out.println(fileList.length );
  112.                 for (File file : fileList) {
  113.                     if (file.isFile()) {
  114.                         System.out.println(file.length());
  115.  
  116.                         byte[] input_file;
  117.                         try {
  118.                             input_file = Files.readAllBytes(Paths.get(file.getPath()));
  119.  
  120.                             byte[] encodedBytes = Base64.getEncoder().encode(input_file);
  121.                             String encodedStringPdf = new String(encodedBytes);
  122.  
  123.                             // read config file and get value
  124.                             String conFig = readFile(CONFIG_FILE);// filename is file config
  125.  
  126.                             JsonObject jsonObject = new JsonParser().parse(conFig).getAsJsonObject();
  127.                             String access_token = jsonObject.get("accessToken").getAsString();
  128.                             String profileIdStr = jsonObject.get("profileId").getAsString();
  129.                             int profileId = Integer.parseInt(profileIdStr);
  130.  
  131.                             // System.out.println(access_token);
  132.                             // System.out.println(profileId);
  133.                             // System.out.println(encodedStringPdf);
  134.  
  135.                             JsonObject json = new JsonObject();
  136.                             json.addProperty("profileId", profileId);
  137.                             json.addProperty("accessToken", access_token);
  138.                             json.addProperty("pdfData", encodedStringPdf);
  139.                             ////////////////////////////////////////////////////////////////
  140.  
  141.                             // send to api p'pae
  142.  
  143.                             BufferedReader br = null;
  144.                             String output;
  145.                             StringBuilder responseBuilder = null;
  146.  
  147.                             HttpClient httpClient = HttpClientBuilder.create().build();
  148.                             URIBuilder uriBuilder;
  149.  
  150.                             try {
  151.                                 uriBuilder = new URIBuilder("http://localhost:8080/OneESign/api/service/signing");
  152.                                 HttpPost postMethod = new HttpPost(uriBuilder.build());
  153.                                 StringEntity params = new StringEntity(json.toString());
  154.  
  155.                                 postMethod.addHeader("content-type", "application/json");
  156.                                 postMethod.setEntity(params);
  157.  
  158.                                 HttpResponse httpResponse = httpClient.execute(postMethod);
  159.                                 int responseCode = httpResponse.getStatusLine().getStatusCode();
  160.                                 if (responseCode == 201 || responseCode == 200) {
  161.                                     br = new BufferedReader(
  162.                                             new InputStreamReader((httpResponse.getEntity().getContent())));
  163.                                     responseBuilder = new StringBuilder();
  164.                                     while ((output = br.readLine()) != null) {
  165.                                         responseBuilder.append(output);
  166.                                     }
  167.  
  168.                                 } else {
  169.                                     System.out.println("Failed : HTTP error code : "
  170.                                             + httpResponse.getStatusLine().getStatusCode());
  171.                                 }
  172.  
  173.                                 // get response from api p'pae
  174.                                 // System.out.println(responseBuilder.toString());
  175.                                 String get_response = responseBuilder.toString();
  176.                                 JsonObject json_response = new JsonParser().parse(get_response).getAsJsonObject();
  177.                                 String responseMessage = json_response.get("responseMessage").getAsString();
  178.                                 String statusCodeStr = json_response.get("responseCode").getAsString();
  179.                                 int statusCode = Integer.parseInt(statusCodeStr);
  180.  
  181.                                 // error case
  182.                                 if (statusCode == -1) {
  183.                                     byte[] decodedBytesError = Base64.getDecoder().decode(encodedStringPdf.getBytes());
  184.                                     FileOutputStream fos = new FileOutputStream(
  185.                                             new File(serviceConfig.getFailFolder(), file.getName()));
  186.                                     fos.write(decodedBytesError);
  187.                                     fos.flush();
  188.                                     fos.close();
  189.  
  190.                                     // totaltime and file size
  191.                                     long totalTime = System.currentTimeMillis() - start;
  192.                                     long fileSize = file.length();
  193.                                     // create .txt for log
  194.                                     String STATUS = responseMessage;
  195.                                     String log = STATUS + ":" + file.getName();
  196.                                     logServer(log, serviceConfig.getLogFolder(), totalTime, fileSize);
  197.  
  198.                                     // delete old file
  199.                                     Files.delete(Paths.get(file.getPath()));
  200.  
  201.                                 } else {
  202.                                     String pdfDataResponse = json_response.get("pdfData").getAsString();
  203.                                     // decoder pdf from response
  204.                                     byte[] decodedBytes = Base64.getDecoder().decode(pdfDataResponse.getBytes());
  205.                                     FileOutputStream fos = new FileOutputStream(
  206.                                             new File(serviceConfig.getOutputFolder(), file.getName()));
  207.                                     fos.write(decodedBytes);
  208.                                     fos.flush();
  209.                                     fos.close();
  210.  
  211.                                     // totaltime and file size
  212.                                     long totalTime = System.currentTimeMillis() - start;
  213.                                     long fileSize = file.length();
  214.                                     // create .txt for log
  215.                                     String STATUS = responseMessage;
  216.                                     String log = STATUS + ":" + file.getName();
  217.                                     logServer(log, serviceConfig.getLogFolder(), totalTime, fileSize);
  218.  
  219.                                     // delete old file
  220.                                     Files.delete(Paths.get(file.getPath()));
  221.                                 }
  222.  
  223.                             } catch (URISyntaxException e1) {
  224.                                 System.out.println("http://localhost:8080/OneESign/api/service/signing");
  225.                                 e1.printStackTrace();
  226.                             }
  227.                         } catch (IOException e) {
  228.                             // TODO Auto-generated catch block
  229.                             e.printStackTrace();
  230.                         }
  231.  
  232.                     } else {
  233.                         System.out.println("Empty");
  234.                     }
  235.  
  236.                 }
  237.  
  238.                 try {
  239.                     Files.write(Paths.get(logFile.getPath()),
  240.                             ("Service execute complete at " + new Date() + ", Total file process = " + fileList.length
  241.                                     + ", Total time consume =" + (System.currentTimeMillis() - start)).getBytes(),
  242.                             StandardOpenOption.APPEND);
  243.                     Files.write(Paths.get(logFile.getPath()),
  244.                             ("-------------------------------------------------------------------------------------------------------------------------------------------------------\n")
  245.                                     .getBytes(),
  246.                             StandardOpenOption.APPEND);
  247.                 } catch (Exception e) {
  248.                     e.printStackTrace();
  249.                 }
  250.  
  251.             }
  252.             try {
  253.                 Thread.sleep(serviceConfig.getMonitorInterval());
  254.                 monitorFolder = new File(serviceConfig.getMonitoringFolder());
  255.             } catch (Exception e) {
  256.                 e.printStackTrace();
  257.             }
  258.         }
  259.  
  260.         return 0;
  261.     }
  262.  
  263.     public static String readFile(String filename) throws IOException {
  264.         String content = null;
  265.         File file = new File(filename);
  266.         FileReader reader = null;
  267.         try {
  268.             reader = new FileReader(file);
  269.             char[] chars = new char[(int) file.length()];
  270.             reader.read(chars);
  271.             content = new String(chars);
  272.             reader.close();
  273.         } catch (IOException e) {
  274.             e.printStackTrace();
  275.         } finally {
  276.             if (reader != null) {
  277.                 reader.close();
  278.             }
  279.         }
  280.         return content;
  281.     }
  282.  
  283.     private static void logServer(String str, String path, long totalTime, long fileSize) {
  284.         Date dNow = new Date();
  285.         SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss ", Locale.ENGLISH);
  286.         SimpleDateFormat daily = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
  287.  
  288.         System.out.println("Current Date: " + ft.format(dNow));
  289.  
  290.         try (FileWriter fw = new FileWriter(new File(path, daily.format(dNow) + ".txt"), true);
  291.                 BufferedWriter bw = new BufferedWriter(fw);
  292.                 PrintWriter out = new PrintWriter(bw)) {
  293.             out.println("[" + ft.format(dNow) + "]" + " [API Resful service]" + str + ":" + "[" + "Timeuse:" + totalTime
  294.                     + "]" + "[" + "Filesize:" + fileSize + "]");
  295.             // more code
  296.         } catch (IOException e) {
  297.  
  298.         }
  299.     }
  300.  
  301. }
Add Comment
Please, Sign In to add comment