Commit f2544089 by Owen Ryan Ang

Submit integration

parent d5ad37b7
...@@ -3,3 +3,7 @@ export function imageCapture(key) { ...@@ -3,3 +3,7 @@ export function imageCapture(key) {
window.ImageCaptureInterface.captureImage(key); window.ImageCaptureInterface.captureImage(key);
} }
export function selfieCapture(key) {
// Call Android function via javaScript interface
window.ImageCaptureInterface.captureSelfie(key);
}
\ No newline at end of file
...@@ -28,7 +28,7 @@ export function processCapture(key) { ...@@ -28,7 +28,7 @@ export function processCapture(key) {
// Set the hidden inputs when a file is selected // Set the hidden inputs when a file is selected
hiddenFnameInput.value = filenameString; hiddenFnameInput.value = filenameString;
hiddenFnameInput.display = ''; hiddenFnameInput.display = '';
hiddenFileContentInput.value = img.value; // This will store the base64-encoded content of the file hiddenFileContentInput.value = img.src; // This will store the base64-encoded content of the file
hiddenFileContentInput.display = ''; hiddenFileContentInput.display = '';
document.getElementById('buttonsContainer-video').style.display = 'none'; document.getElementById('buttonsContainer-video').style.display = 'none';
......
...@@ -6,7 +6,7 @@ import { showError } from "./showError.js"; ...@@ -6,7 +6,7 @@ import { showError } from "./showError.js";
import { submitForm } from "../Submit/submit.js"; import { submitForm } from "../Submit/submit.js";
import { BPO_OBJECT } from "../globalVariable.js"; import { BPO_OBJECT } from "../globalVariable.js";
import { fetchOptionsDB } from "./DBLookup/DBLookup.js"; import { fetchOptionsDB } from "./DBLookup/DBLookup.js";
import { imageCapture } from "./AndroidInterface/androidInterface.js"; import { imageCapture, selfieCapture } from "./AndroidInterface/androidInterface.js";
import { processCapture } from "./ImageCapture/captureImage.js"; import { processCapture } from "./ImageCapture/captureImage.js";
let newOption; let newOption;
...@@ -481,6 +481,20 @@ const inputVideoUpload = (key, validation) => { ...@@ -481,6 +481,20 @@ const inputVideoUpload = (key, validation) => {
input.addEventListener('change', (event) => { input.addEventListener('change', (event) => {
const file = event.target.files[0]; const file = event.target.files[0];
if (file) { if (file) {
// Create hidden inputs for fname and file content
const hiddenFnameInput = document.createElement('input');
hiddenFnameInput.setAttribute('id', `${key}`);
hiddenFnameInput.setAttribute('type', 'hidden');
hiddenFnameInput.setAttribute('name', 'hidden_fname');
container2.appendChild(hiddenFnameInput);
const hiddenFileContentInput = document.createElement('input');
hiddenFileContentInput.setAttribute('id', `${key}`);
hiddenFileContentInput.setAttribute('type', 'hidden');
hiddenFileContentInput.setAttribute('name', 'hidden_file_content');
container2.appendChild(hiddenFileContentInput);
const img = document.getElementById('zz'); const img = document.getElementById('zz');
const thumb = document.getElementById('thumbnail'); const thumb = document.getElementById('thumbnail');
const x = document.getElementsByClassName('x')[0]; const x = document.getElementsByClassName('x')[0];
...@@ -512,10 +526,8 @@ const inputVideoUpload = (key, validation) => { ...@@ -512,10 +526,8 @@ const inputVideoUpload = (key, validation) => {
document.getElementById('buttonsContainer-video').style.display = 'flex'; document.getElementById('buttonsContainer-video').style.display = 'flex';
// Clear the hidden fields // Clear the hidden fields
hiddenFnameInput.display = 'none'; container2.removeChild(hiddenFnameInput);
hiddenFnameInput.value = ''; container2.removeChild(hiddenFileContentInput);
hiddenFileContentInput.display = 'none';
hiddenFileContentInput.value = '';
}); });
}; };
reader.readAsDataURL(file); reader.readAsDataURL(file);
...@@ -549,10 +561,8 @@ const inputVideoUpload = (key, validation) => { ...@@ -549,10 +561,8 @@ const inputVideoUpload = (key, validation) => {
input.value = '' input.value = ''
// Clear the hidden fields // Clear the hidden fields
hiddenFnameInput.display = 'none'; container2.removeChild(hiddenFnameInput);
hiddenFnameInput.value = ''; container2.removeChild(hiddenFileContentInput);
hiddenFileContentInput.display = 'none';
hiddenFileContentInput.value = '';
}); });
} }
} }
...@@ -584,7 +594,7 @@ const inputVideoUpload = (key, validation) => { ...@@ -584,7 +594,7 @@ const inputVideoUpload = (key, validation) => {
input2.setAttribute('id', `${key}`); input2.setAttribute('id', `${key}`);
input2.setAttribute('name', `${key}`); input2.setAttribute('name', `${key}`);
input2.setAttribute('type', 'button'); input2.setAttribute('type', 'button');
input2.setAttribute('value', 'Record Video'); input2.setAttribute('value', 'Capture Photo');
input2.addEventListener('click', () => { input2.addEventListener('click', () => {
imageCapture(key); imageCapture(key);
}); });
...@@ -604,18 +614,95 @@ const inputVideoUpload = (key, validation) => { ...@@ -604,18 +614,95 @@ const inputVideoUpload = (key, validation) => {
filename.setAttribute('type','text'); filename.setAttribute('type','text');
filename.setAttribute('style', 'display: none; font-size: inherit;'); filename.setAttribute('style', 'display: none; font-size: inherit;');
// Create hidden inputs for fname and file content // Append all elements to the container
const hiddenFnameInput = document.createElement('input'); const container3 = document.createElement('div');
hiddenFnameInput.setAttribute('id', `${key}`); container2.appendChild(x);
hiddenFnameInput.setAttribute('type', 'hidden'); container3.setAttribute('id', 'buttonsContainer-video')
hiddenFnameInput.setAttribute('name', 'hidden_fname'); container3.setAttribute('class', 'buttonsContainer');
container2.appendChild(hiddenFnameInput); container3.appendChild(input);
// container3.appendChild(input1);
// container3.appendChild(dash);
container3.appendChild(input2);
container2.appendChild(container3)
container2.appendChild(img);
container2.appendChild(thumbnail);
container2.appendChild(filename);
const hiddenFileContentInput = document.createElement('input'); mandatory ? input.setAttribute('required', 'true') : null
hiddenFileContentInput.setAttribute('id', `${key}`);
hiddenFileContentInput.setAttribute('type', 'hidden'); return container
hiddenFileContentInput.setAttribute('name', 'hidden_file_content'); } catch (err) {
container2.appendChild(hiddenFileContentInput); throw err
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @param {*} validation
* validation of field from schema
* @returns
* created input field element
*/
const inputSelfieCapture = (key, validation) => {
try {
const {
mandatory,
fieldLength
} = validation
const container = document.createElement('div');
const container2 = document.createElement('div');
container.appendChild(container2);
container2.classList.add('image-capture');
const input = document.createElement('input');
input.setAttribute('id', `attachedMedia`);
input.setAttribute('name', `${key}`);
input.setAttribute('type', 'file');
input.setAttribute('style', 'display: none');
// input.setAttribute('accept', 'all/*');
const capturedImage = document.createElement('input');
capturedImage.setAttribute('id', 'capturedImageData');
capturedImage.setAttribute('name', `${key}`);
capturedImage.setAttribute('type', 'hidden');
capturedImage.setAttribute('style', 'display: none');
const x = document.createElement('span')
x.setAttribute('class', 'x');
x.setAttribute('style', 'display: none')
x.textContent = 'x';
const dash = document.createElement('label');
dash.setAttribute('class', 'dash');
dash.innerHTML = ' or ';
const input2 = document.createElement('input');
input2.setAttribute('id', `${key}`);
input2.setAttribute('name', `${key}`);
input2.setAttribute('type', 'button');
input2.setAttribute('value', 'Capture Photo');
input2.addEventListener('click', () => {
selfieCapture(key);
});
window.processCapture = processCapture
const img = document.createElement('img');
const thumbnail = document.createElement('video');
thumbnail.setAttribute('style', 'display: none');
thumbnail.setAttribute('id', 'thumbnail');
img.setAttribute('id', 'zz');
img.setAttribute('style', 'display: none');
const filename = document.createElement('span');
filename.setAttribute('id', 'fname');
filename.setAttribute('name', `${key}`);
filename.setAttribute('type','text');
filename.setAttribute('style', 'display: none; font-size: inherit;');
// Append all elements to the container // Append all elements to the container
const container3 = document.createElement('div'); const container3 = document.createElement('div');
...@@ -623,8 +710,8 @@ const inputVideoUpload = (key, validation) => { ...@@ -623,8 +710,8 @@ const inputVideoUpload = (key, validation) => {
container3.setAttribute('id', 'buttonsContainer-video') container3.setAttribute('id', 'buttonsContainer-video')
container3.setAttribute('class', 'buttonsContainer'); container3.setAttribute('class', 'buttonsContainer');
container3.appendChild(input); container3.appendChild(input);
container3.appendChild(input1); // container3.appendChild(input1);
container3.appendChild(dash); // container3.appendChild(dash);
container3.appendChild(input2); container3.appendChild(input2);
container2.appendChild(container3) container2.appendChild(container3)
container2.appendChild(img); container2.appendChild(img);
...@@ -1057,6 +1144,9 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1057,6 +1144,9 @@ const deconstruct = async (section, container, classAttribute) => {
case 'video-upload': case 'video-upload':
input = inputVideoUpload(key, validation) input = inputVideoUpload(key, validation)
break break
case 'selfie-capture':
input = inputSelfieCapture(key, validation)
break
case 'audio-upload': case 'audio-upload':
input = inputAudioUpload(key, validation) input = inputAudioUpload(key, validation)
break break
...@@ -1402,6 +1492,9 @@ export function clearForm() { ...@@ -1402,6 +1492,9 @@ export function clearForm() {
// Clear the form by resetting its fields // Clear the form by resetting its fields
formElement.reset(); formElement.reset();
// Programatically click media close button
document.getElementsByClassName('x')[0].click();
// Set the selected 'doctype' back // Set the selected 'doctype' back
const options = docTypeField.options; const options = docTypeField.options;
const { elements } = formElement const { elements } = formElement
......
import { GFS_URL } from "../config.js"; import { GFS_URL } from "../config.js";
export const urlFileUpload = GFS_URL + "/upload-file"; export const urlFileUpload = GFS_URL + "/upload-file";
export const uploadDirectory = "C:\\Users\\oang\\Desktop\\Mobile GDE\\test for upload" export const uploadDirectory = "/home/mobilegde-elements"
import { uploadDirectory, urlFileUpload } from "./config.js"; import { uploadDirectory, urlFileUpload } from "./config.js";
export const uploadFile = async (file, projectCode) => { export const uploadFile = async (file, fileName, directory) => {
const fileNameInput = generateFormattedString(projectCode);
const directoryInput = uploadDirectory;
const fileName = fileNameInput.trim();
const directory = directoryInput.trim();
if (fileName === '' || directory === '') { if (fileName === '' || directory === '') {
console.log("Please enter a valid file name and directory."); console.log("Please enter a valid file name and directory.");
return; return;
} }
let base64Data = file.split(',')[1];
const formData = new FormData(); const requestData = {
formData.append('file', file); base64Data: base64Data,
formData.append('fileName', fileName); fileName: fileName,
formData.append('directory', directory); directory: directory
};
fetch(urlFileUpload, { fetch(urlFileUpload, {
method: 'POST', method: 'POST',
body: formData headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
console.log('File uploaded successfully:', data); console.log('File uploaded successfully:', data);
return true;
}) })
.catch(error => { .catch(error => {
console.error('Error uploading file:', error); console.error('Error uploading file:', error);
......
import { GDE_URL } from "../config"; import { GDE_URL } from "../config.js";
export let urlGetIfExisting = GDE_URL + "/" + "get-if-existing"; export let urlGetIfExisting = GDE_URL + "/" + "get-if-existing";
export let urlGetXml = GDE_URL + "/" + "get-xml"; export let urlGetXml = GDE_URL + "/" + "get-xml";
...@@ -7,3 +7,4 @@ export let urlUpdateEob = GDE_URL + "/" + "update-eob"; ...@@ -7,3 +7,4 @@ export let urlUpdateEob = GDE_URL + "/" + "update-eob";
export let urlUpdateException = GDE_URL + "/" + "update-exception"; export let urlUpdateException = GDE_URL + "/" + "update-exception";
export let urlWriteMetrics = GDE_URL + "/" + "write-metrics"; export let urlWriteMetrics = GDE_URL + "/" + "write-metrics";
export let urlGetFields = GDE_URL + "/" + "get-fields"; export let urlGetFields = GDE_URL + "/" + "get-fields";
export let urlGetFile = GDE_URL + "/" + "get-file";
\ No newline at end of file
...@@ -3,7 +3,7 @@ import { SCHEMA_FILE_PATH } from "../../DataInputWidget/config.js"; ...@@ -3,7 +3,7 @@ import { SCHEMA_FILE_PATH } from "../../DataInputWidget/config.js";
import { schema } from "../../DataInputWidget/generateFields.js"; import { schema } from "../../DataInputWidget/generateFields.js";
import { IS_RETRIEVE_FROM_BPO } from "../../config.js"; import { IS_RETRIEVE_FROM_BPO } from "../../config.js";
import { createInfoModal } from "../../genericPopup/genericPopup.js"; import { createInfoModal } from "../../genericPopup/genericPopup.js";
import { PROJECT_CODE, ENCODING_PASS } from "../config.js"; import { PROJECT_CODE, ENCODING_PASS, TEMPORARY_FOLDER } from "../config.js";
import { completeToNextNode } from "../submit.js"; import { completeToNextNode } from "../submit.js";
export async function WriteForm(e,metrics,doctype,section) { export async function WriteForm(e,metrics,doctype,section) {
...@@ -12,19 +12,20 @@ export async function WriteForm(e,metrics,doctype,section) { ...@@ -12,19 +12,20 @@ export async function WriteForm(e,metrics,doctype,section) {
var Nodes=Frm.elements; var Nodes=Frm.elements;
const myArray = Object.values(metrics); const myArray = Object.values(metrics);
const lookup = schema[doctype][section] const lookup = schema[doctype][section]
localStorage.setItem("submit", "1"); // localStorage.setItem("submit", "1");
if (IS_RETRIEVE_FROM_BPO == "Y") {
let fields = {}; let fields = {};
for (var i=0;i<Nodes.length;i++) { for (var i=0;i<Nodes.length;i++) {
if (Nodes[i].style.display === 'none') continue if (Nodes[i].style.display === 'none') continue
let fid = Nodes[i].id; let fid = Nodes[i].id;
if (fid == 'DocType' || fid == 'Section' || fid == '' || fid == "submitButton") continue if (fid == 'DocType' || fid == 'Section' || fid == '' || fid == "submitButton") continue
// Skip elements of type "button", "submit", and files
if (Nodes[i].type === 'button' || Nodes[i].type === 'submit' || Nodes[i].name === 'hidden_file_content') continue;
fields[Object.keys(lookup[fid]).includes('aka') ? lookup[fid].aka.replace("field", "") : fid] = Nodes[i].value; fields[Object.keys(lookup[fid]).includes('aka') ? lookup[fid].aka.replace("field", "") : fid] = Nodes[i].value;
} }
await createOutputXml(fields, myArray, doctype, section); let response = await createOutputXml(fields, myArray, doctype, section);
} return response;
} }
catch(Err) { catch(Err) {
createInfoModal(null, 'OK', "Error: " + Err.description +" while writing form."); createInfoModal(null, 'OK', "Error: " + Err.description +" while writing form.");
...@@ -33,8 +34,75 @@ export async function WriteForm(e,metrics,doctype,section) { ...@@ -33,8 +34,75 @@ export async function WriteForm(e,metrics,doctype,section) {
} }
async function createOutputXml(fields, metrics, doctype, section) { async function createOutputXml(fields, metrics, doctype, section) {
let elementId = sessionStorage.getItem("element_id"); let response = null;
if (IS_RETRIEVE_FROM_BPO == "Y") {
response = await createBPOXML(fields, metrics, doctype, section);
} else{
response = await createNonBPOXML(fields, metrics, doctype, section);
}
return response;
}
async function createNonBPOXML(fields, metrics, doctype, section){
let fileExt = "";
switch(ENCODING_PASS){
case "PASS1":
fileExt = ".DTA"
break;
case "PASS2":
fileExt = ".DTB"
break;
default:
fileExt = ".xml"
break;
}
let userID = sessionStorage.getItem("user_id");
let fileName = userID + "_" + Date.now() + "_" + PROJECT_CODE + fileExt;
let fileNameOnly = userID + "_" + Date.now() + "_" + PROJECT_CODE;
sessionStorage.setItem("recentlySavedFileNameOnly", fileNameOnly);
sessionStorage.setItem("recentlySavedFileName", fileName);
let xmlData = {
"projCode": PROJECT_CODE,
"userId": userID,
"elementId": "",
"schema": SCHEMA_FILE_PATH,
"totalRec":"0",
"maxRec": "1",
"totalKeystroke": metrics[0],
"procTime": "",
"procDuration": metrics[1],
"eob": "",
"exceptionRemark": "",
"recordNo": "0",
"totalSubRec": "1",
"maxSubRec": "1",
"imageName": "",
"subRecordNo": "1",
"eor": "N",
"fields": fields,
"outputDir": TEMPORARY_FOLDER + "/" + fileNameOnly + "/" + fileName,
"doctype": doctype,
"section": section
}
let response = await fetch(urlWriteXml, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(xmlData)
});
return response;
}
async function createBPOXML(fields, metrics, doctype, section){
let elementId = sessionStorage.getItem("element_id");
let filePaths = JSON.parse(sessionStorage.getItem("dir_files")); let filePaths = JSON.parse(sessionStorage.getItem("dir_files"));
let xmlData = { let xmlData = {
...@@ -42,7 +110,6 @@ async function createOutputXml(fields, metrics, doctype, section) { ...@@ -42,7 +110,6 @@ async function createOutputXml(fields, metrics, doctype, section) {
"userId": sessionStorage.getItem("user_id"), "userId": sessionStorage.getItem("user_id"),
"elementId": elementId, "elementId": elementId,
"schema": SCHEMA_FILE_PATH, "schema": SCHEMA_FILE_PATH,
// "totalRec": 0,
"totalRec":filePaths.length, "totalRec":filePaths.length,
"maxRec": "1", "maxRec": "1",
"totalKeystroke": metrics[0], "totalKeystroke": metrics[0],
...@@ -53,10 +120,9 @@ async function createOutputXml(fields, metrics, doctype, section) { ...@@ -53,10 +120,9 @@ async function createOutputXml(fields, metrics, doctype, section) {
"recordNo": parseInt(sessionStorage.getItem("display_counter")) + 1, "recordNo": parseInt(sessionStorage.getItem("display_counter")) + 1,
"totalSubRec": "1", "totalSubRec": "1",
"maxSubRec": "1", "maxSubRec": "1",
//"imageName": "test",
"imageName": filePaths[parseInt(sessionStorage.getItem("display_counter"))], "imageName": filePaths[parseInt(sessionStorage.getItem("display_counter"))],
"subRecordNo": "1", "subRecordNo": "1",
"eor": "Y", "eor": "N",
"fields": fields, "fields": fields,
"outputDir": sessionStorage.getItem("element_file_loc") + "/" + (ENCODING_PASS == "PASS1" ? elementId + ".DTA" : elementId + ".DTB"), "outputDir": sessionStorage.getItem("element_file_loc") + "/" + (ENCODING_PASS == "PASS1" ? elementId + ".DTA" : elementId + ".DTB"),
"doctype": doctype, "doctype": doctype,
...@@ -71,28 +137,10 @@ async function createOutputXml(fields, metrics, doctype, section) { ...@@ -71,28 +137,10 @@ async function createOutputXml(fields, metrics, doctype, section) {
body: JSON.stringify(xmlData) body: JSON.stringify(xmlData)
}); });
if (completenessCheck(await response.text())) { return response;
let response = await fetch(urlUpdateEob, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(xmlData)
});
await completeToNextNode(elementId);
sessionStorage.setItem("isElementComplete", true);
}else{
sessionStorage.removeItem("isElementComplete");
}
}
function completenessCheck(xml) {
let lst = JSON.parse(sessionStorage.getItem("dir_files"));
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, "text/xml");
let files = [...xmlDoc.getElementsByTagName("imagename")].map((name) => name.childNodes[0].nodeValue)
return lst.every(file => files.includes(file));
} }
export const PROJECT_CODE = "PROJCODE01"; export const PROJECT_CODE = "PROJCODE01";
export const ENCODING_PASS = "PASS1"; export const ENCODING_PASS = "PASS1";
export const GDE_URL = "http://localhost:8080" + "/WebGde/svc/gfs-rest"; export const GDE_URL = "http://18.208.163.99:8080" + "/WebGde/svc/gfs-rest";
\ No newline at end of file export const GFS_URL = "http://107.20.193.188/gfs-explorer-ws/svc/gfs-rest/";
export const TEMPORARY_FOLDER = "C:\\Users\\oang\\Desktop\\Mobile GDE\\test for upload\\Elements";
export const GFS_ROOT_FOLDER = "/Users";
\ No newline at end of file
...@@ -5,8 +5,9 @@ import { uploadFile } from "../FileUpload/fileUpload.js"; ...@@ -5,8 +5,9 @@ import { uploadFile } from "../FileUpload/fileUpload.js";
import { global_end_time, saveMetrics, stopMetricCapture, setGlobalEndTime, interval } from "../captureMetrics/captureMetrics.js"; import { global_end_time, saveMetrics, stopMetricCapture, setGlobalEndTime, interval } from "../captureMetrics/captureMetrics.js";
import { createInfoModal } from "../genericPopup/genericPopup.js"; import { createInfoModal } from "../genericPopup/genericPopup.js";
import { Settings } from "./XMLWriter/Global.js"; import { Settings } from "./XMLWriter/Global.js";
import { urlGetFile } from "./XMLWriter/WebServices.js";
import { WriteForm } from "./XMLWriter/XML_Saver.js"; import { WriteForm } from "./XMLWriter/XML_Saver.js";
import { PROJECT_CODE } from "./config.js"; import { PROJECT_CODE, TEMPORARY_FOLDER } from "./config.js";
export const submitForm = async (e) => { export const submitForm = async (e) => {
try { try {
...@@ -22,20 +23,11 @@ export const submitForm = async (e) => { ...@@ -22,20 +23,11 @@ export const submitForm = async (e) => {
for (let element of elements) { for (let element of elements) {
if (element.style.display === 'none') continue if (element.style.display === 'none') continue
const { id, value, type } = element const { id, value, type } = element
const { valid } = validateInput(id, value) // Skip submit, buttons, and files
// Skip submit button
if (type === 'button') continue if (type === 'button') continue
if (type === 'submit') continue if (type === 'submit') continue
// Handle file uploads if (type === 'file') continue
if (type === 'file') { if (type === 'hidden') continue
const fileInput = element;
const files = fileInput.files;
if (files.length > 0) {
const file = files[0];
uploadFile(file, PROJECT_CODE);
}
}
if (id === 'DocType') { if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text; doctype = element.options[element.selectedIndex].text;
continue; continue;
...@@ -45,6 +37,8 @@ export const submitForm = async (e) => { ...@@ -45,6 +37,8 @@ export const submitForm = async (e) => {
continue; continue;
} }
const { valid } = validateInput(id, value)
var { isValidValue, errMsg } = checkValidValues(id, value); var { isValidValue, errMsg } = checkValidValues(id, value);
if (typeof errMsg !== "undefined") { if (typeof errMsg !== "undefined") {
...@@ -53,6 +47,7 @@ export const submitForm = async (e) => { ...@@ -53,6 +47,7 @@ export const submitForm = async (e) => {
// Update display of input field if input is not valid // Update display of input field if input is not valid
if (!valid) { if (!valid) {
console.log(element);
error = true error = true
if (type === 'select-one') { if (type === 'select-one') {
continue continue
...@@ -88,8 +83,25 @@ export const submitForm = async (e) => { ...@@ -88,8 +83,25 @@ export const submitForm = async (e) => {
return false return false
} }
else { else {
const metrics = stopMetricCapture();
await WriteForm(e, metrics, doctype, section); let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form);
if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER +"/"+ folderName
let filePath = { "filePath": folderPath + "/" + sessionStorage.getItem("recentlySavedFileName") };
console.log(filePath);
let getFile = await fetch(urlGetFile, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(filePath)
});
// await uploadTOGFS(await getFile.text(), sessionStorage.getItem("recentlySavedFileName"));
}
saveForm(sessionStorage.getItem("display_counter")); saveForm(sessionStorage.getItem("display_counter"));
} }
return true return true
...@@ -119,3 +131,26 @@ export async function completeToNextNode(elementId) { ...@@ -119,3 +131,26 @@ export async function completeToNextNode(elementId) {
return response; return response;
} }
export async function batchUpload(Form){
let Nodes = Form.elements;
let file;
let fileName;
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let directory = TEMPORARY_FOLDER + "/" + folderName
for (var i=0;i<Nodes.length;i++){
if (Nodes[i].name === 'hidden_file_content'){
var fileId = Nodes[i].id; // Get the ID of the current node
file = Nodes[i].value
if(file){
for (var j = 0; j < Nodes.length; j++) {
// Get file name from other node
if (Nodes[j].name === 'hidden_fname' && Nodes[j].id === fileId) {
fileName = Nodes[j].value;
await uploadFile(file, fileName, directory);
}
}
}
}
}
}
...@@ -38,9 +38,9 @@ export const HIGH_LIGHT_SCHEMA = "./WebGde-Widgets/sample_schema/dbSchema_anno. ...@@ -38,9 +38,9 @@ export const HIGH_LIGHT_SCHEMA = "./WebGde-Widgets/sample_schema/dbSchema_anno.
export const ROOT_FOLDER = "/WebGde-Widgets"; export const ROOT_FOLDER = "/WebGde-Widgets";
//this determines if the images will be retrieved from the gfs //this determines if the images will be retrieved from the gfs
export const DOMAIN = "http://3.84.219.51:8080" export const DOMAIN = "http://18.208.163.99:8080"
export const CONTEXTROOT = "gfs-explorer-ws" export const CONTEXTROOT = "gfs-explorer-ws"
export const GFS_URL = "http://3.84.219.51:8080" + "/MobileGde/svc/gfs-rest" export const GFS_URL = "http://18.208.163.99:8080" + "/WebGde/svc/gfs-rest"
export const FOLDER_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-folder?parentPath=/Users/" export const FOLDER_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-folder?parentPath=/Users/"
export const DOWNLOAD_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-download-link" export const DOWNLOAD_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-download-link"
export const IS_RETRIEVE_FROM_GFS = "N" export const IS_RETRIEVE_FROM_GFS = "N"
...@@ -48,10 +48,10 @@ export const IS_RETRIEVE_FROM_GFS = "N" ...@@ -48,10 +48,10 @@ export const IS_RETRIEVE_FROM_GFS = "N"
export const INVALID_KEYS = "F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,PrintScreen,ScrollLock,Pause,PageUp,PageDown,Insert,Delete,Control" export const INVALID_KEYS = "F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,PrintScreen,ScrollLock,Pause,PageUp,PageDown,Insert,Delete,Control"
//BPO CONFIG //BPO CONFIG
export const IS_RETRIEVE_FROM_BPO = "Y" export const IS_RETRIEVE_FROM_BPO = "N"
// export const BPO_URL = "http://35.171.20.94:8080/bpo-sqa/" // export const BPO_URL = "http://35.171.20.94:8080/bpo-sqa/"
// export const CURRENT_NODE = "Web GDE" // export const CURRENT_NODE = "Web GDE"
export const BPO_URL = "http://3.84.219.51:8080/bpo/" export const BPO_URL = "http://18.208.163.99:8080/bpo/"
export const CURRENT_NODE = "Mobile_GDE_DEV" export const CURRENT_NODE = "Mobile_GDE_DEV"
export const ENCODING_PASS = "PASS1" export const ENCODING_PASS = "PASS1"
export const NEXT_NODE = "Complete" export const NEXT_NODE = "Complete"
......
import { createLoadingScreen, displayNextRecord, removeLoadingScreen, resetGDE } from '../../script.js'; import { submitForm } from '../Submit/submit.js';
import { createRejectWindow } from '../BPO/rejectElement.js'; import { ROOT_FOLDER } from '../config.js';
import { createReturnWindow, returnElementBPO } from '../BPO/returnElement.js';
import { completeToNextNode, submitForm } from '../Submit/submit.js';
import { interval, pauseMetricCapture, saveMetrics, stopMetricCapture } from '../captureMetrics/captureMetrics.js';
import { REASON_LIST, ROOT_FOLDER } from '../config.js';
import { BPO_OBJECT, DISPLAY_FIELD_OBJECT, DOCUMENT_CONTROL_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_STORAGE } from '../globalVariable.js'; import { BPO_OBJECT, DISPLAY_FIELD_OBJECT, DOCUMENT_CONTROL_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_STORAGE } from '../globalVariable.js';
export class DocumentControlWidget { export class DocumentControlWidget {
global = { global = {
container: null, container: null,
// refreshBtn: null,
// pauseBtn: null,
submitBtn: null, submitBtn: null,
returnBtn: null,
rejectBtn: null
} }
constructor() { constructor() {
...@@ -25,41 +17,7 @@ export class DocumentControlWidget { ...@@ -25,41 +17,7 @@ export class DocumentControlWidget {
this.global.container = document.createElement("div"); this.global.container = document.createElement("div");
this.global.container.id = "TiffButtonRight"; this.global.container.id = "TiffButtonRight";
this.global.container.classList.add("ctrl-buttons") this.global.container.classList.add("ctrl-buttons")
//temporary
// this.global.refreshBtn = document.createElement("div");
// this.global.refreshBtn.title = "Refresh";
// this.global.refreshBtn.classList.add("buttonRightClass");
// this.global.refreshBtn.classList.add("buttonRightClass");
// const refreshIcon = document.createElement("img");
// refreshIcon.classList.add("tiffViewerIcons");
// refreshIcon.src = "."+ROOT_FOLDER+"/documentControlWidget/assets/refresh_icon.png";
// refreshIcon.alt = "Refresh";
// refreshIcon.height = "32";
// refreshIcon.width = "32";
// this.global.pauseBtn = document.createElement("div");
// this.global.pauseBtn.title = "Pause";
// this.global.pauseBtn.classList.add("buttonRightClass");
// const pauseIcon = document.createElement("img");
// pauseIcon.classList.add("tiffViewerIcons");
// pauseIcon.src = "."+ROOT_FOLDER+"/documentControlWidget/assets/pause_icon.png";
// pauseIcon.alt = "Pause";
// pauseIcon.height = "32";
// pauseIcon.width = "32";
this.global.returnBtn = document.createElement("div");
this.global.returnBtn.title = "Return";
this.global.returnBtn.classList.add("buttonRightClass");
const returnIcon = document.createElement("img");
returnIcon.classList.add("tiffViewerIcons");
returnIcon.src = "." + ROOT_FOLDER + "/documentControlWidget/assets/return_icon.png";
returnIcon.alt = "Return";
returnIcon.height = "32";
returnIcon.width = "32";
this.global.submitBtn = document.createElement("div"); this.global.submitBtn = document.createElement("div");
this.global.submitBtn.title = "Submit"; this.global.submitBtn.title = "Submit";
...@@ -71,155 +29,31 @@ export class DocumentControlWidget { ...@@ -71,155 +29,31 @@ export class DocumentControlWidget {
submitIcon.alt = "Submit"; submitIcon.alt = "Submit";
submitIcon.height = "32"; submitIcon.height = "32";
submitIcon.width = "32"; submitIcon.width = "32";
this.global.rejectBtn = document.createElement("div");
this.global.rejectBtn.title = "Reject";
this.global.rejectBtn.classList.add("buttonRightClass");
const rejectIcon = document.createElement("img");
rejectIcon.classList.add("tiffViewerIcons");
rejectIcon.src = "." + ROOT_FOLDER + "/documentControlWidget/assets/reject_icon.png";
rejectIcon.alt = "Reject";
rejectIcon.height = "32";
rejectIcon.width = "32";
// this.global.refreshBtn.append(refreshIcon);
// this.global.pauseBtn.append(pauseIcon);
this.global.submitBtn.append(submitIcon); this.global.submitBtn.append(submitIcon);
this.global.returnBtn.append(returnIcon);
this.global.rejectBtn.append(rejectIcon);
// this.global.container.appendChild(this.global.refreshBtn);
// this.global.container.appendChild(this.global.pauseBtn);
this.global.container.appendChild(this.global.submitBtn); this.global.container.appendChild(this.global.submitBtn);
this.global.container.appendChild(this.global.returnBtn);
this.global.container.appendChild(this.global.rejectBtn);
this.addEvenListeners(); this.addEvenListeners();
} }
addEvenListeners() { addEvenListeners() {
// this.global.refreshBtn.onclick = async(e) => {
// document.getElementById("currentImage").remove();
// let urls = JSON.parse(sessionStorage.getItem("dir_files"));
// let currentDisplayIndex = parseInt(sessionStorage.getItem("display_counter"));
// const url = urls[currentDisplayIndex-1];
// let filename = url.split('/').pop();
// let imageBlob = await INDEXED_DB_STORAGE.getStoreFile("imageNum_"+ currentDisplayIndex);
// await IMAGE_VIEWER_OBJECT.createCurrentImage(filename.split(".").pop(), filename, imageBlob);
// }
// this.global.pauseBtn.onclick = (e) => {
// pauseMetricCapture();
// }
// this.global.pauseBtn.onkeydown = (e) => {
// if (event.key === 'Escape' || event.key === 'Esc') {
// pauseMetricCapture();
// }
// }
this.global.submitBtn.onclick = async (e) => { this.global.submitBtn.onclick = async (e) => {
let isSuccessful = await submitForm(e); let isSuccessful = await submitForm(e);
if (isSuccessful) { if (isSuccessful) {
let currentDisplay = parseInt(sessionStorage.getItem("display_counter"));
let totalRecord = JSON.parse(sessionStorage.getItem("dir_files")).length;
//if (currentDisplay + 1 === totalRecord) {
if(sessionStorage.getItem("isElementComplete")){
//move element then fetch new element
//let response = await completeToNextNode(sessionStorage.getItem("element_id"));
createLoadingScreen();
const metrics = stopMetricCapture();
let eoe_ts = new Date().toLocaleString();
await saveMetrics(metrics, eoe_ts);
// if (response.status == 200) {
if (await BPO_OBJECT.getRandomWaitingElement()) {
document.getElementById("counter").innerHTML = "";
clearTimeout(interval);
resetGDE();
};
// } else {
// removeLoadingScreen();
// alert(`Error ${response.status}: Completing element to next node, Check if Complete Node Exist`);
// }
} else {
// document.getElementById("nextRecordImage").click();
//DISPLAY_FIELD_OBJECT.generateFields();
DISPLAY_FIELD_OBJECT.clearForm(); DISPLAY_FIELD_OBJECT.clearForm();
displayNextRecord();
//document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget());
// DISPLAY_FIELD_OBJECT.updateHeaderText(0, "User: " + sessionStorage.getItem("user_id"));
// DISPLAY_FIELD_OBJECT.updateHeaderText(1, "Element ID: " + sessionStorage.getItem("element_id"));
// DISPLAY_FIELD_OBJECT.updateHeaderText(2, "");
}
} }
} }
this.global.returnBtn.onclick = (e) => {
createReturnWindow();
//returnElementBPO(sessionStorage.getItem("element_id"));
// var fileName = sessionStorage.getItem("file_Name");
// if (fileName !== null && fileName !== undefined) {
// document.getElementById("controlsContainer").outerHTML="";
// } else {
// document.getElementById("TiffViewer_ButtonContainer").outerHTML="";
// }
}
this.global.returnBtn.onkeydown = (e) => {
if (e.altKey == true && e.keyCode == 85) {
returnElementBPO(sessionStorage.getItem("element_id"));
// var fileName = sessionStorage.getItem("file_Name");
// if (fileName !== null && fileName !== undefined) {
// document.getElementById("controlsContainer").outerHTML="";
// } else {
// document.getElementById("TiffViewer_ButtonContainer").outerHTML="";
// }
}
}
this.global.rejectBtn.onclick = (e) => {
createRejectWindow();
e.target.disabled = true;
}
this.global.rejectBtn.onkeydown = (e) => {
if (e.ctrlKey == true && e.keyCode == 69) {
createRejectWindow();
e.target.disabled = true;
}
}
} }
getWidget() { getWidget() {
return this.global.container; return this.global.container;
} }
getRefreshBtn() {
return this.global.refreshBtn;
}
getSubmitBtn(){ getSubmitBtn(){
return this.global.submitBtn; return this.global.submitBtn;
} }
getPauseBtn() {
return this.global.pauseBtn;
}
getReturnBtn() {
return this.global.returnBtn;
}
getRejectBtn() {
return this.global.rejectBtn;
}
} }
{
"TEXT FIELDS": {
"SECTION1": {
"First Name": {
"fieldLabel": "First Name",
"aka": "field7",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Middle Name": {
"fieldLabel": "Middle Name",
"aka": "field8",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Surname": {
"fieldLabel": "Surname",
"aka": "field9",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Address": {
"fieldLabel": "Address",
"aka": "field10",
"validation": {
"fieldLength": 100,
"collection": "alphanumeric",
"invalidchar": "`~!$%^*=_[]:\"|\\<>",
"mandatory": false
}
},
"Birthdate": {
"fieldLabel": "Birthate",
"aka": "field5",
"validation": {
"fieldLength": 20,
"collection": "datepicker",
"mandatory": false
}
},
"Civil_Status": {
"fieldLabel": "Civil Status",
"aka": "field28",
"source": "s",
"validation": {
"fieldLength": 15,
"collection": "dropdown",
"options": [
"Single",
"Married",
"Widowed"
],
"mandatory": true
}
},
"Mother's_Name": {
"fieldLabel": "Mother's Name",
"aka": "field31",
"source": "s",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": true
},
"childof": "Civil_Status",
"parentvalue": [
"Single"
]
},
"Spouse_Name": {
"fieldLabel": "Spouse Name",
"aka": "field29",
"source": "s",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": true
},
"childof": "Civil_Status",
"parentvalue": [
"Married",
"Widowed"
]
},
"Date_of_Marriage": {
"fieldLabel": "Date of Marriage",
"aka": "field30",
"source": "s",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": true
},
"childof": "Civil_Status",
"parentvalue": [
"Married",
"Widowed"
]
}
},
"SECTIONNEXT": {
"Name": {
"fieldLabel": "Name",
"aka": "field7",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Subject": {
"fieldLabel": "Subject",
"aka": "field8",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"mandatory": false
}
},
"Document_No": {
"fieldLabel": "Document No",
"aka": "field6",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Date": {
"fieldLabel": "Date",
"aka": "field5",
"validation": {
"fieldLength": 20,
"collection": "datepicker",
"mandatory": false
}
}
}
},
"DATA INPUT": {
"SECTION3": {
"PC Setup": {
"fieldLabel": "PC Setup",
"aka": "field7",
"validation": {
"collection": "image-upload",
"mandatory": false
}
},
"First Name": {
"fieldLabel": "First Name",
"aka": "field7",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Middle Name": {
"fieldLabel": "Middle Name",
"aka": "field8",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Surname": {
"fieldLabel": "Surname",
"aka": "field9",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
}
}
}
}
\ No newline at end of file
...@@ -44,7 +44,7 @@ ...@@ -44,7 +44,7 @@
} }
}, },
"Upload Video": { "Upload Video": {
"fieldLabel": "Upload or Record Video", "fieldLabel": "Capture Image",
"aka": "field7", "aka": "field7",
"validation": { "validation": {
"collection": "video-upload", "collection": "video-upload",
...@@ -156,7 +156,7 @@ ...@@ -156,7 +156,7 @@
} }
}, },
"Upload_Video": { "Upload_Video": {
"fieldLabel": "Upload or Record Video", "fieldLabel": "Capture Image",
"aka": "field7", "aka": "field7",
"validation": { "validation": {
"collection": "video-upload", "collection": "video-upload",
...@@ -186,19 +186,19 @@ ...@@ -186,19 +186,19 @@
"HR FILES": { "HR FILES": {
"SECTION3": { "SECTION3": {
"Upload_Audio": { "Upload_Audio": {
"fieldLabel": "Upload Audio", "fieldLabel": "Capture Selfie",
"aka": "field7", "aka": "field12",
"validation": { "validation": {
"collection": "audio-upload", "collection": "selfie-capture",
"mandatory": true "mandatory": false
} }
}, },
"Upload_Video": { "Upload_Video": {
"fieldLabel": "Upload Video", "fieldLabel": "Capture Image",
"aka": "field7", "aka": "field7",
"validation": { "validation": {
"collection": "video-upload", "collection": "video-upload",
"mandatory": true "mandatory": false
} }
}, },
"Name": { "Name": {
...@@ -217,7 +217,7 @@ ...@@ -217,7 +217,7 @@
"validation": { "validation": {
"fieldLength": 200, "fieldLength": 200,
"collection": "alphanumeric", "collection": "alphanumeric",
"mandatory": true "mandatory": false
} }
}, },
"Employee_No": { "Employee_No": {
......
import { displayField } from "./WebGde-Widgets/DataInputWidget/displayFieldClass.js"; import { displayField } from "./WebGde-Widgets/DataInputWidget/displayFieldClass.js";
import { fetchSchema } from "./WebGde-Widgets/DataInputWidget/fetchSchema.js"; import { fetchSchema } from "./WebGde-Widgets/DataInputWidget/fetchSchema.js";
import { schema } from "./WebGde-Widgets/DataInputWidget/generateFields.js"; import { schema } from "./WebGde-Widgets/DataInputWidget/generateFields.js";
import { DocumentControlWidget } from "./WebGde-Widgets/documentControlWidget/documentControlWidget.js";
// import { DocumentControlWidget } from "./WebGde-Widgets/documentControlWidget/documentControlWidget.js"; // import { DocumentControlWidget } from "./WebGde-Widgets/documentControlWidget/documentControlWidget.js";
import { INDEXED_DB_STORAGE, HIGHLIGHT_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_NAME, INDEXED_DB_TBL_NAME, setIndexedDBStorage, setHighlightObject, setImageViewerObject, setBPOObject, BPO_OBJECT, DISPLAY_FIELD_OBJECT, setDisplayFieldObject, activateGDE, setDocumentControlObject, DOCUMENT_CONTROL_OBJECT, IS_GDE_ACTIVATED } from "./WebGde-Widgets/globalVariable.js"; import { INDEXED_DB_STORAGE, HIGHLIGHT_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_NAME, INDEXED_DB_TBL_NAME, setIndexedDBStorage, setHighlightObject, setImageViewerObject, setBPOObject, BPO_OBJECT, DISPLAY_FIELD_OBJECT, setDisplayFieldObject, activateGDE, setDocumentControlObject, DOCUMENT_CONTROL_OBJECT, IS_GDE_ACTIVATED } from "./WebGde-Widgets/globalVariable.js";
...@@ -18,6 +19,8 @@ async function initializeWebGDE(){ ...@@ -18,6 +19,8 @@ async function initializeWebGDE(){
await createWebGdeInterface(null); await createWebGdeInterface(null);
// setDocumentControlObject(new DocumentControlWidget()); // setDocumentControlObject(new DocumentControlWidget());
// document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget()); // document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget());
setDocumentControlObject(new DocumentControlWidget());
document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget());
removeLoadingScreen(); removeLoadingScreen();
} }
...@@ -48,7 +51,7 @@ async function createInputForm() { ...@@ -48,7 +51,7 @@ async function createInputForm() {
// Instantiate widget and assign it to a container // Instantiate widget and assign it to a container
const displayFieldClass = new displayField(schema, containerId); const displayFieldClass = new displayField(schema, containerId);
// Call Function to generate fields with given schema to provided container // Call Function to generate fields with given schema to provided container
// setDisplayFieldObject(displayFieldClass); setDisplayFieldObject(displayFieldClass);
displayFieldClass.generateFields(); displayFieldClass.generateFields();
// displayFieldClass.editHeader(element-id) // displayFieldClass.editHeader(element-id)
// displayFieldClass.updateHeaderText(0, "User: " + sessionStorage.getItem("user_id")); // displayFieldClass.updateHeaderText(0, "User: " + sessionStorage.getItem("user_id"));
...@@ -127,7 +130,6 @@ function testFunction(){ ...@@ -127,7 +130,6 @@ function testFunction(){
var Nodes=Frm.elements; var Nodes=Frm.elements;
// const myArray = Object.values(metrics); // const myArray = Object.values(metrics);
const lookup = schema[doctype][section] const lookup = schema[doctype][section]
localStorage.setItem("submit", "1");
if (true) { if (true) {
let fields = {}; let fields = {};
......
package com.svi.webgde.restservice.object;
public class Base64UploadRequest {
private String base64Data;
private String fileName;
private String directory;
public String getBase64Data() {
return base64Data;
}
public void setBase64Data(String base64Data) {
this.base64Data = base64Data;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.directory = directory;
}
}
package com.svi.webgde.restservice.services; package com.svi.webgde.restservice.services;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
...@@ -11,6 +13,10 @@ import java.nio.file.Files; ...@@ -11,6 +13,10 @@ import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import javax.json.JsonObject; import javax.json.JsonObject;
...@@ -18,6 +24,7 @@ import javax.ws.rs.Consumes; ...@@ -18,6 +24,7 @@ import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
...@@ -29,6 +36,7 @@ import org.json.simple.JSONObject; ...@@ -29,6 +36,7 @@ import org.json.simple.JSONObject;
import com.opencsv.CSVReader; import com.opencsv.CSVReader;
import com.opencsv.CSVWriter; import com.opencsv.CSVWriter;
import com.svi.webgde.restservice.object.Base64UploadRequest;
import com.svi.webgde.restservice.object.Request; import com.svi.webgde.restservice.object.Request;
import com.svi.webgde.restservice.object.XMLContents; import com.svi.webgde.restservice.object.XMLContents;
import com.svi.webgde.restservice.utils.DBUtil; import com.svi.webgde.restservice.utils.DBUtil;
...@@ -36,6 +44,43 @@ import com.svi.webgde.restservice.utils.XMLUtil; ...@@ -36,6 +44,43 @@ import com.svi.webgde.restservice.utils.XMLUtil;
@Path("/gfs-rest") @Path("/gfs-rest")
public class GDEWebServices { public class GDEWebServices {
private String statusFilePath = "C:\\Users\\oang\\Desktop\\WebGde\\temp\\status.txt";
@GET
@Path("/check-status/{userId}")
public boolean checkStatus(@PathParam("userId") String id) {
Set<String> idsWithTrueStatus = readStatusFile();
if (!idsWithTrueStatus.contains(id)) {
idsWithTrueStatus.add(id);
writeStatusFile(idsWithTrueStatus);
return true;
} else {
return false;
}
}
@GET
@Path("/reset-status/{userId}")
public boolean resetStatus(@PathParam("userId") String id) {
Set<String> idsWithTrueStatus = readStatusFile();
idsWithTrueStatus.remove(id);
writeStatusFile(idsWithTrueStatus);
return true;
}
@GET
@Path("/get-list")
public Response getList() {
JSONObject json = new JSONObject();
Set<String> idsWithTrueStatus = readStatusFile();
for (String string : idsWithTrueStatus) {
json.put(string, true);
}
return Response.ok(json.toString()).build();
}
@GET @GET
@Path("/test-upload") @Path("/test-upload")
...@@ -138,13 +183,30 @@ public class GDEWebServices { ...@@ -138,13 +183,30 @@ public class GDEWebServices {
public Response writeXML(XMLContents xml) { public Response writeXML(XMLContents xml) {
String response = ""; String response = "";
try { try {
File file = new File(xml.getOutputDir()); String filePath = xml.getOutputDir();
int lastSeparatorIndex = filePath.lastIndexOf("/");
if (lastSeparatorIndex == -1) {
lastSeparatorIndex = filePath.lastIndexOf("\\"); // For Windows paths
}
if (lastSeparatorIndex != -1) {
String directoryPath = filePath.substring(0, lastSeparatorIndex);
File directoryFolder = new File(directoryPath);
if (!directoryFolder.exists()) {
directoryFolder.mkdirs();
}
}
File file = new File(filePath);
if (!file.exists()) { if (!file.exists()) {
System.out.println("creating output directory");
response = XMLUtil.generateXML(xml); response = XMLUtil.generateXML(xml);
} else { } else {
response = XMLUtil.udpateXML(xml); response = XMLUtil.udpateXML(xml);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("Fail").build(); return Response.status(500).entity("Fail").build();
} }
return Response.ok(response).build(); return Response.ok(response).build();
...@@ -286,7 +348,8 @@ public class GDEWebServices { ...@@ -286,7 +348,8 @@ public class GDEWebServices {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
} }
// return file contents in blob format with filename in content-disposition header // return file contents in blob format with filename in content-disposition
// header
ResponseBuilder response = Response.ok(file); ResponseBuilder response = Response.ok(file);
response.header("content-disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.header("content-disposition", String.format("attachment; filename=\"%s\"", file.getName()));
return response.build(); return response.build();
...@@ -294,11 +357,13 @@ public class GDEWebServices { ...@@ -294,11 +357,13 @@ public class GDEWebServices {
@POST @POST
@Path("/upload-file") @Path("/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream, public Response uploadFile(Base64UploadRequest request) {
@FormDataParam("fileName") String fileName, String base64Data = request.getBase64Data();
@FormDataParam("directory") String directory) { String fileName = request.getFileName();
String directory = request.getDirectory();
// Sanitize the file name and directory path // Sanitize the file name and directory path
String sanitizedFileName = sanitizeFileName(fileName); String sanitizedFileName = sanitizeFileName(fileName);
String sanitizedDirectory = sanitizeDirectory(directory); String sanitizedDirectory = sanitizeDirectory(directory);
...@@ -313,8 +378,10 @@ public class GDEWebServices { ...@@ -313,8 +378,10 @@ public class GDEWebServices {
directoryFile.mkdirs(); directoryFile.mkdirs();
} }
// Save the file in the specified directory // Decode base64 data and save the file in the specified directory
Files.copy(fileInputStream, Paths.get(finalDirectory, sanitizedFileName)); byte[] fileBytes = java.util.Base64.getDecoder().decode(base64Data);
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
Files.copy(inputStream, Paths.get(finalDirectory, sanitizedFileName));
JSONObject responseJson = new JSONObject(); JSONObject responseJson = new JSONObject();
responseJson.put("status", 200); responseJson.put("status", 200);
...@@ -334,4 +401,28 @@ public class GDEWebServices { ...@@ -334,4 +401,28 @@ public class GDEWebServices {
// Remove special characters, spaces, and directory separators // Remove special characters, spaces, and directory separators
return fileName.replaceAll("[^a-zA-Z0-9.-]", "_"); return fileName.replaceAll("[^a-zA-Z0-9.-]", "_");
} }
private Set<String> readStatusFile() {
try (BufferedReader reader = new BufferedReader(new FileReader(statusFilePath))) {
Set<String> idsWithTrueStatus = new HashSet<>();
String line;
while ((line = reader.readLine()) != null) {
idsWithTrueStatus.add(line);
}
return idsWithTrueStatus;
} catch (IOException e) {
return new HashSet<>();
}
}
private void writeStatusFile(Set<String> idsWithTrueStatus) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(statusFilePath))) {
for (String id : idsWithTrueStatus) {
writer.write(id);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment