ballchaichana

Tip

Sep 3rd, 2018
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.55 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.         File monitorFolder = null;
  76.         File logFile = null;
  77.         try {
  78.             Gson gsonUtil = new Gson();
  79.             JsonReader reader = new JsonReader(new FileReader(new File(CONFIG_FILE)));
  80.  
  81.             serviceConfig = gsonUtil.fromJson(reader, ServiceConfiguration.class);
  82.             if (serviceConfig == null)
  83.                 throw new Exception("Invalid service configuration");
  84.  
  85.             monitorFolder = new File(serviceConfig.getMonitoringFolder());
  86.             if ((!monitorFolder.exists()) || (!monitorFolder.isDirectory())) {
  87.                 throw new Exception("Invalid monitoring folder configuration:" + monitorFolder.getAbsolutePath());
  88.             }
  89.  
  90.             if (!new File(serviceConfig.getLogFolder()).exists()) {
  91.                 throw new Exception("Invalid log folder configuration");
  92.             } else {
  93.                 logFile = new File(serviceConfig.getLogFolder(), "service.log");
  94.             }
  95.         } catch (Exception e) {
  96.             e.printStackTrace();
  97.             return -1;
  98.         }
  99.  
  100.         System.out.println(serviceConfig.getMonitoringFolder());
  101.         while (!shutdown) {
  102.             // at this step, monitoring folder already validate that it is exist and it is a
  103.             // folder.
  104.             // do file list inside folder
  105.             // System.out.println(serviceConfig.getOutputFolder());
  106.             File[] fileList = monitorFolder.listFiles();
  107.             long start = System.currentTimeMillis();
  108.             System.out.println(start);
  109.             if (fileList.length > 0) {
  110.  
  111.                 for (File file : fileList) {
  112.                     if (file.isFile()) {
  113.                         System.out.println(file.getName());
  114.  
  115.                         byte[] input_file;
  116.                         try {
  117.                             input_file = Files.readAllBytes(Paths.get(file.getPath()));
  118.  
  119.                             byte[] encodedBytes = Base64.getEncoder().encode(input_file);
  120.                             String encodedStringPdf = new String(encodedBytes);
  121.  
  122.                             // read config file and get value
  123.                             String conFig = readFile(CONFIG_FILE);// filename is file config
  124.  
  125.                             JsonObject jsonObject = new JsonParser().parse(conFig).getAsJsonObject();
  126.                             String access_token = jsonObject.get("accessToken").getAsString();
  127.                             String profileIdStr = jsonObject.get("profileId").getAsString();
  128.                             int profileId = Integer.parseInt(profileIdStr);
  129.  
  130.                             System.out.println(access_token);
  131.                             System.out.println(profileId);
  132.  
  133.                             JsonObject json = new JsonObject();
  134.                             json.addProperty("profileId", profileId);
  135.                             json.addProperty("accessToken", access_token);
  136.                             json.addProperty("pdfData", encodedStringPdf);
  137.                             ////////////////////////////////////////////////////////////////
  138.  
  139.                             // send to api p'pae
  140.  
  141.                             BufferedReader br = null;
  142.                             String output;
  143.                             StringBuilder responseBuilder = null;
  144.  
  145.                             HttpClient httpClient = HttpClientBuilder.create().build();
  146.                             URIBuilder uriBuilder;
  147.                            
  148.                             long end = System.currentTimeMillis();
  149.                             System.out.println(end-start);
  150.  
  151.                             try {
  152.                                 uriBuilder = new URIBuilder("http://localhost:8080/OneESign/api/service/signing");
  153.                                 HttpPost postMethod = new HttpPost(uriBuilder.build());
  154.                                 StringEntity params = new StringEntity(json.toString());
  155.  
  156.                                 postMethod.addHeader("content-type", "application/json");
  157.                                 postMethod.setEntity(params);
  158.  
  159.                                 HttpResponse httpResponse = httpClient.execute(postMethod);
  160.                                 int responseCode = httpResponse.getStatusLine().getStatusCode();
  161.                                 if (responseCode == 201 || responseCode == 200) {
  162.                                     br = new BufferedReader(
  163.                                             new InputStreamReader((httpResponse.getEntity().getContent())));
  164.                                     responseBuilder = new StringBuilder();
  165.                                     while ((output = br.readLine()) != null) {
  166.                                         responseBuilder.append(output);
  167.                                     }
  168.  
  169.                                 } else {
  170.                                     System.out.println("Failed : HTTP error code : "
  171.                                             + httpResponse.getStatusLine().getStatusCode());
  172.                                 }
  173.  
  174.                                 // get response from api p'pae
  175.                                 System.out.println(responseBuilder.toString());
  176.                                 String get_response = responseBuilder.toString();
  177.                                 JsonObject json_response = new JsonParser().parse(get_response).getAsJsonObject();
  178.                                 String pdfDataResponse = json_response.get("pdfData").getAsString();
  179.                                 String responseMessage = json_response.get("responseMessage").getAsString();
  180.  
  181.                                 // decoder pdf from response
  182.                                 byte[] decodedBytes = Base64.getDecoder().decode(pdfDataResponse.getBytes());
  183.                                 FileOutputStream fos = new FileOutputStream(
  184.                                         serviceConfig.getOutputFolder() + file.getName());
  185.                                 fos.write(decodedBytes);
  186.                                 fos.flush();
  187.                                 fos.close();
  188.  
  189.                                 // create .txt for log
  190.                                 String STATUS = responseMessage;
  191.                                 String log = STATUS + ":" + file.getName();
  192.                                 logServer(log, serviceConfig.getLogFolder());
  193.  
  194.                                 // delete old file
  195.                                 // String Del = PATH_INPUT + file.getName();
  196.                                 Files.delete(Paths.get(serviceConfig.getMonitoringFolder() + file.getName()));
  197.  
  198.                             } catch (URISyntaxException e1) {
  199.                                 System.out.println("http://localhost:8080/OneESign/api/service/signing");
  200.                                 e1.printStackTrace();
  201.                             }
  202.                         } catch (IOException e) {
  203.                             // TODO Auto-generated catch block
  204.                             e.printStackTrace();
  205.                         }
  206.                        
  207.                        
  208.  
  209.                     } else {
  210.                         System.out.println("Empty");
  211.                     }
  212.  
  213.                 }
  214.  
  215.                 // for ( File fileItem : fileList ) {
  216.                 // try {
  217.                 // String logStr = "";
  218.                 // logStr="["+new Date().toString()+"] File \""+fileItem.getName()+ "\" found.
  219.                 // Process and delete "+(fileItem.delete()?"success.\n":"fail.\n");
  220.                 // Files.write(Paths.get(logFile.getPath()), logStr.getBytes(),
  221.                 // StandardOpenOption.APPEND);
  222.                 // }catch (IOException e) {
  223.                 // //exception handling left as an exercise for the reader
  224.                 // System.err.println("Write Log
  225.                 // Failed."+e.getMessage()==null?"":e.getMessage());
  226.                 // }
  227.                 // }
  228.                 try {
  229.                     Files.write(Paths.get(logFile.getPath()),
  230.                             ("Service execute complete at " + new Date() + ", Total file process = " + fileList.length
  231.                                     + ", Total time consume =" + (System.currentTimeMillis() - start)).getBytes(),
  232.                             StandardOpenOption.APPEND);
  233.                     Files.write(Paths.get(logFile.getPath()),
  234.                             ("-------------------------------------------------------------------------------------------------------------------------------------------------------\n")
  235.                                     .getBytes(),
  236.                             StandardOpenOption.APPEND);
  237.                 } catch (Exception e) {
  238.                     e.printStackTrace();
  239.                 }
  240.  
  241.             }
  242.             try {
  243.                 Thread.sleep(serviceConfig.getMonitorInterval());
  244.                 monitorFolder = new File(serviceConfig.getMonitoringFolder());
  245.             } catch (Exception e) {
  246.                 e.printStackTrace();
  247.             }
  248.         }
  249.  
  250.         return 0;
  251.     }
  252.  
  253.     public static String readFile(String filename) throws IOException {
  254.         String content = null;
  255.         File file = new File(filename); // For example, foo.txt
  256.         FileReader reader = null;
  257.         try {
  258.             reader = new FileReader(file);
  259.             char[] chars = new char[(int) file.length()];
  260.             reader.read(chars);
  261.             content = new String(chars);
  262.             reader.close();
  263.         } catch (IOException e) {
  264.             e.printStackTrace();
  265.         } finally {
  266.             if (reader != null) {
  267.                 reader.close();
  268.             }
  269.         }
  270.         return content;
  271.     }
  272.  
  273.     private static void logServer(String str, String path) {
  274.         Date dNow = new Date();
  275.         SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss ", Locale.ENGLISH);
  276.         SimpleDateFormat daily = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
  277.  
  278.         System.out.println("Current Date: " + ft.format(dNow));
  279.  
  280.         try (FileWriter fw = new FileWriter(path + daily.format(dNow) + ".txt", true);
  281.                 BufferedWriter bw = new BufferedWriter(fw);
  282.                 PrintWriter out = new PrintWriter(bw)) {
  283.             out.println("[" + ft.format(dNow) + "]" + " [API Resful service]" + str);
  284.             // more code
  285.         } catch (IOException e) {
  286.  
  287.         }
  288.     }
  289.  
  290. }
Add Comment
Please, Sign In to add comment