Download Application Snapshot (v1)

Downloads the application snapshot from EPM repository to the local location from where client is being run. After receiving the response, if the content type is application/json then there would be an error on server and refer to details. Else, if it’s application/octet-stream, then the content to be downloaded is part of the response and can read from the response body.

Note:

The entire path to the file must be encoded; for example, changing / to %2F and spaces to .

For example, change this path to an .HTML file in the apr directory:

apr/2020-03-04 23_07_20/2020-03-04 23_07_20.html

to this:

apr%2F2020-03-04%2023_07_20%2F2020-03-04%2023_07_20.html

This API is version v1.

Required Roles

Service Administrator

Power User assigned to the Migration Administrator Profitability and Cost Management application role

REST Resource

GET /interop/rest/{api_version}/applicationsnapshots/{applicationSnapshotName}/contents

Supported Media Types: application/x-www-form-urlencoded

Note:

Before using the REST resources, you must understand how to access the REST resources and other important concepts. See Implementation Best Practices for EPM Cloud REST APIs. Using this REST API requires prerequisites. See Prerequisites.

Request

The following table summarizes the GET request parameters.

Table 9-56 Parameters

Name Description Type Required Default
applicationSnapshotName

Application snapshot name or file name to download (for example, "Artifact Snapshot" or s112.csv).

The entire applicationSnapshotName must be encoded before sending the request.

To download a particular file, provide the path to that file as the value of applicationSnapshotName. For example, to download a Data Management file called s112.csv in the inbox, refer to the file as "inbox\s112.csv" in the path parameter.

To download the Activity Reports or access log, use the fully qualified file name as shown in the output of List Files.

For example, to download a specific file from the apr directory, use the following format:
pr%2F2020-03-04%0A23_07_20%2F2020-03-04%0A23_07_20.html
      apr%2F%0A2020-03-04%2023_07_20%2F%0Aaccess_log.zip
      apr%2F%0A2020-03-04%2023_07_20%2F%0Aactivityreport.json.
Path Yes None
api_version Specific API version Path Yes None

Example of Request

https://<SERVICE_NAME>-<TENANT_NAME>.<SERVICE_TYPE>.<dcX>.oraclecloud.com/interop/rest/v1/applicationsnapshots/Vision.zip/contents

Response

Supported Media Types: application/json

Response Header

fileExtension - This will have the file extension that can be used to create a file locally. Can contain values such as zip or csv.

Table 9-57 Parameters

Attribute Description
details

Published in case of errors with the error string

status See Migration Status Codes
links Detailed information about the link
href Links to API call
action The HTTP call type
rel Possible value: self
data Parameters as key value pairs passed in the request

Example of Response Body

The following shows an example of the response body in JSON format in case there is an error during download.

{
    "details":"Not a valid file.",
    "status":8,
    "links":[{
		"href":"https://<SERVICE_NAME>-<TENANT_NAME>.<SERVICE_TYPE>.<dcX>.oraclecloud.com/interop/rest/v1/applicationsnapshots/s112.csv/contents",
		"action":"GET",
		"rel":"self",
		"data":null
    }]
}

Download Sample Code

Java Sample – downloadFile.java

Prerequisites: json.jar

Common Functions: See Common Helper Functions for Java.

public class DownloadV1 {

	private String serverUrl ; // PBCS server URL
	private String apiVersion = "v1";
	private String userName ; // Server Username
	private String password ; //Server Password
	private static String fileName ; //snapshot to be downloaded. 
	private String domain ; 
	
	
	public void downloadFile(String fileName) throws Exception {
		HttpURLConnection connection = null;
		InputStream inputStream = null;
		FileOutputStream outputStream = null;

		try {
			fileName = fileName.replaceAll("/", "\\\\");
			URL url = new URL(
					String.format(
							"%s/interop/rest/%s/applicationsnapshots/%s/contents",
							serverUrl, apiVersion,
							URLEncoder.encode(fileName, "UTF-8")));

			System.out.println("DOWNLOAD URL: " + url);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setInstanceFollowRedirects(false);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setRequestProperty(
					"Authorization",
					"Basic "
							+ new sun.misc.BASE64Encoder().encode((userName
									+ ":" + password).getBytes()));
			int status = connection.getResponseCode();
			if (status == 200) {
				if (connection.getContentType() != null
						&& connection.getContentType().equals(
								"application/json")) {
					JSONObject json = new JSONObject(
							getStringFromInputStream(connection
									.getInputStream()));
					System.out.println("Error downloading file : "
							+ json.getString("details"));
				} else {
					String response = getStringFromInputStream(connection
							.getInputStream());
					String pingURL = fetchPingUrlFromResponse(response,
							"Job Status");

					getJobStatusDownload(pingURL, "GET");
				}
			} else {
				throw new Exception("Http status code: " + status);
			}
		} finally {
			if (connection != null)
				connection.disconnect();
			if (outputStream != null)
				outputStream.close();
			if (inputStream != null)
				inputStream.close();
		}
	}

	
	private void downloadContent(String downloadURL) throws Exception {
		HttpURLConnection connection = null;
		InputStream inputStream = null;
		FileOutputStream outputStream = null;

		try {
			URL url = new URL(downloadURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			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",
					"application/x-www-form-urlencoded");
			int status = connection.getResponseCode();

			if (status == 200) {
				if (connection.getContentType() != null
						&& connection.getContentType().equals(
								"application/json")) {
					JSONObject json = new JSONObject(
							getStringFromInputStream(connection
									.getInputStream()));
					System.out.println("Error downloading file : "
							+ json.getString("details"));
				} else {
					inputStream = connection.getInputStream();
					String downloadedFileName = fileName;
					if (fileName.lastIndexOf("/") != -1) {
						downloadedFileName = fileName.substring(fileName
								.lastIndexOf("/") + 1);
					}

					String ext = ".zip";
					if (connection.getHeaderField("fileExtension") != null) {
						ext = "." + connection.getHeaderField("fileExtension");
					}
					if (fileName.lastIndexOf(".") != -1
							&& fileName.lastIndexOf(".") != 0)
						ext = fileName.substring(fileName.lastIndexOf(".") + 1);

					outputStream = new FileOutputStream(new File(
							downloadedFileName + ext));
					int bytesRead = -1;
					byte[] buffer = new byte[5 * 1024 * 1024];
					while ((bytesRead = inputStream.read(buffer)) != -1)
						outputStream.write(buffer, 0, bytesRead);
					System.out.println("File download completed.");

				}
			} else {
				throw new Exception("Http status code: " + status);
			}
		} finally {
			if (connection != null)
				connection.disconnect();
			if (outputStream != null)
				outputStream.close();
			if (inputStream != null)
				inputStream.close();
		}
	}

		private void getJobStatusDownload(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 {
					String downloadURL = fetchPingUrlFromResponse(pingResponse,
							"Download link");
					downloadContent(downloadURL);
				}
				completed = true;
			}
		}
	}

}

cURL Sample – DownloadFile.sh

Prerequisites: jq (http://stedolan.github.io/jq/download/linux64/jq)

Common Functions: See Common Helper Functions for cURL

#!/bin/sh


SERVER_URL=""
USERNAME=""
PASSWORD="1"

API_VERSION="v1"
FILENAME=$1


funcDownloadContent(){
  output=`cat pingResponse.txt`
  count=`echo $output | jq '.links | length'`
 
        i=0
        pingUrlC=""
        while [ $i -lt $count ]; do
                rel=`echo $output | jq '.links['$i'].rel'`
                rel=`echo "$rel" | tr -d "\""`
                
        if [ "$rel" == "Download link" ]; then
                                pingUrlC=`echo $output | jq '.links['$i'].href'`
                                pingUrlC=`echo "$pingUrlC" | tr -d "\""`
                fi
                i=`expr $i + 1`
        done

        #request has to be get
        statusWrite=`curl -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" --request GET -D "respHeader.txt" -o "$1"  -H "Content-Type: application/x-www-form-urlencoded" "$pingUrlC"`
          
         if [ $statusWrite == 200 ]; then

                 contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
                 #contentbody=`cat writeResponse.txt`
                 if [ ! -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
                         echo "Error occurred. "
                 else
                        fileExtension=`echo $(grep -r "fileExtension: " respHeader.txt | awk  '{print ($2)}') | tr -d [:space:]`
          
                      	if [ ! -z $fileExtension ]; then
				if [[ ! $filepath =~ \.$fileExtension$ ]]; then
					mv "$1" "$1".$fileExtension
				fi
			fi 
                    echo "Downloade file successfully"
                 fi
fi
 funcRemoveTempFiles "response.txt" "respHeader.txt"
}

funcDownloadFile() {

        filepath="/u01/$FILENAME"
	encodedFileName=$(echo $FILENAME | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/contents

   
      statusCode=`curl -X GET -s -w "%{http_code}" -u "$USERNAME:$PASSWORD"  -H "Content-Type: application/x-www-form-urlencoded" -D "respHeader.txt" -o "response.txt" $url`

              if [ $statusCode == 200 ]; then
                     
                contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
 	        contentbody=`cat response.txt`
        	
                if [  -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
			output=`cat $filepath`
			error=`echo $output | jq '.details'`
			echo "Error occurred. " $error
			funcRemoveTempFiles $filepath
		else
			funcGetStatus "GET"
			
		fi
                      
               else
                        echo "Error executing request"
                        if [ $statusCode != 000 ]; then
                                 echo "Response error code : " $statusCode
                                 funcPrintErrorDetails "response.txt"
                                 funcRemoveTempFiles "respHeader.txt" "response.txt"
                        fi
                        exit 0
               fi
		
                   
#funcRemoveTempFiles "respHeader.txt" "response.txt"
 
}
funcDownloadFile $FILENAME

Groovy Sample – DownloadFile.groovy

Prerequisites: json.jar

Common Functions: See CSS Common Helper Functions for Groovy

class DownloadV1 {

	 def serverUrl ; // PBCS server URL
	 def apiVersion = "v1";
	 def userName ; //Server Username
	 def password ; //Server Password
	 def fileName ; //Snapshot to be downloaded

	

	 void downloadFile(def fileName) throws Exception {
		HttpURLConnection connection = null;
		InputStream inputStream = null;
		FileOutputStream outputStream = null;

		try {
			fileName = fileName.replaceAll("/", "\\\\");
			URL url = new URL(String.format("%s/interop/rest/%s/applicationsnapshots/%s/contents", serverUrl,
					apiVersion, URLEncoder.encode(fileName, "UTF-8")));
			
			println "DOWNLOAD URL: "+url
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			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", "application/x-www-form-urlencoded");
			int status = connection.getResponseCode();
			if (status == 200) {
				if (connection.getContentType() != null && connection.getContentType().equals("application/json")) {
					JSONObject json = new JSONObject(getStringFromInputStream(connection.getInputStream()));
					println "Error downloading file : " + json.getString("details")
				} else {
					def response = getStringFromInputStream(connection.getInputStream());
					def pingURL = fetchPingUrlFromResponse(response, "Job Status");

					getJobStatusDownload(pingURL, "GET");
				}
			} else {
				throw new Exception("Http status code: " + status);
			}
		} finally {
			if (connection != null)
				connection.disconnect();
			if (outputStream != null)
				outputStream.close();
			if (inputStream != null)
				inputStream.close();
		}
	}

	

	
	private void downloadContent(def downloadURL) throws Exception {
		HttpURLConnection connection = null;
		InputStream inputStream = null;
		FileOutputStream outputStream = null;

		try {
			URL url = new URL(downloadURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			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", "application/x-www-form-urlencoded");
			int status = connection.getResponseCode();
			if (status == 200) {
				if (connection.getContentType() != null && connection.getContentType().equals("application/json")) {
					JSONObject json = new JSONObject(getStringFromInputStream(connection.getInputStream()));
					System.out.println("Error downloading file : " + json.getString("details"));
				} else {
					inputStream = connection.getInputStream();
					
					def downloadedFileName = fileName;
					if(fileName.lastIndexOf("/") != -1) {
						downloadedFileName = fileName.substring(fileName.lastIndexOf("/") + 1);
					}
					String ext = ".zip";
					if(connection.getHeaderField("fileExtension") !=null){
						ext = "."+connection.getHeaderField("fileExtension");
					}
					if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
						ext = fileName.substring(fileName.lastIndexOf(".")+1);
					outputStream = new FileOutputStream(new File(downloadedFileName+ext));
					int bytesRead = -1;
					byte[] buffer = new byte[5 * 1024 * 1024];
					while ((bytesRead = inputStream.read(buffer)) != -1)
						outputStream.write(buffer, 0, bytesRead);
					System.out.println("File download completed.");

				}
			} else {
				throw new Exception("Http status code: " + status);
			}
		} finally {
			if (connection != null)
				connection.disconnect();
			if (outputStream != null)
				outputStream.close();
			if (inputStream != null)
				inputStream.close();
		}
	}

    private void getJobStatusDownload(def pingUrlString, def methodType) throws Exception {
		boolean completed = false;
		while (!completed) {
			def 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) {
					println "Error occurred: " + json.getString("details")
				} else {
					def downloadURL = fetchPingUrlFromResponse(pingResponse, "Download link");
					downloadContent(downloadURL);
				}
				completed = true;
			}
		}
	}

}
Common Functions