Upload

Uploads a file from the local machine to the Oracle Planning and Budgeting Cloud repository. Files on the repository are maintained by Oracle Planning and Budgeting Cloud and cannot be accessed directly. Use this command to upload data, metadata, and backup snapshots to a service instance. SeeAbout the EPM Automate Utility.

The client calls the Upload REST API multiple times based on the size of file to be uploaded. The client breaks the existing stream into a number of chunks, depending on the logic, so that each chunk size is not greater than 50 * 1024 * 1024 bytes.

If a -1 status is returned and it is the last chunk to be uploaded, this means that an LCM artifact snapshot has been uploaded and zip extraction is in progress. The client pings the URL until the status is a positive integer. This job is done asynchronously.

REST Resource

POST /interop/rest/{api_version}/applicationsnapshots/{applicationSnapshotName}/contents? q={"isLast":true,"chunkSize":444,"isFirst":true}

Note: For Data Management uploads, use the following JSON format for the query parameter:

q={"isLast":true,"extDirPath":"/inbox","chunkSize":444,"isFirst":true}"

Request

Supported Media Types: application/json

Parameters:

The following table summarizes the client request.

Table 6-6 Parameters

Name Description Type Required Default
api_version Version of the API you are developing with Path Yes None

Response

Table 6-7 Parameters

Name Description Type Required Default
applicationSnapshotName Name of the application snapshot to be uploaded. A file with this name is created in the Oracle Planning and Budgeting Cloud repository. If a file or folder with this name exists in the repository, an error is thrown indicating that a file or folder exists Path Yes None
isLast If the chunk being passed is the last one, then set to true Query Yes None
chunkSize Size of the chunk being passed in bytes Query Yes None
isFirst If the chunk being passed is the first one and there will be subsequent requests for upload, then set as true Query Yes None
extDirPath

Used to support upload of Data Management files.

Example: "extDirPath":"/inbox" where /inbox is the folder where the Data Management file is to be uploaded

Examples of query parameters in JSON format:

  • Data Management upload: q="isLast":true,"extDirPath":"/inbox","chunkSize":444,"isFirst":true}"

  • Non-Data Management upload: q={"isLast":true,"chunkSize":444,"isFirst":true}

     

Response Body

Supported Media Types: application/json

Table 6-8 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 Possible values: self, recreate service
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.

{
        "status":0,
        "details":null,
        "links":[{
                "data":null,
                "action":"POST",
        "href":"https://<SERVICE_NAME>-<TENANT_NAME>.<dcX>.oraclecloud.com/interop/rest/11.1.2.3.600/applicationsnapshots/runqueue.sh/contents?q={"isLast":true,"chunkSize":444,"isFirst":true}"
                "rel":"self"
        }]
}

Upload Sample Code

Example 6-7 Java Sample – uploadFile.java

Prerequisites: java-JSON.jar

Common Functions: See Common Helper Functions for Java.

//
// BEGIN - Upload a file to PBCS
//      
public void uploadFile(String fileName) throws Exception {
        final int DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
        InputStream fis = null;
        byte[] lastChunk = null;
        long totalFileSize = new File(fileName).length(), totalbytesRead = 0;
        boolean isLast = false, status = true;
        Boolean isFirst = true;
        int packetNo = 1, lastPacketNo = (int) (Math.ceil(totalFileSize / (double) DEFAULT_CHUNK_SIZE));

        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];
                                totalbytesRead += fis.read(lastChunk);
                                if (packetNo == lastPacketNo) 
                                        isLast = true;
                                status = sendFileContents(isFirst, isLast, lastChunk, fileName);
                                 isFirst=false;
                                packetNo = packetNo + 1;
                                lastChunk = null;
                        }
                }
                System.out.println("Uploaded successfully");
        } finally {
                if (fis != null)
                        fis.close();
        }
}
        
private boolean sendFileContents(Boolean isFirst, boolean isLast, byte[] lastChunk, String fileName) throws Exception { 
        HttpURLConnection connection = null;
                try {
                URL url = new URL(String.format("%s/interop/rest/%s/applicationsnapshots/%s/contents?q={chunkSize:%d,isFirst:%b,isLast:%b}", serverUrl, apiVersion, fileName, lastChunk.length, isFirst, isLast));
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                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/octet-stream");
                
                DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
                wr.write(lastChunk);
                wr.flush();
                int statusCode = connection.getResponseCode();
                String status = getStringFromInputStream(connection.getInputStream());
                if (statusCode == 200 && status != null) {      
                        int commandStatus = getCommandStatus(status);
                                if (commandStatus == 0) {
                                        isFirst = false;
                                        return true;
                                }else if(commandStatus == -1 && isLast){
                                        getJobStatus(fetchPingUrlFromResponse(status, "Job Status"), "GET");
                                }               }
                
                return false;
        } finally {
                if (connection != null) 
                        connection.disconnect();
        }
}
        
public int getCommandStatus(String response) throws Exception {
        JSONObject json = new JSONObject(response);
        if (!JSONObject.NULL.equals(json.get("status")))
                return json.getInt("status");
        else
                return Integer.MIN_VALUE;
}       
//
// END - Upload a file to PBCS
//

Example 6-8 cURL Sample – UploadFile.sh

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

Common Functions: See Common Helper Functions for cURL

funcUploadFile() {
        infile=$1
        if [ ! -f $infile ]; then
                echo "File does not exist"
                exit 0
        fi
        encodedFileName=$(echo $infile | sed -f urlencode.sed)
        url="$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/contents?q="
        filename=$( basename $infile)
        filesize=$( stat -c %s $infile)
        bs=52428800
        noOfPackets=$(($((filesize / bs)) + 1))
        uploadedsize=0
        isFirst=true
        count=1
        isLast="false"
        if [ $noOfPackets = 1 ]; then
          isLast="true"
        fi
        tempFile=/u01/temp/$filename

        if [ ! -d "/u01/temp" ]; then
                mkdir /u01/temp
        fi

        while [ $uploadedsize -ne $filesize ]
        do
                skip=$uploadedsize
                temp=$((filesize - uploadedsize))
                if [ $temp -le $bs ]; then
                        length=$temp
                else
                        length=$bs
                fi
                echo "Skip : $skip"
                echo "Length : $length"
                
                (
                        dd bs=1 skip=$skip count=0 &> /dev/null
                        dd bs=$length count=1 of=$tempFile &> /dev/null
                ) < "$infile"
                
                param=$(echo "{chunkSize=$length,isFirst=$isFirst,isLast=$isLast}" | sed -f urlencode.sed)
                urlwithparam="$url$param"
                echo $urlwithparam
                statusCode=`curl -X POST -s -w "%{http_code}" -T $tempFile -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: application/octet-stream" "$urlwithparam"`

                funcRemoveTempFiles $tempFile //Remove the temp files before the next loop

                if [ $statusCode == 200 ]; then
                        output=`cat response.txt`
                        status=`echo $output | jq '.status'`
                                                             if [ $status -gt 0 ]; then
                                   error=`echo $output | jq '.details'`
                                   echo "Error occurred. " $error
                                   funcRemoveTempFiles "respHeader.txt" "response.txt"
                                                                exit 0
      else if [ $status == -1 ] || [ $isLast == "true" ]; then
                                   funcGetStatus "GET"
                           fi
                        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"
                uploadedsize=$((uploadedsize + length))
                isFirst="false"
                echo "isFirst : $isFirst"
                count=$((count + 1))
                if [ $count = $noOfPackets ]; then
                        isLast="true"
                fi
                echo "Uploaded Size : $uploadedsize"
                echo "isLast : $isLast"
        done

        echo "Uploaded File Successfully"
}

Example 6-9 Groovy Sample – UploadFile.groovy

Prerequisites: java-JSON.jar

Common Functions: See Common Helper Functions for Groovy

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);
                        }
                }
        }
}