Upload New File

parent 2edf1a34
package ibase.webitm.utility.uns;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.http.HttpResponse;
import ibase.ejb.CommonDBAccessEJB;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseException;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.UploadFileEJB;
import ibase.webitm.utility.E12ExternalAPICall;
import ibase.webitm.utility.ITMException;
/*
* Author: Gagan B.
* Date: 07-JUN-2023
* Purpose: Calling UNS API on confirm and sending JSON data for the tran ID.
* */
public class UNSAPICall extends ActionHandlerEJB {
UserInfoBean userInfoGlobal = new UserInfoBean();
StringBuffer compTrace = new StringBuffer("");
public String actionSendJSONData2UNS (String tranID, String xtraParam, Connection conn) throws ITMException {
String result = "";
String updateCNResult = "";
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
E12GenericUtility genericUtility = new E12GenericUtility();
DBAccessEJB dbAccess = new DBAccessEJB();
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS tranID gsb ["+ tranID +"]" );
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS xtraParam ["+ xtraParam +"]" );
String userCode = genericUtility.getValueFromXTRA_PARAMS(xtraParam,"loginCode");
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS userCode ["+ userCode +"]" );
try {
UserInfoBean userInfo = commonDBAccessEJB.createUserInfo(userCode);
userInfoGlobal = userInfo;
String objName = genericUtility.getValueFromXTRA_PARAMS(xtraParam,"objName");
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS objName ["+ objName +"]" );
if (objName.equals("follow_up_actions_logs"))
{
objName = dbAccess.getDBColumnValue( "FOLLOW_UP_ACTIONS_LOGS", "OBJ_NAME",
(" TRAN_ID = '"+ tranID +"' "), userInfo.getTransDB() );
tranID = dbAccess.getDBColumnValue( "FOLLOW_UP_ACTIONS_LOGS", "REF_ID",
(" OBJ_NAME = '"+ objName +"' AND TRAN_ID = '"+ tranID +"' "), userInfo.getTransDB() );
}
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS objName ["+ objName +"]");
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS tranID ["+ tranID +"]");
String xmlString = getDetailXMLDomString(objName, "1", "V", tranID, null);
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS xmlString ["+ xmlString +"]" );
// Tags to be removed
String[] tagsToRemove = { "Taxes", "Tax" };
// Remove tags from XML
xmlString = removeTagsFromXML(xmlString, tagsToRemove);
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS xmlString after removing taxes ["+ xmlString +"]" );
String formattedXML = getFormattedXML(xmlString,objName);
BaseLogger.log("3", null, null, "formattedXML string output="+formattedXML);
String jsonData = getSortedJson(formattedXML,objName);
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS jsonData ["+ jsonData +"]" );
String followUpActionLogDataFilePath = "/wildfly/vision_edi/data" + File.separator + objName
+ File.separator + userInfo.getEnterprise() + File.separator + "follow_up_actions_logs_data";
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS followUpActionLogDataFilePath ["+ followUpActionLogDataFilePath +"]" );
JSONObject jsonDataObj = new JSONObject(jsonData);
/*API CALLING LOGIC from ENT_EXT_API config gsb 28-MAR*/
/*
E12ExternalAPICall e12ExternalAPICall = new E12ExternalAPICall("UNS",userInfo);
String updateCNURL = getExternalAPIURL("UNS","updateCN");
BaseLogger.log("3", null, null, "Inside UNSAPICall updateCNURL [" + updateCNURL + "]");
if (updateCNURL.equalsIgnoreCase("")) {
String errMsg = "External endpoint not defined in AUTH_APPS_API";
result = "<ROOT><STATUS><![CDATA[1]]></STATUS><RESULT><![CDATA[" + errMsg + "]]></RESULT></ROOT>";
return result;
}
updateCNResult = e12ExternalAPICall.apiCallToPostData("UNS", updateCNURL, "A", "E", "", "", null, jsonDataObj, userInfo, "");
BaseLogger.log("3", null, null, "Inside UNSAPICall updateCNResult [" + updateCNResult + "]");
result = "<ROOT><STATUS><![CDATA[1]]></STATUS><RESULT><![CDATA[" + updateCNResult + "]]></RESULT></ROOT>";
BaseLogger.log( "3", null, null, "Inside sendJSONData2UNS updateCNResult ["+ updateCNResult +"]" );
JSONObject apiURLandParamterjsonObject = new JSONObject();
apiURLandParamterjsonObject.put("API_URL", updateCNURL);
apiURLandParamterjsonObject.put("JSON_DATA", jsonDataObj);
apiURLandParamterjsonObject.put("API_NAME", "UNS");
*/
// Gsb 28-mar START
String accessTokenURL = "https://unspride.in/unsccd/api/oauth/token";
// Set headers
Map<String, String> accessTokenHeaders = new HashMap<>();
// JSONObject headers = new JSONObject();
accessTokenHeaders.put("Content-Type", "application/json");
// Set parameters
JSONObject accessTokenParameters = new JSONObject();
accessTokenParameters.put("Username", "proteususer");
accessTokenParameters.put("Password", "Welcome@123");
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS headers [" + accessTokenHeaders + "]");
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS parameters [" + accessTokenParameters + "]");
String accessToken = makeApiCall(accessTokenURL, accessTokenHeaders, accessTokenParameters).getBody()
.toString();
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS accessToken [" + accessToken + "]");
JSONObject accessTokenJsonObject = new JSONObject(accessToken);
accessToken = accessTokenJsonObject.getString("accessToken");
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS accessToken2 [" + accessToken + "]");
BaseLogger.log("3", null, null,
"Inside sendJSONData2UNS accessToken from JSON Object [" + accessToken + "]");
// updateCN API call
// String updateCNURL = "https://wa-unspride-uat-ceindia.azurewebsites.net/api/CreditNoteProcess/UpdateCreditNoteNumber";
String updateCNURL = "https://unspride.in/unsccd/api/CreditNoteProcess/UpdateCreditNoteNumber";
// Set headers
Map<String, String> updateDNHeaders = new HashMap<>();
// JSONObject headers = new JSONObject();
updateDNHeaders.put("Content-Type", "application/json");
updateDNHeaders.put("Authorization", "Bearer " + accessToken);
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS headers [" + updateDNHeaders + "]");
updateCNResult = makeApiCall(updateCNURL, updateDNHeaders, jsonDataObj).getBody().toString();
result = "<ROOT><STATUS><![CDATA[1]]></STATUS><RESULT><![CDATA[" + updateCNResult + "]]></RESULT></ROOT>";
BaseLogger.log("3", null, null, "Inside sendJSONData2UNS updateCNResult [" + updateCNResult + "]");
JSONObject apiURLandParamterjsonObject = new JSONObject();
apiURLandParamterjsonObject.put("API_URL", updateCNURL);
apiURLandParamterjsonObject.put("JSON_DATA", jsonDataObj);
apiURLandParamterjsonObject.put("API_NAME", "UNS");
// Gsb 28-mar end
String apiURLAndParametrString = apiURLandParamterjsonObject.toString();
File DIR = null;
DIR = new File( followUpActionLogDataFilePath );
if ( ! DIR.exists() )
{
DIR.mkdirs();
BaseLogger.log( "3", null, null, "Directory Created..." );
}
String dataFileName = tranID + ".txt";
if ( jsonData.length() > 0 )
{
new E12GenericUtility().writeFile( followUpActionLogDataFilePath, dataFileName , apiURLAndParametrString );
}
} catch(Throwable exp) {
BaseLogger.log("0", null, null, "Exception in actionSendJSONData2UNS" );
exp.printStackTrace();
} finally {
BaseLogger.log("3", null, null, "Comp Trace String: [" +compTrace.toString()+ "]" );
result = "<ROOT><STATUS><![CDATA[1]]></STATUS>"
+ "<RESULT><![CDATA[" + E12GenericUtility.checkNull(updateCNResult) + "]]></RESULT>"
+ "<COMP_TRACE><![CDATA[" + compTrace.toString() + "]]></COMP_TRACE>"
+ "</ROOT>";
BaseLogger.log("3", null, null, "final result str: [" +result+ "]" );
}
return result;
}
private String getDetailXMLDomString( String objName, String objContext, String editFlag, String pkValues, String argFieldValues )throws RemoteException,ibase.webitm.utility.ITMException, ITMException
{
BaseLogger.log("3", null, null, "Inside the getDetailXMLDomString method [" + "]");
String resultString = "";
MasterStatefulLocal masterStateful=null;
try
{
masterStateful = (MasterStatefulLocal) getInitialContext().lookup( "ibase/MasterStatefulEJB/local" );
int randInt = new Random().nextInt();
masterStateful.setEditorId( ""+randInt );
masterStateful.setUserInfo( userInfoGlobal );
resultString = masterStateful.getDetailXMLDomString( objName, objContext, editFlag, pkValues, argFieldValues );
}
catch (NamingException e)
{
BaseLogger.log("0",null,null,"NamingException :: getDetailXMLDomString() :==>\n"+e.getMessage());
throw new ITMException(e);
}
finally
{
if(masterStateful!=null)
{
masterStateful.remove();
masterStateful=null;
}
}
return resultString;
}
private InitialContext getInitialContext() throws ITMException
{
InitialContext ctx = null;
try
{
AppConnectParm appConnect = new AppConnectParm();
ctx = new InitialContext( appConnect.getProperty() );
}
catch( ITMException itme )
{
BaseLogger.log("0",null,null, "ITMException : getInitialContext : "+ itme.getMessage() );
throw itme;
}
catch(Exception e)
{
BaseLogger.log("0",null,null, "Exception : getInitialContext : "+ e.getMessage() );
throw new ITMException(e);
}
return ctx;
}
private String getSortedJson(String xmlStr,String objName)
{
StringBuilder json = new StringBuilder("{\"Root\":{");
Document document = convertStringToDocument(xmlStr);
try {
UploadFileEJB uploadFileEJB = new UploadFileEJB();
Map<Integer, String> formDetailInfo = uploadFileEJB.getFormWiseTitleMap(objName, userInfoGlobal);
Map<String,List<String>> detailDataMap = new TreeMap<>();
for(int mapIndex =1;mapIndex<=formDetailInfo.size();mapIndex++)
{
NodeList detailNodeList = document.getElementsByTagName("Detail"+mapIndex);
for(int detailIndex=0;detailIndex<detailNodeList.getLength();detailIndex++) {
Node detailNode = detailNodeList.item(detailIndex);
BaseLogger.log("3", null, null,"DetailNode="+detailNode.getNodeName());
NodeList detailList = detailNode.getChildNodes();
String data = "";
for(int index=0;index<detailList.getLength();index++)
{
Node child = detailList.item(index);
if(child.getTextContent().contains("{") && child.getTextContent().contains("}") ) {
BaseLogger.log("3", null, null,"Found Json obj"+child.getTextContent());
String jsonData ="\""+ child.getTextContent().replace("\"", "\\\"")+"\"";
BaseLogger.log("3", null, null,"Found Json obj"+jsonData);
data+="\""+child.getNodeName()+"\":"+jsonData+",";
}
else if(child.getTextContent().equals("\"\"")) {
data+="\""+child.getNodeName()+"\":"+child.getTextContent()+",";
}
else {
data+="\""+child.getNodeName()+"\":\""+child.getTextContent()+"\",";
}
}
if(!data.equals("")) {
data="{"+data.substring(0,data.length()-1)+ "}";
}
if(!detailDataMap.containsKey(detailNode.getNodeName())) {
List<String>list = new ArrayList<>();
list.add(data);
detailDataMap.put(detailNode.getNodeName(), list);
}
else
{
List<String>list = detailDataMap.get(detailNode.getNodeName());
list.add(data);
detailDataMap.put(detailNode.getNodeName(),list);
}
}
}
detailDataMap.forEach((key,value)->{
json.append("\""+key+"\":");
json.append(value+",");
});
json.append("}}");
}
catch(Exception e)
{
BaseLogger.log("3", null, null,"Error in getSortedJson()"+e.getMessage());
}
BaseLogger.log("3", null, null,"Json String is :: "+json.toString().replace("],}", "]}"));
return json.toString().replace("],}", "]}");
}
private Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) );
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getFormattedXML(String result,String objName) {//with multiple rows
StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Root>");
try {
UploadFileEJB uploadFileEJB = new UploadFileEJB();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(result.getBytes()));
Map<Integer, String> formDetailInfo = uploadFileEJB.getFormWiseTitleMap(objName, userInfoGlobal);
BaseLogger.log("3", null, null,"formDetailInfoMAP=["+formDetailInfo+"]");
for(int mapIndex =1;mapIndex<=formDetailInfo.size();mapIndex++)
{
NodeList detailNodeList = document.getElementsByTagName("Detail"+mapIndex);
BaseLogger.log("3", null, null,"Detail node count="+detailNodeList.getLength());
for(int detailIndex=0;detailIndex<detailNodeList.getLength();detailIndex++)
{
if(!detailNodeList.item(detailIndex).getNodeName().contains("#"))
{
Node detailNode = detailNodeList.item(detailIndex);
xml.append("<"+detailNode.getNodeName()+">");
NodeList detailChildList = detailNode.getChildNodes();
for(int childIndex=0;childIndex<detailChildList.getLength();childIndex++) {
Node childNode = detailChildList.item(childIndex);
if(!childNode.getNodeName().contains("#") && !childNode.getNodeName().equalsIgnoreCase("attribute")) {
String data="\"\"";
if(childNode.hasChildNodes()) {
data = childNode.getFirstChild().getTextContent();
}
xml.append("<"+childNode.getNodeName()+"><![CDATA["+data+"]]>");
xml.append("</"+childNode.getNodeName()+">");
}//end check child empty
}
xml.append("</"+detailNode.getNodeName()+">");
}
}//end check empty node
}
xml.append("</Root>");
}catch(Exception e) {
e.printStackTrace();
}
BaseLogger.log("3", null, null,"xml String output="+xml.toString());
return xml.toString();
}
/*
public static HttpResponse<String> makeApiCall(String apiURL, Map<String, String> headers, JSONObject parameters) {
Unirest.setTimeouts(0, 0);
HttpResponse<String> response = null;
BaseLogger.log("3", null, null,"Inside makeApiCall");
try {
BaseLogger.log("3", null, null,"Inside makeApiCall try");
Unirest.setTimeouts(0, 0);
response = Unirest.post(apiURL)
.headers(headers)
.body(parameters)
.asString();
} catch (UnirestException e) {
e.printStackTrace();
}
return response;
}
*/
public HttpResponse<String> makeApiCall(String apiURL, Map<String, String> headers, JSONObject parameters) {
BaseLogger.log("3", null, null,"Inside makeApiCall ::");
BaseLogger.log("3", null, null, "Inside makeApiCall apiURL:" + "[" +apiURL+"] headers:" + "[" +headers+"] parameters:" + "[" +parameters+"] ");
compTrace.append("\n-- makeAPICall called apiURL: " +"[" +apiURL+"]");
Unirest.setTimeouts(0, 0);
HttpResponse<String> response = null;
try {
BaseLogger.log("3", null, null,"Inside makeApiCall try");
Unirest.setTimeouts(0, 0);
response = Unirest.post(apiURL)
.headers(headers)
.body(parameters)
.asString();
String statusText = response.getStatusText();
int statusCode = response.getStatus();
String responseString = response.getBody().toString();
System.out.println("Status text in makeApiCall:[" + statusText + "]");
System.out.println("Status Code in makeApiCall:[" + statusCode + "]");
System.out.println("responseString in makeApiCall:[" + responseString + "]");
System.out.println("responseString[" + response.toString() + "]");
compTrace.append("\nStatus text in makeApiCall:[" + statusText + "]");
compTrace.append("\nStatusCode makeApiCall:[" + statusCode + "]");
} catch (UnirestException e) {
e.printStackTrace();
} catch(Throwable exp) {
BaseLogger.log("0", null, null, "Exception getFormattedXML" );
exp.printStackTrace();
}
return response;
}
// Added by Gagan B. on 12th-JULY-23: to remove tags from XML [START]
public String removeTagsFromXML(String xml, String[] tagsToRemove) {
try {
BaseLogger.log("3", null, null,"Inside the removeTagsFromXML() ="+xml);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
// recursive call
removeTagsRecursive(document.getDocumentElement(), tagsToRemove);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
BaseLogger.log("3", null, null," removeTagsFromXML::::="+writer.toString());
return writer.toString();
} catch (Exception e) {
e.printStackTrace();
BaseLogger.log("3", null, null, "Inside the catch removeTagsFromXML Exception: " + e.getMessage());
//e.printStackTrace();
return null;
}
}
// Added by Gagan B. on 12th-JULY-23: to remove tags from XML [END]
// Added by Gagan B. on 10th-OCT-23: recursive method to check the tags to be removed in child nodes too to remove them [START]
private void removeTagsRecursive(Node node, String[] tagsToRemove)
{
BaseLogger.log("3", null, null,"Call the removeTagsRecursive() =");
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
removeTagsRecursive(childNode, tagsToRemove);
}
for (String tag : tagsToRemove) {
NodeList nodeList = element.getElementsByTagName(tag);
if (nodeList.getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node tagNode = nodeList.item(i);
tagNode.getParentNode().removeChild(tagNode);
}
}
}
}
}
// Added by Gagan B. on 10th-OCT-23: recursive method to check the tags to be removed in child nodes too to remove them [END]
// Added by Gagan B. to get API URL for 3rd party external API call's. on 17th-JULY-23 [START]
private String getExternalAPIURL(String appId, String serviceClass)
throws ITMException, SQLException {
BaseLogger.log("3", null, null,"Inside the getExternalAPIURL()and value of appId and serviceClass ="+appId +serviceClass);
String endpoint = "";
UserInfoBean userInfo = userInfoGlobal;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
ConnDriver connDriver = new ConnDriver();
connection = connDriver.getConnectDB(userInfo.getTransDB());
String getAPIDetailsSQL = "SELECT ENDPOINT, SERVICE_SETTING FROM AUTH_APPS_API WHERE APP_ID = ? AND SERVICE_CLASS = ?";
BaseLogger.log("3", null, null,"getAPIDetailsSQL:: ="+getAPIDetailsSQL );
pstmt = connection.prepareStatement(getAPIDetailsSQL);
pstmt.setString(1, appId);
pstmt.setString(2, serviceClass);
rs = pstmt.executeQuery();
while (rs.next()) {
String serviceSettingJson = rs.getString("service_setting");
BaseLogger.log("3", null, null,"serviceSettingJson value :: ="+serviceSettingJson );
if (serviceSettingJson != null) {
try {
BaseLogger.log("3", userInfo, null, "E12ExternalAPICall.getExternalAPIURL() serviceSettingJson = ["+ serviceSettingJson + "]");
JSONObject jsonObject = new JSONObject(serviceSettingJson);
if (jsonObject.has("isExternal") && jsonObject.getString("isExternal").equals("true")) {
endpoint = rs.getString("endpoint");
BaseLogger.log("3", userInfo, null, "E12ExternalAPICall.getExternalAPIURL() endpoint = ["+ endpoint + "]");
return endpoint;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
rs.close();
rs = null;
pstmt.close();
pstmt = null;
connection.close();
connection = null;
} catch (Exception e) {
BaseLogger.log("0", userInfo, null, "E12ExternalAPICall.callLoginApiAndSetSession() Exception = ["
+ E12GenericUtility.getStackTrace(e) + "]");
throw new ITMException(e);
} finally {
if (connection != null) {
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
if (connection != null) {
connection.close();
connection = null;
}
}
}
return endpoint;
}
// Added by Gagan B. to get API URL for 3rd party external API call's. on 17th-JULY-23 [END]
}
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