Thursday 21 April 2022

SOAPAPi Call and Reading

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">

<Rule language="beanshell" name="WorkdayAccountsOrgRoleRuleLibrary">

  <Description> RuleLibrary for Workday OrgRole Hierarchy</Description>

  <Source><![CDATA[


/**************************************************************************

* Single file of all methods required in WorkdayAccounts OrgRole Hierarchy

*************************************************************************/

import java.io.File;

import java.util.Map;

import java.util.HashMap;

import java.io.IOException;

import java.io.OutputStream;

import java.io.FileOutputStream;

//Imports used for XML Reading and Processing

import java.net.URL;

import java.io.StringReader;

import java.io.BufferedReader;

import org.xml.sax.InputSource;

import org.xml.sax.Attributes;

import java.net.URLConnection;

import java.nio.charset.Charset;

import org.xml.sax.SAXException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import javax.xml.parsers.SAXParser;

import java.io.ByteArrayOutputStream;

import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParserFactory;

import javax.xml.parsers.ParserConfigurationException;

//Imports from IIQ

import sailpoint.tools.Util;

import sailpoint.tools.Message;

import sailpoint.object.Application;

import org.apache.commons.logging.Log;

import sailpoint.tools.GeneralException;

import org.apache.commons.logging.LogFactory;


private static Log logger = LogFactory.getLog("com.rule.WorkdayAccountsOrgRoleRuleLibrary");

/*****************************************************************************

*====== PrintOrgDataHandler Class extended from DefaultHandler Class =========

*****************************************************************************/

public class PrintOrgDataHandler extends DefaultHandler

{

private StringBuilder currentValue = new StringBuilder();

private StringBuilder orgdata = new StringBuilder();

public void startDocument()

{

logger.info("Start Document");

}

public void endDocument()

{

logger.info("End Document");

if(!file.exists())

{

file.createNewFile();

}

os = new FileOutputStream(file, true);

writeData(orgdata.toString());

//logger.debug("orgdata: " + orgdata);

}


public void startElement(String uri, String localName, String qName, Attributes attributes)

{

// reset the tag value

currentValue.setLength(0);

}

  

public void endElement(String uri, String localName, String qName)

{

String orgName = "", orgRefId = "", orgSuperRefId = "";

//logger.debug("End Element: "+ qName);

if (qName.equalsIgnoreCase("wd:Name"))

{

orgName = currentValue.toString();

//logger.debug("orgName:" + orgName);

orgdata.append(orgName + ",");

}

else if (qName.equalsIgnoreCase("wd:Reference_ID"))

{

orgRefId = currentValue.toString();

//logger.debug("orgRefId:" + orgRefId);

orgdata.append(orgRefId + ",");

}

else if (qName.equalsIgnoreCase("wd:Superior_Organization_Reference"))

{

orgSuperRefId = currentValue.toString();

//logger.debug("orgSuperRefId:" + orgSuperRefId);

orgdata.append(orgSuperRefId+"\n");

}

}

public void characters(char[] ch, int start, int length)

{

currentValue.append(ch, start, length);

}

}

/*****************************************************************************

*===== PrintPagingInfoHandler Class extended from DefaultHandler Class =======

*****************************************************************************/

public class PrintPagingInfoHandler extends DefaultHandler

{

private StringBuilder currentValue = new StringBuilder();

public void startDocument()

{

logger.info("Start Document");

}

public void endDocument()

{

logger.info("End Document");

}


public void startElement(String uri, String localName, String qName, Attributes attributes)

{

// reset the tag value

currentValue.setLength(0);

}

  

public void endElement(String uri, String localName, String qName)

{

if (qName.equalsIgnoreCase("wd:Total_Pages"))

{

totalPages = currentValue.toString();

logger.debug("totalPages:" + totalPages);

}

}

public void characters(char[] ch, int start, int length)

{

currentValue.append(ch, start, length);

}

}

/*****************************************************************************

*========================= Method to write Data ==============================

*****************************************************************************/

public void writeData(String data)

{

os.write(data.getBytes());

}

/*****************************************************************************

*================= Method to ProcessSoapAPI for Pagging ======================

*****************************************************************************/

public static String processSOAP(String username, String password, String wsEndPoint)

{

    logger.info("*****************************Start Method to ProcessSoapAPI for Pagging*********************************");

URL url = new URL(wsEndPoint);

URLConnection connection = url.openConnection();

HttpURLConnection httpConn = (HttpURLConnection) connection; //connection

// Passing Values in WebServices String

ByteArrayOutputStream bout = new ByteArrayOutputStream();

String xmlInput = "<soapenv:Envelope xmlns:bsvc=\"urn:com.workday/bsvc\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n"

+ "    <soapenv:Header>\r\n"

+ "        <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\r\n"

+ "            <wsse:UsernameToken wsu:Id=\"UsernameToken-29AD2DA69B7633231716503553476444\">\r\n"

+ "                <wsse:Username>"+ username + "</wsse:Username>\r\n"

+ "                <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">"+ password + "</wsse:Password>\r\n"

+ "                <wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">GaNTP/SvdGp77xCD2T2MhQ==</wsse:Nonce>>\r\n"

+ "            </wsse:UsernameToken>\r\n"

+ "        </wsse:Security>\r\n"

+ "    </soapenv:Header>\r\n"

+ "    <soapenv:Body>\r\n"

+ "        <bsvc:Get_Organizations_Request bsvc:version=\"v37.1\">\r\n"

+ "            <bsvc:Response_Filter>\r\n"

+ "                <bsvc:Count>10</bsvc:Count>\r\n"

+ "            </bsvc:Response_Filter>\r\n"

+ "            <bsvc:Response_Group>\r\n"

+ "                <bsvc:Include_Roles_Data>false</bsvc:Include_Roles_Data>\r\n"

+ "                <bsvc:Include_Hierarchy_Data>true</bsvc:Include_Hierarchy_Data>\r\n"

+ "                <bsvc:Include_Supervisory_Data>false</bsvc:Include_Supervisory_Data>\r\n"

+ "            </bsvc:Response_Group>\r\n"

+ "        </bsvc:Get_Organizations_Request>\r\n"

+ "    </soapenv:Body>\r\n"

+ "</soapenv:Envelope>";

byte[] buffer = new byte[xmlInput.length()];

buffer = xmlInput.getBytes();

bout.write(buffer);

byte[] b = bout.toByteArray();

httpConn.setRequestProperty("Content-Type", "application/xml");

httpConn.setRequestMethod("POST");

httpConn.setDoOutput(true);

httpConn.setDoInput(true);


OutputStream out = httpConn.getOutputStream();

// Write the content of the request to the outputstream of the HTTP

// Connection.

out.write(b);

out.close();

// Ready with sending the request.

// Read the response.

InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), Charset.forName("UTF-8"));

BufferedReader in = new BufferedReader(isr);

String responseString ="";

String returnString ="";

// Write the SOAP message response to a String.

while ((responseString = in.readLine()) != null) 

{

returnString = returnString + responseString.toString();

}

return returnString;

}

/*****************************************************************************

*================= Method to ProcessSoapAPI for OrgData ======================

*****************************************************************************/

public static String processSOAP(String username, String password, String wsEndPoint, String pageNum)

{

    logger.info("*****************************Start Method to ProcessSoapAPI for OrgData*********************************");

URL url = new URL(wsEndPoint);

URLConnection connection = url.openConnection();

HttpURLConnection httpConn = (HttpURLConnection) connection; //connection

// Passing Values in WebServices String

ByteArrayOutputStream bout = new ByteArrayOutputStream();

String xmlInput = "<soapenv:Envelope xmlns:bsvc=\"urn:com.workday/bsvc\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n"

+ "    <soapenv:Header>\r\n"

+ "        <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\r\n"

+ "            <wsse:UsernameToken wsu:Id=\"UsernameToken-29AD2DA69B7633231716503553476444\">\r\n"

+ "                <wsse:Username>"+ username + "</wsse:Username>\r\n"

+ "                <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">"+ password + "</wsse:Password>\r\n"

+ "                <wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">GaNTP/SvdGp77xCD2T2MhQ==</wsse:Nonce>>\r\n"

+ "            </wsse:UsernameToken>\r\n"

+ "        </wsse:Security>\r\n"

+ "    </soapenv:Header>\r\n"

+ "    <soapenv:Body>\r\n"

+ "        <bsvc:Get_Organizations_Request bsvc:version=\"v37.1\">\r\n"

+ "            <bsvc:Response_Filter>\r\n"

+ "                <bsvc:Page>"+ pageNum +"</bsvc:Page>\r\n"

+ "                <bsvc:Count>10</bsvc:Count>\r\n"

+ "            </bsvc:Response_Filter>\r\n"

+ "            <bsvc:Response_Group>\r\n"

+ "                <bsvc:Include_Roles_Data>false</bsvc:Include_Roles_Data>\r\n"

+ "                <bsvc:Include_Hierarchy_Data>true</bsvc:Include_Hierarchy_Data>\r\n"

+ "                <bsvc:Include_Supervisory_Data>false</bsvc:Include_Supervisory_Data>\r\n"

+ "            </bsvc:Response_Group>\r\n"

+ "        </bsvc:Get_Organizations_Request>\r\n"

+ "    </soapenv:Body>\r\n"

+ "</soapenv:Envelope>";

byte[] buffer = new byte[xmlInput.length()];

buffer = xmlInput.getBytes();

bout.write(buffer);

byte[] b = bout.toByteArray();

httpConn.setRequestProperty("Content-Type", "application/xml");

httpConn.setRequestMethod("POST");

httpConn.setDoOutput(true);

httpConn.setDoInput(true);


OutputStream out = httpConn.getOutputStream();

// Write the content of the request to the outputstream of the HTTP

// Connection.

out.write(b);

out.close();

// Ready with sending the request.

// Read the response.

InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), Charset.forName("UTF-8"));

BufferedReader in = new BufferedReader(isr);

String responseString ="";

String returnString ="";

// Write the SOAP message response to a String.

while ((responseString = in.readLine()) != null) 

{

returnString = returnString + responseString.toString();

}

return returnString;

}


/*****************************************************************************

*=============================== Main Code ===================================

*****************************************************************************/

//Variable Decleration

logger.info("*****************************Start Rule*********************************");

OutputStream os = null;

String filePath = config.get("fileNameWithPathAndExtension");

logger.debug("filePath: " + filePath);

File file = new File(filePath);

os = new FileOutputStream(file);

writeData("OrganizationId,OrganizationName,OrganizationSuperId\n"); //writing headers in file

Map connectionMap = new HashMap();

String totalPages = "";

SAXParserFactory factory = SAXParserFactory.newInstance();

SAXParser saxParser = factory.newSAXParser();

//PrintOrgDataHandler orgDataHandler8 = new PrintOrgDataHandler();

//PrintPagingInfoHandler pagingDataHandler8 = new PrintPagingInfoHandler();

try

{

//Fetching API Connection Details

Application application = context.getObjectByName(Application.class, "<>");

logger.debug("application: " + application.getName());

if(application!=null)

{

connectionMap = application.getAttributes().getMap();

logger.debug("Connection Map: " + connectionMap);

}

    

String username = connectionMap.get("user");

logger.debug("username: " + username);

String password = context.decrypt(connectionMap.get("password"));

logger.debug("password: " + password);

String contextUrl = connectionMap.get("url");

logger.debug("contextUrl: " + contextUrl);

    

// Gathering paging & number of results information

String pagingResponse = processSOAP(username, password, contextUrl);

saxParser.parse(new InputSource(new StringReader(pagingResponse)), new PrintPagingInfoHandler());

logger.debug("totalPages: " + totalPages);

//Generating csv file with Role OrgData

int pages = Util.atoi(totalPages);

for(int i=1; i<=pages; i++)

{

String orgResponse = processSOAP(username, password, contextUrl, Util.itoa(i));

saxParser.parse(new InputSource(new StringReader(orgResponse)), new PrintOrgDataHandler());

}

os.close();

taskResult.addMessage(new Message(Message.Type.Info, "Task is successfully executed. OrgFile is created", null));

}

catch (GeneralException generalException)

{

taskResult.addMessage(new Message(Message.Type.Error, generalException.printStackTrace(), null));

}


]]></Source>

</Rule>

No comments:

Post a Comment

SOAPAPi Call and Reading

<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">...