Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package th.in.oneauthen.client;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintStream;
- import java.io.PrintWriter;
- import java.net.URISyntaxException;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.nio.file.StandardOpenOption;
- import java.text.SimpleDateFormat;
- import java.util.Base64;
- import java.util.Date;
- import java.util.Locale;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.utils.URIBuilder;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.boris.winrun4j.AbstractService;
- import org.boris.winrun4j.ServiceException;
- import com.google.gson.Gson;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import com.google.gson.stream.JsonReader;
- public class FolderMonitoring extends AbstractService {
- public static final String CONFIG_FILE = "config.json";
- private volatile boolean shutdown = false;
- public int doRequest(int request) throws ServiceException {
- switch (request) {
- case SERVICE_CONTROL_STOP:
- case SERVICE_CONTROL_SHUTDOWN:
- shutdown = true;
- break;
- }
- return 0;
- }
- public int getControlsAccepted() {
- return 0;
- }
- public String getName() {
- return "One Authen Signing Application Client";
- }
- public String getDescription() {
- return "One Authen Signing Application Client.";
- }
- public static void main(String[] args) {
- try {
- new FolderMonitoring().serviceMain(args);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Override
- public int serviceMain(String[] args) throws ServiceException {
- ServiceConfiguration serviceConfig = new ServiceConfiguration();
- File monitorFolder = null;
- File logFile = null;
- try {
- Gson gsonUtil = new Gson();
- JsonReader reader = new JsonReader(new FileReader(new File(CONFIG_FILE)));
- serviceConfig = gsonUtil.fromJson(reader, ServiceConfiguration.class);
- if (serviceConfig == null)
- throw new Exception("Invalid service configuration");
- monitorFolder = new File(serviceConfig.getMonitoringFolder());
- if ((!monitorFolder.exists()) || (!monitorFolder.isDirectory())) {
- throw new Exception("Invalid monitoring folder configuration:" + monitorFolder.getAbsolutePath());
- }
- if (!new File(serviceConfig.getLogFolder()).exists()) {
- throw new Exception("Invalid log folder configuration");
- } else {
- logFile = new File(serviceConfig.getLogFolder(), "service.log");
- }
- } catch (Exception e) {
- e.printStackTrace();
- return -1;
- }
- System.out.println(serviceConfig.getMonitoringFolder());
- while (!shutdown) {
- // at this step, monitoring folder already validate that it is exist and it is a
- // folder.
- // do file list inside folder
- // System.out.println(serviceConfig.getOutputFolder());
- File[] fileList = monitorFolder.listFiles();
- long start = System.currentTimeMillis();
- // System.out.println(serviceConfig.getMonitoringFolder());
- if (fileList.length > 0) {
- // System.out.println(fileList.length );
- for (File file : fileList) {
- if (file.isFile()) {
- System.out.println(file.length());
- byte[] input_file;
- try {
- input_file = Files.readAllBytes(Paths.get(file.getPath()));
- byte[] encodedBytes = Base64.getEncoder().encode(input_file);
- String encodedStringPdf = new String(encodedBytes);
- // read config file and get value
- String conFig = readFile(CONFIG_FILE);// filename is file config
- JsonObject jsonObject = new JsonParser().parse(conFig).getAsJsonObject();
- String access_token = jsonObject.get("accessToken").getAsString();
- String profileIdStr = jsonObject.get("profileId").getAsString();
- int profileId = Integer.parseInt(profileIdStr);
- // System.out.println(access_token);
- // System.out.println(profileId);
- // System.out.println(encodedStringPdf);
- JsonObject json = new JsonObject();
- json.addProperty("profileId", profileId);
- json.addProperty("accessToken", access_token);
- json.addProperty("pdfData", encodedStringPdf);
- ////////////////////////////////////////////////////////////////
- // send to api p'pae
- BufferedReader br = null;
- String output;
- StringBuilder responseBuilder = null;
- HttpClient httpClient = HttpClientBuilder.create().build();
- URIBuilder uriBuilder;
- try {
- uriBuilder = new URIBuilder("http://localhost:8080/OneESign/api/service/signing");
- HttpPost postMethod = new HttpPost(uriBuilder.build());
- StringEntity params = new StringEntity(json.toString());
- postMethod.addHeader("content-type", "application/json");
- postMethod.setEntity(params);
- HttpResponse httpResponse = httpClient.execute(postMethod);
- int responseCode = httpResponse.getStatusLine().getStatusCode();
- if (responseCode == 201 || responseCode == 200) {
- br = new BufferedReader(
- new InputStreamReader((httpResponse.getEntity().getContent())));
- responseBuilder = new StringBuilder();
- while ((output = br.readLine()) != null) {
- responseBuilder.append(output);
- }
- } else {
- System.out.println("Failed : HTTP error code : "
- + httpResponse.getStatusLine().getStatusCode());
- }
- // get response from api p'pae
- // System.out.println(responseBuilder.toString());
- String get_response = responseBuilder.toString();
- JsonObject json_response = new JsonParser().parse(get_response).getAsJsonObject();
- String responseMessage = json_response.get("responseMessage").getAsString();
- String statusCodeStr = json_response.get("responseCode").getAsString();
- int statusCode = Integer.parseInt(statusCodeStr);
- // error case
- if (statusCode == -1) {
- byte[] decodedBytesError = Base64.getDecoder().decode(encodedStringPdf.getBytes());
- FileOutputStream fos = new FileOutputStream(
- new File(serviceConfig.getFailFolder(), file.getName()));
- fos.write(decodedBytesError);
- fos.flush();
- fos.close();
- // totaltime and file size
- long totalTime = System.currentTimeMillis() - start;
- long fileSize = file.length();
- // create .txt for log
- String STATUS = responseMessage;
- String log = STATUS + ":" + file.getName();
- logServer(log, serviceConfig.getLogFolder(), totalTime, fileSize);
- // delete old file
- Files.delete(Paths.get(file.getPath()));
- } else {
- String pdfDataResponse = json_response.get("pdfData").getAsString();
- // decoder pdf from response
- byte[] decodedBytes = Base64.getDecoder().decode(pdfDataResponse.getBytes());
- FileOutputStream fos = new FileOutputStream(
- new File(serviceConfig.getOutputFolder(), file.getName()));
- fos.write(decodedBytes);
- fos.flush();
- fos.close();
- // totaltime and file size
- long totalTime = System.currentTimeMillis() - start;
- long fileSize = file.length();
- // create .txt for log
- String STATUS = responseMessage;
- String log = STATUS + ":" + file.getName();
- logServer(log, serviceConfig.getLogFolder(), totalTime, fileSize);
- // delete old file
- Files.delete(Paths.get(file.getPath()));
- }
- } catch (URISyntaxException e1) {
- System.out.println("http://localhost:8080/OneESign/api/service/signing");
- e1.printStackTrace();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- } else {
- System.out.println("Empty");
- }
- }
- try {
- Files.write(Paths.get(logFile.getPath()),
- ("Service execute complete at " + new Date() + ", Total file process = " + fileList.length
- + ", Total time consume =" + (System.currentTimeMillis() - start)).getBytes(),
- StandardOpenOption.APPEND);
- Files.write(Paths.get(logFile.getPath()),
- ("-------------------------------------------------------------------------------------------------------------------------------------------------------\n")
- .getBytes(),
- StandardOpenOption.APPEND);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(serviceConfig.getMonitorInterval());
- monitorFolder = new File(serviceConfig.getMonitoringFolder());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return 0;
- }
- public static String readFile(String filename) throws IOException {
- String content = null;
- File file = new File(filename);
- FileReader reader = null;
- try {
- reader = new FileReader(file);
- char[] chars = new char[(int) file.length()];
- reader.read(chars);
- content = new String(chars);
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (reader != null) {
- reader.close();
- }
- }
- return content;
- }
- private static void logServer(String str, String path, long totalTime, long fileSize) {
- Date dNow = new Date();
- SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss ", Locale.ENGLISH);
- SimpleDateFormat daily = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
- System.out.println("Current Date: " + ft.format(dNow));
- try (FileWriter fw = new FileWriter(new File(path, daily.format(dNow) + ".txt"), true);
- BufferedWriter bw = new BufferedWriter(fw);
- PrintWriter out = new PrintWriter(bw)) {
- out.println("[" + ft.format(dNow) + "]" + " [API Resful service]" + str + ":" + "[" + "Timeuse:" + totalTime
- + "]" + "[" + "Filesize:" + fileSize + "]");
- // more code
- } catch (IOException e) {
- }
- }
- }
Add Comment
Please, Sign In to add comment