C Common Helper Functions for Groovy

import org.json.JSONObject
import groovy.json.JsonSlurper

serverUrl="SERVER:PORT"
username="epm_default_cloud_admin"
password="epm_cloud"
apiVersion="v3"
appName="Vision"
applicationSnapshotName="DemoApplication_HSS_Vision"

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

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 || statusCode == 201) {
                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 getMigrationJobStatus(pingUrlString, methodType) {

    def pingUrl = new URL(pingUrlString)
        def completed = false
        while (!completed) {
                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 {
                                if (status != "Completed"){
                                        println("Error occured")
                                        def object = new JsonSlurper().parseText(pingResponse)
                                        def itemsArray = object.items
                                        if(itemsArray.size() <= 0){
                                                println object.details
                                        }else{
                                        itemsArray.each{
                                                def source = it.source 
                                        def destination = it.destination
                                                def links = it.links
                                                taskURL = ""
                                                links.each{
                                                        if (it.rel.equals("Job Details")) {
                                                        taskURL = it.href
                                                        }
                                                }
                                                println "taskURL: " + taskURL
                                        println "Details:"
                                        println "Source: " + source
                                        println "Destination: "+ destination
                                        def errorsCompleted = false
                                        def currentMessageCategory = ""
                                        def nextPingURL = new URL(taskURL);
                                        while(!errorsCompleted){
                                                        def nextPingResponse =  executeRequest(nextPingURL, "GET", null, "application/x-www-form-urlencoded")
                                                def jsonObj = new JsonSlurper().parseText(nextPingResponse)
                                                int nextStatus = jsonObj.status
                                                if(nextStatus == 0){
                                                        def artifactArray = jsonObj.items
                                                        artifactArray.each{
                                                                def artifact = it.artifact
                                                                def msgCategory = it.msgCategory
                                                                def msgText = it.msgText
                                                                if(!currentMessageCategory.equals(msgCategory)){
                                                                        currentMessageCategory = msgCategory
                                                                        println currentMessageCategory
                                                                }
                                                                println artifact +" - " + msgText
                                                        }
                                                        nextPingURL = null
                                                                def nextLinks = jsonObj.links
                                                                nextLinks.each{
                                                                        if (it.rel.equals("next")) {
                                                                        nextPingURL= new URL(it.href)
                                                                        }
                                                                }                                                       
                                                if(nextPingURL == null)
                                                        errorsCompleted = true
                                                }else if(nextStatus > 0){
                                                        println "Error occured while fetching error details: "+ jsonObj.details
                                                        errorsCompleted = true
                                                }
                                        }
                                        }
                                        }
                                }else if(status == "Completed"){
                                        println "Completed"
                                }
                                completed = true
                        }
                }
        }

def getJobStatus(pingUrlString, methodType) {
        
        def pingUrl = new URL(pingUrlString);
        def completed = false;
        while (!completed) {
                pingResponse = executeRequest(pingUrl, methodType, null, "application/x-www-form-urlencoded");
                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(jobType, jobName, parameters) {
        def url = new URL(serverUrl + "/HyperionPlanning/rest/" + apiVersion + "/applications/" + appName + "/jobs");
        JSONObject payload = new JSONObject();
        try {
                if (parameters != null) {
                        JSONObject params = new JSONObject();
                        def args = parameters.split(';');
                        for (int i = 0; i < args.length; i++) {
                                if (args[i].indexOf("=") != -1) {
                                        String[] param = args[i].split("=");
                                        if (param[0].equalsIgnoreCase("clearData")) {
                                                params.put("clearData",Boolean.valueOf(param[1]));
                                        }
                                        else {
                                                params.put(param[0],param[1]);
                                        }
                                }
                        }
                        payload.put("jobName",jobName);
                        payload.put("jobType",jobType);
                        payload.put("parameters",params);
                }
                else {
                        payload.put("jobName",jobName);
                        payload.put("jobType",jobType);
                }
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "POST", payload.toString(), "application/json");
        if (response != null) {
                getJobStatus(fetchPingUrlFromResponse(response, "self"), "GET");
        }
}

def importSnapshot(applicationSnapshotName) {
        def url;
        try {
                String snapshotName = URLEncoder.encode(applicationSnapshotName, "UTF-8");
                JSONObject params = new JSONObject();
                params.put("type","import");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + snapshotName + "/migration?q=" + params.toString());
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "POST", null, "application/x-www-form-urlencoded");
        if (response != null) {
                getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "POST");
        }
}

def exportSnapshot(applicationSnapshotName) {
        def url;
        try {
                String snapshotName = URLEncoder.encode(applicationSnapshotName, "UTF-8");
                JSONObject params = new JSONObject();
                params.put("type","export");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + snapshotName + "/migration?q=" + params.toString());
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "POST", null, "application/x-www-form-urlencoded");
        if (response != null) {
                getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "POST");
        }
}

def getLCMVersions() {
        def url;
        try {
                        url = new URL(serverUrl + "/interop/rest/")
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def items = object.items
                println "List of versions :"
                items.each{
                        println "Version : " + it.version
                        println "Lifecycle : " + it.lifecycle
                        println "Latest : " + it.latest
                        println "Link : " + it.links[0].href + "\n"
                }
        } else {
                println "Error occurred while listing versions"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def getLCMVersionDetails() {
        def url;
        try {
                        url = new URL(serverUrl + "/interop/rest/" + apiVersion)
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def links = object.links
                println "Version " + apiVersion + " details :"
                links.each{
                        println "Service : " + it.rel
                        println "URL : " + it.href
                        println "Action : " + it.action + "\n"
                }
        } else {
                println "Error occurred while fetching version details"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def getServices() {
        def url;
        try {
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/services")
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def links = object.links
                println "Services list :"
                links.each{
                        if (!it.rel.equals("self")) {
                                println "Service : " + it.rel
                                println "URL : " + it.href
                                println "Action : " + it.action + "\n"
                        }
                }
        } else {
                println "Error occurred while fetching services list"
                if (object.details != null)
                        println "Error details: " + object.details
        }
}

def recreateService(serviceName) {
        def toCreate = System.console().readLine 'Are you sure you want to recreate the EPM environment (yes/no): no ?[Press Enter]'
        if (!toCreate.equals("yes")) {
                println "User cancelled the recreate command"
                System.exit(0)
        }
        def url;
        try {
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/services/" + serviceName + "/recreate");
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "POST", null, "application/x-www-form-urlencoded");
        if (response != null) {
                waitForCompletion(response)
        }
}

def waitForCompletion(pingUrlString) {
                def pingUrl = new URL(pingUrlString);
        def completed = false;
        while (!completed) {
                def wait = false;
                HttpURLConnection connection = (HttpURLConnection) pingUrl.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("Authorization", basicAuth);
                
                int statusCode
                try {
                        statusCode = connection.responseCode;
                        def pingResponse
                        if (statusCode == 200) {
                                if (connection.getContentType() != null && !connection.getContentType().startsWith("application/json")) {
                                        wait = true
                                }
                                else {
                                        InputStream is = connection.getInputStream();
                                        if (is != null) {
                                                pingResponse = fetchResponse(is)
                                                status = fetchJobStatusFromResponse(pingResponse);
                                                if (status == "Processing")
                                                        wait = true
                                                else {
                                                        println status
                                                        completed = true
                                                }
                                        }
                                        else
                                                wait = true
                                }
                        } else {
                                wait = true
                        }
                        connection.disconnect();
                } catch (all) {
                        wait = true
                }

                if (wait) {
                        try {
                                println "Please wait..."
                                Thread.sleep(20000);
                        } catch (InterruptedException e) {
                                completed = true
                        }
                }
        }
}

def getApplicationSnapshotDetails(applicationSnapshotName) {
        def url;
        try {
                String snapshotName = URLEncoder.encode(applicationSnapshotName, "UTF-8");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + snapshotName)
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                println "Application details :"
                println "Application snapshot name : " + object.items[0].name
                println "Application snapshot type : " + object.items[0].type
                println "Can be exported flag : " + object.items[0].canExport
                println "Can be imported flag : " + object.items[0].canImport
                println "Can be uploaded flag : " + object.items[0].canUpload
                println "Can be downloaded flag : " + object.items[0].canDownload
                def links = object.links
                println "Services details :"
                links.each{
                        println "Service : " + it.rel
                        println "URL : " + it.href
                        println "Action : " + it.action + "\n"
                }
        } else {
                println "Error occurred while fetching application snapshot details"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def listFiles() {
        def url;
        try {
                        url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots")
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def items = object.items
                if (items == null) {
                        println "No files found"
                }
                else {
                        println "List of files :"
                        items.each{
                                println it.name
                        }
                }
        } else {
                println "Error occurred while listing files"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def deleteFile(filename) {
        def url;
        try {
                String encodedFileName = URLEncoder.encode(filename, "UTF-8");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + encodedFileName)
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "DELETE", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 )
                println "File deleted successfully"
        else {
                println "Error occurred while deleting file"
                if (object.details != null)
                        println "Error details: " + object.details
        }
}

def downloadFile(filename) {
        def url;
        try {
                String encodedFileName = URLEncoder.encode(filename, "UTF-8");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + encodedFileName + "/contents");
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", basicAuth);

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

        if (statusCode == 200) {
                InputStream is;
                if (connection.getContentType() != null && connection.getContentType().contains("application/json")) {
                        is = connection.getInputStream();
                        if (is != null) {
                                response = fetchResponse(is)
                                def object = new JsonSlurper().parseText(response)
                                println "Error occurred while downloading file"
                                if (object.details != null)
                                        println "Error details: " + object.details
                        }
                } else {
                        final int BUFFER_SIZE = 5 * 1024 * 1024;
                        fileExt = connection.getHeaderField("fileExtension");
                        saveFilePath = "/u01/" + filename + "." + fileExt;
                        File f = new File(saveFilePath);
                        is = connection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(f);
                        int bytesRead = -1;
                        byte[] buffer = new byte[BUFFER_SIZE];
                        while ((bytesRead = is.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                        }
                        println "Downloaded " + filename + " successfully";
                }
        } 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();
}

def sendRequestToRest(isFirst, isLast, lastChunk,fileName) throws Exception {
    JSONObject params = new JSONObject();
    params.put("chunkSize", lastChunk.length);
    params.put("isFirst", isFirst);
    params.put("isLast", isLast);

    def url;
    try {
        url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + fileName + "/contents?q=" + params.toString());
    } catch (MalformedURLException e) {
        println "Malformed URL. Please pass valid URL"
        System.exit(0);
    }

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setInstanceFollowRedirects(false);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Authorization", basicAuth);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.write(lastChunk);
    wr.flush();

    boolean status = false
    int statusCode
    try {
                statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                        InputStream is;
                        if (connection.getContentType() != null && connection.getContentType().contains("application/json")) {
                                is = connection.getInputStream();
                                if (is != null) {
                                        response = fetchResponse(is)
                                        def object = new JsonSlurper().parseText(response)
                                        if (object.status == 0)
                                                status = true;
                                        }else if(object.status == -1 && isLast == true){
                                                getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "GET");
                                        }else {
                                                println "Error occurred while uploading file"
                                                if (object.details != null)
                                                        println "Error details: " + object.details
                                        }
                                }
                        }
                }
    } catch (Exception e) {
                println "Exception occurred while uploading file";
                System.exit(0);
    } finally {
                if (connection != null) {
                        connection.disconnect();
                }
    }
    return status;
}

def uploadFile(fileName) {
        final int DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
        int packetNo = 1;
        boolean status = true;
        byte[] lastChunk = null;
        File f = new File(fileName);
        InputStream fis = null;
        long totalFileSize = f.length();
        boolean isLast = false;
        Boolean isFirst = true;
        int lastPacketNo = (int) (Math.ceil(totalFileSize/ (double) DEFAULT_CHUNK_SIZE));
        long totalbytesRead = 0;
        try {
                fis = new BufferedInputStream(new FileInputStream(fileName));
                while (totalbytesRead < totalFileSize && status) {
                        int nextChunkSize = (int) Math.min(DEFAULT_CHUNK_SIZE, totalFileSize - totalbytesRead);
                        if (lastChunk == null) {
                                lastChunk = new byte[nextChunkSize];
                                int bytesRead = fis.read(lastChunk);
                                totalbytesRead += bytesRead;
                                if (packetNo == lastPacketNo) {
                                        isLast = true;
                                }
                                status = sendRequestToRest(isFirst, isLast,lastChunk,fileName);
                                isFirst=false;
                                if (status) {
                                        println "\r" + ((100 * totalbytesRead)/ totalFileSize) + "% completed";
                                } else {
                                        break;
                                }
                                packetNo = packetNo + 1;
                                lastChunk = null;
                        }
                }
        } catch (Exception e) {
                println "Exception occurred while uploading file";
                System.exit(0);
        } finally {
                if (null != fis) {
                        try {
                                fis.close();
                        } catch (IOException e) {
                                println "Error while closing input stream";
                                System.exit(0);
                        }
                }
        }
}

def provideFeedback(description) {
        def url;
        JSONObject params = new JSONObject();
        try {
                JSONObject config = new JSONObject();
                config.put("URL",serverUrl)
                params.put("configuration",config);
                params.put("description",description);
                url = new URL(serverUrl + "/interop/rest/" + lcmVersion + "/feedback");
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "POST", params.toString(), "application/json");

        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                println "Feedback successful"
        } else {
                println "Error occured while providing feedback"
                if (object.details != null)
                        println "Error details: " + object.details
        }
}

def hardReset(comment) {
        def userInput = System.console().readLine 'Are you sure you want to restart the service instance (yes/no): no ?[Press Enter] '
        if (userInput.equals("yes")) {
                def url;
                JSONObject params = new JSONObject();
                try {
                        params.put("comment",comment);
                        url = new URL(serverUrl + "/interop/rest/" + lcmVersion + "/services/PBCS/resetservice");
                } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
                }
                response = executeRequest(url, "POST", params.toString(), "application/json");

                response = executeRequest(url, "POST", payload);
                if (response != null) {
                        waitForCompletion(fetchPingUrlFromResponse(response, "Job Status"));
                }       
        } else {
                println "User cancelled the resetservice command"
        }
}
def integrationScenarioImportMetadataIntoApplication() {
        uploadFile("DemoApplication_HSS_Vision.zip")
        executeJob("IMPORT_METADATA", "accountMetadata", "importZipFileName=accounts.zip");
        executeJob("CUBE_REFRESH", "cubeRefresh", null);
}

def integrationScenarioImportDataRunCalcCopyToAso() {
    uploadFile("data.csv");
    executeJob("IMPORT_DATA", "loadingq1data", "importFileName=data.csv");
    executeJob("CUBE_REFRESH", "cubeRefresh", null);
    executeJob("PLAN_TYPE_MAP", "CampaignToReporting", "clearData=false");
}

def integrationScenarioExportMetadataAndDataAndDownloadFiles() {
    executeJob("EXPORT_METADATA", "exportentitymetadata", "exportZipFileName=entitydata.zip");
    executeJob("EXPORT_DATA", "Forecastdata", "exportFileName=forecastdata.zip");
    listFiles();       
    downloadFile("entitydata.zip");
    downloadFile("forecastdata.zip");  
}

def integrationScenarioRemoveUnnecessaryFiles() {
    listFiles();
    deleteFile("entitymetadata.csv");
    deleteFile("forecastdata.csv");
}

def integrationScenarioExportDataAndDownloadFiles() {
    executeJob("EXPORT_DATA", "entitydata", "exportFileName:entitydata.zip");
    executeJob("EXPORT_DATA", "forecastdata", "exportFileName:forecastdata.zip");
    listFiles();
    downloadFile("entitydata.zip");
    downloadFile("forecastdata.zip");
}

def integrationScenarioRefreshTheApplication() {
    uploadFile("accounts.zip");
    executeJob("IMPORT_METADATA", "accountMetadata", "importZipFileName:accounts.zip");
    executeJob("CUBE_REFRESH", "cubeRefresh", null);
}

executeJob("IMPORT_METADATA", "ImportMd1", "importZipFileName=ImportMD.zip");import org.json.JSONObject
import groovy.json.JsonSlurper

serverUrl="SERVER:PORT"
username="epm_default_cloud_admin"
password="epm_cloud"
apiVersion="v3"
appName="Vision"
applicationSnapshotName="DemoApplication_HSS_Vision"

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

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 || statusCode == 201) {
                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) {
                pingResponse = executeRequest(pingUrl, methodType, null, "application/x-www-form-urlencoded");
                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(jobType, jobName, parameters) {
        def url = new URL(serverUrl + "/HyperionPlanning/rest/" + apiVersion + "/applications/" + appName + "/jobs");
        JSONObject payload = new JSONObject();
        try {
                if (parameters != null) {
                        JSONObject params = new JSONObject();
                        def args = parameters.split(';');
                        for (int i = 0; i < args.length; i++) {
                                if (args[i].indexOf("=") != -1) {
                                        String[] param = args[i].split("=");
                                        if (param[0].equalsIgnoreCase("clearData")) {
                                                params.put("clearData",Boolean.valueOf(param[1]));
                                        }
                                        else {
                                                params.put(param[0],param[1]);
                                        }
                                }
                        }
                        payload.put("jobName",jobName);
                        payload.put("jobType",jobType);
                        payload.put("parameters",params);
                }
                else {
                        payload.put("jobName",jobName);
                        payload.put("jobType",jobType);
                }
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "POST", payload.toString(), "application/json");
        if (response != null) {
                getJobStatus(fetchPingUrlFromResponse(response, "self"), "GET");
        }
}

def importSnapshot(applicationSnapshotName) {
        def url;
        try {
                String snapshotName = URLEncoder.encode(applicationSnapshotName, "UTF-8");
                JSONObject params = new JSONObject();
                params.put("type","import");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + snapshotName + "/migration?q=" + params.toString());
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "POST", null, "application/x-www-form-urlencoded");
        if (response != null) {
                getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "POST");
        }
}

def exportSnapshot(applicationSnapshotName) {
        def url;
        try {
                String snapshotName = URLEncoder.encode(applicationSnapshotName, "UTF-8");
                JSONObject params = new JSONObject();
                params.put("type","export");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + snapshotName + "/migration?q=" + params.toString());
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "POST", null, "application/x-www-form-urlencoded");
        if (response != null) {
                getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "POST");
        }
}

def getLCMVersions() {
        def url;
        try {
                        url = new URL(serverUrl + "/interop/rest/")
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def items = object.items
                println "List of versions :"
                items.each{
                        println "Version : " + it.version
                        println "Lifecycle : " + it.lifecycle
                        println "Latest : " + it.latest
                        println "Link : " + it.links[0].href + "\n"
                }
        } else {
                println "Error occurred while listing versions"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def getLCMVersionDetails() {
        def url;
        try {
                        url = new URL(serverUrl + "/interop/rest/" + apiVersion)
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def links = object.links
                println "Version " + apiVersion + " details :"
                links.each{
                        println "Service : " + it.rel
                        println "URL : " + it.href
                        println "Action : " + it.action + "\n"
                }
        } else {
                println "Error occurred while fetching version details"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def getServices() {
        def url;
        try {
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/services")
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def links = object.links
                println "Services list :"
                links.each{
                        if (!it.rel.equals("self")) {
                                println "Service : " + it.rel
                                println "URL : " + it.href
                                println "Action : " + it.action + "\n"
                        }
                }
        } else {
                println "Error occurred while fetching services list"
                if (object.details != null)
                        println "Error details: " + object.details
        }
}

def recreateService(serviceName) {
        def toCreate = System.console().readLine 'Are you sure you want to recreate the EPM environment (yes/no): no ?[Press Enter]'
        if (!toCreate.equals("yes")) {
                println "User cancelled the recreate command"
                System.exit(0)
        }
        def url;
        try {
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/services/" + serviceName + "/recreate");
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "POST", null, "application/x-www-form-urlencoded");
        if (response != null) {
                waitForCompletion(response)
        }
}

def waitForCompletion(pingUrlString) {
                def pingUrl = new URL(pingUrlString);
        def completed = false;
        while (!completed) {
                def wait = false;
                HttpURLConnection connection = (HttpURLConnection) pingUrl.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("Authorization", basicAuth);
                
                int statusCode
                try {
                        statusCode = connection.responseCode;
                        def pingResponse
                        if (statusCode == 200) {
                                if (connection.getContentType() != null && !connection.getContentType().startsWith("application/json")) {
                                        wait = true
                                }
                                else {
                                        InputStream is = connection.getInputStream();
                                        if (is != null) {
                                                pingResponse = fetchResponse(is)
                                                status = fetchJobStatusFromResponse(pingResponse);
                                                if (status == "Processing")
                                                        wait = true
                                                else {
                                                        println status
                                                        completed = true
                                                }
                                        }
                                        else
                                                wait = true
                                }
                        } else {
                                wait = true
                        }
                        connection.disconnect();
                } catch (all) {
                        wait = true
                }

                if (wait) {
                        try {
                                println "Please wait..."
                                Thread.sleep(20000);
                        } catch (InterruptedException e) {
                                completed = true
                        }
                }
        }
}

def getApplicationSnapshotDetails(applicationSnapshotName) {
        def url;
        try {
                String snapshotName = URLEncoder.encode(applicationSnapshotName, "UTF-8");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + snapshotName)
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                println "Application details :"
                println "Application snapshot name : " + object.items[0].name
                println "Application snapshot type : " + object.items[0].type
                println "Can be exported flag : " + object.items[0].canExport
                println "Can be imported flag : " + object.items[0].canImport
                println "Can be uploaded flag : " + object.items[0].canUpload
                println "Can be downloaded flag : " + object.items[0].canDownload
                def links = object.links
                println "Services details :"
                links.each{
                        println "Service : " + it.rel
                        println "URL : " + it.href
                        println "Action : " + it.action + "\n"
                }
        } else {
                println "Error occurred while fetching application snapshot details"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def listFiles() {
        def url;
        try {
                        url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots")
        } catch (MalformedURLException e) {
                        println "Malformed URL. Please pass valid URL"
                        System.exit(0);
        }
        response = executeRequest(url, "GET", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 ) {
                def items = object.items
                if (items == null) {
                        println "No files found"
                }
                else {
                        println "List of files :"
                        items.each{
                                println it.name
                        }
                }
        } else {
                println "Error occurred while listing files"
                if (object.details != null)
                                println "Error details: " + object.details
        }
}

def deleteFile(filename) {
        def url;
        try {
                String encodedFileName = URLEncoder.encode(filename, "UTF-8");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + encodedFileName)
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        response = executeRequest(url, "DELETE", null, "application/x-www-form-urlencoded");
        def object = new JsonSlurper().parseText(response)
        def status = object.status
        if (status == 0 )
                println "File deleted successfully"
        else {
                println "Error occurred while deleting file"
                if (object.details != null)
                        println "Error details: " + object.details
        }
}

def downloadFile(filename) {
        def url;
        try {
                String encodedFileName = URLEncoder.encode(filename, "UTF-8");
                url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + encodedFileName + "/contents");
        } catch (MalformedURLException e) {
                println "Malformed URL. Please pass valid URL"
                System.exit(0);
        }
        
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", basicAuth);

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

        if (statusCode == 200) {
                InputStream is;
                if (connection.getContentType() != null && connection.getContentType().contains("application/json")) {
                        is = connection.getInputStream();
                        if (is != null) {
                                response = fetchResponse(is)
                                def object = new JsonSlurper().parseText(response)
                                println "Error occurred while downloading file"
                                if (object.details != null)
                                        println "Error details: " + object.details
                        }
                } else {
                        final int BUFFER_SIZE = 5 * 1024 * 1024;
                        fileExt = connection.getHeaderField("fileExtension");
                        saveFilePath = "/u01/" + filename + "." + fileExt;
                        File f = new File(saveFilePath);
                        is = connection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(f);
                        int bytesRead = -1;
                        byte[] buffer = new byte[BUFFER_SIZE];
                        while ((bytesRead = is.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                        }
                        println "Downloaded " + filename + " successfully";
                }
        } 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();
}

def sendRequestToRest(isFirst, isLast, lastChunk,fileName) throws Exception {
    JSONObject params = new JSONObject();
    params.put("chunkSize", lastChunk.length);
    params.put("isFirst", isFirst);
    params.put("isLast", isLast);

    def url;
    try {
        url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/applicationsnapshots/" + fileName + "/contents?q=" + params.toString());
    } catch (MalformedURLException e) {
        println "Malformed URL. Please pass valid URL"
        System.exit(0);
    }

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setInstanceFollowRedirects(false);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Authorization", basicAuth);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.write(lastChunk);
    wr.flush();

    boolean status = false
    int statusCode
    try {
                statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                        InputStream is;
                        if (connection.getContentType() != null && connection.getContentType().contains("application/json")) {
                                is = connection.getInputStream();
                                if (is != null) {
                                        response = fetchResponse(is)
                                        def object = new JsonSlurper().parseText(response)
                                        if (object.status == 0)
                                                status = true;
                                        else {
                                                println "Error occurred while uploading file"
                                                if (object.details != null)
                                                        println "Error details: " + object.details
                                        }
                                }
                        }
                }
    } catch (Exception e) {
                println "Exception occurred while uploading file";
                System.exit(0);
    } finally {
                if (connection != null) {
                        connection.disconnect();
                }
    }
    return status;
}

def uploadFile(fileName) {
        final int DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
        int packetNo = 1;
        boolean status = true;
        byte[] lastChunk = null;
        File f = new File(fileName);
        InputStream fis = null;
        long totalFileSize = f.length();
        boolean isLast = false;
        Boolean isFirst = true;
        int lastPacketNo = (int) (Math.ceil(totalFileSize/ (double) DEFAULT_CHUNK_SIZE));
        long totalbytesRead = 0;
        try {
                fis = new BufferedInputStream(new FileInputStream(fileName));
                while (totalbytesRead < totalFileSize && status) {
                        int nextChunkSize = (int) Math.min(DEFAULT_CHUNK_SIZE, totalFileSize - totalbytesRead);
                        if (lastChunk == null) {
                                lastChunk = new byte[nextChunkSize];
                                int bytesRead = fis.read(lastChunk);
                                totalbytesRead += bytesRead;
                                if (packetNo == lastPacketNo) {
                                        isLast = true;
                                }
                                status = sendRequestToRest(isFirst, isLast,lastChunk,fileName);
                                isFirst=false;
                                if (status) {
                                        println "\r" + ((100 * totalbytesRead)/ totalFileSize) + "% completed";
                                } else {
                                        break;
                                }
                                packetNo = packetNo + 1;
                                lastChunk = null;
                        }
                }
        } catch (Exception e) {
                println "Exception occurred while uploading file";
                System.exit(0);
        } finally {
                if (null != fis) {
                        try {
                                fis.close();
                        } catch (IOException e) {
                                println "Error while closing input stream";
                                System.exit(0);
                        }
                }
        }
}

def integrationScenarioImportMetadataIntoApplication() {
        uploadFile("DemoApplication_HSS_Vision.zip")
        executeJob("IMPORT_METADATA", "accountMetadata", "importZipFileName=accounts.zip");
        executeJob("CUBE_REFRESH", "cubeRefresh", null);
}

def integrationScenarioImportDataRunCalcCopyToAso() {
    uploadFile("data.csv");
    executeJob("IMPORT_DATA", "loadingq1data", "importFileName=data.csv");
    executeJob("CUBE_REFRESH", "cubeRefresh", null);
    executeJob("PLAN_TYPE_MAP", "CampaignToReporting", "clearData=false");
}

def integrationScenarioExportMetadataAndDataAndDownloadFiles() {
    executeJob("EXPORT_METADATA", "exportentitymetadata", "exportZipFileName=entitydata.zip");
    executeJob("EXPORT_DATA", "Forecastdata", "exportFileName=forecastdata.zip");
    listFiles();       
    downloadFile("entitydata.zip");
    downloadFile("forecastdata.zip");  
}

def integrationScenarioRemoveUnnecessaryFiles() {
    listFiles();
    deleteFile("entitymetadata.csv");
    deleteFile("forecastdata.csv");
}

def integrationScenarioExportDataAndDownloadFiles() {
    executeJob("EXPORT_DATA", "entitydata", "exportFileName:entitydata.zip");
    executeJob("EXPORT_DATA", "forecastdata", "exportFileName:forecastdata.zip");
    listFiles();
    downloadFile("entitydata.zip");
    downloadFile("forecastdata.zip");
}

def integrationScenarioRefreshTheApplication() {
    uploadFile("accounts.zip");
    executeJob("IMPORT_METADATA", "accountMetadata", "importZipFileName:accounts.zip");
    executeJob("CUBE_REFRESH", "cubeRefresh", null);
}

executeJob("IMPORT_METADATA", "ImportMd1", "importZipFileName=ImportMD.zip");

Note:

Note on Proxy Setting: In case of proxies, set the proxy host and port as the system arguments.