Commit f451ef83 authored by Ajit Deshmukh's avatar Ajit Deshmukh

Added Manage SQL folder

parent b31f72af
update user_rights set ACC_FILT = '(
''<entityCode>'' = ''GAGANB'' OR
((SELECT dept_code
FROM employee
WHERE emp_code = ''<entityCode>'') = ''0070''
AND sql_changes.exec_rights = ''D''
)
OR
((SELECT dept_code
FROM employee
WHERE emp_code = ''<entityCode>'') = ''0100''
AND sql_changes.exec_rights = ''Q''
)
)' where obj_name = 'sql_changes';
/**
* PURPOSE : Home screen confirm comp
* AUTHOR : Mrunalini Sinkar
*/
package ibase.webitm.ejb.wsfa.masters;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
public class ManageSqlConf extends ActionHandlerEJB
{
int reUpdateCnt = 0;
String sqlError = "";
public String confirm( String tranId, String xtraParams, String forcedFlag ) throws RemoteException,ITMException
{
System.out.println("HeaderDetailConf Called!!!!!........["+tranId+"]");
System.out.println("xtraParams !!!!!........["+xtraParams+"]");
String enterprise = getUserInfo().getEnterprise();
enterprise = enterprise.trim();
System.out.println("enterprise !!!!!........["+enterprise+"]");
boolean isError = false;
String applDB = "",enterprises="";
String sql = "";
String requestID = "";
ResultSet rs = null;
PreparedStatement pstmt = null;
Connection con = null;
String errString = "";
String schemaName = "";
String enterpriseSQL="";
ITMDBAccessEJB itmdbAccessLocal = null ;
boolean isThisObject=false;
try
{
itmdbAccessLocal = new ITMDBAccessEJB();
GenericUtility genericUtility = GenericUtility.getInstance();
con = getConnection();
con.setAutoCommit(false);
String userId = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
String chgTerm = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId"));
//Changes Start -- 13 Nov AJIT
// After fetching applDB, enterprises, requestID
System.out.println("Checking exec_rights dependency for tran_id: " + tranId);
String execRights = "";
String tranIdRef = "";
String selectedEnterprise = "";
String checkSql = "SELECT tran_id__ref,EXEC_RIGHTS,enterprises FROM SQL_CHANGES WHERE TRAN_ID = ?";
pstmt = con.prepareStatement(checkSql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
if (rs.next()) {
tranIdRef = checkNull(rs.getString("tran_id__ref"));
execRights = checkNull(rs.getString("EXEC_RIGHTS"));
selectedEnterprise = checkNull(rs.getString("enterprises"));
}
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
// Commented by Ajit D. on 03-DEC-25 -- START
// if ("Q".equalsIgnoreCase(execRights)) {
// System.out.println("This transaction has exec_rights = 'D'");
// if(!enterprise.equalsIgnoreCase(selectedEnterprise.trim())) {
// System.out.println("Enterprise Mismatch "+selectedEnterprise);
// errString = itmdbAccessLocal.getErrorString("confirmed", "ENTMIS", "","",con);
// return errString; // Stop execution here
// }
// }
// Commented by Ajit D. on 03-DEC-25 -- END
if ("Q".equalsIgnoreCase(execRights)) {
System.out.println("This transaction has exec_rights = 'Q', checking for dependent 'D' confirmation...");
// if(!enterprise.equalsIgnoreCase(selectedEnterprise.trim())) {
// System.out.println("Enterprise Mismatch "+selectedEnterprise);
// errString = itmdbAccessLocal.getErrorString("confirmed", "ENTMIS", "","",con);
// return errString; // Stop execution here
// }
String qCheckSql = "SELECT CONFIRMED FROM SQL_CHANGES WHERE EXEC_RIGHTS = 'D' and tran_id__ref = "+tranIdRef;
pstmt = con.prepareStatement(qCheckSql);
rs = pstmt.executeQuery();
boolean qConfirmed = false;
if (rs.next()) {
String confirmedFlag = checkNull(rs.getString("CONFIRMED"));
if ("Y".equalsIgnoreCase(confirmedFlag)) {
qConfirmed = true;
}
}
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
if (!qConfirmed) {
System.out.println("Cannot confirm this transaction. The dependent record with exec_rights = 'Q' is not yet confirmed.");
errString = itmdbAccessLocal.getErrorString("confirmed", "MSQNCONF", "","",con);
return errString; // Stop execution here
}
}
//Changes Start -- 13 Nov AJIT (Condition for exec_rights = 'A')
if ("A".equalsIgnoreCase(execRights)) {
System.out.println("This transaction has exec_rights = 'A', checking if dependent transactions are confirmed...");
String depCheckSql = "SELECT TRAN_ID, CONFIRMED FROM SQL_CHANGES " +
"WHERE TRAN_ID__REF = ? AND EXEC_RIGHTS IN ('D', 'Q')";
pstmt = con.prepareStatement(depCheckSql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
boolean recordFound = false;
boolean unconfirmedFound = false;
String pendingTranId = "";
while (rs.next()) {
recordFound = true;
String confirmedFlag = checkNull(rs.getString("CONFIRMED"));
String depTranId = checkNull(rs.getString("TRAN_ID"));
// If any dependent (D or Q) is not confirmed → block confirmation
if (!"Y".equalsIgnoreCase(confirmedFlag)) {
unconfirmedFound = true;
pendingTranId = depTranId;
}
}
if (rs != null) { rs.close(); rs = null; }
if (pstmt != null) { pstmt.close(); pstmt = null; }
// No dependent D/Q records found → workflow not yet approved
if (!recordFound) {
System.out.println("Cannot confirm. Workflow not approved for tran_id: " + tranId);
errString = itmdbAccessLocal.getErrorString("confirmed", "WRKFNA", "", "", con);
return errString;
}
// Dependent D or Q exists but NOT confirmed → return error
if (unconfirmedFound) {
System.out.println("Cannot confirm. Dependent transaction [" + pendingTranId + "] is not yet confirmed.");
errString = itmdbAccessLocal.getErrorString("confirmed", "MSDNCONF", "", "", con);
return errString;
}
System.out.println("All dependent D and Q transactions are confirmed. Proceeding...");
}
//Changes End -- 13 Nov AJIT (Condition for exec_rights = 'A')
//Changes End -- 13 Nov AJIT (Condition for exec_rights = 'A')
//Changes End -- 13 Nov AJIT
HashMap<String,String> schemaListMap= new HashMap<String,String>();
sql = "SELECT APPL_DB,ENTERPRISES,REQ_ID FROM SQL_CHANGES WHERE TRAN_ID=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
if( rs.next() )
{
applDB = checkNull( rs.getString("APPL_DB") );
enterprises = checkNull( rs.getString("ENTERPRISES") );
requestID = checkNull( rs.getString("REQ_ID") );
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
if(applDB.equalsIgnoreCase("E"))
{
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- START
Connection entCon = null;
ConnDriver connDriver = new ConnDriver();
entCon = connDriver.getConnectDB("Driver");
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- END
sql = "SELECT SCHEMA_NAME,ENTERPRISE FROM ENTERPRISE WHERE SCHEMA_NAME IS NOT NULL";
pstmt = entCon.prepareStatement(sql);
rs = pstmt.executeQuery();
while( rs.next() )
{
schemaName = checkNull( rs.getString("SCHEMA_NAME") );
enterpriseSQL = checkNull( rs.getString("ENTERPRISE") );
schemaListMap.put(schemaName,enterpriseSQL);
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- START
if( entCon != null && !entCon.isClosed() )
{
System.out.println( "Closing entCon " );
entCon.close();
entCon = null;
connDriver = null;
}
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- END
}
if(applDB.equalsIgnoreCase("S"))
{
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- START
Connection entCon = null;
ConnDriver connDriver = new ConnDriver();
entCon = connDriver.getConnectDB("Driver");
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- END
String EnterPriseInFormat=getFormattedStringBuff(enterprises);
sql = "SELECT SCHEMA_NAME,ENTERPRISE FROM ENTERPRISE WHERE ENTERPRISE IN("+EnterPriseInFormat+") " ;
pstmt = entCon.prepareStatement(sql);
rs = pstmt.executeQuery();
while( rs.next() )
{
schemaName = checkNull( rs.getString("SCHEMA_NAME") );
enterpriseSQL = checkNull( rs.getString("ENTERPRISE") );
schemaListMap.put(schemaName,enterpriseSQL);
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- START
if( entCon != null && !entCon.isClosed() )
{
System.out.println( "Closing entCon " );
entCon.close();
entCon = null;
connDriver = null;
}
// Added by Gagan B. on 13-NOV-25 [make connection with Driver for ENTERPRISE] -- END
}
sql = "SELECT ORA_STMNT,LINE_NO FROM SQL_CHANGES_DET WHERE TRAN_ID=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
while( rs.next() )
{
String oracleStatment = checkNull( rs.getString("ORA_STMNT") );
String linNo = checkNull( rs.getString("LINE_NO") );
System.out.println("oracle execute statment["+oracleStatment+"]");
if( oracleStatment.lastIndexOf(";") != -1 )
{
if(!oracleStatment.toUpperCase().startsWith("CREATE"))
{
BaseLogger.log("3", null, null, "Inside if oracleStatment [" + oracleStatment + "]");//Added by Ashish.J
int endIndex=oracleStatment.lastIndexOf(";");
oracleStatment=oracleStatment.substring(0, endIndex);
}
else if(oracleStatment.toUpperCase().startsWith("CREATE TABLE"))
{
BaseLogger.log("3", null, null, "Inside else oracleStatment [" + oracleStatment + "]");//Added by Ashish.J
int endIndex=oracleStatment.lastIndexOf(";");
oracleStatment=oracleStatment.substring(0, endIndex);
}
}
if(oracleStatment.toUpperCase().startsWith("CREATE") && !oracleStatment.toUpperCase().startsWith("CREATE TABLE"))
{
BaseLogger.log("3", null, null, "Inside is the object oracleStatment [" + oracleStatment + "]");//Added by Ashish.J
isThisObject=true;
}
if ("A".equalsIgnoreCase(execRights))
{
BaseLogger.log("3", null, null, "multiple schema execution for provided enterprise:: oracleStatment::" + oracleStatment + " enterprise:: "+enterprise+ "]");//Added by Ashish.J
processSqlForEnterprise(con, enterprise, oracleStatment);
continue;
}
//if( oracleStatment.toUpperCase().startsWith("ALTER") || oracleStatment.toUpperCase().startsWith("INSERT INTO") || oracleStatment.toUpperCase().startsWith("UPDATE") || oracleStatment.toUpperCase().startsWith("DELETE"))
//{
executeQueries(con,schemaListMap, oracleStatment,tranId,linNo,requestID,userId,chgTerm,isThisObject) ;
//}
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
String upSql="UPDATE SQL_CHANGES SET CONFIRMED='Y',CONF_DATE=SYSDATE,EMP_CODE_APRV=?,EXECUTED='Y' WHERE TRAN_ID=?";
pstmt = con.prepareStatement(upSql);
pstmt.setString(1, userId);
pstmt.setString(2, tranId);
int updCnt = pstmt.executeUpdate();
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
System.out.println("update count is["+updCnt+"]");
if(updCnt>0)
{
errString = itmdbAccessLocal.getErrorString("confirmed", "VTCONFIRM", "","",con);
System.out.println("errString is "+ errString);
}
}
catch(Exception e)
{
isError = true;
try
{
con.rollback();
}
catch(Exception e1)
{
e1.printStackTrace();
}
e.printStackTrace();
throw new ITMException(e);
}
finally
{
try
{
System.out.println("Commiting and Closing Connection..........");
if ( !(isError) )
{
System.out.println( "inside finally if" );
con.commit();
//errString = itmdbAccessLocal.getErrorString("","TEMCONFIRM",loginEmpCode);
//errString = itmdbAccessLocal.getErrorString("confirmed", "TEMCONFIRM", "","",con);
}
else
{
System.out.println( "inside finally rollback else" );
con.rollback();
}
if( pstmt != null )
{
System.out.println( "inside finally if pstmt " );
pstmt.close();
pstmt = null;
}
if( con != null && !con.isClosed() )
{
System.out.println( "inside finally if con " );
con.close();
con = null;
}
}
catch( Exception e)
{
e.printStackTrace();
}
}
System.out.println("errString is +++:"+errString);
return errString;
}
private String checkNull(String input)
{
if(input == null)
{
input = "";
}
return input;
}
private String getFormattedStringBuff( String data )
{
StringBuffer dataString = new StringBuffer();
try
{
String[] dataArr = null;
if ( data.indexOf(",") == -1 )
{
dataString.append( "'"+data+"'" );
}
else
{
dataArr = data.split(",");
for (int i=0; i < dataArr.length; i++ )
{
if ( i == 0 )
{
dataString.append( "'"+dataArr[i]+"'" );
}
else
{
dataString.append( "," );
dataString.append( "'"+dataArr[i]+"'" );
}
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return dataString.toString();
}
// Commented by Gagan B. on 13-NOV-25 -- START
/*
private int executeQueries(Connection connection,HashMap<String,String> schemaListMap, String Sql,String tranID,String lineNo,String requestID,String userId,String chgTerm,boolean isThisObjectType)
{
BaseLogger.log("3", null, null, "Inside executeQueries gsb1 [" + Sql + "]");
BaseLogger.log("3", null, null, "Inside executeQueries schemaListMap [" + schemaListMap + "]");
ConnDriver connDriver = new ConnDriver();
Connection conn = null;
Statement stmnt = null;
int updateCount=0;
CallableStatement callableStmt = null;
String error = "";//Added by Ashish.J
try
{
System.out.println("isThisObjectType gsb----:::::["+isThisObjectType+"]");
if(!schemaListMap.isEmpty())
{
Iterator<String> itr = schemaListMap.keySet().iterator();
while (itr.hasNext())
{
String schema = itr.next();
String enterprise = schemaListMap.get(schema);
int updCount = 0;
try {
conn = connDriver.getConnectDB(schema);
} catch (Exception e) {
error=e.getMessage();
BaseLogger.log("3", null, null, "Inside catch of error..["+error+"]");
insertIntoSqlExectionLog(connection,tranID,enterprise,lineNo,requestID,Sql,updCount, "E" , userId,chgTerm,error);
}
if( conn == null )
{
BaseLogger.log("3", null, null, "Unable to get connection for gsb"
+ " [" + schema + "]");
//throw new Exception("Unable to get connection for [" + schema + "]");
}
if(checkNull(Sql).trim().length() > 0)
{
BaseLogger.log("3", null, null, "is the object---[" + isThisObjectType + "]");
if(isThisObjectType)
{
BaseLogger.log("3", null, null, "is the object if [" + isThisObjectType + "]");
String plsql = " begin " +
" dbms_metadata.set_transform_param ( DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', false ); " +
" end; ";
callableStmt = conn.prepareCall(plsql);
callableStmt.execute();
}
try
{
BaseLogger.log("3", null, null, "Inside try....");//Added by Ashish.J
stmnt = conn.createStatement();
updCount = stmnt.executeUpdate(Sql);
error="";
BaseLogger.log("3", null, null, "Inside try of error..["+error+"]");//Added by Ashish.J
BaseLogger.log("3", null, null, "schema...["+schema+"]updateCnt to get Sql [" + updCount + "]");
insertIntoSqlExectionLog(connection,tranID,enterprise,lineNo,requestID,Sql,updCount, "C" , userId,chgTerm,error);
}
catch(SQLException ise)
{
error=ise.getMessage();//Added by Ashish.J
BaseLogger.log("3", null, null, "Inside catch of error..["+error+"]");
//insertIntoSqlExectionLog(connection,tranID,enterprise,lineNo,requestID,Sql, userId,chgTerm);
BaseLogger.log("3", null, null, "Inside catch....");
insertIntoSqlExectionLog(connection,tranID,enterprise,lineNo,requestID,Sql,updCount, "E" , userId,chgTerm,error);
}//Added by Ashish.J
finally
{
if (stmnt != null)
{
stmnt.close();
stmnt = null;
}
}
}
Thread.sleep(100);
conn.commit();
}
}
}
catch (Exception e)
{
try
{
BaseLogger.log("3", null, null, "Excepotion in executeAlterQueries occured while executing Alter Queries>>>>" +
E12GenericUtility.checkNull(e.getMessage()));
//conn.rollback();
}
// catch (SQLException sqle)
catch (Exception sqle)
{
BaseLogger.log("3", null, null, "SQLException executeAlterQueries occured during rollback:: " + sqle.getMessage());
sqle.printStackTrace();
}
e.printStackTrace();
}
finally
{
try
{
if (callableStmt != null)
{
callableStmt.close();
callableStmt = null;
}
if (conn != null)
{
conn.close();
conn = null;
}
}
catch (SQLException sqle)
{
BaseLogger.log("3", null, null, "SQLException executeAlterQueries inside finally:: "+ sqle.getMessage());
sqle.printStackTrace();
}
}
return updateCount;
}
*/
// Commented by Gagan B. on 13-NOV-25 -- END
/*
Added by Gagan B. on 13-NOV-25 [modifications in method to optimize and properly handle cases when
connection could not be made with any schema in case of All Enterprise] -- START
*/
private int executeQueries(Connection connection, HashMap<String, String> schemaListMap, String Sql, String tranID, String lineNo, String requestID, String userId, String chgTerm, boolean isThisObjectType)
{
ConnDriver connDriver = new ConnDriver();
int updateCount = 0;
if (schemaListMap == null || schemaListMap.isEmpty())
{
BaseLogger.log("3", null, null, "Schema list is empty, skipping execution.");
return 0;
}
BaseLogger.log("3", null, null, "Inside executeQueries. SQL to run: [" + Sql + "]");
BaseLogger.log("3", null, null, "Total schemas to process: [" + schemaListMap.size() + "]");
// Iterate through each schema provided in the map.
Iterator<String> itr = schemaListMap.keySet().iterator();
while (itr.hasNext())
{
String schema = itr.next();
String enterprise = schemaListMap.get(schema);
Connection conn = null;
Statement stmnt = null;
CallableStatement callableStmt = null;
String error = "";
int updCount = 0;
try
{
BaseLogger.log("3", null, null, "Attempting to connect to schema: [" + schema + "]");
conn = connDriver.getConnectDB(schema);
if (conn == null)
{
throw new Exception("Unable to get a valid connection for schema [" + schema + "]");
}
if (checkNull(Sql).trim().length() > 0)
{
if (isThisObjectType)
{
BaseLogger.log("3", null, null, "Executing as object type for schema [" + schema + "]");
String plsql = " begin " +
" dbms_metadata.set_transform_param ( DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', false ); " +
" end; ";
callableStmt = conn.prepareCall(plsql);
callableStmt.execute();
}
try
{
stmnt = conn.createStatement();
updCount = stmnt.executeUpdate(Sql);
updateCount = updCount; // Set the return value to the latest count.
error = ""; // Clear any previous error string
BaseLogger.log("3", null, null, "SUCCESS for schema [" + schema + "]. Rows affected: [" + updCount + "]");
insertIntoSqlExectionLog(connection, tranID, enterprise, lineNo, requestID, Sql, updCount, "C", userId, chgTerm, error);
}
catch (SQLException ise)
{
error = ise.getMessage();
BaseLogger.log("3", null, null, "FAILURE (SQLException) for schema [" + schema + "]. Error: [" + error + "]");
insertIntoSqlExectionLog(connection, tranID, enterprise, lineNo, requestID, Sql, updCount, "E", userId, chgTerm, error);
}
}
if (conn != null) {
conn.commit();
}
}
catch (Exception e)
{
error = e.getMessage();
BaseLogger.log("3", null, null, "FAILURE (General Exception) for schema [" + schema + "]. Error: [" + error + "]");
e.printStackTrace(); // Good for server logs to see the full trace.
try
{
insertIntoSqlExectionLog(connection, tranID, enterprise, lineNo, requestID, Sql, 0, "E", userId, chgTerm, error);
}
catch (Exception logEx)
{
BaseLogger.log("3", null, null, "CRITICAL: Failed to log error for schema [" + schema + "]");
logEx.printStackTrace();
}
}
finally
{
BaseLogger.log("3", null, null, "Cleaning up resources for schema [" + schema + "]");
try
{
if (callableStmt != null)
{
callableStmt.close();
}
if (stmnt != null)
{
stmnt.close();
}
if (conn != null)
{
conn.close();
}
}
catch (SQLException sqle)
{
BaseLogger.log("3", null, null, "SQLException during resource cleanup for schema ["+ schema +"]: " + sqle.getMessage());
sqle.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore the interrupted status
}
}
return updateCount;
}
/*
Added by Gagan B. on 13-NOV-25 [modifications in method to optimize and properly handle cases when
connection could not be made with any schema in case of All Enterprise] -- END
*/
//Added by Ashish.J one more parameter has added sql_exception
private String insertIntoSqlExectionLog( Connection conn, String refTranID, String enterprise, String lineNo,String requestID,String Sql,int updateCnt, String status, String userId,String chgTerm,String error) throws ITMException, RemoteException
{
System.out.println("inside insertIntoSqlExectionLog method");
String errorString="";
int insCount=0;
PreparedStatement pstmtIns=null;
ITMDBAccessEJB itmdbAccessLocal = new ITMDBAccessEJB();
try
{
System.out.println("inside try of method");
GenericUtility genericUtility = GenericUtility.getInstance();
String Aformat= genericUtility.getApplDateFormat();
java.text.SimpleDateFormat dtf= new java.text.SimpleDateFormat(Aformat);
String currDate = dtf.format(new java.util.Date());
System.out.println("currDate --> ["+currDate+"]");
System.out.println("insertIntoSqlExectionLog in --> ["+error+"]");
String tranID=generateTranID(conn);
String insSql="INSERT INTO SQL_EXEC_LOG(TRAN_ID,REF_TRAN_ID,ENTERPRISE,LINE_NO,REQ_ID,ORA_STMNT,CHG_DATE,CHG_USER,CHG_TERM,RESULT,STATUS,SQL_EXCEPTION) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
pstmtIns = conn.prepareStatement(insSql);
pstmtIns.setString(1, tranID);
pstmtIns.setString(2, refTranID);
pstmtIns.setString(3,enterprise);
pstmtIns.setString(4, lineNo);
pstmtIns.setString(5, requestID);
pstmtIns.setString(6, Sql);
pstmtIns.setTimestamp( 7,java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(checkNull(currDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()))); //Added by kailash on 24-04-18.
pstmtIns.setString( 8,userId);
pstmtIns.setString( 9,chgTerm);
pstmtIns.setInt( 10,updateCnt);
pstmtIns.setString( 11,status);
pstmtIns.setString( 12,error);
insCount = pstmtIns.executeUpdate();//Added by Ashish.J one more parameter has added sql_exception
System.out.println("insCount into strg_meet_items["+lineNo+"] insCount= ["+insCount+"]");
pstmtIns.clearParameters();
if (pstmtIns != null)
{
pstmtIns.close();
pstmtIns = null;
}
}
catch (Exception e)
{
errorString= itmdbAccessLocal.getErrorString("confirmed", "CONFFAILED", "","",conn);
return errorString;
}
finally
{
{
try
{
if (pstmtIns != null)
{
pstmtIns.close();
pstmtIns = null;
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
return errorString;
}
public String CancelLogTransaction( String tranId, String xtraParams, String forcedFlag ) throws RemoteException,ITMException
{
boolean isError = false;
ResultSet rs = null;
PreparedStatement pstmt = null;
Connection con = null;
ITMDBAccessEJB itmdbAccessLocal = null ;
String errString="";
String status="";
try
{
itmdbAccessLocal = new ITMDBAccessEJB();
GenericUtility genericUtility = GenericUtility.getInstance();
con = getConnection();
con.setAutoCommit(false);
String sql = "SELECT STATUS FROM SQL_EXEC_LOG WHERE TRAN_ID=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
if( rs.next() )
{
status = checkNull( rs.getString("STATUS") );
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
if("C".equalsIgnoreCase(status))
{
errString = itmdbAccessLocal.getErrorString("confirmed", "VTECLNCANC", "","",con);
System.out.println("errString is "+ errString);
}
else if("X".equalsIgnoreCase(status))
{
errString = itmdbAccessLocal.getErrorString("confirmed", "VTMCANL1", "","",con);
System.out.println("errString is "+ errString);
}
else
{
String userId = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
String upSql="UPDATE SQL_EXEC_LOG SET STATUS='X' WHERE TRAN_ID=?";
pstmt = con.prepareStatement(upSql);
pstmt.setString(1, tranId);
int updCnt = pstmt.executeUpdate();
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
System.out.println("update count is["+updCnt+"]");
if(updCnt>0)
{
errString = itmdbAccessLocal.getErrorString("confirmed", "VTLVECAR01", "","",con);
System.out.println("errString is "+ errString);
}
}
}
catch(Exception e)
{
isError = true;
try
{
con.rollback();
}
catch(Exception e1)
{
e1.printStackTrace();
}
e.printStackTrace();
throw new ITMException(e);
}
finally
{
try
{
if ( !(isError) )
{
con.commit();
//errString = itmdbAccessLocal.getErrorString("","TEMCONFIRM",loginEmpCode);
//errString = itmdbAccessLocal.getErrorString("confirmed", "TEMCONFIRM", "","",con);
}
else
{
con.rollback();
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if( con != null && !con.isClosed() )
{
con.close();
con = null;
}
}
catch( Exception e)
{
e.printStackTrace();
}
}
System.out.println("errString is +++:"+errString);
return errString;
}
public String ConfirmLog( String tranId, String xtraParams, String forcedFlag ) throws RemoteException,ITMException
{
System.out.println("managelogsql ConfirmLog........["+tranId+"]");
boolean isError = false;
String enterprises="";
String sql = "";
ResultSet rs = null;
PreparedStatement pstmt = null;
Connection con = null;
String errString = "";
String schemaName = "";
ITMDBAccessEJB itmdbAccessLocal = null ;
boolean isThisObject=false;
String sqlExecute="";
try
{
itmdbAccessLocal = new ITMDBAccessEJB();
GenericUtility genericUtility = GenericUtility.getInstance();
con = getConnection();
con.setAutoCommit(false);
String userId = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
sql = "SELECT ENTERPRISE FROM SQL_EXEC_LOG WHERE TRAN_ID=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
if( rs.next() )
{
enterprises = checkNull( rs.getString("ENTERPRISE") );
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
String EnterPriseInFormat=getFormattedStringBuff(enterprises);
sql = "SELECT SCHEMA_NAME,ENTERPRISE FROM ENTERPRISE WHERE ENTERPRISE IN("+EnterPriseInFormat+") " ;
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
if( rs.next() )
{
schemaName = checkNull( rs.getString("SCHEMA_NAME") );
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}
sql = "SELECT ORA_STMNT FROM SQL_EXEC_LOG WHERE TRAN_ID=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, tranId);
rs = pstmt.executeQuery();
if( rs.next() )
{
String oracleStatment = checkNull( rs.getString("ORA_STMNT") );
System.out.println("oracle execute statment["+oracleStatment+"]");
if( oracleStatment.lastIndexOf(";") != -1 )
{
if(!oracleStatment.toUpperCase().startsWith("CREATE"))
{
int endIndex=oracleStatment.lastIndexOf(";");
oracleStatment=oracleStatment.substring(0, endIndex);
}
else if(oracleStatment.toUpperCase().startsWith("CREATE TABLE"))
{
int endIndex=oracleStatment.lastIndexOf(";");
oracleStatment=oracleStatment.substring(0, endIndex);
}
}
if(oracleStatment.toUpperCase().startsWith("CREATE") && !oracleStatment.toUpperCase().startsWith("CREATE TABLE"))
{
isThisObject=true;
}
//if( oracleStatment.toUpperCase().startsWith("ALTER") || oracleStatment.toUpperCase().startsWith("INSERT INTO") || oracleStatment.toUpperCase().startsWith("UPDATE") || oracleStatment.toUpperCase().startsWith("DELETE"))
//{
sqlExecute=executeLogQueries(con,schemaName, oracleStatment,isThisObject) ;
//}
}
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
if ( rs != null )
{
rs.close();
rs = null;
}//changed by Ashish.J
if("SUCCESS".equalsIgnoreCase(sqlExecute))
{
//String upSql="UPDATE SQL_EXEC_LOG SET STATUS='C' WHERE TRAN_ID=?";
String upSql="UPDATE SQL_EXEC_LOG SET STATUS='C', RESULT = ?, SQL_EXCEPTION = ? WHERE TRAN_ID=?";
pstmt = con.prepareStatement(upSql);
pstmt.setInt(1, reUpdateCnt);
pstmt.setString(2, sqlError);
pstmt.setString(3, tranId);
int updCnt = pstmt.executeUpdate();
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
System.out.println("inside if update count is["+updCnt+"]");
if(updCnt>0)
{
errString = itmdbAccessLocal.getErrorString("confirmed", "VTCONFIRM", "","",con);
System.out.println("errString is "+ errString);
}
}
else
{
String upSql="UPDATE SQL_EXEC_LOG SET STATUS='E', RESULT = ?, SQL_EXCEPTION = ? WHERE TRAN_ID=?";
pstmt = con.prepareStatement(upSql);
pstmt.setInt(1, reUpdateCnt);
pstmt.setString(2, sqlError);
pstmt.setString(3, tranId);
int updCnt = pstmt.executeUpdate();
if( pstmt != null )
{
pstmt.close();
pstmt = null;
}
System.out.println("inside else update count is["+updCnt+"]");
errString = itmdbAccessLocal.getErrorString("confirmed", "CONFFAILED", "","",con);
}
}//Changed by Ashish.J
catch(Exception e)
{
isError = true;
try
{
con.rollback();
}
catch(Exception e1)
{
e1.printStackTrace();
}
e.printStackTrace();
throw new ITMException(e);
}
finally
{
try
{
System.out.println("Commiting and Closing Connection..........");
if ( !(isError) )
{
System.out.println( "inside finally if" );
con.commit();
//errString = itmdbAccessLocal.getErrorString("","TEMCONFIRM",loginEmpCode);
//errString = itmdbAccessLocal.getErrorString("confirmed", "TEMCONFIRM", "","",con);
}
else
{
System.out.println( "inside finally rollback else" );
con.rollback();
}
if( pstmt != null )
{
System.out.println( "inside finally if pstmt " );
pstmt.close();
pstmt = null;
}
if( con != null && !con.isClosed() )
{
System.out.println( "inside finally if con " );
con.close();
con = null;
}
}
catch( Exception e)
{
e.printStackTrace();
}
}
System.out.println("errString is +++:"+errString);
return errString;
}
private String executeLogQueries(Connection connection,String schemaName, String Sql,boolean isThisObjectType)
{
BaseLogger.log("3", null, null, "Inside executeQueries1 [" + Sql + "]");
ConnDriver connDriver = new ConnDriver();
Connection conn = null;
Statement stmnt = null;
int updateCount=0;
CallableStatement callableStmt = null;
String ExecuteSql="SUCCESS";
try
{
System.out.println("isThisObjectType1:::::["+isThisObjectType+"]");
conn = connDriver.getConnectDB(schemaName);
if( conn == null )
{
BaseLogger.log("3", null, null, "Unable to get connection for [" + schemaName + "]");
throw new Exception("Unable to get connection for [" + schemaName + "]");
}
if(checkNull(Sql).trim().length() > 0)
{
if(isThisObjectType)
{
String plsql = " begin " +
" dbms_metadata.set_transform_param ( DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', false ); " +
" end; ";
callableStmt = conn.prepareCall(plsql);
callableStmt.execute();
}
try
{
BaseLogger.log("3", null, null, "Inside manageconf try");
stmnt = conn.createStatement();
//int updateCnt = stmnt.executeUpdate(Sql);
reUpdateCnt = stmnt.executeUpdate(Sql);
BaseLogger.log("3", null, null, "schema["+schemaName+"]updateCnt to get Sql [" + updateCount + "]");
}
catch(SQLException ise)
{
sqlError = ise.getMessage();
BaseLogger.log("3", null, null, "Inside manageconf catch::"+ise.getMessage());
ExecuteSql="NOT EXECUTE";
throw new ITMException(ise);
}
finally
{
if (stmnt != null)
{
stmnt.close();
stmnt = null;
}
}
}
Thread.sleep(100);
conn.commit();
}
catch (Exception e)
{
try
{
BaseLogger.log("3", null, null, "Excepotion in executeAlterQueries occured while executing Alter Queries>>>>::" + e.getMessage());
ExecuteSql="NOT EXECUTE";
conn.rollback();
//sqlError = e.getMessage();
}
catch (SQLException sqle)
{
BaseLogger.log("3", null, null, "SQLException executeAlterQueries occured during rollback:: " + sqle.getMessage());
sqle.printStackTrace();
}
e.printStackTrace();
}
finally
{
try
{
if (callableStmt != null)
{
callableStmt.close();
callableStmt = null;
}
if (conn != null)
{
conn.close();
conn = null;
}
}
catch (SQLException sqle)
{
BaseLogger.log("3", null, null, "SQLException executeAlterQueries inside finally:: "+ sqle.getMessage());
sqle.printStackTrace();
}
}
return ExecuteSql;
}
private String generateTranID( Connection conn ) throws ITMException
{
String uniqueKey = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
//System.out.println("RealTimeReportPos : Generating Primary Key ...........");
String keyStringQuery = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = 'w_sql_exec_log' ";
pstmt = conn.prepareStatement(keyStringQuery);
rs = pstmt.executeQuery();
if(rs.next())
{
String keyString = rs.getString("KEY_STRING");
String keyCol = rs.getString("TRAN_ID_COL");
String tranSer = rs.getString("REF_SER");
String xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
xmlValues = xmlValues + "<Header></Header>";
xmlValues = xmlValues + "<Detail1>";
xmlValues = xmlValues + "<tran_id></tran_id>";
xmlValues = xmlValues + "</Detail1></Root>";
TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
uniqueKey = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
}
rs.close(); rs = null;
pstmt.close();
pstmt = null;
}
catch(Exception exp)
{
System.out.println("Exception : RealTimeReportPos :generateTransID :==>\n");
throw new ITMException(exp);
}
finally
{
try
{
if(rs != null)
{
rs.close();
rs = null;
}
if(pstmt != null)
{
pstmt.close();
pstmt = null;
}
}
catch (Exception e)
{
System.out.println("Exception : RealTimeReportPos :getUniqueKey :finally==>");
throw new ITMException(e);
}
}
System.out.println("Generated Primary Key :"+uniqueKey);
return uniqueKey;
}
//Created a method to execute the SQL in the schemas stored in the Enterprise table for the provided enterprise value by Ajit on 03-DEC-25 -- START
public void processSqlForEnterprise(Connection conn, String enterpriseCode, String inputSql) throws Exception {
inputSql = injectSchemaPlaceholder(inputSql);
System.out.println("inputSql :" + inputSql);
// Step 1: Fetch schemas
String query = "SELECT DB_DEV, DB_MAIN, DB_READ, DB_PILOT FROM enterprise WHERE enterprise = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, enterpriseCode);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
throw new Exception("No enterprise found for: " + enterpriseCode);
}
String dbDev = rs.getString("DB_DEV");
String dbMain = rs.getString("DB_MAIN");
String dbRead = rs.getString("DB_READ");
String dbPilot = rs.getString("DB_PILOT");
rs.close();
ps.close();
// Step 2: Schema execution rules
Map<String, String> schemaRules = new LinkedHashMap<>();
schemaRules.put(dbMain, "ALL");
schemaRules.put(dbDev, "ALL");
schemaRules.put(dbRead, "SYN");
schemaRules.put(dbPilot, "SYN");
boolean isCreateTable = inputSql.trim().toUpperCase().startsWith("CREATE TABLE");
// Extract table name from CREATE TABLE SCHEMA.TABLE pattern
String tableName = null;
if (isCreateTable) {
tableName = extractTableName(inputSql);
}
// Step 3: Execute based on rule
for (Map.Entry<String, String> entry : schemaRules.entrySet()) {
String schemaName = entry.getKey();
String rule = entry.getValue();
if (schemaName == null || schemaName.trim().isEmpty())
continue;
if (isCreateTable) {
// ===========================
// SPECIAL LOGIC FOR CREATE TABLE
// ===========================
if (rule.equals("ALL")) {
// Execute CREATE TABLE normally for MAIN + DEV
String finalSql = inputSql.replace("{SCHEMA}", schemaName);
System.out.println("Executing CREATE TABLE for schema: " + schemaName);
System.out.println("SQL: " + finalSql);
try (Statement stmt = conn.createStatement()) {
stmt.execute(finalSql);
}
}
else if (rule.equals("SYN")) {
// READ / PILOT special handling:
System.out.println("Processing CREATE TABLE special logic for schema: " + schemaName);
// 1. Create Synonym
String synonymSql =
"CREATE SYNONYM " + schemaName + "." + tableName +
" FOR " + dbMain + "." + tableName;
System.out.println("SQL: " + synonymSql);
try (Statement stmt = conn.createStatement()) {
stmt.execute(synonymSql);
}
// 2. Grant Privileges
String grantSql = "";
if (schemaName.equals(dbRead)) {
grantSql =
"GRANT SELECT ON " + dbMain + "." + tableName + " TO " + dbRead;
}
else if (schemaName.equals(dbPilot)) {
grantSql =
"GRANT INSERT, UPDATE, DELETE ON " + dbMain + "." + tableName + " TO " + dbPilot;
}
System.out.println("SQL: " + grantSql);
try (Statement stmt = conn.createStatement()) {
stmt.execute(grantSql);
}
}
continue; // skip normal execution
}
// ===========================
// Normal Flow (non CREATE TABLE)
// ===========================
if (rule.equals("SYN")) {
// Only allow CREATE SYNONYM
boolean isSynonymSql = inputSql.trim().toUpperCase().startsWith("CREATE SYNONYM");
if (!isSynonymSql) {
System.out.println("Skipping SQL for schema (only SYN allowed): " + schemaName);
continue;
}
}
String finalSql = inputSql.replace("{SCHEMA}", schemaName);
System.out.println("Executing for schema: " + schemaName);
System.out.println("SQL: " + finalSql);
try (Statement stmt = conn.createStatement()) {
stmt.execute(finalSql);
}
}
System.out.println("Execution completed successfully.");
}
//Created a method to execute the SQL in the schemas stored in the Enterprise table for the provided enterprise value by Ajit on 03-DEC-25 -- END
//Created a method to fetch the table name from provided SQL string by Ajit on 03-DEC-25 -- START
private String extractTableName(String sql) {
sql = sql.replace("\n", " ").replace("\t", " ");
sql = sql.toUpperCase();
// Expected: CREATE TABLE {SCHEMA}.TABLE_NAME
int idx = sql.indexOf("CREATE TABLE");
if (idx == -1) return null;
String after = sql.substring(idx + "CREATE TABLE".length()).trim();
// Remove schema
if (after.contains(".")) {
after = after.substring(after.indexOf(".") + 1).trim();
}
// Remove ( column definitions
if (after.contains("(")) {
after = after.substring(0, after.indexOf("(")).trim();
}
return after;
}
//Created a method to fetch the table name from provided SQL string by Ajit on 03-DEC-25 -- END
//Created a method to add a placeholder before the table name which will be replaced by the schema name by Ajit on 03-DEC-25 -- START
public static String injectSchemaPlaceholder(String sql) {
String trimmed = sql.trim().toUpperCase();
// For CREATE SYNONYM → It already contains schema explicitly
if (trimmed.startsWith("CREATE SYNONYM")) {
return sql; // Do NOT modify
}
// Patterns: UPDATE table, DELETE FROM table, INSERT INTO table
String regex = "(UPDATE|INTO|FROM)\\s+([A-Za-z0-9_]+)";
return sql.replaceAll(regex, "$1 {SCHEMA}.$2");
}
//Created a method to add a placeholder before the table name which will be replaced by the schema name by Ajit on 03-DEC-25 -- 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