Summary Table

Categories Total Count
PII 0
URL 8
DNS 9
EKL 0
IP 0
PORT 8
VsID 0
CF 0
AI 0
VPD 0
PL 0
Other 0

File Content

package gov.va.med.ewv.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import gov.va.med.ars.constants.ErrorMessages;
import gov.va.med.ars.dao.ewv.IEwvPdfReferenceRepository;
import gov.va.med.ars.exceptions.GenericException;
import gov.va.med.domain.ewv.EwvReferences;
import gov.va.med.ewv.bean.ArchivedPdfReference;
import gov.va.med.ewv.model.response.EwdPdfReferencesFileArchiveResponse;
import gov.va.med.ewv.model.response.EwdPdfReferencesFileUploadResponse;
import gov.va.med.ewv.model.response.EwvPdfReferencesResponse;
import gov.va.med.ewv.service.IEwvPdfReferenceService;
import gov.va.med.ewv.util.PdfReference;

/**
* Implements all the methods needed to get, create, update, and delete the PDF References
* in the database.
*
* @author
DNS
*
*/
@Service
public class EwvPdfReferenceServiceImpl implements IEwvPdfReferenceService {

/**
* Contains information about the server environment. It's used in this Controller to get the
* Destination Directory where File contents will be saved.
*/
@Autowired
Environment env;

/**
* JPA Repository sub-interface used to get, update, and add information in the
* EWV_REFERENCES table of the EWV database.
*/
/*@Autowired
IEwvPdfReferenceRepository ewvPdfReferenceRepository;*/

@Autowired
IEwvPdfReferenceRepository ewvPdfReferenceRepository;

private static final Logger logger = LogManager.getLogger(EwvPdfReferenceServiceImpl.class);

/**
* Gets all the PDF References that are in the database.
*
* @return - the Web Service Response for all the PDF References that are in the database
* @throws GenericException - thrown if any type of Exception occurs
*/
@Override
public EwvPdfReferencesResponse getAllPdfReferences() throws GenericException {
EwvPdfReferencesResponse pdfReferencesResponse = new EwvPdfReferencesResponse();

logger.info("Inside of \"getAllPdfReferences\" method");

try {
List <PdfReference> pdfReferencesList = getRealAllPdfReferences();
pdfReferencesResponse.setPdfReferencesList(pdfReferencesList);
} catch (Throwable e) {
String errorDescription = "Getting of all the PDF References failed with exception : " + e;
logger.error(errorDescription);
throw new GenericException("ERROR", errorDescription, HttpStatus.BAD_REQUEST);
}

logger.info("Returning the EwvPdfReferencesResponse: " + pdfReferencesResponse);
return pdfReferencesResponse;
}

/**
* Inserts a PDF Reference into the database having the information as in the given
* "ewvReferences" input parameter.
*
* The method will do the following:
* 1) Check for valid inputs. The following constitutes invalid inputs and an Exception will be thrown
* for any of the following invalid inputs:
* a) "ewvReferences" is null
* b) Reference Name of "ewvReferences" is null
* c) Reference Name of "ewvReferences" is an empty string or is composed of spaces
* d) Reference File Name of "ewvReferences" is null
* e) Reference File Name of "ewvReferences" is an empty string or is composed of spaces
* f) An un-archived PDF Reference exists in the database that has the same Reference Name (Trimmed)
* value of "ewvReferences"
* g) An un-archived PDF Reference exists in the database that has the same Reference File Name (Trimmed)
* value of "ewvReferences" input
* 2) Sets the "guid" value of "ewvReferences" to null
* 3) Sets the "archive" value to "false", since only un-archived PDF References will be permitted to be
* inserted into the database
* 4) Trims the Reference Name and Reference File Name values of the "ewvReferences" input
* 5) Inserts a PDF Reference into the database from the information in the "ewvReference" input parameter
*
* @param ewvReferences - the input parameter that contains the PDF References information to be inserted
* into the database
* @param commitToDatabase - boolean flag to indicate if the insert should be committed to the database;
* boolean "true" means to commit to the database;
* boolean "false" means to NOT commit to the database
*
* @return - a reference to the EwvRefernces object inserted into the database; it will have the information that
* was stored in the database including the unique non-null "guid" value.
*
* @throws Exception - an Exception is throws in one of the following scenarios:
* 1) The "ewvReferences" input parameter has invalid input value(s)
* 2) Insert of PDF Reference into the database was not successful
*/
private EwvReferences insertPdfReference(EwvReferences ewvReferences) throws Exception {
EwvReferences insertedEwvReferences = null;

if (ewvReferences == null) {
throw new Exception("Null argument fed into \"EwvPdfReferenceServiceImpl.insertPdfReference\" method!");
}

if (ewvReferences.getReferenceName() == null) {
throw new Exception("Null Reference Name fed into \"EwvPdfReferenceServiceImpl.insertPdfReference\" method!");
}

if (ewvReferences.getReferenceName().trim().isEmpty()) {
throw new Exception("Reference Name fed into \"EwvPdfReferenceServiceImpl.insertPdfReference\" method has only empty spaces or is an empty string!");
}

if (ewvReferences.getReferenceFileName() == null) {
throw new Exception("Null Reference File Name fed into \"EwvPdfReferenceServiceImpl.insertPdfReference\" method!");
}

if (ewvReferences.getReferenceFileName().trim().isEmpty()) {
throw new Exception("Reference File Name fed into \"EwvPdfReferenceServiceImpl.insertPdfReference\" method has only empty spaces or is an empty string!");
}

logger.info("calling ewvPdfReferenceRepository.findByReferenceNameAndArchive()");
List<EwvReferences> ewvReferencesList = ewvPdfReferenceRepository.findByReferenceNameAndArchive(
ewvReferences.getReferenceName(), ewvReferences.getArchive());
if (ewvReferencesList != null && !ewvReferencesList.isEmpty()) {
throw new Exception("Attempt to insert already existing PDF Reference that has the same Reference Name!");
}

logger.info("calling ewvPdfReferenceRepository.findByReferenceFileNameAndArchive()");
ewvReferencesList = ewvPdfReferenceRepository.findByReferenceFileNameAndArchive(
ewvReferences.getReferenceFileName(), ewvReferences.getArchive());
if (ewvReferencesList != null && !ewvReferencesList.isEmpty()) {
throw new Exception("Attempt to insert already existing PDF Reference that has the same Reference File Name!");
}

logger.info("calling ewvPdfReferenceRepository.saveAndFlush()");
insertedEwvReferences = ewvPdfReferenceRepository.saveAndFlush(ewvReferences);
if (insertedEwvReferences == null) {
throw new Exception("Attemp to insert the given PDF Reference was not successful due to NULL reference " +
"returned when attempting to do insert operation!");
}

logger.info("Value for insertedEwvReferences: "+insertedEwvReferences.getReferenceFileName());
return insertedEwvReferences;
}

/**
* Gets all the PDF References that are in the database.
*
* @return - List of PdfReference objects
*/
private List <PdfReference> getRealAllPdfReferences() {
List <PdfReference> pdfReferencesList = new ArrayList<PdfReference>();

logger.info("About to call \"ewvPdfReferenceRepository.findAll\" method");
List <EwvReferences> ewvReferencesList = ewvPdfReferenceRepository.findByArchive("false");
logger.info("Just finished calling \"ewvPdfReferenceRepository.findAll\" method");
for (int i = 0; i < ewvReferencesList.size(); i++) {
PdfReference pdfReference = new PdfReference();
pdfReference.setGuid(ewvReferencesList.get(i).getGuid().toPlainString());
pdfReference.setAlt(ewvReferencesList.get(i).getReferenceName());
pdfReferencesList.add(pdfReference);
}

return pdfReferencesList;
}

/**
* Stub method used ONLY for test purposes that returns back
* a list of hard-coded PDF References.
*
* @return - List of PdfReference objects
*/
private List <PdfReference> getStubAllPdfReferences() {
List <PdfReference> pdfReferencesList = new ArrayList<PdfReference>();

PdfReference pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/CARC.pdf");
pdfReference.setAlt("Codeset: Claim Adjustment Reason Codes");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/RARC.pdf");
pdfReference.setAlt("Codeset: Remittance Remark Codes");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/POA-Indicators.pdf");
pdfReference.setAlt("POA Indicators");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/OHI-Type-Coverage.pdf");
pdfReference.setAlt("OHI Type of Coverage Guide");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/GUI-POA-Indicators-Inpatient.pdf");
pdfReference.setAlt("OHI Payment Sequence Indicators");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/Medicare-Payer-IDs.pdf");
pdfReference.setAlt("Medicare Contractor Payer IDs");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/X-Job-Code.pdf");
pdfReference.setAlt("X-Codes");
pdfReferencesList.add(pdfReference);

pdfReference = new PdfReference();
// pdfReference.setHref("https://
DNS.URL:PORT /help/ASC-Job-Code-Aid.pdf");
pdfReference.setAlt("ASC Rev Codes");
pdfReferencesList.add(pdfReference);

return pdfReferencesList;
}

/**
* Uploads (i.e., saves the contents into the server file system) a list of "files" into the server file system as
* well as insert PDF References of those files into the database.
*
* @param files - a list of MultipartFile objects; each such object contains the appropriate information for one
* file that will be used to save its contents into the server file system as well as its PDF
* Reference information in the database
*
* @return - instance of EwdPdfReferencesFileUploadResponse Java class; it will show which Files
* have had their contents stored successfully into the server file system as well as their PDF Reference
* information in the database and which have not. In those instances that are unsuccessful, the reason
* for not being successful will be included in the response
*/
@Override
public EwdPdfReferencesFileUploadResponse saveUploadedFiles(List<MultipartFile> files) {

String referenceName = "";
// Make sure directory exists!
File uploadDir = new File(FilenameUtils.normalize(env.getProperty("destination_folder")));
uploadDir.mkdirs();

// StringBuilder sb = new StringBuilder();
EwdPdfReferencesFileUploadResponse response = new EwdPdfReferencesFileUploadResponse();

for (MultipartFile file : files) {
EwvReferences ewvReferences = new EwvReferences();

try {
if (file.isEmpty()) {
continue;
}

String uploadFilePath = env.getProperty("destination_folder") + File.separator + file.getOriginalFilename();

byte[] bytes = file.getBytes();
Path path = Paths.get(FilenameUtils.normalize(uploadFilePath));
Files.write(path, bytes);
// insert a record to the database
//ewvReferences.setGuid(null);
ewvReferences.setArchive("false");
ewvReferences.setReferenceFileName(uploadFilePath.trim());
if(file.getOriginalFilename().contains(".")) {
referenceName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf('.')) ;
}
else {
referenceName = file.getOriginalFilename();
}

ewvReferences.setReferenceName(referenceName.trim());
ewvReferences.setDateCreated(new Date());
EwvReferences returnedEwvReferences = insertPdfReference(ewvReferences);
logger.info("Adding the object to the response"+returnedEwvReferences.getReferenceFileName()+" with referenece name: "+returnedEwvReferences.getReferenceName());
response.addSuccessfulFileUpload(file);
response.addEwvReferences(returnedEwvReferences);

} catch (Exception ex) {
response.addUnSuccessfulFileUploadsList(file);
response.addErrorMessage(ex.getMessage());
}

}

return response;
}


/**
* Marks one or more PDF References to the Archived state.
*
* @param archivedPdfReferences - a list of ArchivedPdfReference objects; each such object contains the appropriate
* information to identify which PDF Reference in the database will be marked as archived
*
* @return - EwvClaimDetailResponse Java class instance; it will show which PDF References have been placed
* successfully in the Archived state and which have not. In those instances that are unsuccessful, the
* reason for not being successful will be included in the response
*/
@Override
public EwdPdfReferencesFileArchiveResponse updateUploadedFiles(List<ArchivedPdfReference> archivedPdfReferences) {

EwdPdfReferencesFileArchiveResponse response = new EwdPdfReferencesFileArchiveResponse();

for (ArchivedPdfReference archivedPdfReference : archivedPdfReferences) {

try {
EwvReferences ewvReference = ewvPdfReferenceRepository.findOne(new BigDecimal(archivedPdfReference.getGuid()));

if (ewvReference == null) {
throw new Exception("PDF Reference with GUID \"" + archivedPdfReference.getGuid() + "\" does not exist!");
}
ewvReference.setArchive("true");
ewvReference.setReferenceName(archivedPdfReference.getAlt());
ewvReference.setDateArchived(new Date());
ewvReference = ewvPdfReferenceRepository.saveAndFlush(ewvReference);

response.addSuccessfulFileArchive(archivedPdfReference);
response.addEwvReferences(ewvReference);

} catch (Exception ex) {
response.addUnSuccessfulFileArchive(archivedPdfReference);
response.addErrorMessage(ex.getMessage());
}
}

return response;
}

/**
* Gets the Reference File Name of an EWV_REFERENCE record given it's GUID Id.
*
* @param fileId - the GUID that uniquely identifies a record in the EWV_REFERENCES table
*
* @return - the Reference File Name associated with the EWV_REFERENCE table record
*
* @throws GenericException - thrown if some error occurs
*/
@Override
public String getPathForTheAttachment(String fileId) throws GenericException {
String filePath = null;
if(!StringUtils.isEmpty(fileId)) {
EwvReferences ewvReferences = ewvPdfReferenceRepository.findByGuid(new BigDecimal(fileId));
if(ewvReferences != null) {
filePath = ewvReferences.getReferenceFileName();
return filePath;
} else {
throw new GenericException(ErrorMessages.NOT_FOUND, "File not found for a given uniqueId", HttpStatus.NOT_FOUND);
}
} else {
throw new GenericException(ErrorMessages.INVALID_REQUEST, "Unique Id should not be empty/null", HttpStatus.BAD_REQUEST);
}
}

}