Download

Downloads a file from the repository to the local environment.

If the content type of the response is application/JSON, then an error with details is displayed on the server. If the content type of the response is application/octet-stream, then the content to be downloaded is part of the response and can read from the response body.

This REST API is version v1.

REST Resource

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

Request

Supported Media Types: application/json

Parameters:

The following table summarizes the GET request parameters.

Table 6-9 Parameters

Name Description Type Required Default
applicationSnapshotName

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

Note: To download Data Management files, for example, a file called s112.csv in the inbox, refer to this file as "inbox\s112.csv" in the path parameter. The entire applicationSnapshotName must be encoded before sending the request.

Path Yes None
api_version Specific API version Path Yes None

Response

Parameters

Name Description
fileExtension Specifies a file extension that can be used to create a file locally; can contain values such as zip and csv.

Parameters:

Table 6-10 Parameters

Name Description
Details In case of errors, details are published 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 Possibly 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/11.1.2.3.600/applicationsnapshots/s112.csv/contents",
		"action":"GET",
		"rel":"self",
		"data":null
    }]
}

Download Sample Code

Example 6-10 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()));
			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 {
					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;
			}
		}
	}

}

Example 6-11 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

Example 6-12 Groovy Sample – DownloadFile.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;
			}
		}
	}

}

Prerequisites: json.jar

Common Functions: See CSS Common Helper Functions for Groovy