Oracle Profitability and Cost Management Cloud Common Helper Functions for Java

package com.hyperion.profitability.rest.client.java.samples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;


public class PCMCSRestSamples {
    
    private String userName;        // PCMCS user name
    private String password;        // PCMCS user password
    private String serverUrl;       // PCMCS server URL
    private String apiVersion;      // Version of the PCMCS API that you are developing/compiling with.
    private String applicationName; // PCMCS application used in this sample
    
    public PCMCSRestSamples(String userName, String password, String serverUrl, String apiVersion, String applicationName) {
        this.userName = userName;
        this.password = password;
        this.serverUrl = serverUrl;
        this.apiVersion = apiVersion;
        this.applicationName = applicationName;
    }
    
    public static void main(String args[]) throws Exception {
        
        PCMCSRestSamples restSamplesObj = new PCMCSRestSamples(<USER_NAME>, <PASSWORD>, "https://<SERVICE_NAME>-<TENANT_NAME>.<SERVICE_TYPE>.<dcX>.oraclecloud.com", "v1", "BksML30");
        restSamplesObj.getRestAPIVersionsInfo();
        restSamplesObj.getRestAPIVersionInfo();
        restSamplesObj.importTemplate();
        restSamplesObj.deployCube();
        restSamplesObj.applyDataGrants();
        restSamplesObj.loadData();
        restSamplesObj.runRuleBalancing();
        restSamplesObj.runCalculation();
        restSamplesObj.exportTemplate();
        restSamplesObj.copyPOVData();
        restSamplesObj.clearPOVData();
        restSamplesObj.exportQueryResult();
        restSamplesObj.createFlatFileApplication();
        restSamplesObj.updateDimensions();
        restSamplesObj.updateDimensionsJob();
        restSamplesObj.enableApplication();
        restSamplesObj.generatePrgrmDocReport();
        restSamplesObj.mergeSlices();
    }    
    
    public void getRestAPIVersionsInfo() throws Exception {      
        
        String urlString = String.format("%s/epm/rest", serverUrl);
        String response = executeRequest(urlString, "GET", null, "application/json");
        JSONObject jsonObj = new JSONObject(response);
        JSONArray itemsArray = jsonObj.getJSONArray("items");        
        System.out.println("Details : " + itemsArray.toString());
    }
    
    public void getRestAPIVersionInfo() throws Exception {      
        
        String urlString = String.format("%s/epm/rest/%s", serverUrl, "v1");
        String response = executeRequest(urlString, "GET", null, "application/json");
        JSONObject jsonObj = new JSONObject(response);        
        JSONArray itemsArray = jsonObj.getJSONArray("items");        
        System.out.println("Details : " + itemsArray.toString());     
    } 
    
    public void importTemplate() throws Exception {
        
        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", "HPCM_BksML12_20160128_200053.zip");
        json.put("isApplicationOverwrite", true);
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/templateImportJob";
        executeJob(urlString, "POST", json.toString());
        
    }  
    
    public void deployCube() throws Exception {
        
        JSONObject json = new JSONObject();
        json.put("isKeepData", true);
        json.put("isReplaceCube", true);
        json.put("isRunNow", true);
        json.put("comment", "Cube deployment");
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/ledgerDeployCubeJob";
        executeJob(urlString, "POST", json.toString());
        
    }
    
    public void loadData() throws Exception {
        
        JSONObject json = new JSONObject();
        json.put("clearAllDataFlag", false);
        json.put("dataLoadValue", "ADD_EXISTING_VALUES");
        json.put("dataFileName", "BksML12C.txt");
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/essbaseDataLoadJob";
        executeJob(urlString, "POST", json.toString());
        
    }
    
    public void runRuleBalancing() throws Exception {
        
        String modelViewName = null;
        
        JSONObject json = new JSONObject();        
        json.put("stringDelimter", "_");        
        json.put("modelViewName", modelViewName);
        
        String povGroupMember = "2014_January_Actual";
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + applicationName + "/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/ruleBalance";
        urlString = urlString + "?" + "queryParameter=" + json.toString();
        
        String response = executeRequest(urlString, "GET", null, "application/json");
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            System.out.println("Rule Balancing ran successfully");
            JSONArray itemsArray = jsonObj.getJSONArray("items");        
            System.out.println("Details : " + itemsArray.toString());
        } else {
            String details = jsonObj.getString("details");
            System.out.println("Rule Balancing failed. Details : " + details);
        }        
        
    }
    
    public void runCalculation() throws Exception {
        
        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 = "%s/epm/rest/%s/applications/%s/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/jobs/runLedgerCalculationJob";
        executeJob(urlString, "POST", json.toString());
        
    }   
    
    public void exportTemplate() throws Exception {
        String fileName = applicationName + "_Template_Export_File";
        
        JSONObject json = new JSONObject();
        json.put("fileName", fileName);
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/templateExportJob";
        executeJob(urlString, "POST", json.toString());
        
    }
    
    public void exportQueryResult()  throws Exception {
        String queryName = "Profitability - Product";
        String fileName = applicationName +"_"+ queryName + "_Query_Result";
            
        JSONObject json = new JSONObject();
        json.put("queryName", queryName);
        json.put("fileName", fileName);
        json.put("exportOnlyLevel0Flg", false);
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/exportQueryResultsJob";
        executeJob(urlString, "POST", json.toString());
    }
    
    public void copyPOVData() throws Exception {
        
        String modelViewName = "Balancing - 1 Operating Expenses";
        JSONObject json = new JSONObject();
        json.put("isManageRule", true);
        json.put("isInputData", true);
        json.put("modelViewName", modelViewName);
        json.put("createDestPOV", true);
        json.put("stringDelimter", "_");
        
        String sourcePovGroupMember = "2014_January_Actual";
        String destPovGroupMember = "2014_December_Actual";
        
        String urlString = "%s/epm/rest/%s/applications/%s/povs/" + sourcePovGroupMember.trim().replaceAll(" ", "%20") + "/jobs/copyPOVJob/"+  destPovGroupMember.trim().replaceAll(" ", "%20");
        executeJob(urlString, "POST", json.toString()); 
    }
    
    public void clearPOVData() throws Exception {
        
        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 = "%s/epm/rest/%s/applications/%s/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/jobs/clearPOVJob";
        executeJob(urlString, "POST", json.toString());        
    }
    
    public void mergeSlices() throws Exception {
        
        JSONObject json = new JSONObject();
        json.put("removeZeroCells", "true");
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/mergeSlices";
        executeJob(urlString, "POST", json.toString());        
    }
    
    public void generatePrgrmDocReport() throws Exception {
        
        JSONObject json = new JSONObject();
        json.put("fileType", "PDF");
        json.put("useAlias", false);
        json.put("stringDelimter", "_");
        
        String povGroupMember = "2016_January_Actual";
        
        String urlString = serverUrl + "/epm/rest/"+ apiVersion + "/applications/" + applicationName + "/povs/" + povGroupMember.trim().replaceAll(" ", "%20") + "/programDocumentationReport";
        urlString = urlString + "?" + "queryParameter=" + json.toString();
        
        String response = executeRequest(urlString, "GET", null, "application/json");
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            System.out.println("Program Documentation Report Generated Successfully");
        }
        String details = jsonObj.getString("details");
        System.out.println(details);
            
    }    
    
    public void createFlatFileApplication() throws Exception {
            
        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";
        String response = executeRequest(urlString, "POST", json.toString(), "application/json");
        
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            System.out.println("Application created successfully");
        } else {
            System.out.println("Application creation failed");
        }   
    }
    
    public void updateDimensions() throws Exception {
        
        JSONObject json = new JSONObject();
        json.put("dataFileName", "Accounts.txt");
        
        String urlString =  serverUrl + "/epm/rest/"+ apiVersion + "/fileApplications/" + applicationName +"/updateDimension";
        String response = executeRequest(urlString, "POST", json.toString(), "application/json");
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");
        
        if(resStatus == 0) {
            System.out.println("Dimensions updated successfully");
        } else {
            System.out.println("Dimensions update failed");
        } 
    }
    
    public void updateDimensionsJob() throws Exception {
        
        JSONObject json = new JSONObject();
        json.put("dataFileName", "Account.txt,Activity.txt");
        
        String urlString =  serverUrl + "/epm/rest/"+ apiVersion + "/fileApplications/" + applicationName + "/jobs" + "/updateDimension";
        executeJob(urlString, "POST", json.toString()); 
    }
    
    
    public void applyDataGrants() throws Exception {
        
        
        String urlString = "%s/epm/rest/%s/applications/%s/jobs/applyDataGrants";
        executeJob(urlString, "POST", null);
    }
    
    
    public void enableApplication() throws Exception {
        String urlString = "%s/epm/rest/%s/fileApplications/%s" +"/enableApplication";
        executeJob(urlString, "POST", null);
    }
    
    public void executeJob(String urlString, String httpMethodType, String payload) throws Exception {    
            urlString = String.format(urlString, serverUrl, apiVersion, applicationName);
            String response = executeRequest(urlString, httpMethodType, payload, "application/json");
            if(response != null) {
                System.out.println("Job started successfully");
                getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "GET");
            }
    }
                                                                     
   	private String executeRequest(String urlString, String requestMethod,
                                  String payload,
                                  String contentType) throws Exception {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setInstanceFollowRedirects(false);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setRequestProperty("Authorization",
                                          "Basic " + new sun.misc.BASE64Encoder().encode((userName +
                                                                                          ":" +
                                                                                          password).getBytes()));
            connection.setRequestProperty("Content-Type", contentType);
            if (payload != null) {
                OutputStreamWriter writer =
                    new OutputStreamWriter(connection.getOutputStream());
                writer.write(payload);
                writer.flush();
            }

            int status = connection.getResponseCode();
            
            if (status == 200) {
                return getStringFromInputStream(connection.getInputStream());
            } else {               
                System.out.println("Error occured while executing request");
                System.out.println("Response error code : " + status);
                String responseStr  = getStringFromInputStream(connection.getErrorStream());
                JSONObject json = new JSONObject(responseStr);
                System.out.println("Error details : " + json.getString("details"));
                return null;
            }
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }
	
	private void getJobStatus(String pingUrlString, String methodType) throws Exception {
		boolean completed = false;
		while (!completed) {
			String pingResponse = executeRequest(pingUrlString, methodType, null, "application/x-www-form-urlencoded");
			JSONObject json = new JSONObject(pingResponse);
			int status = json.getInt("status");
			if (status == -1) {
				try {
					System.out.println("Please wait...");
					Thread.sleep(20000);
				} catch (InterruptedException e) {
					completed = true;
					throw e;
				}
			}
			else {
				if (status > 0) {
					System.out.println("Error occurred: " + json.getString("details"));
				}
				else {
					System.out.println("Completed");
				}
				completed = true;
			}
		}
	}
        
    public String fetchPingUrlFromResponse(String response, String retValue) throws Exception {
            String pingUrlString = null;
            JSONObject jsonObj = new JSONObject(response);
            int resStatus = jsonObj.getInt("status");
            if (resStatus == -1) {
                    JSONArray lArray = jsonObj.getJSONArray("links");
                    for (int i = 0; i < lArray.length(); i++) {
                            JSONObject arr = lArray.getJSONObject(i);
                            if (arr.get("rel").equals(retValue))
                                    pingUrlString = (String) arr.get("href");                                                       
                    }
            }
            return pingUrlString;
    }
    
    private String getStringFromInputStream(InputStream is) {
            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();
            String line;
            
            try {
                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                            sb.append(line);
                    }
            } catch (IOException e) {
                    e.printStackTrace();
            } finally {
                    if (br != null) {
                            try {
                                    br.close();
                            } catch (IOException e) {
                                    e.printStackTrace();
                            }
                    }
            }
            
            return sb.toString();
    }

    
}