Profitability and Cost Management Common Helper Functions for Groovy

import org.json.JSONObject;
import groovy.json.JsonSlurper
import org.json.JSONArray;

class PCMCSRestSamples {


String serverUrl="https://<SERVICE_NAME>-<TENANT_NAME>.<SERVICE_TYPE>.<dcX>.oraclecloud.com"
String username="<USER_NAME>"
String password="<PASSWORD>"
String apiVersion="v1"
String appName="BksML30"

String userCredentials = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes());

static void main(String[] args) {
    PCMCSRestSamples restSamplesObj = new PCMCSRestSamples();
    restSamplesObj.getRestAPIVersionsInfo();
    restSamplesObj.getRestAPIVersionInfo();
    restSamplesObj.importTemplate();
    restSamplesObj.deployCube();
    restSamplesObj.applyDataGrants();
    restSamplesObj.loadData();
    restSamplesObj.runRuleBalancing();
    restSamplesObj.runCalculation();
    restSamplesObj.exportTemplate();
    restSamplesObj.exportQueryResult();
    
    restSamplesObj.copyPOVData();
    restSamplesObj.clearPOVData();
    restSamplesObj.createFlatFileApplication();
    restSamplesObj.updateDimensions();
    restSamplesObj.updateDimensionsJob();
    restSamplesObj.enableApplication();
    restSamplesObj.generatePrgrmDocReport();
	restSamplesObj.mergeSlices();
}

def getRestAPIVersionsInfo() {
	def url;
        def response;
	try {
			url = new URL(serverUrl + "/epm/rest");
	} catch (MalformedURLException e) {
			println "Malformed URL. Please pass valid URL"
			System.exit(0);
	}
	response = executeRequest(url, "GET", null, "application/json");
	def object = new JsonSlurper().parseText(response)       
        
        if(object != null) {
            def items = object.items
            println "Rest API Versions Info : " + items
	} else {
            println "Error occurred while fetching rest api versions details"
	}
}

def getRestAPIVersionInfo() {
	def url;
        def response;
	try {
            url = new URL(serverUrl + "/epm/rest/" + apiVersion)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
	response = executeRequest(url, "GET", null, "application/json");
	def object = new JsonSlurper().parseText(response)       
        
        if(object != null) {
            def items = object.items
            println "Rest API Version "+ apiVersion +" Info : " + items
	} else {
            println "Error occurred while fetching Rest API version " + apiVersion +  "details"
	}
}

 def importTemplate() {
                
        JSONObject json = new JSONObject();
        json.put("description", "Import Template");
        json.put("instanceName", "PROFITABILITY_WEB_APP");
        json.put("essApplicationServer", "EssbaseCluster-1");
        json.put("sharedServicesProject", "EssbaseCluster-1");
        json.put("applicationType", "Management Ledger");
        json.put("fileName", "BksML12_Template.zip");
        json.put("isApplicationOverwrite", true);
        
        def url;
        def response;
	try {
            url = new URL(serverUrl + "/epm/rest/" + apiVersion + "/applications/" + appName + "/jobs/templateImportJob")
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        println "URL : " + url
        println "Payload : " + json.toString()
        executeJob(url, "POST", json.toString());

}  

def deployCube() {
        
        JSONObject json = new JSONObject();
        json.put("isKeepData", true);
        json.put("isReplaceCube", true);
        json.put("isRunNow", true);
        json.put("comment", "Cube deployment");     
        
        def url;
        def response;
	try {
            url = new URL(serverUrl + "/epm/rest/" + apiVersion + "/applications/" + appName + "/jobs/ledgerDeployCubeJob")
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
        
}

    def loadData() {
        
        JSONObject json = new JSONObject();
        json.put("clearAllDataFlag", false);
        json.put("dataLoadValue", "ADD_EXISTING_VALUES");
        json.put("dataFileName", "BksML12C.txt");
        
        def url;
        def response;
	try {
            url = new URL(serverUrl + "/epm/rest/" + apiVersion + "/applications/" + appName + "/jobs/essbaseDataLoadJob")
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
        
    }
    
    def runRuleBalancing() {        
        
        String modelViewName = null;
        
        JSONObject json = new JSONObject();        
        json.put("stringDelimter", "_");        
        json.put("modelViewName", modelViewName);
        
        String povGroupMember = "2014_January_Actual";       
        
        def url;
        def response;
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/ruleBalance";
        urlString = urlString + "?" + "queryParameter=" + json.toString();
        
	try {
            url = new URL(urlString);
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}       
        
        response = executeRequest(url, "GET", null, "application/json");
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            println "Rule Balancing ran successfully"
            JSONArray itemsArray = jsonObj.getJSONArray("items");        
            println "Details : " + itemsArray.toString()
        } else {
            String details = jsonObj.getString("details");
            println "Rule Balancing failed. Details : " + details
        }       
    }
    
    def runCalculation() {
        
        String subsetStart = null;
        String subsetEnd = null;
        String ruleName = null;
        String ruleSetName = null;
        
        JSONObject json = new JSONObject();
        json.put("isClearCalculated", true);
        json.put("isExecuteCalculations", true);
        json.put("isRunNow", true);        
        json.put("comment", "Run Calculation");
        json.put("subsetStart", subsetStart);
        json.put("subsetEnd", subsetEnd);        
        json.put("ruleName", ruleName);
        json.put("ruleSetName", ruleSetName);
        json.put("exeType", "ALL_RULES");
        json.put("stringDelimter", "_");
        
        String povGroupMember = "2014_January_Actual";        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/jobs/runLedgerCalculationJob";
                
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
        
    }   
    
    def exportTemplate() {
        String fileName = appName + "_Template_Export_File";
        
        JSONObject json = new JSONObject();
        json.put("fileName", fileName);
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/jobs/templateExportJob";
                
        def url;    
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
        
    }
    
    def exportQueryResult() {
        String queryName = "Profitability - Product";
        String fileName = appName +"_"+ queryName + "_Query_Result";
            
        JSONObject json = new JSONObject();
        json.put("queryName", queryName);
        json.put("fileName", fileName);
        json.put("exportOnlyLevel0Flg", false);
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/jobs/exportQueryResultsJob";
                
        def url;   
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
    }
    
    def copyPOVData() {
        
        JSONObject json = new JSONObject();
        json.put("isManageRule", true);
        json.put("isInputData", true);
        
        String modelViewName = "Balancing - 1 Operating Expenses";
        json.put("modelViewName", modelViewName);
        
        json.put("createDestPOV", true);
        json.put("stringDelimter", "_");
        
        String sourcePovGroupMember = "2014_January_Actual";
        String destPovGroupMember = "2014_December_Actual";        
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/povs/" + sourcePovGroupMember.trim().replaceAll(" ", "%20") + "/jobs/copyPOVJob/" + destPovGroupMember.trim().replaceAll(" ", "%20");
                
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
    }
    
    def clearPOVData() {
        
        JSONObject json = new JSONObject();
        json.put("isManageRule", true);
        json.put("isInputData", true);
        json.put("isAdjustmentValues", true);        
        json.put("isAllocatedValues", true);
        json.put("stringDelimter", "_");
        
        String povGroupMember = "2014_January_Actual";    
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/jobs/clearPOVJob";
                
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString());
    }    
	
	def mergeSlices() {
		
		JSONObject json = new JSONObject();
		json.put("removeZeroCells", "true");
		
		String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/jobs/mergeSlices";
				
		def url;
		
	try {
			url = new URL(urlString)
	} catch (MalformedURLException e) {
			println "Malformed URL. Please pass valid URL"
			System.exit(0);
	}
		
		executeJob(url, "POST", json.toString());
	}
    
    def generatePrgrmDocReport() {
        
        JSONObject json = new JSONObject();
        json.put("fileType", "PDF");
        json.put("useAlias", false);
        json.put("stringDelimter", "_");
        
        String povGroupMember = "2016_January_Actual";
        
        def url;
        def response;
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName + "/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/programDocumentationReport";
        urlString = urlString + "?" + "queryParameter=" + json.toString();
        
        try {
            url = new URL(urlString);
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}    
        
        response = executeRequest(url, "GET", null, "application/json");
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            println "Program Documentation Report Generated Successfully"
        }
        String details = jsonObj.getString("details");
        println details
            
    }    
    
    def createFlatFileApplication() {
        
        JSONObject json = new JSONObject();
        json.put("description", "Flat file based application");
        json.put("ruleDimensionName", "Rule");
        json.put("balanceDimensionName", "Balance");       
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/fileApplications/" + "BksML13";
        
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        String response = executeRequest(url, "POST", json.toString(), "application/json")
        
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            println "Application created successfully"
        } else {
            println "Application creation failed"
        }   
    }
    
    def updateDimensions() {
        
        JSONObject json = new JSONObject();
        json.put("dataFileName", "Accounts.txt");
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/fileApplications/"+ appName + "/updateDimension";
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        String response = executeRequest(url, "POST", json.toString(), "application/json");
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            println "Dimensions updated successfully"
        } else {
            println "Dimensions update failed"
        } 
    }
    
    def updateDimensionsJob() {
        
        JSONObject json = new JSONObject();
        json.put("dataFileName", "Account.txt,Activity.txt");
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/fileApplications/"+ appName + "/jobs" + "/updateDimension";
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", json.toString()); 
    }
    
    def applyDataGrants() {
                
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + appName +"/jobs/applyDataGrants";
        def url;
        
	try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", null);
    }
    
    
    def enableApplication() {
    
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/fileApplications/"+ appName +"/enableApplication";
        def url;
        
        try {
            url = new URL(urlString)
	} catch (MalformedURLException e) {
            println "Malformed URL. Please pass valid URL"
            System.exit(0);
	}
        
        executeJob(url, "POST", null);
    }
    
def fetchResponse(is) {
	BufferedReader br = new BufferedReader(new InputStreamReader(is));
	StringBuilder sb = new StringBuilder();
	String line;
	while ((line = br.readLine()) != null) {
		sb.append(line+"\n");
	}
	br.close();
	return sb.toString();
}

def fetchPingUrlFromResponse(response, relValue) {
    def object = new JsonSlurper().parseText(response)
    def pingUrlStr
	if (object.status == -1) {
		println "Started executing successfully"
		def links = object.links
		links.each{
			if (it.rel.equals(relValue)) {
				pingUrlStr=it.href
			}
		}
	} else {
		println "Error details: " + object.details
		System.exit(0);
	}
	return pingUrlStr
}

def fetchJobStatusFromResponse(response) {
	def object = new JsonSlurper().parseText(response)
	def status = object.status
	if (status == -1)
		return "Processing"
	else if (status == 0)
		return "Completed"
	else
		return object.details
}

def executeRequest(url, requestType, payload, contentType) {
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setDoOutput(true);
	connection.setUseCaches(false);
	connection.setDoInput(true);
	connection.setRequestMethod(requestType);
	connection.setRequestProperty("Content-Type", contentType);
	connection.setRequestProperty("Authorization", basicAuth);
	if (payload != null) {
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		writer.write(payload);
		writer.flush();
	}

	int statusCode
	try {
		statusCode = connection.responseCode;
	} catch (all) {
		println "Error connecting to the URL"
		System.exit(0);
	}

	def response
	if (statusCode == 200) {
		if (connection.getContentType() != null && !connection.getContentType().startsWith("application/json")) {
			println "Error occurred in server"
			System.exit(0)
		}
		InputStream is = connection.getInputStream();
		if (is != null)
			response = fetchResponse(is)
	} else {
		println "Error occurred while executing request"
		println "Response error code : " + statusCode
		InputStream is = connection.getErrorStream();
		if (is != null && connection.getContentType() != null && connection.getContentType().startsWith("application/json"))
			println fetchJobStatusFromResponse(fetchResponse(is))
		System.exit(0);
	}
	connection.disconnect();
	return response;
}

def getJobStatus(pingUrlString, methodType) {
	
	def pingUrl = new URL(pingUrlString);
	def completed = false;
	while (!completed) {
		def pingResponse = executeRequest(pingUrl, methodType, null, "application/x-www-form-urlencoded");
		def status = fetchJobStatusFromResponse(pingResponse);
		if (status == "Processing") {
			try {
				println "Please wait..."
				Thread.sleep(20000);
			} catch (InterruptedException e) {
				completed = true
			}
		}
		else {
			println status
			completed = true
		}
	}
}

def executeJob(urlString, httpMethod, payload) {	
	
	def response = executeRequest(urlString, httpMethod, payload, "application/json");
	if (response != null) {
		getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "GET");
	}
}

}