Upload New File

parent d95c74df
package ibase.webitm.utility;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
//import java.util.concurrent.CompletableFuture;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.concurrent.Future;
import javax.jms.JMSException;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.json.JSONObject;
import ibase.bean.ExtAuthAppAPIBean;
import ibase.bean.ExtAuthApplicationBean;
import ibase.ejb.CommonDBAccessEJB;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.CryptographyUtil;
import ibase.utility.E12GenericUtility;
import ibase.utility.JSONtoXMLConverter;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.BckgrndProcessEJB; //Added by Gagan B. on 22-OCT-24 [V24FPRO003]
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMUploadFileEJB;
import ibase.webitm.ejb.MasterApplyEJB;
/*
* Author: Gagan B.
*
* Purpose: Contains the logic for VisionEDIService.java
*
* */
public class VisionEDIUtility
{
// private static ExecutorService executorService = Executors.newFixedThreadPool(5);
E12ExtServiceUtility e12ExtServiceUtility = new E12ExtServiceUtility();
RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
protected ibase.utility.UserInfoBean userInfo = null;
String fileWriteResult="";
String ignoreValError = "";
String batchId = "";
String templateResult = "";
String ediDataFilePath = "";
String ediDataFileName = "";
String ediLogFileName = "";
String PKValue = "";
public static String serviceConfigGlobal = "";
StringBuffer responseInfo = new StringBuffer("");
public String getEdiDataFileName()
{
return ediDataFileName;
}
public void setEdiDataFileName(String ediDataFileName)
{
this.ediDataFileName = ediDataFileName;
}
public String handleRequest( String serviceName, String enterprise, String appId, String inputData, String serviceConfig, String tokenId, HttpServletRequest request ) throws Exception
{
//Added by Amol S on 01-Apr 25 --strt
BaseLogger.log( "3", null, null, "Inside the method handleRequest==> 02-April-25" );
String callStatus = "";
String status = "Reject";
String tranId="";
if (status.equalsIgnoreCase("Reject"))
{
callStatus = "F";
}
else
{
callStatus = "Y";
}
APIUtility apiUtility = new APIUtility();
tranId=apiUtility.writeApiCallLog(userInfo, responseInfo.toString(), callStatus, appId, request.getRemoteAddr(), "", "", "", "", "", PKValue, "");
//Added by Amol S on 01-Apr 25 end
E12GenericUtility genericUtility = new E12GenericUtility();
RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
CommonDBAccessEJB commonDBAcessEJB = restapiserviceutility.getCommonDBAcessEJB();
JSONObject resultJson = new JSONObject();
responseInfo.append("1) VisionEDIService called."); //Added by Gagan B. to store RESPONSE_INFO in API_CALL_LOG.
String responseWithBatchID = "";
//Added by Gagan B. to write file each time handleRequest is called irrespective of whether input data is correct or not at Path: /wildfly/vision_edi/data/*/<file_name> [START]
String dataFilePath = CommonConstants.EDI_DATA_PATH + File.separator + "ALL_REQUEST";
BaseLogger.log( "3", null, null, "filePath::::" + dataFilePath);
File DIR = null;
DIR = new File( dataFilePath );
if ( ! DIR.exists() )
{
DIR.mkdirs();
BaseLogger.log( "3", null, null, "Directory Created..." );
}
String timeStamp = new SimpleDateFormat("dd.MM.yyyy.HH.mm.ss").format(new java.util.Date()) + ".txt";
// String dataFileName = "edi_service_" + timeStamp;
String dataFileName = appId + "_" + serviceName + "_" + serviceConfig + "_" + timeStamp;
inputData = restapiserviceutility.checkNull( inputData );
if ( inputData.length() > 0 )
{
BaseLogger.log( "3", null, null, "inputData " + "[" + inputData + "]" );
new E12GenericUtility().writeFile( dataFilePath, dataFileName , inputData );
}
//Added by Gagan B. to write file each time handleRequest is called irrespective of whether input data is correct or not at Path: /wildfly/vision_edi/data/*/<file_name> [END]
String result = "";
String resultFromtransLoad = ""; //Added by Gagan B. on 17th-FEB-23 declared variable to store result from transLoad method.
//Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject - START
//String status = "error";
//Commented by amol s , declare it globaly -Start
//String status = "Reject";
//Commented by amol s , declare it globaly -End
//Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject - STOP
StringBuffer logBuff = new StringBuffer();
SimpleDateFormat formatter = new SimpleDateFormat( genericUtility.getApplDateTimeFormat() );
if(serviceConfig.equals(null) || serviceConfig.isEmpty() || serviceConfig.equals("")) {
serviceConfig = "writefile";
}
try
{
BaseLogger.log( "3", null, null, "serviceName gsb: ["+ serviceName +"], enterprise : ["+ enterprise +"], appId : ["+ appId +"]" );
BaseLogger.log( "3", null, null, "inputString : ["+ inputData +"]" );
BaseLogger.log( "3", null, null, "tokenId : ["+ tokenId +"]" );
BaseLogger.log( "3", null, null, "serviceConfig : ["+ serviceConfig +"]" );
BaseLogger.log( "3", null, null, "API callers ip : ["+ request.getRemoteAddr() +"]" );
String queryString = request.getQueryString();
BaseLogger.log( "3", null, null, "request.getQueryString(): ["+ request.getQueryString() +"]" );
if ( E12GenericUtility.checkNull( queryString ).length() == 0 )
{
StringBuffer paramString = new StringBuffer();
if(serviceConfig.equalsIgnoreCase("writeFile")) {
paramString.append( "/ibase/rest/EDIService/setData/" ).append( serviceName ).append( "/" ).append( enterprise ).append( "/" ).append( appId );
//Changed by Gagan B. to validate setDataAndConfrim endpoint on 16th-FEB-23.
//Added by Gagan B. to validate writefilesavetransbg endpoint on 22-OCT-24. [V24FPRO003]
} else if(serviceConfig.equalsIgnoreCase("writeFilesavetrans") || serviceConfig.equalsIgnoreCase("setDataAndConfirm") || serviceConfig.equalsIgnoreCase("writefilesavetransbg")) {
paramString.append( "/ibase/rest/EDIService/setData/" ).append( serviceName ).append( "/" ).append( enterprise ).append( "/" ).append( appId ).append( "/" ).append( serviceConfig );
}
queryString = paramString.toString();
}
BaseLogger.log( "3", null, null, "In VisionEDIService :: queryString gsb : ["+ queryString +"]" );
// Added by Gagan B. to validate TOKEN ID if provided at start and create userInfo from it. on 04-APR-23 [START]
// Changes by Gagan B. on 13-SEP-24 [Using E12ExtServiceUtility's validateToken, which also uses appId and endpoint in VisionEDIUtility while validating token]
boolean isTokenValid = e12ExtServiceUtility.validateToken(request, tokenId, true, appId, queryString);
if(isTokenValid) {
userInfo = e12ExtServiceUtility.getUserInfo();
BaseLogger.log( "3", null, null, "In VisionEDIService userInfo ::: ["+ userInfo +"]" );
BaseLogger.log( "3", null, null, "In VisionEDIService transDB ::: ["+ userInfo.getTransDB() +"]" );
commonDBAcessEJB.setTransDB(userInfo.getTransDB());
restapiserviceutility.setTransDB(userInfo.getTransDB());
restapiserviceutility.setCommonDBAcessEJB(commonDBAcessEJB);
result = "valid";
}
// Added by Gagan B. to validate TOKEN ID if provided at start and create userInfo from it. on 04-APR-23 [END]
//Added by Prasad on 08/01/2021 [file write related implementation for success factor]
String ipAddress = restapiserviceutility.getRequestedIP( request );
logBuff.append( "(" ).append( queryString ).append( ")" ).append( " " ).append( ipAddress ).append( " " ).append( formatter.format( new Date() ) ).append( " " );
ExtAuthAppAPIBean authAppAPIBean =null;
//Added if condition By Ankush S on 05-JUNE-2024 [to exclude FLUTTERAPP to validating endpoint]
if(!appId.equals("FLUTTERAPP")) {
authAppAPIBean = commonDBAcessEJB.getAuthAppAPIDetails( queryString, null);
BaseLogger.log( "3", null, null, "visionEdiBean : ["+ authAppAPIBean +"]");
}
else {
authAppAPIBean = new ExtAuthAppAPIBean();
}
if (!appId.equals("FLUTTERAPP")&& authAppAPIBean == null )
{
status = "Reject"; //Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject
result = "This service not available";
}
else
{
String authAppId = restapiserviceutility.checkNull( authAppAPIBean.getAppId() );
boolean isWhiteListIP = restapiserviceutility.isWhiteListIP( request, authAppId );
//Added By Ankush on 06-JUNE-2024 [to exclude FLUTTERAPP]
if(appId.equals("FLUTTERAPP"))authAppId="FLUTTERAPP";
if (!appId.equals("FLUTTERAPP")&& ! isWhiteListIP )
{
status = "Reject"; //Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject
result = "Requested IP not registered for AppID ("+ authAppId +")";
}
else
{
//Added by Prasad on 08/01/2021 [external user authentication using USER_ACC_CHANNEL] START
//Changed by Prasad on 08/01/2021 [checked provided token_id, if not provided then check from USER_ACC_CHANNEL] START
tokenId = restapiserviceutility.checkNull( tokenId );
if ( tokenId.length() == 0 )
{
//Changed by Ravindra C on 15/02/2021 [get user_id from AUTH_APPS_API table to authenticate] START
String authAppUserId = restapiserviceutility.checkNull( authAppAPIBean.getUserId() );
DBAccessEJB dbAccess = new DBAccessEJB();
tokenId = dbAccess.getDBColumnValue( "USER_ACC_CHANNEL", "TOKEN_ID", (" ENTERPRISE = '"+ enterprise +"' AND USER_ID = '"+ authAppUserId +"' "), "Driver" );
dbAccess = null;
//Changed by Ravindra C on 15/02/2021 [get user_id from AUTH_APPS_API table to authenticate] END
}
String reqDataFormat = restapiserviceutility.checkNull( authAppAPIBean.getReqDataFormat() );
reqDataFormat = getDataFormat( reqDataFormat );
//Added By Ankush on 06-JUNE-2024 [to exclude FLUTTERAPP]
if(appId.equals("FLUTTERAPP"))reqDataFormat="JSON";
BaseLogger.log( "3", null, null, "reqDataFormat : ["+ reqDataFormat +"]" );
if ( !result.equalsIgnoreCase("valid") ) {
BaseLogger.log( "3", null, null, "Calling validate request in case of token ID validation failed in case of token ID provided from user." );
result = e12ExtServiceUtility.validateRequest(request, reqDataFormat, tokenId, isWhiteListIP, appId, queryString);
userInfo = e12ExtServiceUtility.getUserInfo();
BaseLogger.log( "3", null, null, "userInfo VisionEDIUtility : ["+ userInfo +"]" );
}
BaseLogger.log( "3", null, null, "e12ExtServiceUtility.validateRequest result : ["+ result +"]" );
if ( "valid".equalsIgnoreCase( result ) )
{
// Changes by Gagan B. on 11-08-23 [for checking daily API limit]
//commeted by Amol S , it get the object from gloabal -Start
//APIUtility apiUtility = new APIUtility();
//commeted by Amol S , it get the object from gloabal -End
if (apiUtility.checkDailyAPILimit(userInfo)) {
status = "Reject";
result = "Daily API call limit exceeded";
} else {
String clientIP = restapiserviceutility.checkNull( request.getRemoteHost() );
userInfo.setRemoteHost( ( clientIP != null && clientIP.length() > 0 ) ? clientIP : "SYSTEM" );
BaseLogger.log( "3", null, null, "userInfo : ["+ userInfo +"]");
String serviceClass = restapiserviceutility.checkNull( authAppAPIBean.getServiceClass() );
//Added By Ankush on 06-JUNE-2024 [to exclude FLUTTERAPP]
if(appId.equals("FLUTTERAPP"))serviceClass = serviceConfig;
BaseLogger.log( "3", null, null, "serviceClass : ["+ serviceClass +"]");
// Added By Gagan B. on 17-FEB-23 [START]
//Added by Gagan B. to validate writefilesavetransbg endpoint on 22-OCT-24. [V24FPRO003]
if( serviceClass.equalsIgnoreCase("writeFile") || serviceClass.equalsIgnoreCase("writeFileSaveTrans") || serviceClass.equalsIgnoreCase("setDataAndConfirm") || serviceClass.equalsIgnoreCase("writefilesavetransbg")) {
serviceClass = "fileWrite";
}
// Added By Gagan B. on 17-FEB-23 [END]
String serviceSetting = restapiserviceutility.checkNull( authAppAPIBean.getServiceSetting() );
//IF Added By Ankush on 06-JUNE-2024 [to exclude FLUTTERAPP]
if(appId.equals("FLUTTERAPP")) {
serviceSetting="{\"obj_name\":\""+serviceName+"\", \"field_name\":\"CHG_DATE\", \"template_id\":\"\" ,\"field_data_type\": \"DATE\",\"field_data_format\": \"dd-MM-yy\" }";
}
BaseLogger.log( "3", null, null, "serviceSetting : ["+ serviceSetting +"]");
JSONObject serviceSettingJson = null;
if( serviceSetting.length() > 0 )
{
try
{
serviceSettingJson = new JSONObject( serviceSetting );
}
catch (JSONException e)
{
e.printStackTrace();
BaseLogger.log( "0", null, null, "JSONException :: while parsing serviceSetting : ["+ e.getMessage() +"]" );
}
}
BaseLogger.log( "3", null, null, "serviceSettingJson : ["+ serviceSettingJson +"]" );
responseWithBatchID = E12GenericUtility.getJSONValue( serviceSettingJson, "RESPONSE_WITH_BATCH_ID" );
BaseLogger.log( "3", null, null, "responseWithbatchID : ["+ responseWithBatchID +"]" );
//Added By Ravindra C on 06-08-21 to decrypt the Edi Data - Start
Decryption decryption = new Decryption();
ExtAuthApplicationBean applicationBean = commonDBAcessEJB.getExtAuthApplicationInfo( authAppId );
String encryptMth = applicationBean.getEncryptMth();
//IF Added By Ankush on 06-JUNE-2024 [to exclude FLUTTERAPP and avoid null]
encryptMth = restapiserviceutility.checkNull(encryptMth);
BaseLogger.log( "3", null, null, "encryptMth : ["+ encryptMth +"]");
String secretKey = applicationBean.getSecretKey();
BaseLogger.log( "3", null, null, "secretKey : ["+ secretKey +"]");
if( restapiserviceutility.checkNull(encryptMth).length() > 0 && restapiserviceutility.checkNull(secretKey).length() > 0 )
{
//Changed by Ravindra on 02/10/2021 [encryption type related logic implementation] START
String encryptType = E12GenericUtility.getJSONValue( serviceSettingJson, "ENC_TYPE" );
/**
* ENC_TYPE will be
* 1. AFV - All field value encryption,
* 2. PAYLOAD - Payload encryption,
* 3. SFV - Selected field value encryption
*/
encryptType = restapiserviceutility.checkNull( encryptType );
if( encryptType.length() == 0 )
{
encryptType = "AFV";
}
BaseLogger.log( "3", null, null, "encryptType : ["+ encryptType +"]");
if ( "AFV".equalsIgnoreCase( encryptType ) )
{
if ( genericUtility.isJSONValid( inputData ) )
{
org.codehaus.jettison.json.JSONObject inputDataJson = new org.codehaus.jettison.json.JSONObject( inputData );
BaseLogger.log( "3", null, null, "inputDataJson : ["+ inputDataJson +"]");
inputDataJson = (org.codehaus.jettison.json.JSONObject) (new JSONtoXMLConverter()).getJSONArrayJSONObject( inputDataJson );
BaseLogger.log( "3", null, null, "inputDataJson after getJSONArrayJSONObject : ["+ inputDataJson +"]");
inputDataJson = decryption.decrypt(inputDataJson, encryptMth, secretKey);
BaseLogger.log( "3", null, null, "inputDataJson after decrypt : ["+ inputDataJson +"]");
inputData = inputDataJson.toString();
}
}
else if ( "PAYLOAD".equalsIgnoreCase( encryptType ) )
{
inputData = decryption.decrypt(inputData, encryptMth, secretKey);
}
//Changed by Ravindra on 02/10/2021 [encryption type related logic implementation] END
}
BaseLogger.log( "3", null, null, "inputData after Decryption : ["+ inputData +"]");
//Added By Ravindra C on 06-08-21 to decrypt the Edi Data - End
inputData = restapiserviceutility.checkNull( inputData );
if( "json".equalsIgnoreCase( reqDataFormat ) ) {
// Changes by Gagan B. to remove properties with empty values from JSON input Data.
int detailCount = genericUtility.jsonDetailCount(inputData);
BaseLogger.log( "3", null, null, "detailCount::" + "[" + detailCount + "]" );
inputData = E12GenericUtility.removeEmptyProperties(inputData);
BaseLogger.log( "3", null, null, "inputData after removePropertiesWithEmptyValues:" + "[" + inputData + "]" );
}
//Added by Prasad on 27/02/2021 [to check provided data format is proper or not] START
if ( "json".equalsIgnoreCase( reqDataFormat ) && ! genericUtility.isJSONValid( inputData ) )
{
status = "Reject"; //Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject
result = "Invalid input data. Data Format selected against object is JSON.";
}
else if ( "xml".equalsIgnoreCase( reqDataFormat ) && ! genericUtility.isXMLString( inputData ) )
{
status = "Reject"; //Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject
result = "Invalid input data. Data Format selected against object is XML.";
}
//Added by Prasad on 27/02/2021 [to check provided data format is proper or not] END
else if ( "fileWrite".equalsIgnoreCase( serviceClass ) )
{
String defaultEDIDataFilePath = CommonConstants.EDI_DATA_PATH + File.separator + serviceName + File.separator + enterprise + File.separator + appId;
String ediDataFile = writeFile( serviceSettingJson, reqDataFormat, defaultEDIDataFilePath, inputData );
BaseLogger.log( "3", null, null, "ediDataFile : ["+ ediDataFile +"]" );
ediDataFile = restapiserviceutility.checkNull( ediDataFile );
if ( ediDataFile.length() > 0 )
{
// Added by Gagan B. for dropdown given for serviceConfig on 12-SEP-22 [START]
BaseLogger.log( "3", null, null, "serviceConfig : ["+ serviceConfig +"]" );
// Changed by Gagan B. on 17th-FEB-23 added option for setDataAndConfirm endpoint.
if( serviceConfig.equalsIgnoreCase("writeFileSaveTrans") || serviceConfig.equals(("setDataAndConfirm")))
{
preProcessData( queryString, ipAddress, serviceSettingJson, ediDataFile, authAppId, userInfo );
BaseLogger.log( "3", null, null, "fileWriteResult::::" + fileWriteResult);
if(fileWriteResult.equalsIgnoreCase("success"))
{
BaseLogger.log( "3", null, null, "Calling transload...");
// Added by Gagan B. to store result from transLoad method.
resultFromtransLoad = transLoad(batchId, appId, userInfo, inputData, serviceConfig);
BaseLogger.log( "3", null, null, "resultFromtransLoad from transLoad::::" + resultFromtransLoad);
BaseLogger.log( "3", null, null, "result from transLoad::::" + result);
}
//Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change status and result values - START
//status = "success";
//result = "File written successfully";
String messageFromBatchLoad = "";
BaseLogger.log("3",null,null,"batchId --> handleRequest:: " + batchId);
if (userInfo != null)
{
DBAccessEJB dbAccessEJB = new DBAccessEJB();
try
{
messageFromBatchLoad = dbAccessEJB.getDBColumnValue("BATCHLOAD", "ERROR_MSG", "BATCH_ID = '"+batchId+"'" + "AND ERROR_MSG IS NOT NULL", userInfo.getTransDB());
}
catch (RemoteException | ITMException e)
{
e.printStackTrace();
}
}
BaseLogger.log("3",null,null,"messageFromBatchLoad --> handleRequest:: " + messageFromBatchLoad);
//Changes by Gagan B. status to failed for exception cases [START]
result = messageFromBatchLoad;
if (messageFromBatchLoad.trim().equals("Uploaded successfully")) {
status = "Accept";
} else {
status = "Reject"; // //Changes by Gagan B on 23/06/2023 as suggested by Danish sir to change error to Reject.
// result = result + " and " + resultFromtransLoad;
}
//Changes by Gagan B. status to failed for exception cases [END]
}
else if( serviceConfig.equalsIgnoreCase("writeFile") )
{
preProcessData( queryString, ipAddress, serviceSettingJson, ediDataFile, authAppId, userInfo );
status = "Accept";
result = "";
}
// Added by Gagan B. for dropdown given for serviceConfig on 12-SEP-22 [END]
//Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change status and result values - END
//Added by Ravindra C on 27/02/2021 [add app_id to identify the source]
/*
* Added by Gagan B. on 22-OCT-24. [V24FPRO003]
* Logic for new endpoint: writeFileSaveTransBG
* This endpoint will give the response instantly and do the transaction saving in background in Thread.
* [START]
*/
else if( serviceConfig.equalsIgnoreCase("writeFileSaveTransBG") ) {
BckgrndProcessEJB bckgrndProcess = new BckgrndProcessEJB();
String saveBckgrndPrcData = bckgrndProcess.saveBckgrndProcessData("true", serviceName, "O", serviceConfig, "<Root></Root>", "", "", userInfo.getLoginCode(), userInfo.getSiteCode(), "E", userInfo);
final String jobId = bckgrndProcess.getJobIdFromXML(saveBckgrndPrcData);
//GSB21OCT24
preProcessData( queryString, ipAddress, serviceSettingJson, ediDataFile, authAppId, userInfo );
BaseLogger.log( "3", null, null, "fileWriteResult::::" + fileWriteResult);
if(fileWriteResult.equalsIgnoreCase("success"))
{
BaseLogger.log( "3", null, null, "Calling transload...in BG Using Thread");
status = "Accept";
result = "";
String inputDataForES = inputData;
String serviceConfigForES = serviceConfig;
try {
new Thread("Thread-1") {
@Override
public void run()
{
try
{
BaseLogger.log("3", null, null, "Thread Process Started......................");
String transLoadResponse = transLoad(batchId,
appId, userInfo, inputDataForES, serviceConfigForES);
BaseLogger.log( "3", null, null, "transload...in BG Using Thread["+ transLoadResponse+"]");
HashMap<String, String> updateColumnSet = new HashMap<String, String>();
updateColumnSet.put( "JOB_STAT", "C" );
updateColumnSet.put( "REMARKS", PKValue );
BckgrndProcessEJB bckgrndProcess = new BckgrndProcessEJB();
bckgrndProcess.updateBackgroundJob( jobId, updateColumnSet, serviceName, userInfo.getLoginCode(), userInfo );
} catch (Exception e) {
BaseLogger.log("3", null, null, "transLoad writeFileSaveTransBG catch [" + E12GenericUtility.getStackTrace(e) + "]");
}
}
}.start();
} catch (Exception e) {
BaseLogger.log("3", null, null, "Exception in running thread writeFileSaveTransBG... [" + E12GenericUtility.getStackTrace(e) + "]");
}
BaseLogger.log("3", null, null, "handleRequest writeFileSaveTransBG jobId [" + jobId + "]");
}
}
/*
* Added by Gagan B. on 22-OCT-24. [V24FPRO003]
* Logic for new endpoint: writeFileSaveTransBG
* This endpoint will give the response instantly and do the transaction saving in background in Thread.
* [START]
*/
}
else
{
status = "Reject"; //Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject
result = "File not written successfully";
}
}
else
{
BaseLogger.log( "3", null, null, "Invalid configuration" );
status = "Reject"; //Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change error to Reject
result = "Invalid configuration. Please check service configuration.";
}
}
}
// Added by Gagan B. for showing response message when token ID validation is failed.
else {
status = "Reject";
result = "Token ID Validation Failed!";
}
//Added by Prasad on 08/01/2021 [external user authentication using USER_ACC_CHANNEL] END
//Changed by Prasad on 08/01/2021 [checked provided token_id, if not provided then check from USER_ACC_CHANNEL] END
}
}
//add here
//Added by Amol S move block in try block on 02-april -Start
result = result.substring(0, Math.min(result.length(), 250));
responseInfo.append("\n2) Status: " + status + " Result: " + result);
//Added by Gagan B. to save correct filename and filepath in case of incorrect input data. [START]
if(ediDataFilePath.equalsIgnoreCase("") && ediDataFileName.equalsIgnoreCase(""))
{
ediDataFilePath = dataFilePath;
ediDataFileName = dataFileName;
}
//Added by Gagan B. to save correct filename and filepath in case of incorrect input data. [END]
responseInfo.append("\n3) \n--Data File Path: " + ediDataFilePath + "\n--Data File Name: " + ediDataFileName );
responseInfo.append("\n4) Log File Name: " + ediLogFileName );
/* Changes by Gagan B on 16-JAN-23 for storing batch ID in API_CALL_LOG.RESPONSE_INFO, if
* AUTH_APPS_API.SERVICE_SETTING (this contains a JSON), if the key "RESPONSE_WITH_BATCH_ID" is Yes.
*/
if (!E12GenericUtility.checkNull(batchId).equalsIgnoreCase("") && responseWithBatchID.equalsIgnoreCase("Yes")) {
responseInfo.append("\n5) Batch ID: " + batchId );
}
BaseLogger.log( "3", userInfo, null, "responseInfo: VisionEDIUtility ["+ responseInfo +"]");
BaseLogger.log( "3", userInfo, null, "resultJson: VisionEDIUtility ["+ resultJson.toString() +"]");
APIUtility APIUtility = new APIUtility();
// Changes by Gagan B. to store Transaction ID from vision EDI service in REF_ID column of API call log. on 14-SEP-23
//APIUtility.writeApiCallLog(userInfo, responseInfo, callStatus, appId, request.getRemoteAddr());
// Changes by Gagan B. on 16-FEB-24 to set the value of Batch ID in API_CALL_LOG.RESPONSE_ID [START]
APIUtility.setResponseID(batchId);
// Changes by Gagan B. on 16-FEB-24 to set the value of Batch ID in API_CALL_LOG.RESPONSE_ID [END]
// tranId =APIUtility.writeApiCallLog(userInfo, responseInfo.toString(), callStatus, appId, request.getRemoteAddr(), "", "", "", "", "",PKValue, "");
BaseLogger.log( "3", userInfo, null, "Value of tranId:: ["+ tranId +"]");
//Changes by Amol S to call the method updateApiCallLog --start
APIUtility.updateApiCallLog(userInfo, responseInfo.toString(), callStatus, appId,
request.getRemoteAddr(), "", "", "", "", "", PKValue, "", tranId);
//Added by Amol S move block in try block on 02-april -End
}
catch (Exception e)
{
status = "Reject"; //Changes by Gagan B on 22/06/2023 as suggested by Danish sir to change error to Reject.
result = "Getting exception ("+ e.getMessage() +") in EDI Service.";
//Added by Amol S to add to append stacktrace --02-april -Start
String stackTrace = E12GenericUtility.getStackTrace(e);
stackTrace = stackTrace.length() > 500 ? stackTrace.substring(0, 500) : stackTrace;
e.printStackTrace();
System.out.println("An Exception occurred::: " + e.getMessage());
responseInfo.append("\nStatus text in makeApiCall:[Exception occurred]:: " + stackTrace);
apiUtility.updateApiCallLog(userInfo,responseInfo.toString(),callStatus,appId,request.getRemoteAddr(),"","","","","",PKValue,"",tranId);
//Added by Amol S to add to append stacktrace --02-april -End
}
finally
{
logBuff.append( formatter.format( new Date() ) ).append( " " ).append( status ).append( " " ).append( result );
BaseLogger.log( "0", null, null, "logBuff : ["+ logBuff.toString() +"]" );
String fileName = "edi_log_" + new SimpleDateFormat( "yyyyMMdd" ).format( new Date() ) + ".txt";
genericUtility.writeFile( CommonConstants.EDI_LOG, fileName, logBuff.toString(), true );
ediLogFileName = fileName;
if (userInfo != null)
{
DBAccessEJB dbAccessEJB = new DBAccessEJB();
try
{
ignoreValError = dbAccessEJB.getDBColumnValue("AUTH_APPS", "IGNORE_VAL_ERR", "APP_ID = '"+appId+"'", userInfo.getTransDB());
}
catch (RemoteException | ITMException e)
{
e.printStackTrace();
}
} else {
ignoreValError = "N";
}
BaseLogger.log("3",null,null,"ignoreValError --> handleRequest:: " + ignoreValError);
//Added by Amol S on 02-April 25 to call updateApiCallLog -start
if( tranId != null && !tranId.isEmpty())
{
//chnage to test it
apiUtility.updateApiCallLog(userInfo,responseInfo.toString(),callStatus,appId,request.getRemoteAddr(),"","","","","",PKValue,"",tranId);
}
//Added by Amol S on 02-April 25 to call updateApiCallLog -- End
if(! templateResult.equalsIgnoreCase(""))
{
resultJson.put( "Status", status );
// Changes by Gagan B. on 05-JAN-23 for returning batch ID in response of API.
// Changes by Gagan B. on 22-OCT-24 for returning batch ID in response of API. endpoint: writefilesavetransbg [V24FPRO003]
if (!E12GenericUtility.checkNull(batchId).equalsIgnoreCase("") &&
(serviceConfig.equalsIgnoreCase("writefile") || serviceConfig.equalsIgnoreCase("writefilesavetransbg")) &&
responseWithBatchID.equalsIgnoreCase("Yes")) {
resultJson.put( "Batch ID", batchId );
}
if(!E12GenericUtility.checkNull(templateResult).equalsIgnoreCase("")) {
resultJson.put( "Message", templateResult );
}
}
else if (ignoreValError.equalsIgnoreCase("Y") || ignoreValError.equalsIgnoreCase(null) || ignoreValError.equalsIgnoreCase(""))
{
resultJson.put( "Status", status );
}
else
{
resultJson.put( "Status", status );
resultJson.put( "Status", status );
// Changes by Gagan B. on 22-OCT-24 for returning batch ID in response of API. endpoint: writefilesavetransbg [V24FPRO003]
if (!E12GenericUtility.checkNull(batchId).equalsIgnoreCase("") &&
(serviceConfig.equalsIgnoreCase("writefile") || serviceConfig.equalsIgnoreCase("writefilesavetransbg")) &&
responseWithBatchID.equalsIgnoreCase("Yes")) {
resultJson.put( "Batch ID", batchId );
}
if(!E12GenericUtility.checkNull(result).equalsIgnoreCase("")) {
resultJson.put( "Message", result );
}
// Changes by Gagan B. on 11-08-23 [to add transaction id only if status is Accept]
if (!status.equalsIgnoreCase("Reject")) {
if(!E12GenericUtility.checkNull(PKValue).equalsIgnoreCase("")) {
resultJson.put("Transaction_id:", PKValue); // Added by Gagan B. to show Transaction ID in response.
}
}
}
}
//Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change key name for JSONObject - START
/*resultJson.put( "status", status );
resultJson.put( "result", result );*/
/* resultJson.put( "Status", status );
resultJson.put( "Reject_Reason", result ); */
//Changes by Jatin M on 17/02/2022 as suggested by Danish sir to change key name for JSONObject - END
// Added by Gagan B to store api call status in api_call_log [START]
//Commented By Amol S to declare globaally --Start---------------------
/*
String callStatus = "";
if (status.equalsIgnoreCase("Reject"))
{
callStatus = "F";
}
else
{
callStatus = "Y";
}
*/
//Commented By Amol S to declare globaally --End----------------------
// ediDataFile
// s = s.substring(0, Math.min(s.length(), 10));
//Commented by amol S on 02-April beause this part move in try block ------------------------------------------------
/*
result = result.substring(0, Math.min(result.length(), 250));
responseInfo.append("\n2) Status: " + status + " Result: " + result);
//Added by Gagan B. to save correct filename and filepath in case of incorrect input data. [START]
if(ediDataFilePath.equalsIgnoreCase("") && ediDataFileName.equalsIgnoreCase(""))
{
ediDataFilePath = dataFilePath;
ediDataFileName = dataFileName;
}
//Added by Gagan B. to save correct filename and filepath in case of incorrect input data. [END]
responseInfo.append("\n3) \n--Data File Path: " + ediDataFilePath + "\n--Data File Name: " + ediDataFileName );
responseInfo.append("\n4) Log File Name: " + ediLogFileName );
/* Changes by Gagan B on 16-JAN-23 for storing batch ID in API_CALL_LOG.RESPONSE_INFO, if
* AUTH_APPS_API.SERVICE_SETTING (this contains a JSON), if the key "RESPONSE_WITH_BATCH_ID" is Yes.
if (!E12GenericUtility.checkNull(batchId).equalsIgnoreCase("") && responseWithBatchID.equalsIgnoreCase("Yes")) {
responseInfo.append("\n5) Batch ID: " + batchId );
}
BaseLogger.log( "3", userInfo, null, "responseInfo: VisionEDIUtility ["+ responseInfo +"]");
BaseLogger.log( "3", userInfo, null, "resultJson: VisionEDIUtility ["+ resultJson.toString() +"]");
APIUtility APIUtility = new APIUtility();
// Changes by Gagan B. to store Transaction ID from vision EDI service in REF_ID column of API call log. on 14-SEP-23
//APIUtility.writeApiCallLog(userInfo, responseInfo, callStatus, appId, request.getRemoteAddr());
// Changes by Gagan B. on 16-FEB-24 to set the value of Batch ID in API_CALL_LOG.RESPONSE_ID [START]
APIUtility.setResponseID(batchId);
// Changes by Gagan B. on 16-FEB-24 to set the value of Batch ID in API_CALL_LOG.RESPONSE_ID [END]
// tranId =APIUtility.writeApiCallLog(userInfo, responseInfo.toString(), callStatus, appId, request.getRemoteAddr(), "", "", "", "", "",PKValue, "");
BaseLogger.log( "3", userInfo, null, "Value of tranId:: ["+ tranId +"]");
//Changes by Amol S to call the method updateApiCallLog --start
//TO TEST -START
String transID = null;
try {
//to test
transID.trim();
APIUtility.updateApiCallLog(userInfo, responseInfo.toString(), callStatus, appId,
request.getRemoteAddr(), "", "", "", "", "", PKValue, "", transID);
} catch (Exception e) {
String stackTrace = E12GenericUtility.getStackTrace(e);
stackTrace = stackTrace.length() > 500 ? stackTrace.substring(0, 500) : stackTrace;
e.printStackTrace();
System.out.println("An Exception occurred::: " + e.getMessage());
responseInfo.append("\nStatus text in makeApiCall:[Exception occurred]:: " + stackTrace);
APIUtility.updateApiCallLog(userInfo,responseInfo.toString(),callStatus,appId,request.getRemoteAddr(),"","","","","",PKValue,"",transID);
}
*/
//Commented by amol S on 02-April beause this part move in try & block --------------------------------
//END
// APIUtility.updateApiCallLog(userInfo,responseInfo.toString(),callStatus,appId,request.getRemoteAddr(),"","","","","",PKValue,"",tranId);
//Changes by Amol S to call the method updateApiCallLog --End
// Added by Gagan B to store api call status in api_call_log [END]
return resultJson.toString();
}
private String getDataFormat( String inputDataFormat )
{
String dataFormat = "txt";
if ( "0".equals( inputDataFormat ) )
{
dataFormat = "json";
}
else if ( "1".equals( inputDataFormat ) )
{
dataFormat = "xml";
}
BaseLogger.log( "3", null, null, "getDataFormat : ["+ dataFormat +"]");
return dataFormat;
}
private String writeFile( JSONObject serviceSettingJson, String reqDataFormat, String defaultEDIDataFilePath, String inputData ) throws ITMException
{
String ediDataFile = "";
try
{
if( serviceSettingJson != null )
{
try
{
if ( serviceSettingJson.has( "FILE_PATH" ) )
{
ediDataFilePath = serviceSettingJson.getString( "FILE_PATH" );
}
else if ( serviceSettingJson.has( "file_path" ) )
{
ediDataFilePath = serviceSettingJson.getString( "file_path" );
}
}
catch (JSONException e)
{
e.printStackTrace();
ediDataFilePath = "";
}
}
RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
ediDataFilePath = restapiserviceutility.checkNull( ediDataFilePath );
if( ediDataFilePath.length() == 0 )
{
ediDataFilePath = defaultEDIDataFilePath;
}
BaseLogger.log( "3", null, null, "ediDataFilePath : ["+ ediDataFilePath +"]");
ediDataFileName = "edi_data_"+ System.currentTimeMillis() + "." + reqDataFormat;
new E12GenericUtility().writeFile( ediDataFilePath, ediDataFileName, inputData );
BaseLogger.log( "3", null, null, "ediDataFileName : ["+ ediDataFileName +"]");
ediDataFile = ediDataFilePath + File.separator + ediDataFileName;
File file = new File( ediDataFile );
BaseLogger.log( "3", null, null, "file : ["+ file +"]" );
if ( file.exists() )
{
BaseLogger.log( "3", null, null, "File written successfully" );
}
else
{
ediDataFile = "";
BaseLogger.log( "3", null, null, "File not written successfully" );
}
}
catch (Exception e)
{
e.printStackTrace();
BaseLogger.log( "0", null, null, "Exception in VisionEDIService :: writeFile : ["+ e.getMessage() +"]");
throw new ITMException( e );
}
return ediDataFile;
}
private void preProcessData( final String queryString, final String ipAddress, final JSONObject serviceSettingJson, final String ediDataFile, final String appId, final UserInfoBean userInfo ) throws ITMException, Exception
{
E12GenericUtility genericUtility = new E12GenericUtility();
SimpleDateFormat formatter = new SimpleDateFormat( genericUtility.getApplDateTimeFormat() );
String result = "";
String status = "error";
StringBuffer preProcessDataLogBuff = new StringBuffer();
try
{
preProcessDataLogBuff.append( "(" ).append( queryString ).append( ")" ).append( " " ).append( ipAddress ).append( " " ).append( formatter.format( new Date() ) ).append( " " );
String fileData = genericUtility.readFile( ediDataFile );
BaseLogger.log( "3", userInfo, null, "fileData : ["+ fileData +"]" );
String collection = "EDI_DATA";
JSONObject dataJson = new JSONObject();
dataJson.put( "ENDPOINT", queryString );
dataJson.put( "ENTERPRISE", userInfo.getEnterprise() );
dataJson.put( "USER_ID", userInfo.getLoginCode() );
dataJson.put( "INPUT_DATA", fileData );
dataJson.put( "RECEIVE_DATE", formatter.format( new Date() ) );
dataJson.put( "COLLECTION", collection );
dataJson.put( "EDI_FILE_NAME", ediDataFile );
dataJson.put( "REQUEST_IP", ipAddress );
dataJson.put( "USER_INFO", userInfo.toString() );
dataJson.put( "SERVICE_SETTING", serviceSettingJson );
dataJson.put( "APP_ID", appId );
dataJson.put("CALLED_FROM", "VisionEDIServiceUtility"); //Added by Gagan B.
BaseLogger.log( "3", userInfo, null, "dataJson : ["+ dataJson +"]" );
BaseLogger.log( "3", userInfo, null, "Removed thread over here ... " );
// Changed by Gagan B. removed thread implementation for writing file action for making loading into DB synchronized on 29-AUG-22.
try
{
// Commented by Gagan B.
/*
JMSSender jmsSender = new JMSSender( userInfo );
if ( jmsSender != null && jmsSender.getConnection() != null )
{
jmsSender.getMessage().setJMSType( "FOLLOWUP_EDI_SERVICE" );
jmsSender.send( dataJson.toString() );
jmsSender = null;
BaseLogger.log( "3", userInfo, null, "Data send to process using JMSSender" );
}
else
{
JMSFollowupActions jmsFollowUpEDIService = new JMSFollowupActions();
jmsFollowUpEDIService.executeFollowUpEDIService( dataJson.toString() );
jmsFollowUpEDIService = null;
BaseLogger.log( "3", userInfo, null, "Data send to process using JMSFollowupActions" );
}
*/
JMSFollowupActions jmsFollowUpEDIService = new JMSFollowupActions();
jmsFollowUpEDIService.executeFollowUpEDIService( dataJson.toString() );
batchId = jmsFollowUpEDIService.getBatchIDShare();
// jmsFollowUpEDIService = null;
BaseLogger.log( "3", userInfo, null, "Data send to process using JMSFollowupActions" );
}
catch (ITMException e)
{
e.printStackTrace();
BaseLogger.log( "0", userInfo, null, "ITMException in VisionEDIService :: preProcessData : ["+ e.getMessage() +"]");
}
catch (JMSException e)
{
e.printStackTrace();
BaseLogger.log( "0", userInfo, null, "JMSException in VisionEDIService :: preProcessData : ["+ e.getMessage() +"]");
}
catch (Exception e)
{
e.printStackTrace();
BaseLogger.log( "0", userInfo, null, "Exception in VisionEDIService :: preProcessData : ["+ e.getMessage() +"]");
}
status = "success";
result = "Data send to process";
fileWriteResult = status;
}
catch (Exception e)
{
e.printStackTrace();
BaseLogger.log( "0", null, null, "Exception in VisionEDIService :: preProcessData : ["+ e.getMessage() +"]");
status = "Reject"; //Changes by Gagan B on 22/06/2023 as suggested by Danish sir to change error to Reject.
result = "Getting exception ("+ e.getMessage() +") while sending data to process";
}
finally
{
preProcessDataLogBuff.append( formatter.format( new Date() ) ).append( " " ).append( status ).append( " " ).append( result );
BaseLogger.log( "3", null, null, "preProcessDataLogBuff : ["+ preProcessDataLogBuff.toString() +"]" );
String fileName = "edi_preProcessData_log_" + new SimpleDateFormat( "yyyyMMdd" ).format( new Date() ) + ".txt";
try
{
genericUtility.writeFile( CommonConstants.EDI_LOG, fileName, preProcessDataLogBuff.toString(), true );
}
catch (ITMException e)
{
e.printStackTrace();
}
}
//Changed by Prasad on 15/02/2021 [Used JMS to write file instead of Thread] END
}
// Added by Gagan B. on 11-AUG-22 for directly loading API data to their respective transactions. [S22EBAS003] -- START
public String transLoad(String batchID, String appId, UserInfoBean userInfo, String inputData, String serviceConfig) throws ITMException
{
String result = "";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
//boolean isError = false;
try
{
ConnDriver connDriver = new ConnDriver();
conn = connDriver.getConnectDB( userInfo.getTransDB() );
connDriver = null;
BaseLogger.log( "3", userInfo, null, "appId : ["+ appId +"]" );
String appIdAddr = "";
if ( appId.length() > 0 )
{
appIdAddr = (appId + "_");
BaseLogger.log( "3", userInfo, null, "gsb appIdAddr : ["+ appIdAddr +"]" );
}
String sql = "SELECT BATCH.BATCH_ID, BATCH.WIN_NAME, BATCH.DATA_FILE_NAME, BATCH.SUBJECT, BATCH.XFRM_TEMPLATE, TEMPL.TEMPLATE_NAME, BATCH.TRAN_SL, BATCH.EDI_ADDR, BATCH.THREAD_KEY, BATCH.ADD_USER, BATCH.LOAD_STAT, TRAN.LOAD_ORDER, BATCH.LOAD_ORDER " +
" FROM TRANSETUP TRAN, BATCHLOAD BATCH LEFT OUTER JOIN OBJ_FILE_TEMPLATE TEMPL ON BATCH.XFRM_TEMPLATE = TEMPL.TEMPLATE_ID " +
" WHERE BATCH.LOAD_STAT IN ( 'N', 'R' ) " +
" AND TRAN.TRAN_WINDOW = BATCH.WIN_NAME " +
" AND BATCH.BATCH_ID = ?" +
" AND BATCH.EDI_ADDR IS NOT NULL AND BATCH.EDI_ADDR IN ( '"+ appIdAddr +"fileSystem', '"+ ( appIdAddr + CommonConstants.API_FILE_DESTINATION ) +"' ) " +
" ORDER BY TRAN.LOAD_ORDER, BATCH.LOAD_ORDER, BATCH.ADD_DATE, BATCH.BATCH_ID, BATCH.TRAN_SL ";
pstmt = conn.prepareStatement( sql );
pstmt.setString(1, batchID);
rs = pstmt.executeQuery();
BaseLogger.log( "3", userInfo, null, "gsb sql : ["+ sql +"]" );
HashMap<Integer, HashMap<String, String>> dataMap = new LinkedHashMap<Integer, HashMap<String,String>>();
BaseLogger.log( "3", userInfo, null, "gsb dataMap transLoad : ["+ dataMap +"]" );
ResultSetMetaData rsmd = rs.getMetaData();
int noOfColumns = rsmd.getColumnCount();
while( rs.next() )
{
HashMap<String, String> tempMap = new HashMap<String, String>();
for(int ctr = 1; ctr <= noOfColumns; ctr++)
{
if( "mysql".equalsIgnoreCase( CommonConstants.DB_NAME ) )
{
tempMap.put( rsmd.getColumnName(ctr).toUpperCase(), rs.getString(ctr) );
}
else
{
tempMap.put( rsmd.getColumnName(ctr), rs.getString(ctr) );
}
}
dataMap.put( 1, tempMap ); // Changed by Gagan B. for storing only latest transaction in map.
}
rs.close();
rs = null;
pstmt.close();
pstmt = null;
MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
masterApplyEJB.updateBatchLoad( dataMap, "I", conn, userInfo );
if ( conn != null )
{
conn.close();
conn = null;
}
String fileName = "";
String objName = "";
String subject = "";
String templateId = "";
String templateName = "";
String ediAddr = "";
String threadKey = "";
String dependency = "";
String addUser = "";
String loadStat = "";
String tranSlStr = "0";
int tranSl = 0;
for( Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet() )
{
HashMap<String, String> tempDataMap = dataEntry.getValue();
RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
objName = restapiserviceutility.checkNull( tempDataMap.get( "WIN_NAME" ) );
objName = objName.substring( objName.indexOf("_") + 1 );
batchID = restapiserviceutility.checkNull( tempDataMap.get( "BATCH_ID" ) );
fileName = restapiserviceutility.checkNull( tempDataMap.get( "DATA_FILE_NAME" ) );
subject = restapiserviceutility.checkNull( tempDataMap.get( "SUBJECT" ) );
templateId = restapiserviceutility.checkNull( tempDataMap.get( "XFRM_TEMPLATE" ) );
templateName = restapiserviceutility.checkNull( tempDataMap.get( "TEMPLATE_NAME" ) );
tranSlStr = restapiserviceutility.checkNull( tempDataMap.get( "TRAN_SL" ) );
if ( tranSlStr.length() > 0 )
{
tranSl = Integer.parseInt( tranSlStr );
}
ediAddr = restapiserviceutility.checkNull( tempDataMap.get( "EDI_ADDR" ) );
threadKey = restapiserviceutility.checkNull( tempDataMap.get( "THREAD_KEY" ) );
addUser = restapiserviceutility.checkNull( tempDataMap.get( "ADD_USER" ) ).trim();
loadStat = restapiserviceutility.checkNull( tempDataMap.get( "LOAD_STAT" ) );
BaseLogger.log( "3", userInfo, null, "objName : ["+ objName +"]" );
BaseLogger.log( "3", userInfo, null, "batchID : ["+ batchID +"]" );
BaseLogger.log( "3", userInfo, null, "fileName : ["+ fileName +"]" );
BaseLogger.log( "3", userInfo, null, "subject : ["+ subject +"]" );
BaseLogger.log( "3", userInfo, null, "templateId : ["+ templateId +"]" );
BaseLogger.log( "3", userInfo, null, "templateName : ["+ templateName +"]" );
BaseLogger.log( "3", userInfo, null, "ediAddr : ["+ ediAddr +"]" );
BaseLogger.log( "3", userInfo, null, "threadKey : ["+ threadKey +"]" );
BaseLogger.log( "3", userInfo, null, "addUser : ["+ addUser +"]" );
BaseLogger.log( "3", userInfo, null, "loadStat : ["+ loadStat +"]" );
if ( fileName.length() == 0 || fileName.indexOf( "." ) == -1 )
{
continue;
}
dependency = "";
threadKey = restapiserviceutility.checkNull( threadKey );
if ( threadKey.length() > 0 )
{
dependency = getDBAccess().getDBColumnValue( "BATCHLOAD", "(BATCH_ID || ':' || TRAN_SL)~AS~DEPENDENCY", (" THREAD_KEY = '"+ threadKey +"' AND LOAD_STAT = 'E' "), userInfo.getTransDB() );
}
dependency = restapiserviceutility.checkNull( dependency );
if ( dependency.length() > 0 )
{
masterApplyEJB.updateBatchLoad( batchID, tranSl, loadStat, dependency, null, userInfo );
continue;
}
else
{
String[] fileInfoArr = new String[6];
fileInfoArr[0] = "false";
fileInfoArr[1] = fileName;
fileInfoArr[2] = objName;
fileInfoArr[3] = "";
fileInfoArr[4] = templateName;
fileInfoArr[5] = subject;
//fileInfoArr[7] = "true"; //isRetXML
String fileType = fileName.substring( fileName.lastIndexOf(".") + 1 );
BaseLogger.log( "3", userInfo, null, "fileType : ["+ fileType +"]" );
String uploadFilePath = "";
String dataDumpFolderName = "";
if( "json".equalsIgnoreCase( fileType ) )
{
dataDumpFolderName = "JSON_UPLOAD";
}
else
{
dataDumpFolderName = "XLS_UPLOAD";
fileType = "xml";
}
//uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + userInfo.getLoginCode() + File.separator + batchID;
uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + addUser + File.separator + batchID;
File DUMP_DIR = null;
DUMP_DIR = new File( uploadFilePath );
if ( ! DUMP_DIR.exists() )
{
DUMP_DIR.mkdirs();
}
//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] START
if( "R".equalsIgnoreCase( loadStat ) )
{
moveFailedFileToUpload( uploadFilePath, fileName );
}
//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] END
// Changes by Gagan B. as per suggestions of Danish Sir to remove condition and pass inputData to writeFile method which is passed to transLoad as parameter.
new E12GenericUtility().writeFile( uploadFilePath, fileName, inputData );
//new E12GenericUtility().writeFile( uploadFilePath, fileName + "GSB", inputData );
ITMUploadFileEJB itmUploadFileEJB = new ITMUploadFileEJB();
serviceConfigGlobal = serviceConfig;
result = itmUploadFileEJB.insertFileData( fileInfoArr, userInfo, DUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", false, false, batchID, tranSl );
String messageFromBatchLoad = "";
BaseLogger.log("3",null,null,"batchId --> handleRequest:: " + batchId);
if (userInfo != null)
{
DBAccessEJB dbAccessEJB = new DBAccessEJB();
try
{
//Changes by Gagan B. to not retrieve value if ERROR_MSG column's value is null.
messageFromBatchLoad = dbAccessEJB.getDBColumnValue("BATCHLOAD", "ERROR_MSG", "BATCH_ID = '"+batchId+"'" + "AND ERROR_MSG IS NOT NULL", userInfo.getTransDB());
}
catch (RemoteException | ITMException e)
{
e.printStackTrace();
}
}
//Added by Gagan B. for setDataAndConfirm endpoint functionality [START]
BaseLogger.log("3",null,null,"messageFromBatchLoad --> transLoad:: " + messageFromBatchLoad);
BaseLogger.log( "3", null, null, "result from transLoad gsb:::" + result);
String parentPKValues = itmUploadFileEJB.globalTranID;
PKValue = parentPKValues;
BaseLogger.log( "3", null, null, "parentPKValues from transLoad gsb:::" + parentPKValues);
/* Commented by Gagan B. as changed way of executing setDataAndConfirm API (not manually executing "pre_confirm" event but by setting runMode as B
while saving transction via API which inturn executes "auto_confirm" event).*/
/*if (serviceConfig.equals("setDataAndConfirm") && messageFromBatchLoad.trim().equals("Uploaded successfully")) {
BaseLogger.log("3",null,null,"Inside setDataAndConfirm scope...");
String eventResult = "";
EventManagerEJB eventManagerEJB = new EventManagerEJB();
String transString = "<?xml version='1.0' encoding='"+CommonConstants.ENCODING+"'?>"
+ "<Root><header>"
+ "<objName><![CDATA[" + objName + "]]></objName>"
+ "<objContext><![CDATA[1]]></objContext>" //$NON-NLS-1$
+ "<editFlag><![CDATA[A]]></editFlag>"
+ "<keyValue><![CDATA["+parentPKValues+"]]></keyValue>"
+ "<tran_id><![CDATA["+parentPKValues+"]]></tran_id>"
+ "<forcedSave><![CDATA[false]]></forcedSave>"
+ "</header>"
+ "</Root>";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Document doc = builder.parse( new InputSource( new StringReader( xml ) ) );
Document transDom = documentBuilder.parse( new InputSource( new StringReader( transString ) ) );
BaseLogger.log( "3", null, null, "transDom from transLoad gsb:::" + transDom);
eventResult = eventManagerEJB.executeSystemEvent(objName, "pre_confirm", null, transDom, transDom, getXtraParams(), "N", conn, null, userInfo);
BaseLogger.log( "3", null, null, "eventResult from transLoad gsb:::" + eventResult);
Document eventResultDOM = documentBuilder.parse( new InputSource( new StringReader( eventResult ) ) );
String eventResultType = eventResultDOM.getElementsByTagName("type").item(0).getNodeName();
String eventResultDescription = eventResultDOM.getElementsByTagName("description").item(0).getNodeName();
eventResultType = genericUtility.getColumnValue(eventResultType, eventResultDOM);
eventResultDescription = genericUtility.getColumnValue(eventResultDescription, eventResultDOM);
BaseLogger.log( "3", null, null, "eventResultDescription from transLoad gsb:::" + eventResultDescription + "eventResultType from transLoad gsb:::" + eventResultType);
result = eventResultDescription;
if( !(eventResultType.equals("W") || eventResultType.equals("P")) ) {
result = "Error in Confirming Transaction!";
}
//Added by Gagan B. for setDataAndConfirm endpoint functionality [END]
}*/
}
}
}
catch (SQLException e)
{
BaseLogger.log( "0", null, null, "SQLException :: from transLoad() : ["+ e.getMessage() +"]" );
e.printStackTrace();
throw new ITMException( e );
}
catch (Exception e)
{
BaseLogger.log( "0", null, null, "Exception :: from transLoad() : ["+ e.getMessage() +"]" );
e.printStackTrace();
throw new ITMException( e );
}
finally
{
try
{
if ( rs != null )
{
rs.close();
rs = null;
}
if ( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( conn != null )
{
conn.close();
conn = null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
return result;
}
// Added by Gagan B. on 11-AUG-22 for directly loading API data to their respective transactions. [S22EBAS003] -- END
private DBAccessEJB getDBAccess()
{
DBAccessEJB dbAccess = null;
try
{
if ( dbAccess == null )
{
//AppConnectParm appConnect = new AppConnectParm();
//InitialContext initialContext = new InitialContext(appConnect.getProperty());
//dbAccess = (DBAccessLocal) initialContext.lookup("ibase/DBAccessEJB/local");
dbAccess = new DBAccessEJB();
}
}
/*catch (NamingException e)
{
e.printStackTrace();
}*/
catch (Exception e)
{
e.printStackTrace();
}
return dbAccess;
}
private void moveFailedFileToUpload( String uploadFilePath, String fileName )
{
String commonUploadSuccessFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_success";
String commonUploadFailedFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_failed";
File file = new File( commonUploadFailedFilePath + File.separator + fileName );
if ( file.exists() )
{
File dir = new File( uploadFilePath );
if ( ! dir.exists() )
{
dir.mkdirs();
}
BaseLogger.log( "3", userInfo, null, "dir --> ["+ dir +"]" );
boolean success = file.renameTo( new File( dir, file.getName() ) );
if ( ! success )
{
BaseLogger.log( "3", userInfo, null, "File was not moved" );
}
}
else
{
BaseLogger.log( "3", userInfo, null, "File not exist In the failed path" );
file = new File( commonUploadSuccessFilePath + File.separator + fileName );
if ( file.exists() )
{
File dir = new File( uploadFilePath );
if ( ! dir.exists() )
{
dir.mkdirs();
}
BaseLogger.log( "3", userInfo, null, "dir --> ["+ dir +"]" );
boolean success = file.renameTo( new File( dir, file.getName() ) );
if ( ! success )
{
BaseLogger.log( "3", userInfo, null, "File was not moved" );
}
}
}
}
// Added by Gagan B. on 20-SEP-22 for reading file content and returning it to API. [S22FBAS001] -- START
public String ReadFileContent(String filePath)
{
byte[] decodedBytes = Base64.getDecoder().decode(filePath);
filePath = new String(decodedBytes);
String fileContent = "";
try
{
BaseLogger.log( "3", null, null, "filePath from ReadFileContent: ["+ filePath +"]" );
fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
System.out.println(fileContent);
} catch (IOException e)
{
e.printStackTrace();
}
return fileContent;
}
// Added by Gagan B. on 20-SEP-22 for reading file content and returning it to API. [S22FBAS001] -- END
/* Commented by Gagan B. as changed way of executing setDataAndConfirm API (not manually executing "pre_confirm" event but by setting runMode as B
while saving transction via API which inturn executes "auto_confirm" event).*/
/*
// Added by Gagan B. on 16th-FEB-23 [START]
public String getXtraParams() throws ITMException
{
final String XTRA_PARAMS_SEPARATOR = "~~"; //$NON-NLS-1$
StringBuffer xtraParamsBuff = new StringBuffer();
xtraParamsBuff.append("loginCode=" + this.userInfo.getLoginCode()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginEmpCode=" + this.userInfo.getEmpCode()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginSiteCode=" + this.userInfo.getSiteCode()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("entityCode=" + this.userInfo.getEntityCode()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("profileId=" + this.userInfo.getProfileId()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("userType=" + this.userInfo.getUserType()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("termId="+this.userInfo.getRemoteHost()); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("isAutoConfirm=false"); //$NON-NLS-1$
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("isDataUpload=true"); //$NON-NLS-1$ //runMode
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("runMode=B"); //$NON-NLS-1$
String chgTerm = this.userInfo.getRemoteHostName();
if( chgTerm != null && chgTerm.length() > 15 )
{
chgTerm = chgTerm.substring(0, 15);
}
else if( chgTerm == null || chgTerm.length() == 0 )
{
chgTerm = this.userInfo.getRemoteHost();
}
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("chgTerm=" + chgTerm ); //$NON-NLS-1$
return xtraParamsBuff.toString();
}
// Added by Gagan B. on 16th-FEB-23 [END]
* */
/*
// Added by Gagan B. to validate TOKEN ID on 05-APR-23 [START]
public boolean validateToken(HttpServletRequest request, String tokenId, boolean toValidateSession, String appId, String endpoint) {
boolean isValid = false;
String result = "valid";
if ( toValidateSession && ! e12ExtServiceUtility.validateUserSession( request, tokenId ))
{
result = "You are not authorized to access.";
}
userInfo = e12ExtServiceUtility.getUserInfo();
BaseLogger.log( "3", null, null, "result from validateToken VisionEDIUtility: ["+ result +"]" );
if(!result.equalsIgnoreCase("valid")) {
isValid = validateLLT(tokenId);
BaseLogger.log( "3", null, null, "isValid from validateToken VisionEDIUtility: ["+ isValid +"]" );
} else {
isValid = true;
}
return isValid;
}
// Added by Gagan B. to validate TOKEN ID on 05-APR-23 [END]
*
*/
// Added by Gagan B. on 21-MAR-23 : created separate method for validating LLT [START]
private boolean validateLLT(String tokenId) {
String sharedKey = "a3edd11a09ea4e0ccd09c6cd2828021b";
boolean isValidUser = false;
String result = "";
result = restapiserviceutility.validateJWT(tokenId, "", sharedKey);
if (result.equalsIgnoreCase("valid")) {
isValidUser = true;
HashMap<String, String> jwtData = CryptographyUtil.parseBase64EncodedJWTToken(tokenId, sharedKey);
userInfo = restapiserviceutility.createUserInfo(jwtData);
}
return isValidUser;
}
// Added by Gagan B. on 21-MAR-23 : created separate method for validating LLT [END]
}
\ No newline at end of file
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