Commit 957b4dca by Jhunel Adam Calub

return element bugs fix commit

parent 77429298
......@@ -24,7 +24,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.payara.tools.lib.system">
<classpathentry kind="con" path="fish.payara.eclipse.tools.server.lib.system">
<attributes>
<attribute name="owner.project.facets" value="jst.web"/>
</attributes>
......
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="Payara Server 5 (5.2022.5)"/>
<runtime name="Payara"/>
<fixed facet="jst.web"/>
<fixed facet="java"/>
<fixed facet="wst.jsdt.web"/>
......
......@@ -24,4 +24,5 @@ USERNAME=root
PASSWORD=p455w0rd
[SSO CONFIG]
PUBKEY = C:/Users/oang/git/web-ui-mobile2/WebGde/WebContent/WEB-INF/config/sso/pubkey.pem
\ No newline at end of file
PUBKEY = C:/Users/jcalub/git/web-ui-479/WebGde/WebContent/WEB-INF/config/sso/pubkey.pem
\ No newline at end of file
......@@ -7,13 +7,17 @@ import { interval } from "../captureMetrics/captureMetrics.js";
import { createConfirmationModal, createInfoModal, createModal } from "../genericPopup/genericPopup.js";
import { BPO_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_STORAGE } from "../globalVariable.js";
import { getUrlReturnElement } from "./bpoService.js";
import { returnForm } from "../Submit/submit.js";
export async function returnElementBPO(elementId) {
try {
let response = await fetch(getUrlReturnElement(elementId), { method: "POST" });
if (response.ok) {
// If the response status is 200
console.log("RETURNED")
return { success: true, data: await response.json() };
} else {
// If the response status is not 200
......@@ -28,7 +32,7 @@ export async function returnElementBPO(elementId) {
async function returnElementLogout(elementId) {
let response = await fetch(getUrlReturnElement(elementId), {method: "POST"});
let response = await fetch(getUrlReturnElement(elementId), { method: "POST" });
if (response.status == 200) {
console.log('Element Returned');
......@@ -43,25 +47,25 @@ async function returnElementLogout(elementId) {
function returnSaveXML(){
function returnSaveXML() {
var elementId = sessionStorage.getItem("element_id");
let doctype;
let section;
// Validate all elements again
for(let element of document.getElementById("fields").elements) {
for (let element of document.getElementById("fields").elements) {
if (element.style.display === 'none') continue
const { id, value,type } = element
const { id, value, type } = element
const { valid } = validateInput(id, value)
// Skip submit button
if(type==='submit') continue
if(id==='DocType') {
if (type === 'submit') continue
if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text;
continue;
}
if(id==='Section') {
if (id === 'Section') {
section = element.options[element.selectedIndex].text;
continue;
}
......@@ -74,7 +78,7 @@ function returnSaveXML(){
"userId": sessionStorage.getItem("user_id"),
"elementId": elementId,
"schema": SCHEMA_FILE_PATH,
"totalRec":"1",
"totalRec": "1",
"maxRec": "1",
"totalKeystroke": "",
"procTime": "",
......@@ -97,18 +101,25 @@ function returnSaveXML(){
return false;
}
export function createReturnWindow() {
/*export function createReturnWindow() {
async function returnButtonFunction() {
createLoadingModal("Returning Element", "Returning Element", null, null, null);
let response = await returnElementBPO(sessionStorage.getItem("element_id"));
if (response.success) {
let submitStatus;
submitStatus = await submitForm(e)
if (submitStatus) {
console.log("SUBMITTED")
sessionStorage.removeItem("section");
sessionStorage.removeItem("doctype");
removeLoadingModal();
goBackToElementListViewer();
} else {
console.log("LOL")
}
}else{
function errorReturn(){
} else {
function errorReturn() {
removeLoadingModal();
}
createInfoModal(errorReturn, 'Error', `${response.error} while returning the element.`);
......@@ -116,8 +127,37 @@ export function createReturnWindow() {
}
createConfirmationModal(returnButtonFunction, "Return to Item List Menu?", "Any unsubmitted inputs and items will be lost.");
}*/
export function createReturnWindow() {
async function returnButtonFunction(e) {
createLoadingModal("Returning Element", "Returning Element", null, null, null);
let response = await returnElementBPO(sessionStorage.getItem("element_id"));
if (response.success) {
let submitStatus;
submitStatus = await returnForm(e);
if (submitStatus) {
sessionStorage.removeItem("section");
sessionStorage.removeItem("doctype");
removeLoadingModal();
goBackToElementListViewer();
} else {
sessionStorage.removeItem("section");
sessionStorage.removeItem("doctype");
removeLoadingModal();
}
} else {
function errorReturn() {
removeLoadingModal();
}
createInfoModal(errorReturn, 'Error', `${response.error} while returning the element.`);
}
}
createConfirmationModal(returnButtonFunction, "Return to Item List Menu?", null);
}
function createButtonElem(className, buttonName, icon) {
/* let buttonElem = document.createElement("button"); */
let buttonElem;
......
......@@ -17,10 +17,10 @@ let newOption;
export let schema;
export async function generateFields(inputSchema, containerId) {
if(IS_RETRIEVE_FROM_BPO){
if (IS_RETRIEVE_FROM_BPO) {
let elementId = sessionStorage.getItem("element_id");
window.addEventListener('beforeunload', function (event) {
window.addEventListener('beforeunload', function(event) {
returnElementBPO(elementId);
});
}
......@@ -166,7 +166,7 @@ export async function generateFields(inputSchema, containerId) {
// add handler event handler for dropdown
// separate handler is used to fit with the library used 'select2'
$(document.body).ready(function () {
$(document.body).ready(function() {
// Initialize Select2
const dropdowns = $('.dropdown-input').select2({
focus: false
......@@ -1331,15 +1331,15 @@ const inputChecklist = (key, validation) => {
dropdown1.classList.add('dropdown');
var dropdownContent = document.createElement('div');
dropdownContent.classList.add('dropdown-content');
dropdownContent.setAttribute('id',`checklistContainer_${key}`);
dropdownContent.setAttribute('id', `checklistContainer_${key}`);
dropdown1.appendChild(dropdownContent);
var isOther = false;
// Create the checkboxes for each item
items.forEach(function (item, index) {
if (item.toLowerCase() === "other" || item.toLowerCase() === "others"){
items.forEach(function(item, index) {
if (item.toLowerCase() === "other" || item.toLowerCase() === "others") {
isOther = true;
}else{
} else {
var div = document.createElement('div');
div.classList.add('checkbox');
......@@ -1360,7 +1360,7 @@ const inputChecklist = (key, validation) => {
}
})
if(isOther){
if (isOther) {
// Create the checkbox dependent on an input text value
var dependentDiv = document.createElement('div');
dependentDiv.classList.add('checkbox');
......@@ -1384,7 +1384,7 @@ const inputChecklist = (key, validation) => {
dropdownContent.appendChild(inputTextBox);
// Add event listener to the "other" checkbox
dropdownContent.addEventListener('change', function () {
dropdownContent.addEventListener('change', function() {
if (dependentCheckbox.checked) {
inputTextBox.style.display = 'inline-block';
} else {
......@@ -1399,7 +1399,7 @@ const inputChecklist = (key, validation) => {
});
}
dropdownContent.addEventListener('change', function () {
dropdownContent.addEventListener('change', function() {
const checkboxButtons = document.getElementsByName(`checkboxChoices_${key}`);
checkboxButtons.forEach(checkbox => {
if (checkbox.checked) {
......@@ -1435,15 +1435,15 @@ const inputRadiolist = (key, validation) => {
dropdown1.classList.add('dropdown');
var dropdownContent = document.createElement('div');
dropdownContent.classList.add('dropdown-content');
dropdownContent.setAttribute('id',`dropdownContainer_${key}`);
dropdownContent.setAttribute('id', `dropdownContainer_${key}`);
dropdown1.appendChild(dropdownContent);
var isOther = false;
// Create radio buttons for each item
items.forEach((item, index) => {
if (item.toLowerCase() === "other" || item.toLowerCase() === "others"){
if (item.toLowerCase() === "other" || item.toLowerCase() === "others") {
isOther = true;
}else{
} else {
var radioDiv = document.createElement('div');
radioDiv.classList.add('radio-like-checkbox');
......@@ -1463,7 +1463,7 @@ const inputRadiolist = (key, validation) => {
dropdownContent.appendChild(radioDiv);
}
});
if (isOther){
if (isOther) {
// Create the radio button dependent on an input text value
var dependentDiv = document.createElement('div');
dependentDiv.classList.add('radio-like-checkbox');
......@@ -1486,7 +1486,7 @@ const inputRadiolist = (key, validation) => {
dropdownContent.appendChild(inputTextBox);
// Add event listener to the "other" radio button
dropdownContent.addEventListener('change', function () {
dropdownContent.addEventListener('change', function() {
if (dependentRadio.checked) {
inputTextBox.style.display = 'inline-block';
} else {
......@@ -1502,7 +1502,7 @@ const inputRadiolist = (key, validation) => {
});
}
dropdownContent.addEventListener('change', function () {
dropdownContent.addEventListener('change', function() {
const radioButtons = document.getElementsByName(`radioChoices_${key}`);
radioButtons.forEach(radio => {
if (radio.checked) {
......@@ -1579,7 +1579,7 @@ const inputDropdown = (key, validation) => {
$(input).select2();
$(input).on('select2:select', function (e) {
$(input).on('select2:select', function(e) {
// Get the selected value
var selectedValue = e.params.data.id;
......@@ -1608,7 +1608,7 @@ const inputDropdown = (key, validation) => {
} catch (err) {
throw err;
}
};
};
const inputDbLookup = async (key, validation) => {
......@@ -1805,7 +1805,7 @@ const deconstruct = async (section, container, classAttribute) => {
mandatoryMarker.classList.add('asterisk');
mandatoryMarker.textContent = "*";
if(mandatory){
if (mandatory) {
labelContainer.appendChild(mandatoryMarker)
};
......@@ -1882,7 +1882,7 @@ const deconstruct = async (section, container, classAttribute) => {
input.classList.add(classAttribute)
inputContainer.appendChild(input)
if (hidden && ["geotag", "altitude", "direction"].includes(validation.collection)){
if (hidden && ["geotag", "altitude", "direction"].includes(validation.collection)) {
newField.style.display = 'none'; // Hide the input
newField.classList.add('hidden'); // Add 'hidden' class
}
......@@ -1917,7 +1917,7 @@ const deconstruct = async (section, container, classAttribute) => {
const parentValues = section[element]["parentvalue"];
const childOf = section[element]["childof"];
if(childOf === selectId){
if (childOf === selectId) {
if (parentValues.includes(selectedValue)) {
grandParentInput.style.display = "flex";
childInput.setAttribute("required", "required");
......@@ -1933,12 +1933,12 @@ const deconstruct = async (section, container, classAttribute) => {
//logic for show hide
// get id of element that triggered select
selectElementId.on('select2:select', function (event) {
selectElementId.on('select2:select', function(event) {
selectId = $(this).attr('id');
console.log('select Id:' + selectId);
});
// get value of selected option
selectElement.on('select2:select', function (event) {
selectElement.on('select2:select', function(event) {
selectedValue = event.params.data.id;
console.log('selected value: ' + selectedValue);
showHideElements(section);
......@@ -2162,7 +2162,7 @@ export async function populateFields() {
document.querySelector('#DocType').value = doctype;
sessionStorage.setItem("doctype", doctype);
const docType = $("#DocType");
if(docType[0]){
if (docType[0]) {
for (let i = 0; i < docType[0].options.length; i++) {
if (docType[0].options[i].value == doctype) {
docType[0].options[i].selected = "selected"
......@@ -2173,11 +2173,11 @@ export async function populateFields() {
sessionStorage.setItem("section", section);
document.querySelector('#Section').value = section;
const sectionElem =$("Section");
const sectionElem = $("Section");
for (let i = 0; i < document.getElementById("Section").options.length; i++) {
if (document.getElementById("Section").options[i].value == section) {
document.getElementById("Section").options[i].selected = "selected";
if(sectionElem[0]){
if (sectionElem[0]) {
sectionElem.trigger('change');
}
}
......@@ -2211,69 +2211,69 @@ export async function populateFields() {
for (let key of Object.keys(schema[doctype][section])) {
if (schema[doctype][section][key].aka == "field" + k) {
console.log("key = " + key + +", value ="+v);
console.log("key = " + key + ", value =" + v);
//console.log("validation: " + schema[doctype][section][key].validation.collection);
fields["field" + k] = v;
if (schema[doctype][section][key].hidden){
if (schema[doctype][section][key].hidden) {
document.getElementById(key).value = v;
continue;
}
if(schema[doctype][section][key].validation.collection === 'radiolist'){
if (schema[doctype][section][key].validation.collection === 'radiolist') {
//retrieve the radio button value from the XML
const radioButton = document.querySelector(`#dropdownContainer_${key} input[value="${v}"]`);
if(radioButton){
if (radioButton) {
radioButton.checked = true;
} else {
const radOther1 = document.querySelector(`#dropdownContainer_${key} input[value="other"]`);
if(radOther1){
if (radOther1) {
radOther1.checked = true;
}
const radOther2 = document.querySelector(`#dropdownContainer_${key} input[value="others"]`);
if(radOther2){
if (radOther2) {
radOther2.checked = true;
}
document.getElementById(`dependentTB_${key}`).value = v;
document.getElementById(`dependentTB_${key}`).style.display = 'inline-block';
}
} else if(schema[doctype][section][key].validation.collection === 'checklist') {
} else if (schema[doctype][section][key].validation.collection === 'checklist') {
const checklistArrayValues = v.split(",");
let otherValues = "";
let isFirstCheckboxOtherValue = true;
let checkboxOtherValue = "";
for(let checklistValue of checklistArrayValues){
for (let checklistValue of checklistArrayValues) {
console.log("Array Values: " + checklistValue);
const checklistbox = document.querySelector(`#checklistContainer_${key} input[value="${checklistValue}"]`);
if(checklistbox){
if (checklistbox) {
checklistbox.checked = true;
if(checklistValue === "other" || checklistValue === "others"){
if (checklistValue === "other" || checklistValue === "others") {
checkboxOtherValue = checklistValue;
document.getElementById(`dependentTB_${key}`).value = checkboxOtherValue;
document.getElementById(`dependentTB_${key}`).style.display = 'inline-block';
isFirstCheckboxOtherValue = false;
}
} else {
if(isFirstCheckboxOtherValue){
if (isFirstCheckboxOtherValue) {
checkboxOtherValue = checklistValue;
isFirstCheckboxOtherValue = false;
} else{
} else {
checkboxOtherValue = checkboxOtherValue + "," + checklistValue;
}
const checkOther1 = document.querySelector(`#checklistContainer_${key} input[value="other"]`);
if(checkOther1){
if (checkOther1) {
console.log("checkOther1 checked");
checkOther1.checked = true;
}
const checkOther2 = document.querySelector(`#checklistContainer_${key} input[value="others"]`);
if(checkOther2){
if (checkOther2) {
console.log("checkOther2 checked");
checkOther2.checked = true;
}
......@@ -2282,7 +2282,105 @@ export async function populateFields() {
document.getElementById(`dependentTB_${key}`).style.display = 'inline-block';
}
}
} else{
} else if (schema[doctype][section][key].validation.collection === 'image-capture') {
let fileSizeStr;
const endpointUrl = sessionStorage.getItem('gde_domain') + "svc/gfs-rest/fetch-local";
const elementFileLoc = sessionStorage.getItem('element_file_loc');
const filePath = `file://${elementFileLoc}/${v}`;
// JSON payload
const payload = {
"dir": filePath
};
// Bearer token from sessionStorage
const token = sessionStorage.getItem('token');
// Headers
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
// Fetch options
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
};
// Make the fetch request
fetch(endpointUrl, options)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const contentDisposition = response.headers.get('content-disposition');
const fileSizeMatch = /size="([^"]+)"/.exec(contentDisposition);
fileSizeStr = fileSizeMatch ? fileSizeMatch[1] : null;
return response.blob();
})
.then(blobData => {
let blobUrl = URL.createObjectURL(blobData);
var img = document.getElementById(key + '_zz');
img.src = blobUrl;
processCapture(key, v, fileSizeStr);
})
.catch(error => {
console.error('Fetch error:', error);
});
} else if (schema[doctype][section][key].validation.collection === 'fingerprint') {
const endpointUrl = sessionStorage.getItem('gde_domain') + "svc/gfs-rest/fetch-local";
const elementFileLoc = sessionStorage.getItem('element_file_loc');
const filePath = `file://${elementFileLoc}/${v}`;
// JSON payload
const payload = {
"dir": filePath
};
// Bearer token from sessionStorage
const token = sessionStorage.getItem('token');
// Headers
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
// Fetch options
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
};
// Make the fetch request
fetch(endpointUrl, options)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.blob();
})
.then(blobData => {
let blobUrl = URL.createObjectURL(blobData);
var img = document.getElementById(key + '_zz');
img.src = blobUrl;
processFingerprint(key, v);
})
.catch(error => {
console.error('Fetch error:', error);
});
} else {
document.getElementById(key).value = v;
}
continue;
......
......@@ -16,17 +16,17 @@ export const validateInput = (fieldID, value) => {
try {
const { valid, error } = validateSchema()
if(!valid) return { valid: false, error: [`${error}`]}
if (!valid) return { valid: false, error: [`${error}`] }
const validation = getValidation(fieldID)
if(!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] }
if (!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] }
// Skip validation for hidden fields
if (isFieldHidden(fieldID)){
if (isFieldHidden(fieldID)) {
return { valid: true };
}
switch(validation.collection) {
switch (validation.collection) {
case 'email':
return validateEmail(validation, value)
case 'alphanumeric':
......@@ -56,12 +56,64 @@ export const validateInput = (fieldID, value) => {
case 'checklist':
return validateChecklist(validation, fieldID);
default:
return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`]}
return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`] }
}
} catch(err) {
return { valid: false, error: [err]}
} catch (err) {
return { valid: false, error: [err] }
}
}
export const validateReturnInput = (fieldID, value) => {
try {
const { valid, error } = validateSchema()
if (!valid) return { valid: false, error: [`${error}`] }
const validation = getValidation(fieldID)
if (!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] }
// Skip validation for hidden fields
if (isFieldHidden(fieldID)) {
return { valid: true };
}
console.log(validation.collection)
switch (validation.collection) {
case 'email':
return validateReturnEmail(validation, value)
case 'alphanumeric':
return validateReturnAlphanumeric(validation, value)
case 'alphabet':
return validateReturnAlphabet(validation, value)
case 'specific':
case 'dropdown':
return validateReturnSpecific(validation, value)
case 'numeric':
return validateReturnNumeric(validation, value)
case 'timepicker':
case 'daterange':
case 'datepicker':
case 'date':
// console.log('date')
return validateReturnDate(validation, value)
case 'image-capture':
case 'video-capture':
case 'fingerprint':
case 'file-upload':
return validateReturnMedia(validation, fieldID);
case 'radiolist':
return validateReturnRadio(validation, fieldID);
case 'checklist':
return validateReturnChecklist(validation, fieldID);
default:
return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`] }
}
} catch (err) {
return { valid: false, error: [err] }
}
}
/**
*
* @param {*} fieldID
......@@ -73,13 +125,29 @@ const validateEmail = (validation, value) => {
const PATTERN_EMAIL = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
let errors = []
const { mandatory, fieldLength } = validation
if(!mandatory && value.length===0) return { valid: true, errors: ['Field is required'] }
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if(!value.match(PATTERN_EMAIL)) errors = [...errors, 'Please input valid email address.']
if (!mandatory && value.length === 0) return { valid: true, errors: ['Field is required'] }
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (!value.match(PATTERN_EMAIL)) errors = [...errors, 'Please input valid email address.']
return {
valid: errors.length === 0,
errors
}
}
const validateReturnEmail = (validation, value) => {
const PATTERN_EMAIL = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
let errors = []
const { fieldLength } = validation
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (value && !value.match(PATTERN_EMAIL)) {
errors = [...errors, 'Please input a valid email address.'];
}
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
}
}
......@@ -93,13 +161,13 @@ const validateEmail = (validation, value) => {
export const getValidation = (fieldID) => {
// const { SECTION } = schema
let section = schema[sessionStorage.getItem("currentDoctype").replaceAll("_"," ")][sessionStorage.getItem("currentSection").replaceAll("_"," ")];
let section = schema[sessionStorage.getItem("currentDoctype").replaceAll("_", " ")][sessionStorage.getItem("currentSection").replaceAll("_", " ")];
try{
try {
if (Object.keys(section).includes(fieldID)) return section[fieldID].validation;
return null;
} catch(err) {
} catch (err) {
return null
}
}
......@@ -120,22 +188,46 @@ const validateAlphanumeric = (validation, value) => {
const { mandatory, fieldLength, invalidchar } = validation
try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters']
if(invalidchar) {
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters']
if (invalidchar) {
// method for escaping characters
// source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escaped_pattern = invalidchar.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&')
const pattern = new RegExp(`[${escaped_pattern}]`)
if (pattern.test(value)) errors = [...errors, 'Has invalid character(s).']
}
return {
valid: errors.length === 0,
errors
}
} catch (err) {
throw err
}
}
const validateReturnAlphanumeric = (validation, value) => {
let errors = []
const { fieldLength, invalidchar } = validation
try {
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters']
if (invalidchar) {
// method for escaping characters
// source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escaped_pattern = invalidchar.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&')
const pattern = new RegExp(`[${escaped_pattern}]`)
if(pattern.test(value)) errors = [...errors, 'Has invalid character(s).']
if (pattern.test(value)) errors = [...errors, 'Has invalid character(s).']
}
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
}
} catch(err) {
} catch (err) {
throw err
}
}
......@@ -155,12 +247,25 @@ const validateAlphabet = (validation, value) => {
const PATTERN_ALPHABET = /[^A-Za-z\s]/g
let errors = []
const { mandatory, fieldLength } = validation
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if(PATTERN_ALPHABET.test(value)) errors = [...errors, 'Has invalid character(s).']
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (PATTERN_ALPHABET.test(value)) errors = [...errors, 'Has invalid character(s).']
return {
valid: errors.length === 0,
errors
}
}
const validateReturnAlphabet = (validation, value) => {
const PATTERN_ALPHABET = /[^A-Za-z\s]/g
let errors = []
const { fieldLength } = validation
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (PATTERN_ALPHABET.test(value)) errors = [...errors, 'Has invalid character(s).']
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
}
}
......@@ -182,15 +287,33 @@ const validateNumeric = (validation, value) => {
const { mandatory, fieldLength } = validation
try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if(PATTERN_NUMERIC.test(value)) errors = [...errors, 'Has invalid character(s).']
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (PATTERN_NUMERIC.test(value)) errors = [...errors, 'Has invalid character(s).']
return {
valid: errors.length === 0,
errors
}
} catch (err) {
throw err
}
}
const validateReturnNumeric = (validation, value) => {
const PATTERN_NUMERIC = /[^0-9/-]/g
let errors = []
const { fieldLength } = validation
try {
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (PATTERN_NUMERIC.test(value)) errors = [...errors, 'Has invalid character(s).']
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
}
} catch(err) {
} catch (err) {
throw err
}
}
......@@ -209,15 +332,28 @@ const validateNumeric = (validation, value) => {
const validateDateRange = (validation, value) => {
const { mandatory, regexformat } = validation
try{
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
try {
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
return { valid: true }
} catch (err) {
throw err
}
}
const validateReturnDateRange = (validation, value) => {
try {
if ((value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Does not match required format'] }
return { valid: true }
} catch(err) {
} catch (err) {
throw err
}
}
/**
*
* @param {*} validation
......@@ -232,9 +368,58 @@ const validateDateRange = (validation, value) => {
const validateDate = (validation, value) => {
const { mandatory, regexformat, validdate } = validation
try{
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(validdate!=""){
try {
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if (validdate != "") {
if (value.length === 0) {
return { valid: true };
}
const enteredDateParts = value.split('-');
if (enteredDateParts.length !== 3) {
return { valid: false, errors: ['Invalid date format.'] };
}
const enteredYear = parseInt(enteredDateParts[0]);
const enteredMonth = parseInt(enteredDateParts[1]) - 1; // Months are 0-based
const enteredDay = parseInt(enteredDateParts[2]);
const enteredDate = new Date(enteredYear, enteredMonth, enteredDay);
const currentDate = new Date();
console.log(currentDate);
switch (validdate) {
case "past":
if (enteredDate < currentDate) {
return { valid: true }; // The date is in the past
} else {
return { valid: false, errors: ['Only past dates are allowed.'] };
}
case "current":
if (enteredDate = currentDate) {
return { valid: true }; // The date is today
} else {
return { valid: false, errors: ['Only current date is allowed.'] };
}
case "future":
if (enteredDate > currentDate) {
return { valid: true }; // The date is in the future
} else {
return { valid: false, errors: ['Only future dates are allowed.'] };
}
}
}
return { valid: true }
} catch (err) {
throw err
}
}
const validateReturnDate = (validation, value) => {
const { validdate } = validation
try {
if (validdate != "") {
if (value.length === 0) {
return { valid: true };
}
......@@ -251,7 +436,7 @@ const validateDate = (validation, value) => {
const currentDate = new Date();
console.log(currentDate);
switch(validdate){
switch (validdate) {
case "past":
if (enteredDate < currentDate) {
return { valid: true }; // The date is in the past
......@@ -274,7 +459,7 @@ const validateDate = (validation, value) => {
}
return { valid: true }
} catch(err) {
} catch (err) {
throw err
}
}
......@@ -293,11 +478,22 @@ const validateDate = (validation, value) => {
const validateTime = (validation, value) => {
const { mandatory, regexformat } = validation
try{
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
try {
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
return { valid: true }
} catch (err) {
throw err
}
}
const validateReturnTime = (validation, value) => {
try {
if ((value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Does not match required format'] }
return { valid: true }
} catch(err) {
} catch (err) {
throw err
}
}
......@@ -319,17 +515,25 @@ const validateSpecific = (validation, value) => {
const { mandatory, validchars, options } = validation
try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required'] }
if(validchars && validchars.includes(value)) return { valid: true }
if(options && options.includes(value)) return {valid: true }
if(!mandatory) return { valid: true }
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required'] }
if (validchars && validchars.includes(value)) return { valid: true }
if (options && options.includes(value)) return { valid: true }
if (!mandatory) return { valid: true }
return { valid: false, errors: ['No option selected.'] }
} catch(err) {
} catch (err) {
throw err
}
}
const validateReturnSpecific = (validation, value) => {
let errors = [];
return {
valid: errors.length === 0,
errors
}
}
/**
*
* @param {*} validation
......@@ -360,7 +564,16 @@ const validateMedia = (validation, fieldID) => {
errors = [...errors, 'No File Attached.']
}
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
};
}
const validateReturnMedia = (validation, fieldID) => {
let errors = [];
return {
valid: errors.length === 0,
errors
};
}
......@@ -381,7 +594,7 @@ const validateRadio = (validation, fieldID) => {
const { mandatory } = validation
const radioButtons = document.getElementsByName(`radioChoices_${fieldID}`);
if (mandatory){
if (mandatory) {
let isChecked;
radioButtons.forEach(radio => {
if (radio.checked) {
......@@ -394,7 +607,16 @@ const validateRadio = (validation, fieldID) => {
}
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
};
}
const validateReturnRadio = (validation, fieldID) => {
let errors = [];
return {
valid: errors.length === 0,
errors
};
}
......@@ -415,7 +637,7 @@ const validateChecklist = (validation, fieldID) => {
const { mandatory } = validation
const checkboxButtons = document.getElementsByName(`checkboxChoices_${fieldID}`);
if (mandatory){
if (mandatory) {
let isChecked;
checkboxButtons.forEach(checkbox => {
if (checkbox.checked) {
......@@ -428,7 +650,16 @@ const validateChecklist = (validation, fieldID) => {
}
return {
valid: errors.length===0,
valid: errors.length === 0,
errors
};
}
const validateReturnChecklist = (validation, fieldID) => {
let errors = [];
return {
valid: errors.length === 0,
errors
};
}
......@@ -437,9 +668,9 @@ export const checkValidValues = (fieldID, value) => {
try {
const validation = getValidation(fieldID);
if(!validation) return { isValidValue: false, errMsg: [`FieldName: '${fieldID}' not in schema`] };
if (!validation) return { isValidValue: false, errMsg: [`FieldName: '${fieldID}' not in schema`] };
if(typeof validation.validvalues !== "undefined") {
if (typeof validation.validvalues !== "undefined") {
let validValues = validation.validvalues;
const result = validValues.findIndex(item => value.toUpperCase() === item.toUpperCase());
......@@ -451,8 +682,8 @@ export const checkValidValues = (fieldID, value) => {
}
}
return { isValidValue: true };
} catch(err) {
return { isValidValue: false, errMsg: [err]}
} catch (err) {
return { isValidValue: false, errMsg: [err] }
}
}
......@@ -465,4 +696,4 @@ function isFieldHidden(key) {
}
}
return false;
}
\ No newline at end of file
}
\ No newline at end of file
......@@ -2,7 +2,7 @@ import { initializeWebpage } from "../../startup.js";
import { initializeConfig } from "../config.js";
import { createInfoModal } from "../genericPopup/genericPopup.js";
export function loginGde(token){
export function loginGde(token) {
sessionStorage.setItem("token", token);
var decodedToken = parseJwt(token);
......@@ -14,10 +14,11 @@ export function loginGde(token){
console.log("Preferred Username:", preferred_username);
sessionStorage.setItem("user_id", preferred_username);
console.log("Domain:", gde_domain);
sessionStorage.setItem("gde_domain", gde_domain);
console.log("Bpo Domain:", gde_bpo_domain);
console.log("Node:", gde_bpo_node);
initializeConfig(gde_domain, gde_bpo_domain, gde_bpo_node);
createInfoModal(null, "OK", "Success! Logged in as "&preferred_username);
createInfoModal(null, "OK", "Success! Logged in as " & preferred_username);
initializeWebpage();
// You can return these values or perform any other actions with them here
......@@ -27,13 +28,13 @@ export function loginGde(token){
}
}
export function fallbackLogin(user_id, gde_domain, bpo_domain, node){
export function fallbackLogin(user_id, gde_domain, bpo_domain, node) {
sessionStorage.setItem("user_id", user_id);
initializeConfig(gde_domain, bpo_domain, node);
initializeWebpage();
}
function parseJwt (token) {
function parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
......
import { getUrlCompleteToNextNode } from "../BPO/bpoService.js";
import { saveForm } from "../DataInputWidget/generateFields.js";
import { checkValidValues, validateInput } from "../DataInputWidget/validateInput.js";
import { checkValidValues, validateInput, validateReturnInput } from "../DataInputWidget/validateInput.js";
import { goBackToElementListViewer } from "../ElementListWidget/ElementListWidget.js";
import { uploadFile } from "../FileUpload/fileUpload.js";
import { createLoadingModal, removeLoadingModal } from "../LoadingModal/LoadingModal.js";
......@@ -53,6 +53,7 @@ export const submitForm = async (e) => {
const { valid, errors } = validateInput(id, value)
var { isValidValue, errMsg } = checkValidValues(id, value);
console.log(valid + " " + errors + " " + isValidValue + " " + errMsg)
if (typeof errMsg !== "undefined") {
errorMsg = errMsg;
......@@ -65,15 +66,15 @@ export const submitForm = async (e) => {
if (type === 'select-one') {
continue
}
if (type === 'button'){
if (type === 'button') {
errorContainer.innerHTML = errors;
continue
}
if (type === 'radio'){
if (type === 'radio') {
errorContainer.innerHTML = errors;
continue
}
if (type === 'checkbox'){
if (type === 'checkbox') {
errorContainer.innerHTML = errors;
continue
}
......@@ -94,7 +95,7 @@ export const submitForm = async (e) => {
}
// TO-DO Separate validation for attached media (Image, Video, File)
for (let key of keys){
for (let key of keys) {
const inputElement = document.getElementById(`${key}_attachedMedia`);
if (inputElement.files.length === 0) {
console.log(key + " empty");
......@@ -120,12 +121,12 @@ export const submitForm = async (e) => {
}
else {
if(IS_RETRIEVE_FROM_BPO === "N"){
if (IS_RETRIEVE_FROM_BPO === "N") {
let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form);
if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER +"/"+ folderName
let folderPath = TEMPORARY_FOLDER + "/" + folderName
let filePath = { "filePath": folderPath + "/" + sessionStorage.getItem("recentlySavedFileName") };
console.log(filePath);
const authToken = sessionStorage.getItem('token');
......@@ -143,12 +144,12 @@ export const submitForm = async (e) => {
createInfoModal(null, 'OK', 'Error while generating output.');
return false
}
}else {
} else {
let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form);
if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER +"/"+ folderName
let folderPath = TEMPORARY_FOLDER + "/" + folderName
let filePath = { "filePath": sessionStorage.getItem("element_file_loc") };
console.log(filePath);
const authToken = sessionStorage.getItem('token');
......@@ -174,17 +175,179 @@ export const submitForm = async (e) => {
}
}
export async function createSubmitWindow(e){
export const returnForm = async (e) => {
try {
setGlobalEndTime(new Date().toLocaleString());
const Form = document.getElementById("fields");
const { elements } = Form
let error = false;
let errorMsg = null;
let doctype;
let section;
let keys = [];
// Validate all elements again
for (let element of elements) {
if (element.style.display === 'none' || element.classList.contains('hidden')) {
continue;
}
const { id, value, type, name } = element
const errorContainer = document.getElementById(`${id}_error`);
// Skip submit, buttons, and files
if (element.classList.contains('radioOther') || element.classList.contains('checkboxOther')) continue;
if (element.classList.contains('geotag') || element.classList.contains('altitude') || element.classList.contains('direction')) {
continue;
}
if (type === 'submit') continue
if (type === 'file') continue
if (type === 'hidden') continue
if (element.classList.contains('radioOption') && id.length === 0) continue
if (element.classList.contains('checkboxOption') && id.length === 0) continue
if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text;
continue;
}
if (id === 'Section') {
section = element.options[element.selectedIndex].text;
continue;
}
const { valid, errors } = validateReturnInput(id, value)
/* var { isValidValue, errMsg } = checkValidValues(id, value);*/
console.log(valid + " " + errors);
/* if (typeof errMsg !== "undefined") {
errorMsg = errMsg;
}
*/
// Update display of input field if input is not valid
if (!valid) {
console.log(element);
error = true
if (type === 'select-one') {
continue
}
if (type === 'button') {
errorContainer.innerHTML = errors;
continue
}
if (type === 'radio') {
errorContainer.innerHTML = errors;
continue
}
if (type === 'checkbox') {
errorContainer.innerHTML = errors;
continue
}
const field = document.getElementById(id)
const newEvent = new Event('focusout')
field.dispatchEvent(newEvent)
}
/* if (!isValidValue) {
error = true
const field = document.getElementById(id);
field.classList.remove('input-valid');
field.classList.add('input-invalid');
errorContainer.innerHTML = errors;
field.select();
}*/
}
// TO-DO Separate validation for attached media (Image, Video, File)
for (let key of keys) {
const inputElement = document.getElementById(`${key}_attachedMedia`);
if (inputElement.files.length === 0) {
console.log(key + " empty");
let emptyMedia = document.getElementsByClassName(key);
console.log(emptyMedia[0]);
}
}
// Update display of dropdown field if input is not valid
const dropdowns = $('.dropdown-input').select2();
for (let dropdown of dropdowns) {
const newEvent = new Event('select2:close')
dropdown.dispatchEvent(newEvent)
}
if (error) {
if (errorMsg !== null) {
createErrorModal(null, 'Return', errorMsg);
} else {
createErrorModal(null, 'Return', 'Invalid or Missing data on highlighted fields!');
}
return
}
else {
if (IS_RETRIEVE_FROM_BPO === "N") {
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);
const authToken = sessionStorage.getItem('token');
let getFile = await fetch(urlGetFile, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(filePath)
});
console.log(getFile.text());
// await uploadTOGFS(getFile.text(), sessionStorage.getItem("recentlySavedFileName"));
} else {
createInfoModal(null, 'OK', 'Error while generating output.');
return false
}
} else {
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": sessionStorage.getItem("element_file_loc") };
console.log(filePath);
const authToken = sessionStorage.getItem('token');
let getFile = await fetch(urlGetFile, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(filePath)
});
} else {
createInfoModal(null, 'OK', 'Error while generating output.');
return false
}
}
// saveForm(sessionStorage.getItem("display_counter"));
}
return true
} catch (err) {
console.log(err)
return false
}
}
export async function createSubmitWindow(e) {
let submitStatus;
async function okButtonFunction() {
createLoadingModal("Submitting Element", "Please wait...", null, null, null);
submitStatus = await submitForm(e);
if(submitStatus){
if (submitStatus) {
removeLoadingModal();
DISPLAY_FIELD_OBJECT.clearForm();
if (SHOW_ELEMENT_LIST_VIEWER === "Y") {
console.log("PUMASOK DITO");
createInfoModal(goBackToElementListViewer, 'ok', 'Form Submitted.');
} else {
createInfoModal(null, 'ok', 'Form Submitted.');
......@@ -192,7 +355,7 @@ export async function createSubmitWindow(e){
if (IS_RETRIEVE_FROM_BPO === "Y") {
let response = await completeToNextNode(sessionStorage.getItem("element_id"));
}
} else{
} else {
removeLoadingModal();
}
};
......@@ -200,7 +363,7 @@ export async function createSubmitWindow(e){
return createConfirmationModal(okButtonFunction, "Submit Element?");
}
function validateMedia(key){
function validateMedia(key) {
const inputElement = document.getElementById(`${key}_attachedMedia`);
if (inputElement.files.length === 0) {
console.log(key + " empty");
......@@ -230,23 +393,23 @@ export async function completeToNextNode(elementId) {
return response;
}
export async function batchUpload(Form){
export async function batchUpload(Form) {
let Nodes = Form.elements;
let file;
let fileName;
let folderName;
let directory;
if(IS_RETRIEVE_FROM_BPO==="N"){
if (IS_RETRIEVE_FROM_BPO === "N") {
folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
directory = TEMPORARY_FOLDER + "/" + folderName
} else{
} else {
directory = sessionStorage.getItem("element_file_loc")
}
for (var i=0;i<Nodes.length;i++){
if (Nodes[i].name === 'hidden_file_content'){
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){
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) {
......@@ -260,15 +423,15 @@ export async function batchUpload(Form){
}
async function uploadTOGFS(stream, filename){
await checkIfFolderExists(GFS_ROOT_FOLDER+"/"+sessionStorage.getItem("user_id"), "uploads");
await checkIfFolderExists(GFS_ROOT_FOLDER+"/"+sessionStorage.getItem("user_id")+"/uploads", PROJECT_CODE);
async function uploadTOGFS(stream, filename) {
await checkIfFolderExists(GFS_ROOT_FOLDER + "/" + sessionStorage.getItem("user_id"), "uploads");
await checkIfFolderExists(GFS_ROOT_FOLDER + "/" + sessionStorage.getItem("user_id") + "/uploads", PROJECT_CODE);
let xml = new File([stream], filename, {type: "text/plain"});
let xml = new File([stream], filename, { type: "text/plain" });
let formData = new FormData();
formData.append("file", xml);
formData.append("parentPath", GFS_ROOT_FOLDER+"/"+sessionStorage.getItem("user_id")+ "/uploads/"+PROJECT_CODE);
formData.append("parentPath", GFS_ROOT_FOLDER + "/" + sessionStorage.getItem("user_id") + "/uploads/" + PROJECT_CODE);
formData.append("extraData", "{}");
formData.append("remarks", "Non-BPO Upload");
formData.append("description", "");
......@@ -290,8 +453,8 @@ async function uploadTOGFS(stream, filename){
console.log(response);
}
async function checkIfFolderExists(parentPath, folderName ){
let url = GFS_URL + "check-folder?" + new URLSearchParams({folderPath: parentPath+"/"+folderName , isSudo: false });
async function checkIfFolderExists(parentPath, folderName) {
let url = GFS_URL + "check-folder?" + new URLSearchParams({ folderPath: parentPath + "/" + folderName, isSudo: false });
let response = await fetch(url, {
method: "GET",
headers: {
......@@ -301,7 +464,7 @@ async function checkIfFolderExists(parentPath, folderName ){
let result = response.json;
if(result !== null && result.isExists === false){
if (result !== null && result.isExists === false) {
let createObj = {
"folderName": folderName,
"parentPath": parentPath,
......@@ -318,7 +481,7 @@ async function checkIfFolderExists(parentPath, folderName ){
}
async function createGFSFolder(jsonObj){
async function createGFSFolder(jsonObj) {
let response = await fetch(GFS_URL + "add-folder", {
method: "PUT",
headers: {
......
......@@ -10,6 +10,24 @@
"mandatory" : true
}
},
"capture_location_clearance_photo" : {
"fieldLabel" : "Capture Locational Clearance Photo",
"aka" : "field75",
"validation" : {
"fieldLength" : 1.0,
"collection" : "image-capture",
"mandatory" : true
}
},
"fingerprint" : {
"fieldLabel" : "Fingerprint",
"aka" : "field76",
"validation" : {
"fieldLength" : 1.0,
"collection" : "fingerprint",
"mandatory" : true
}
},
"registered_owner" : {
"fieldLabel" : "Registered Owner",
"aka" : "field3",
......
......@@ -429,10 +429,25 @@ public class GDEWebServices {
return Response.status(Response.Status.NOT_FOUND).build();
}
// return file contents in blob format with filename in content-disposition
// header
// Get file size
long size = file.length();
String[] units = { "B", "KB", "MB", "GB", "TB" };
int unitIndex = 0;
double fileSize = size;
while (fileSize > 1024 && unitIndex < units.length - 1) {
fileSize /= 1024;
unitIndex++;
}
String fileSizeStr = String.format("%.2f %s", fileSize, units[unitIndex]);
// return file contents in blob format with filename and filesize in
// content-disposition header
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\"; size=\"%s\"", file.getName(), fileSizeStr));
return response.build();
}
......
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