APISampleServlet

parent 4362b392
package ibase.webitm.servlet;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
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.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import ibase.ejb.CommonDBAccessEJB;
import ibase.planner.utility.ITMException;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.utility.XMLtoJSONConverter;
import ibase.webitm.bean.TemplateDetails;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.UploadFileEJB;
public class APISampleServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
//ArrayList<String> objName = new ArrayList<String>();
UserInfoBean userInfoGlobal = new UserInfoBean();
E12GenericUtility genericUtility = new E12GenericUtility();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside doGet method :: APISampleServlet Ankushs");
genericUtility = new E12GenericUtility();
String action = request.getParameter("action");
BaseLogger.log( "3", null, null, "action with file Type: APISample.jsp => ANKUSHS[ " + action + " ] ");
BaseLogger.log( "3", null, null, "Calling Ankushs");
if( action!=null && action.equals("downloadSampleData") ) {
BaseLogger.log( "3", null, null, "action: APISample.jsp => [ " + action + " ] ");
String result = "";
String objName = request.getParameter("objName");
String fileType = request.getParameter("fileType");
String refId = request.getParameter("reffId");
//String primaryKey = getTableAndPrimaryKey(objName, userInfoGlobal.getLoginCode()).get(1);
//String refId = getRandomPrimaryKeyValue(primaryKey, getTableAndPrimaryKey(objName, userInfoGlobal.getLoginCode()).get(0), userInfoGlobal.getLoginCode());
//refId = "GSBAPP";
BaseLogger.log( "3", null, null, "refId: APISample.jsp => [ " + refId + " ] ");
BaseLogger.log( "3", null, null, "fileType: APISample.jsp ==> [ " + fileType + " ] ");
BaseLogger.log( "3", null, null, "userInfoGlobal.getLoginCode(): APISample.jsp => [ " + userInfoGlobal.getLoginCode() + " ] ");
if(fileType!=null && fileType.equalsIgnoreCase("xml") ) {
result = downloadSampleDataXML(objName, refId, request, response);
}
else if(fileType!=null && fileType.equalsIgnoreCase("json")) {
//result = downloadSampleDataWithAttributes(objName, refId, request, response);
result = downloadJSONSampleData(objName, refId, request, response);
BaseLogger.log( "3", null, null, "JSON Data: APISample.jsp ==> [ " + result + " ] ");
}
else if(fileType!=null && fileType.equalsIgnoreCase("xmlWithAttrib")) {
//result = downloadSampleDataWithAttributes(objName, refId, request, response);
result = downloadSampleDataWithAttributes(objName, refId, request, response);
BaseLogger.log( "3", null, null, "XML Data with Attribute: APISample.jsp ==> [ " + result + " ] ");
}
BaseLogger.log( "3", null, null, "result: APISample.jsp => [ " + result + " ] ");
return;
}
String userCode = request.getParameter("userCode");
BaseLogger.log( "3", null, null, "userCode in APISampleCode from APISampleServlet : ["+ userCode +"]" );
String appId = request.getParameter("appId");
BaseLogger.log( "3", null, null, "appId in APISampleCode from APISampleServlet : ["+ appId +"]" );
Map<String, List<String>> endpoint_objectMap = new HashMap<>();
endpoint_objectMap = APISampleDropDown(userCode, appId);
BaseLogger.log( "3", null, null, "endpoint_objectMaps: APISample.jssp => [ " + endpoint_objectMap + " ] ");
PrintWriter out = response.getWriter();
JSONObject endpointObjectJSON = new JSONObject(endpoint_objectMap);
response.setContentType("application/json");
out.print(endpointObjectJSON);
BaseLogger.log( "3", null, null, "endpointObjectJSON: APISample.jsp => [ " + endpointObjectJSON + " ] ");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(arg0, arg1);
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(req, res);
}
public Map<String, List<String>> APISampleDropDown(String userCode, String appId) {
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
Map<String, List<String>> endpoint_objectMap = new HashMap<String, List<String>>();
try {
UserInfoBean userInfo = commonDBAccessEJB.createUserInfo(userCode);
userInfoGlobal = userInfo;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ConnDriver connDriver = new ConnDriver();
String sqlEndpointandObjectList = "SELECT ENDPOINT, OBJ_NAME FROM AUTH_APPS_API WHERE APP_ID = ?";
try {
if ( userInfo != null ) {
BaseLogger.log( "3", null, null, "userInfo: APISample.jsp => [ " + userInfo + " ] ");
}
conn = connDriver.getConnectDB(userInfo);
pstmt = conn.prepareStatement(sqlEndpointandObjectList);
pstmt.setString(1, appId);
rs = pstmt.executeQuery();
while (rs.next()) {
if(endpoint_objectMap.containsKey(rs.getString("OBJ_NAME"))) {
endpoint_objectMap.get(rs.getString("OBJ_NAME")).add(rs.getString("ENDPOINT"));
} else {
ArrayList<String> endpointList = new ArrayList<String>();
endpointList.add(rs.getString("ENDPOINT"));
endpoint_objectMap.put(rs.getString("OBJ_NAME"), endpointList);
}
}
BaseLogger.log( "3", null, null, "endpoint_objectMap: APISample.jsp => [ " + endpoint_objectMap + " ] ");
} catch (SQLException e)
{
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();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return endpoint_objectMap;
}
public String downloadSampleDataWithAttributes(String objName, String refId, HttpServletRequest request, HttpServletResponse response) {
BaseLogger.log( "3", null, null, "Inside downloadSampleData() ");
String result = "";
Document valueDom = null;
List<Node>domList = new ArrayList<>();
List<NodeList>columnObjList = new ArrayList<>();
List<NodeList>textObjList = new ArrayList<>();
try {
UploadFileEJB uploadFileEJB = new UploadFileEJB();
result = getDetailXMLDomString( objName, "1", "V", refId, null );
Map<Integer, String> formDetailInfo = uploadFileEJB.getFormWiseTitleMap(objName, userInfoGlobal);
//NodeList attribNodeList = null;
for(int mapIndex=1;mapIndex<=formDetailInfo.size();mapIndex++) {
domList.add(getTableDefinitionaNode(objName, mapIndex));
columnObjList.add(getColumnObjectNodeList(objName,mapIndex,"ColumnObject"));
textObjList.add(getColumnObjectNodeList(objName,mapIndex,"TextObject"));
}
valueDom = convertStringToDocument(result);
//result = getXMLAttribute;
BaseLogger.log( "3", userInfoGlobal, null, "DomList size=["+domList.size()+"]");
BaseLogger.log( "3", userInfoGlobal, null, "columnObjList size=["+columnObjList.size()+"]");
BaseLogger.log( "3", userInfoGlobal, null, "textObjList size=["+textObjList.size()+"]");
} catch (RemoteException e) {
e.printStackTrace();
} catch (ibase.webitm.utility.ITMException e) {
e.printStackTrace();
} catch (ITMException e) {
e.printStackTrace();
}
String resultXMLWithAttributes = getXMLWithAttribute(valueDom,domList,columnObjList,textObjList);
BaseLogger.log("3", null, null, "result: downloadSampleData() = [ " + resultXMLWithAttributes + " ] ");
byte[] byteArrray = resultXMLWithAttributes.getBytes();
BaseLogger.log("3", null, null, "byteArrray: downloadSampleData() =[ " + Arrays.asList(byteArrray) + " ] ");
//response.setContentType("application/text");
response.setContentType("text/xml");
response.setHeader("Content-Disposition", "attachment;filename=SampleData.xml");
OutputStream out;
try {
out = response.getOutputStream();
out.write(byteArrray);
BaseLogger.log("3", null, null, "Writting done to response " );
} catch (IOException e) {
BaseLogger.log("3", null, null, "catch: downloadSampleData() => [ " + e.getMessage() + " ] ");
e.printStackTrace();
}
return resultXMLWithAttributes;
}
//Added By Ankush S on 08-MAR-2023 [to get column Attributes]START
private String getXMLWithAttribute(Document valueDom, List<Node> nodeList,List<NodeList> columnObjList,List<NodeList> textObjList) {
StringBuilder xml=new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Root>");
try {
for(int detail=0;detail<nodeList.size();detail++) {
NodeList detailNodeList = valueDom.getElementsByTagName("Detail"+(detail+1));
BaseLogger.log("3", null, null, "Detail Node Name =[ "+detailNodeList.getLength()+"]");
String detailWithAttrib = getDetailAttributes(detailNodeList,nodeList.get(detail),columnObjList.get(detail),textObjList.get(detail));
xml.append(detailWithAttrib);
}
} catch (Exception e) {
}
xml.append("</Root>");
BaseLogger.log("3", null, null, "xml stinrg with Attributes String if not size====> [ "+xml.toString());
return xml.toString();
}
//Added By Ankush S on 08-MAR-2023 [to get column Attributes]END
//Added By Ankush S on 08-MAR-2023 [to get Detail node Attributes]START
private String getDetailAttributes(NodeList detailNodeList, Node attribNode,NodeList colNodeList,NodeList textNodeList) {
StringBuilder detailString = new StringBuilder("");
BaseLogger.log("3", null, null, "AttribNode name => [ "+attribNode.getNodeName());
BaseLogger.log("3", null, null, "Detail Node List size => [ "+detailNodeList.getLength());
BaseLogger.log("3", null, null, "col Node List size => [ "+colNodeList.getLength());
BaseLogger.log("3", null, null, "text Node List size => [ "+textNodeList.getLength());
try {
for(int detailIndex=0;detailIndex<detailNodeList.getLength();detailIndex++) {
String pkName="";
Node detailNode = detailNodeList.item(detailIndex);
detailString.append("<"+detailNode.getNodeName());
//detailString.append(" dbID=\""+detailNode.getAttributes().getNamedItem("dbID").getNodeValue());
//detailString.append("\" domID=\""+detailNode.getAttributes().getNamedItem("domID").getNodeValue());
//detailString.append("\" id=\""+detailNode.getAttributes().getNamedItem("id").getNodeValue());
//detailString.append("\" objContext=\""+detailNode.getAttributes().getNamedItem("objContext").getNodeValue());
detailString.append(" objName=\""+detailNode.getAttributes().getNamedItem("objName").getNodeValue()+"\"");
NodeList detailChailds = detailNode.getChildNodes();
/* Node attributeNode = detailChailds.item(0);
if(attributeNode!=null) {
BaseLogger.log("3", null, null, "attributeNode Node Name => [ "+attributeNode.getNodeName());
detailString.append(attributeNode.getAttributes().getNamedItem("pkNames")+" ");
}*/
//detailString.append("\">");
//detailString.append(">");
for(int childIndex=0;childIndex<detailChailds.getLength();childIndex++) {
Node childNode = detailChailds.item(childIndex);
String columnWithAttribute="";
String isRequired="";
if(!childNode.getNodeName().contains("#")) {
BaseLogger.log("3", null, null, "child node to check=======>"+childNode.getNodeName());
if(childNode.getNodeName().equalsIgnoreCase("attribute")) {
columnWithAttribute+="<"+childNode.getNodeName()+" "
+childNode.getAttributes().getNamedItem("pkNames")+" "
+childNode.getAttributes().getNamedItem("selected")+" "
+childNode.getAttributes().getNamedItem("status")+" "
+childNode.getAttributes().getNamedItem("updateFlag")+" />";
pkName=childNode.getAttributes().getNamedItem("pkNames").toString();
detailString.append(" "+pkName+" ");
detailString.append(">");
//detailString.append(columnWithAttribute);
//detailString.append(childNode.getAttributes().getNamedItem("pkNames")+" ");
//detailString.append("\">");
// BaseLogger.log("3", null, null, "Attributes tag with attribute new=> [ "+columnWithAttribute);
}else {
//BaseLogger.log("3", null, null, "col name name => [ "+childNode.getNodeName()+"] label="+getLabelName(childNode.getNodeName(),textNodeList));
columnWithAttribute ="<"+childNode.getNodeName()+" "+getLabelName(childNode.getNodeName(),textNodeList);
columnWithAttribute =columnWithAttribute+ getColumnAttributes(attribNode,childNode.getNodeName());
//BaseLogger.log("3", null, null, "columnWithAttribute==>"+columnWithAttribute);
if(columnWithAttribute.length()!=0) {
isRequired = getIsRequired(childNode.getNodeName(),colNodeList);
//BaseLogger.log("3", null, null, "required column check==>"+childNode.getNodeName()+" isRequired="+isRequired);
if(isRequired.equalsIgnoreCase("Yes")) {
//BaseLogger.log("3", null, null, "required column==>"+isRequired);
columnWithAttribute=columnWithAttribute+" required=\""+isRequired+"\">";
}
else {
columnWithAttribute=columnWithAttribute+">";
}
columnWithAttribute+="<![CDATA["+childNode.getTextContent()+"]]></"+childNode.getNodeName()+">";
//BaseLogger.log("3", null, null, "Column with Attribute=====> "+columnWithAttribute);
detailString.append(columnWithAttribute);
}
}
}
}
detailString.append("</"+detailNode.getNodeName()+">");
}
BaseLogger.log("3", null, null, "Detail String [ "+detailString.toString());
} catch (Exception e) {
BaseLogger.log("3", null, null, "Error in getDetailAttributes() [ "+e.getMessage());
}
return detailString.toString();
}
//Added By Ankush S on 08-MAR-2023 [to get Detail node Attributes]END
//Added By Ankush S on 08-MAR-2023 [to get Column Attributes]START
private String getColumnAttributes(Node attribNode, String nodeName) {
StringBuilder attribute = new StringBuilder("");
try {
BaseLogger.log("3", null, null, "Find Attributes for column===> [ "+nodeName);
NodeList tableDefinitionList = attribNode.getChildNodes();
Node attributeNode = null;
for(int index=0;index<tableDefinitionList.getLength();index++) {
if(attributeNode!=null) {
break;
}
Node tableColNode = tableDefinitionList.item(index);
if(!tableColNode.getNodeName().contains("#") &&!tableColNode.getNodeName().equalsIgnoreCase("attribute") ) {
//BaseLogger.log("3", null, null, "Table column Node Name===> [ "+tableColNode.getNodeName());
NodeList tableColumnChilds = tableColNode.getChildNodes();
for(int childIndex=0;childIndex<tableColumnChilds.getLength();childIndex++) {
Node child = tableColumnChilds.item(childIndex);
if(!child.getNodeName().contains("#")) {
//BaseLogger.log("3", null, null, "Table column Child Node Name===> [ "+child.getNodeName()+" value=["+child.getTextContent());
}
if(child.getNodeName().equalsIgnoreCase("name")&& child.getTextContent().equalsIgnoreCase(nodeName)) {
attributeNode = tableColNode;
break;
}
}
}
}
if(attributeNode!=null) {
NodeList attribNodes = attributeNode.getChildNodes();
//String attributeStr="<"+nodeName+" ";
String attributeStr=" ";
for(int index=0;index<attribNodes.getLength();index++) {
Node attrNode = attribNodes.item(index);
if(attrNode!=null && !attrNode.getNodeName().contains("#") &&!attrNode.getNodeName().equalsIgnoreCase("retrieve"))
{
BaseLogger.log("3", null, null, "Attrib Node name="+attrNode.getNodeName());
if (attrNode.getNodeName().equalsIgnoreCase("type")) {
attributeStr = attributeStr + attrNode.getNodeName() + "=\"" + attrNode.getTextContent() + "\" ";
if(attrNode.getAttributes().getNamedItem("size")!=null)
{
attributeStr+="size=\""+attrNode.getAttributes().getNamedItem("size").getNodeValue()+"\" ";
}
if(attrNode.getAttributes().getNamedItem("precision")!=null)
{
attributeStr+="precision=\""+attrNode.getAttributes().getNamedItem("precision").getNodeValue()+"\" ";
}
}
else if(!attrNode.getNodeName().equalsIgnoreCase("values")) {
//attributeStr = attributeStr + attrNode.getNodeName() + "=\"" + attrNode.getTextContent() + "\" ";
}
else {
}
}
}
//attributeStr=attributeStr+">";
//BaseLogger.log("3", null, null, "Attribute String with Attribute===> [ "+attributeStr.toString());
attribute.append(attributeStr);
}
} catch (Exception e) {
BaseLogger.log("3", null, null, "Error in getColumnAttributes() for ===> [ "+nodeName+""+e.getMessage());
e.printStackTrace();
}
return attribute.toString();
}
//Added By Ankush S on 15-MAR-2023[to get label name from column Object Node List List]START
private String getIsRequired(String columnName, NodeList colNodeList) {
String isRequired="N";
try {
for(int nodeIndex=0;nodeIndex<colNodeList.getLength();nodeIndex++) {
Node node = colNodeList.item(nodeIndex);
//BaseLogger.log("3", null, null, "colNode Name="+node.getNodeName());
NodeList colObjList = node.getChildNodes();
int flag=0;
for(int colObjIndex = 0;colObjIndex<colObjList.getLength();colObjIndex++) {
Node childNode = colObjList.item(colObjIndex);
if(childNode.getNodeName().equalsIgnoreCase("name") && childNode.getTextContent().equals(columnName)) {
flag=1;
}
if(flag==1) {
if(childNode.getNodeName().equalsIgnoreCase("EditStyle")) {
NodeList editChildList = childNode.getChildNodes();
for(int index=0;index<editChildList.getLength();index++) {
if(editChildList.item(index).getNodeName().equals("required")) {
isRequired=editChildList.item(index).getTextContent();
BaseLogger.log("3", null, null, "column Name to check="+columnName+" Required="+isRequired);
return isRequired;
}
}
}
}
//BaseLogger.log("3", null, null, "childNode Name="+childNode.getNodeName());
}
}
} catch (Exception e) {
BaseLogger.log("3", null, null, "Error in getIsRequired() [ "+e.getMessage());
}
return isRequired;
}
//Added By Ankush S on 15-MAR-2023[to get label name from column Object Node List List]END
//Added By Ankush S on 15-MAR-2023[to get label name from textObjectNode List]START
private String getLabelName(String columnName,NodeList textNodeList) {
try {
Node textObjNode =null;
String label = "";
for(int textNodeIndex=0;textNodeIndex<textNodeList.getLength();textNodeIndex++) {
Node textNode = textNodeList.item(textNodeIndex);
for(int index=0;index<textNode.getChildNodes().getLength();index++) {
Node childNode = textNode.getChildNodes().item(index);
if(childNode.getNodeName().equalsIgnoreCase("name") && childNode.getTextContent().equalsIgnoreCase(columnName+"_t")) {
textObjNode = textNode;
break;
}
}
}
if(textObjNode!=null) {
for(int index=0;index<textObjNode.getChildNodes().getLength();index++) {
if(textObjNode.getChildNodes().item(index).getNodeName().equalsIgnoreCase("text")) {
label = textObjNode.getChildNodes().item(index).getTextContent();
}
}
}
label = label.length()>0?label.substring(0, label.length()-1):"";
return "label=\""+label.trim()+"\" ";
} catch (Exception e) {
BaseLogger.log("3", null, null, "Error in getLabelName() [ "+e.getMessage());
return "";
}
}
//Added By Ankush S on 15-MAR-2023[to get label name from textObjectNode List]END
//Added By Ankush S on 08-MAR-2023 [to get Column Attributes]START
public String downloadSampleDataXML(String objName, String refId, HttpServletRequest request, HttpServletResponse response) {
BaseLogger.log( "3", null, null, "Inside downloadSampleData() ");
String result = "";
try {
result = getDetailXMLDomString( objName, "1", "V", refId, null );
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ibase.webitm.utility.ITMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ITMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedXML = getFormattedXML(result, objName);
BaseLogger.log("3", null, null, "result: downloadSampleData() => [ " + formattedXML + " ] ");
byte[] byteArrray = formattedXML.getBytes();
BaseLogger.log("3", null, null, "byteArrray: downloadSampleData() => [ " + byteArrray + " ] ");
//response.setContentType("application/text");
response.setContentType("text/xml");
response.setHeader("Content-Disposition", "attachment;filename=SampleData.xml");
OutputStream out;
try {
out = response.getOutputStream();
out.write(byteArrray);
} catch (IOException e) {
BaseLogger.log("3", null, null, "catch: downloadSampleData() => [ " + e.getMessage() + " ] ");
e.printStackTrace();
}
return result;
}
public String downloadJSONSampleData(String objName, String refId, HttpServletRequest request, HttpServletResponse response) {
BaseLogger.log( "3", null, null, "JSON Inside downloadSampleData() ");
String result = "";
String JSONString = "";
try {
result = getDetailXMLDomString( objName, "1", "V", refId, null );
XMLtoJSONConverter converter = new XMLtoJSONConverter();
//JSONString = converter.xmlToJSONString(result);
BaseLogger.log("3", null, null, "result: downloadJSONSampleData() => [ " +result+ " ] ");
String formattedXML = getFormattedXML(result,objName);
BaseLogger.log("3", null, null, "formattedXML string output="+formattedXML);
//JSONString = converter.xmlToJSONString(formattedXML);
//Commented by Ankush S on 24-MAR-2023 [It will not maintain detail tag order]
//JSONString = XML.toJSONObject(formattedXML).toString();
//json = XML.toJSONObject(formattedXML);
JSONString = getSortedJson(formattedXML,objName);
BaseLogger.log("3", null, null, "json string output="+JSONString);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error=====>"+e.getMessage());
e.printStackTrace();
}
BaseLogger.log("3", null, null, "result: downloadSampleData() => [ " + JSONString + " ] ");
//JSONString = getFormattedJSON(JSONString);
byte[] byteArrray = JSONString.getBytes();
BaseLogger.log("3", null, null, "byteArrray: downloadSampleData() => [ " + byteArrray + " ] ");
response.setContentType("application/text");
//response.setContentType("application/json");
response.setHeader("Content-Disposition", "attachment;filename=SampleData.json");
OutputStream out;
try {
out = response.getOutputStream();
out.write(byteArrray);
//out.write(json);
} catch (IOException e) {
BaseLogger.log("3", null, null, "catch: downloadSampleData() => [ " + e.getMessage() + " ] ");
e.printStackTrace();
}
return result;
}
//Added By Ankush s on 29-JAN-2023 to formate xml data START
private String getFormattedXML2(String result,String objName) {
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 nodes = document.getElementsByTagName("Detail"+mapIndex);
BaseLogger.log("3", null, null,"Detail node count="+nodes.getLength());
for(int i=0;i<nodes.getLength();i++) {
BaseLogger.log("3", null, null,"detailNodeName===>"+nodes.item(i).getNodeName());
NodeList detailList = nodes.item(i).getChildNodes();
if(xml.indexOf("<"+nodes.item(i).getNodeName()+">")==-1) {
BaseLogger.log("3", null, null,"detail not exist=======>"+"<"+nodes.item(i).getNodeName()+">");
xml.append("<"+nodes.item(i).getNodeName()+">");
for(int dindex=0;dindex<detailList.getLength();dindex++) {
Node colNode = detailList.item(dindex);
if(!colNode.getNodeName().contains("#")&&!colNode.getNodeName().equals("attribute")) {
BaseLogger.log("3", null, null,"NodeName===>"+detailList.item(dindex).getNodeName());
String data="\"\"";
if(colNode.hasChildNodes()) {
data = colNode.getFirstChild().getTextContent();
}
xml.append("<"+colNode.getNodeName()+"><![CDATA["+data+"]]>");
xml.append("</"+colNode.getNodeName()+">");
}
}
xml.append("</"+nodes.item(i).getNodeName()+">");
}
}
}
xml.append("</Root>");
}catch(Exception e) {
e.printStackTrace();
}
return xml.toString();
}
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()+">"); //add code for detail1 extra attributes
xml.append("<objName>"+objName + "</objName>");
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();
}
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(child.getTextContent().equals("\"\"")) {
data+="\""+child.getNodeName()+"\":"+child.getTextContent()+",";
}
else {
data+="\""+child.getNodeName()+"\":\""+child.getTextContent()+"\",";
}*/
}
if(!data.equals("")) {
data="{"+data.substring(0,data.length()-1)+ "}";
}
// BaseLogger.log("3", null, null,"Data Json=="+data);
//
//BaseLogger.log("3", null, null,"data string="+detailNode.getNodeName()+"["+data+"}");
if(!detailDataMap.containsKey(detailNode.getNodeName())) {
//BaseLogger.log("3", null, null,"Key Not Found==");
List<String>list = new ArrayList<>();
list.add(data);
detailDataMap.put(detailNode.getNodeName(), list);
}
else
{
//BaseLogger.log("3", null, null,"Key Found==");
List<String>list = detailDataMap.get(detailNode.getNodeName());
list.add(data);
detailDataMap.put(detailNode.getNodeName(),list);
}
}
}
detailDataMap.forEach((key,value)->{
//BaseLogger.log("3", null, null,"Key json="+key);
json.append("\""+key+"\":");
//BaseLogger.log("3", null, null,"value json="+value);
json.append(value+",");
});
json.append("}}");
//BaseLogger.log("3", null, null,"Detail Data with quot treeMap"+detailDataMap.toString());
//BaseLogger.log("3", null, null,"Formatted with old JSON String==["+json);
}catch(Exception e) {
BaseLogger.log("3", null, null,"Error in getSortedJson()"+e.getMessage());
}
return json.toString().replace("],}", "]}");
}
//Added By Ankush s on 29-JAN-2023 to formate xml data END
//Added By Ankush S on 16-JAN-2023 [for getting Json file as Json Array format] START
public String getFormattedJSON(String jsonString) {
try {
JSONObject jsonObj = new JSONObject(jsonString);
Iterator keys = jsonObj.keys();
List<String> objList = new ArrayList<>();
while (keys.hasNext()) {
String key = keys.next().toString();
JSONObject rootJson = jsonObj.getJSONObject(key);
Iterator rootKeys = rootJson.keys();
while (rootKeys.hasNext()) {
String childKey = rootKeys.next().toString();
JSONObject detail = rootJson.getJSONObject(childKey);
objList.add("\"" + childKey + "\":[" + detail + "]");
}
}
Collections.sort(objList);
StringBuffer finalJsonString = new StringBuffer("{\"Root\":{");
for (String string : objList) {
if (objList.indexOf(string) != objList.size() - 1) {
finalJsonString.append(string.replace("\"\\\"\\\"\"", "\"\""));
finalJsonString.append(",");
} else {
finalJsonString.append(string.replace("\"\\\"\\\"\"", "\"\""));
}
}
finalJsonString.append("}}");
System.out.println(finalJsonString.toString());
return finalJsonString.toString();
} catch (Exception e) {
return "";
}
}
//Added By Ankush S on 16-JAN-2023 [for getting Json file as Json Array format] START
/**
* get detail xmlstring from MasterStatefulEJB for provided object
*
* @param objName
* @param objContext
* @param editFlag
* @param pkValues
* @param argFieldValues
* @return
* @throws RemoteException
* @throws ITMException
*/
private String getDetailXMLDomString( String objName, String objContext, String editFlag, String pkValues, String argFieldValues )throws RemoteException,ibase.webitm.utility.ITMException, ITMException
{
String resultString = "";
//Added By Nilesh Start ::12-05-2017
MasterStatefulLocal masterStateful=null;
//Added By Nilesh End ::12-05-2017
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);
}
//Added By Nilesh Start ::12-05-2017
finally
{
if(masterStateful!=null)
{
masterStateful.remove();
masterStateful=null;
}
}
//Added By Nilesh End ::12-05-2017
return resultString;
}
/**
* It creates a object of InitialContext & returns the same.
*
* @return
* @throws ITMException
*/
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;
}
@SuppressWarnings("unused")
private List<String>getTableAndPrimaryKey(String objName, String userCode){
List<String> dataList = new ArrayList<>();
Connection conn = null;
Statement pstmt = null;
try {
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
ConnDriver connDriver = new ConnDriver();
UserInfoBean userInfo = commonDBAccessEJB.createUserInfo(userCode);
String sql = "SELECT TABLE_NAME,TRAN_ID_COL FROM TRANSETUP WHERE TRAN_WINDOW='w_"+objName+"'";
conn = connDriver.getConnectDB(userInfo);
pstmt = conn.createStatement();
ResultSet rs = pstmt.executeQuery(sql);
if(rs.next()) {
dataList.add(rs.getString("TABLE_NAME"));
dataList.add(rs.getString("TRAN_ID_COL"));
}
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
if(dataList.size()>0) {
System.out.println("Query="+dataList.get(1));
if("null".equals(dataList.get(1)) ||
null==dataList.get(1) ||
dataList.get(1).equals(""))
{
String query = "SELECT cols.column_name "
+ "FROM all_constraints cons, all_cons_columns cols "
+ "WHERE cols.table_name = '"+dataList.get(0).toUpperCase()+"' "
+ "AND cons.constraint_type = 'P' "
+ "AND cons.constraint_name = cols.constraint_name "
+ "AND cons.owner = cols.owner "
+ "AND POSITION='1' "
+ "ORDER BY cols.table_name, cols.position";
System.out.println("Query="+query);
pstmt = conn.createStatement();
rs = pstmt.executeQuery(query);
if(rs.next()) {
dataList.add(1,rs.getString("column_name"));
}
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
}
}
return dataList;
}
public String getRandomPrimaryKeyValue(String primaryKey, String tableName, String userCode ) {
String randomValue = "";
Connection conn = null;
Statement pstmt = null;
try {
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
ConnDriver connDriver = new ConnDriver();
UserInfoBean userInfo = commonDBAccessEJB.createUserInfo(userCode);
String sql = "SELECT " + primaryKey + " FROM " + tableName + " ORDER BY DBMS_RANDOM.value FETCH NEXT 1 ROWS ONLY";
conn = connDriver.getConnectDB(userInfo);
pstmt = conn.createStatement();
ResultSet rs = pstmt.executeQuery(sql);
if(rs.next()) {
randomValue = rs.getString(1);
}
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
}
}
return randomValue;
}
public FileOutputStream writeFile(String fileContent) {
String fileName = "SampleData.txt";
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
byte[] strToBytes = fileContent.getBytes();
outputStream.write(strToBytes);
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outputStream;
}
//Added By Ankush S on 08-MAR-2023 [to get column Attributes]START
private Node getTableDefinitionaNode(String objName,int tabNo) {
Document document =null;
Node node =null;
try {
document = getMetaDocument(objName, tabNo,"1");
node =document.getElementsByTagName("TableDefinition").item(0);
} catch (Exception e) {
BaseLogger.log("3", null, null, "Exception reading sample=[ " + e.getMessage() + "]");
}
return node;
}
//Added By Ankush S on 08-MAR-2023 [to get column Attributes]END
private NodeList getColumnObjectNodeList(String objName, int tabNo,String tagName){
NodeList objList = null;
try {
objList =getMetaDocument(objName, tabNo,"2").getElementsByTagName(tagName);
} catch (Exception e) {
BaseLogger.log( "3", null, null, "Erorr in getTextObjectNodeList "+e.getMessage());
}
return objList;
}
//Added By Ankush S on 08-MAR-2023 [to create Document from String]START
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;
}
//Added By Ankush S on 08-MAR-2023 [to create Document from String]END
private Document getMetaDocument(String objName, int tabNo,String pageContext) {
Document document = null;
try {
//String pageContext = "1";
String objContext = String.valueOf(tabNo);
String editor = "WebEditor";
// Map<String,String>colNames = getActualColListMap(objName,tabNo);
HashMap<String, String> propEditorInfoMap = new HashMap<String, String>();
if (userInfoGlobal != null) {
propEditorInfoMap.put("PROFILE_ID_RES", userInfoGlobal.getProfileIdRes());
propEditorInfoMap.put("ENTERPRISE_ID_RES", "");
propEditorInfoMap.put("USER_ID", checkNull(userInfoGlobal.getLoginCode()));
}
propEditorInfoMap.put("EDITOR", editor);
String formName = checkNull(TemplateDetails.get(objName).getFormName(objContext));
String metadataFilePath = genericUtility.getMetaDataFilePath(objName, objContext, pageContext, formName,
propEditorInfoMap, userInfoGlobal.getTransDB());
BaseLogger.log("3", null, null, "metadataFilePath === [" + metadataFilePath + "]");
DocumentBuilder documentBuilder;
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
document = documentBuilder.parse(metadataFilePath);
return document;
} catch (Exception e) {
return null;
}
}
private String checkNull( String nullStr )
{
return E12GenericUtility.checkNull(nullStr);
}
}
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