Upload

Uploads a file from the local machine to the repository. Files on the repository cannot be accessed directly. Use this command to upload data, metadata, and backup snapshots to a service instance. See About 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.

This REST API is version v1.

REST Resource

POST /interop/rest/v1/applicationsnapshots/{applicationSnapshotName}/contents?q={"isFirst":true,"chunkSize":14,"fileSize":"3318004","isLast":false}

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

q={"isFirst":true,"chunkSize":14,"fileSize":"3318004","isLast":false,"extDirPath":"inbox"}

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 or file name to be uploaded (for example, “Artifact Snapshot.zip” or s112.csv). A file with this name is created in the repository. If a file or folder with this name exists in the repository, an error indicates 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={"isFirst":true,"chunkSize":14,"fileSize":"3318004","isLast":false,"extDirPath":"inbox"}

  • Non-Data Management upload: q={"isFirst":true,"chunkSize":14,"fileSize":"3318004","isLast":false}

No No None
fileSize The size of the file being uploaded Query Yes None

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>.<SERVICE_TYPE>.<dcX>.oraclecloud.com/interop/rest/v1/applicationsnapshots/{applicationSnapshotName}/contents?q={"isFirst":true,"chunkSize":14,"fileSize":"3318004","isLast":false}

Upload Sample Code

Example 6-7 Java Sample – uploadFile.java

Prerequisites: json.jar

Common Functions: See Common Helper Functions for Java.


/**
 * 
 * @author anupvisw
 * Class to execute Upload functionality for API version V1.
 */
public class UploadV1
{

	private final static String userName ; // User name
	private final static String password ; // Password
	private final static String serverUrl; // Server URL
	private String filePath ; //zip File to be Uploaded
	public final static String LCM_UPLOAD_URL_V1 = "/interop/rest/v1/applicationsnapshots/"; //Upload URL v1 is the API


  /**
   * Method to Upload the File.
   * Upload happens in 3 steps 1) Creation of a file in server.
   *                           2) Uploading the file step by step in chunks where the chunk size can be modified by the user.
   *                           3) The Unzipping of uploaded file is done and written to the server.
   *                       Only after completion of the 3 steps the file is uploaded successfully.  
   * @param fileName
   * @return
   * @throws IOException
   */
	
	boolean uploadFile(String fileName) throws IOException {

		final int DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024;
		InputStream fis = null;
		byte[] lastChunk = null;
		long totalFileSize = new File(fileName).length(), totalbytesRead = 0;
		boolean statusFileCreate = true, statusUpload = true, statusUnzip = true, finalStatus = false;

		int packetNo = 1;

		long start = 0;
		long end = 0;

		lastChunk = "dummydata".getBytes();
		statusFileCreate = createFile(lastChunk, fileName, totalFileSize);

		try {
			if (statusFileCreate) {
				fis = new BufferedInputStream(new FileInputStream(fileName));
				
				int totalChunks = (int) (totalFileSize / DEFAULT_CHUNK_SIZE);
				totalChunks = totalChunks
						+ (totalFileSize % DEFAULT_CHUNK_SIZE > 0 ? 1 : 0);
				
				long prevEnd = 0;
				int nextChunkSize = (int) Math.min(DEFAULT_CHUNK_SIZE,
						totalFileSize - prevEnd);

				start = 0;
				end = nextChunkSize - 1;
				
				while (prevEnd < totalFileSize - 1) {					

					lastChunk = new byte[nextChunkSize];
					totalbytesRead = totalbytesRead + fis.read(lastChunk);
							

					statusUpload = sendFileContents(lastChunk,fileName, 
							packetNo, start, end,totalFileSize);
					
					prevEnd = end;
					
					nextChunkSize = (int) Math.min(DEFAULT_CHUNK_SIZE,
							totalFileSize - prevEnd);
					
					start = prevEnd + 1;
					end = prevEnd + nextChunkSize;
					
					packetNo++;
				
				} 
               
				if (statusUpload) {
					lastChunk = "dummydata".getBytes();
					statusUnzip = unZip(lastChunk, fileName, totalFileSize);
				}
				if(fis !=null){
					fis.close();
				}}
			if (statusFileCreate && statusUpload && statusUnzip) {
				finalStatus = true;
			}

			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fis !=null)
			fis.close();}
		return finalStatus;

	}
	/**
	 * Method to Unzip the file
	 * @param lastChunk
	 * @param filePath
	 * @param totalFileLength
	 * @return
	 */
	private boolean unZip(byte[] lastChunk, String filePath, long totalFileLength) {
		HttpURLConnection connection = null;

		boolean finalStatus = true;
		try {
			String connectionParam = getConnectionParameters(false,true,lastChunk,totalFileLength,-1,-1,-1);
			connection =  getConnection(lastChunk,connection,connectionParam);
			
			int statusCode = connection.getResponseCode();
			String status = getStringFromInputStream(connection.getInputStream());
			System.out.println("Response for Unzip  File:"  + statusCode + "Status" + status);
			
			if (statusCode == 200 && status != null) {
				int commandStatus = getCommandStatus(status);
			
				if (commandStatus == 0) {
					finalStatus = false;
					System.out.println("Error Occured while unzipping" + getDetails(status));
				} else if (commandStatus == -1) {
					getJobStatus(fetchPingUrlFromResponse(status, "Job Status"), "GET");
					finalStatus = true;
				} else {
					System.out.println("Error during unzip");
					finalStatus = false;
				}
			}		

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				connection.disconnect();
		}
		return finalStatus;
	}

	
	/**
	 * Method to Upload the file
	 * @param isFirst
	 * @param isLast
	 * @param lastChunk
	 * @param filePath
	 * @param packetNo
	 * @param lastPacketNo
	 * @param start
	 * @param end
	 * @param length
	 * @param totalFileLength
	 * @return
	 */
	
	private boolean sendFileContents(byte[] lastChunk, String filePath, int packetNo,
			long start, long end, long totalFileLength) {
		HttpURLConnection connection = null;

		boolean finalStatus = false;
		try {

			
			String connectionParam = getConnectionParameters(false, false,
					lastChunk, totalFileLength,start,end,packetNo);
			connection = getConnection(lastChunk, connection, connectionParam);
			
			int statusCode = connection.getResponseCode();
			String status = getStringFromInputStream(connection.getInputStream());
			System.out.println("Response Sending the file for Step: " + packetNo + " "+ statusCode + " Status" + status);
	
			if (statusCode == 200 && status != null) {
				int commandStatus = getCommandStatus(status);
					if (commandStatus == 0) {
					finalStatus = true;
				}
				else {
					System.out.println(" Chunk upload failed" + getDetails(status));
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (connection != null)
				connection.disconnect();
		}
	
		return finalStatus;
	}

	
	/**
	 * Step 1 : Creation of File
	 * @param lastChunk
	 * @param filePath - File to be uploaded
	 * @param totalFileLength 
	 * @return the status of the step
	 */
	Boolean createFile(byte[] lastChunk, String filePath, long totalFileLength) {

		HttpURLConnection connection = null;
		Boolean finalStatus = true;
		try {
			String connectionParam = getConnectionParameters(true, false,
					lastChunk, totalFileLength,-1,-1,0);

			connection = getConnection(lastChunk, connection, connectionParam);

			int statusCode = connection.getResponseCode();
			String status = getStringFromInputStream(connection
					.getInputStream());

			System.out.println("Response for Create File:" + statusCode
					+ "Status" + status);

			if (statusCode == 200 && status != null) {
				int commandStatus = getCommandStatus(status);

				if (commandStatus == 0) {
					finalStatus = true;
				} else if (commandStatus > 0) {
					System.out.println("Error in File creation : "+ getDetails(status));
					finalStatus = false;
				}

			}
		} catch (IOException i) {
			System.out.println(" Error in File Creation" + i.getMessage());
		} catch (Exception e) {
			System.out.println("Error occured" + e.getMessage());
		}

		return finalStatus;
	}

	/**
	 * Helper Method to determine the filename.
	 */
	String getfileName(String fileName) {
		if (fileName.contains("\\")) {

			fileName = fileName.substring(fileName.lastIndexOf("\\") + 1,
					fileName.length());
		}else if (fileName.contains("/")) {

			fileName = fileName.substring(fileName.lastIndexOf("/") + 1,
					fileName.length());

		}
		return fileName;

	}
	
	/**
	 * Helper Method to create the Connection String
	 * @param chunk
	 * @param connection
	 * @param connectionParam
	 * @return
	 */
	HttpURLConnection getConnection(byte[] chunk, HttpURLConnection connection,
			String connectionParam) {

		try {
			URL url = new URL(connectionParam);

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

			// request property ..... for chunk size.
			DataOutputStream wr;

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

		} catch (IOException e) {
			System.out.println("Error occured white writing to connection"
					+ e.getMessage());
		}

		return connection;
	}
	/**
	 * Helper Method for Creation Of String for URL COnnection
	 * @param isFirst
	 * @param isLast
	 * @param chunk
	 * @param totalFileLength
	 * @return
	 */
	String getConnectionParameters (boolean isFirst,boolean isLast,byte[] chunk,long totalFileLength,long start, long end,int packetNo){
		StringBuffer buffer = new StringBuffer();
		try {
		String fileName = getfileName(filePath);
		String urlReq = serverUrl + LCM_UPLOAD_URL_V1
				+ URLEncoder.encode(fileName, "UTF-8") + "/contents";
		// buffer.append(serverUrl);
		buffer.append(urlReq);

		List<String> opts = new ArrayList<String>();
		opts.add("isFirst=" + isFirst);
		opts.add("isLast=" + isLast);
		opts.add("chunkSize=" + chunk.length);
		opts.add("fileSize=" + totalFileLength);
		if(start !=-1 && end != -1){
			opts.add("startRange=" + start);
			opts.add("endRange=" + end);
			opts.add("chunkNo=" + packetNo);
		}

		
			buffer.append("?q="
					+ URLEncoder.encode(createJsonString(opts), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			System.out.println("Error in Encoding"+e.getMessage());
		}

		return buffer.toString();
	}
	
	 /**
	  * Helper Method for Creation of Json String for Upload
	  * @param options
	  * @return
	  */
	private String createJsonString(List<String>options) {

		String jsonString = null;
		HashMap<String, Object> optMap = new HashMap<String, Object>();
		JSONObject jObj = null;
		String[] optArray;
		Boolean tmpBool = null;
		for (int i = 0; i < options.size(); i++) {
			if (options.get(i).indexOf("=") != -1) {
				optArray = options.get(i).split("=");
				if (optArray[0].equalsIgnoreCase("clearData") || optArray[0].equalsIgnoreCase("isFirst")
						|| optArray[0].equalsIgnoreCase("isLast")) {
					if (optArray[1] != null && !optArray[1].isEmpty()) {
						tmpBool = Boolean.valueOf(optArray[1]);
						optMap.put(optArray[0], (Boolean) tmpBool);
					}
				} else if (optArray[0].equalsIgnoreCase("chunkSize") || optArray[0].equalsIgnoreCase("chunkNo")) {
					optMap.put(optArray[0], (Integer) Integer.parseInt(optArray[1]));
				} else if (optArray[0].equalsIgnoreCase("extDirPath")) {
					int pos = options.get(i).indexOf("=");
					if (pos != -1) {
						optMap.put(optArray[0], options.get(i).substring(pos + 1, options.get(i).length()));
					} else {
						optMap.put(optArray[0], (String) optArray[1]);
					}
				} else {
					optMap.put(optArray[0], (String) optArray[1]);
				}
			}

		}
		if (optMap.size() > 0) {
			try {
				jObj = new JSONObject(optMap);
				jsonString = jObj.toString();
			} catch (Exception e) {
				System.out.println("Error:" + e);
			}
		}
		return jsonString;
	}
	/**
	 * Helper Method to Determine the Job Status
	 * @param pingUrlString
	 * @param methodType
	 * @throws Exception
	 */
	private void getJobStatus(String pingUrlString, String methodType) throws Exception {
		boolean completed = false;
		while (!completed) {
			String pingResponse = executeRequest(pingUrlString, methodType, null, "application/x-www-form-urlencoded");

			
			JSONObject json = new JSONObject(pingResponse);
			int status = json.getInt("status");
			if (status == -1) {
				try {
					System.out.println("Please wait...");
					Thread.sleep(20000);
				} catch (InterruptedException e) {
					completed = true;
					throw e;
				}
			} else {
				if (status > 0) {
					System.out.println("Error occurred: " + json.getString("details"));
				} else {
				}
				completed = true;
			}
		}
	}
  
/**
 * Method to retrieve the error message
 * @param response
 * @return
 * @throws Exception
 */
	private String getDetails(String response) throws Exception {
		JSONObject json = new JSONObject(response);
		if (!JSONObject.NULL.equals(json.get("details")))
			return json.getString("details");
		else
			return "NA";
	}

}

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

#!/bin/sh

SERVER_URL=""
USERNAME=""
PASSWORD=""
API_VERSION="v1"
DOMAIN=""
FILENAME=$1

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)
  
        param=$(echo "{"isLast":"false","fileSize":'$filesize',"chunkSize":"9","isFirst":"true"}" | sed -f urlencode.sed)
        urlwithparam="$url$param"
         cstatusCode=`curl -X POST -s -w "%{http_code}"  -u "$USERNAME:$PASSWORD" -o "cresponse.txt" -D "crespHeader.txt" -H "Content-Type: application/octet-stream" "$urlwithparam"`
       				   
                if [[ $cstatusCode == 200 ]]; then
                        coutput=`cat cresponse.txt`
                        cstatus=`echo $coutput | jq '.status'`
                                if [ $cstatus -gt 0 ]; then
                                   error=`echo $coutput | jq '.details'`
                                   echo "Error occurred. " $error
                                   funcRemoveTempFiles "crespHeader.txt" "cresponse.txt"
                                                                exit 0
				else if [ $cstatus == 0 ]; then
                                  
                           fi
                        fi
                else
                        echo "Error executing request"
                        if [[ $cstatusCode != 000 ]]; then
                                   echo "Response error code : " $cstatusCode
                                   funcPrintErrorDetails "cresponse.txt"
                                funcRemoveTempFiles "crespHeader.txt" "cresponse.txt"
                        fi
                        exit 0
                fi
		
	 funcRemoveTempFiles "crespHeader.txt" "cresponse.txt"
	
       
        bs=10485760
        noOfPackets=$(($((filesize / bs)) + 1))
        uploadedsize=0
        isFirst="false"
        count=1
        isLast="false"
        start=0
        
    temp1=$((filesize - uploadedsize))
    if [ $bs -gt $temp1 ];
    then
        nextChunksize=$temp1 
    else
     
        nextChunksize=$bs 
    fi
    
        end=`expr $nextChunksize - 1` 
  
        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,fileSize='$filesize',startRange='$start',endRange='$end',chunkNo=$count}" | sed -f urlencode.sed)
                urlwithparam="$url$param"
                echo "step 2 url:"$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
                                 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"                
                count=$((count + 1))
                if [ $count = $noOfPackets ]; then
                        isLast="true"
                fi
                echo "Uploaded Size : $uploadedsize"
                echo "isLast : $isLast"
        done

        param=$(echo "{"isLast":"true","fileSize":'$filesize',"chunkSize":"9","isFirst":"false"}" | sed -f urlencode.sed)
        urlwithparam="$url$param"

        ustatusCode=`curl -X POST -s -w "%{http_code}"  -u "$USERNAME:$PASSWORD" -o "uresponse.txt" -D "urespHeader.txt" -H "Content-Type: application/octet-stream" "$urlwithparam"`
                isLast="true"    
                if [[ $ustatusCode == 200 ]]; then
                        uoutput=`cat uresponse.txt`
                        ustatus=`echo $uoutput | jq '.status'`
                               echo "ustatus "$ustatus
                                if [ $ustatus -gt 0 ]; then
                                   uerror=`echo $uoutput | jq '.details'`
                                   echo "Error occurred. " $uerror
                                   funcRemoveTempFiles "urespHeader.txt" "uresponse.txt"
                                                                exit 0
                                else if [ $ustatus == -1 ]; then
                                   funcGetStatus "GET"
                           fi
                        fi
                else
                        echo "Error executing request"
                        if [[ $ustatusCode != 000 ]]; then
                                   echo "Response error code : " $ustatusCode
                                   funcPrintErrorDetails "uresponse.txt"
                                funcRemoveTempFiles "urespHeader.txt" "uresponse.txt"
                        fi
                        exit 0
                fi

        funcRemoveTempFiles "urespHeader.txt" "uresponse.txt"
        
        echo "Uploaded File Successfully"
}

funcUploadFile $FILENAME

Example 6-9 Groovy Sample – UploadFile.groovy

Prerequisites: json.jar

Common Functions: See CSS Common Helper Functions for Groovy


 class UploadV1
{

	   def userName ; // User name
	   def password ; // Password
	   def serverUrl ; // Server URL
	   def filePath ; // File to be Uploaded
	   
	   def LCM_UPLOAD_URL_V1 = "/interop/rest/v1/applicationsnapshots/"; //Upload URL v1 is the API

		
	
  /**
   * Method to Upload the FIle
   * @param fileName
   * @return
   * @throws IOException
   */
	
	boolean uploadFile(def filePath) throws IOException {

		int DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024;
		InputStream fis = null;
		byte[] lastChunk = null;
		long totalFileSize = new File(filePath).length(), totalbytesRead = 0;
		boolean statusFileCreate = true, statusUpload = true, statusUnzip = true, Status = false;

		int packetNo = 1;
		int lastPacketNo = (int) (Math.ceil(totalFileSize
				/ (double) DEFAULT_CHUNK_SIZE));

		long start = 0;
		long end = 0;
				
		
		lastChunk = "dummydata".getBytes();
		statusFileCreate = createFile(lastChunk, filePath, totalFileSize);

		try {
			if (statusFileCreate) {
				fis = new BufferedInputStream(new FileInputStream(filePath));
				
				int totalChunks = (int) (totalFileSize / DEFAULT_CHUNK_SIZE);
				totalChunks = totalChunks
						+ (totalFileSize % DEFAULT_CHUNK_SIZE > 0 ? 1 : 0);
				
				long prevEnd = 0;
				int nextChunkSize = (int) Math.min(DEFAULT_CHUNK_SIZE,
						totalFileSize - prevEnd);

				start = 0;
				end = nextChunkSize - 1;
			
				while (prevEnd < totalFileSize - 1) {					

					lastChunk = new byte[nextChunkSize];
					totalbytesRead = totalbytesRead + fis.read(lastChunk);
					
					statusUpload = sendFileContents(lastChunk,filePath, 
							packetNo, start, end,totalFileSize);
					
					prevEnd = end;
					
					nextChunkSize = (int) Math.min(DEFAULT_CHUNK_SIZE,
							totalFileSize - prevEnd);
					
					start = prevEnd + 1;
					end = prevEnd + nextChunkSize;
					packetNo++;
				
				} 
               
				if (statusUpload) {
					lastChunk = "dummydata".getBytes();
					statusUnzip = unZip(lastChunk, filePath, totalFileSize);
				}
				if(fis !=null){
					fis.close();
				}}
			
			
			if (statusFileCreate && statusUpload && statusUnzip) {
				Status = true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return Status;

	}
	
	
	/**
	 * Method to Unzip the file
	 * @param lastChunk
	 * @param filePath
	 * @param totalFileLength
	 * @return
	 */
	 boolean unZip(byte[] lastChunk, def fileName, long totalFileLength) {
		HttpURLConnection connection = null;

		boolean Status = true;
		try {
			def connectionParam = getConnectionParameters(false,true,lastChunk,totalFileLength,-1,-1,-1);
			connection =  getConnection(lastChunk,connection,connectionParam);
			
			int statusCode = connection.getResponseCode();
			def status = getStringFromInputStream(connection.getInputStream());
			println "Response for Unzip  File:"  + statusCode 
			
			if (statusCode == 200 && status != null) {
				int commandStatus = getCommandStatus(status);
			
				if (commandStatus == 0) {
					Status = false;
					println "Error Occured while unzipping" + getDetails(status)
				} else if (commandStatus == -1) {
					getJobStatus(fetchPingUrlFromResponse(status, "Job Status"), "GET");
					Status = true;
				} else {
					println "Error during unzip"
					Status = false;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				connection.disconnect();
		}
		return Status;
	}

	
	/**
	 * Method to Upload the file
	 * @param isFirst
	 * @param isLast
	 * @param lastChunk
	 * @param filePath
	 * @param packetNo
	 * @param lastPacketNo
	 * @param start
	 * @param end
	 * @param length
	 * @param totalFileLength
	 * @return
	 */
	
	 boolean sendFileContents(byte[] lastChunk, def fileName, int packetNo,
			 long start, long end,  long totalFileLength) {
		HttpURLConnection connection = null;

		boolean Status = false;
		try {

			
			def connectionParam = getConnectionParameters(false, false,
					lastChunk, totalFileLength,start,end,packetNo);
			connection = getConnection(lastChunk, connection, connectionParam);
			
			int statusCode = connection.getResponseCode();
			def status = getStringFromInputStream(connection.getInputStream());
			println "Response Sending the file:"  + statusCode 
			println "Step No:"  + packetNo
			println	"Status" + status
	
			if (statusCode == 200 && status != null) {
				int commandStatus = getCommandStatus(status);
					if (commandStatus == 0) {
					Status = true;
				}
				else {
					println " Chunk upload failed" + getDetails(status)
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (connection != null)
				connection.disconnect();
		}
	
		return Status;
	}

	
	/**
	 * Step 1 : Creation of File
	 * @param lastChunk
	 * @param filePath - File to be uploaded
	 * @param totalFileLength
	 * @return the status of the step
	 */
	Boolean createFile(byte[] lastChunk, def filePath, long totalFileLength) {

		HttpURLConnection connection = null;
		Boolean Status = true;
		try {
			def connectionParam = getConnectionParameters(true, false,
					lastChunk, totalFileLength,-1,-1,0);

			connection = getConnection(lastChunk, connection, connectionParam);

			int statusCode = connection.getResponseCode();
			def status = getStringFromInputStream(connection
					.getInputStream());

			println "Response for Create File:" + statusCode
			println	"Status" + status

			if (statusCode == 200 && status != null) {
				int commandStatus = getCommandStatus(status);

				if (commandStatus == 0) {
					// println "Success on first request"
					Status = true;
				} else if (commandStatus > 0) {
					println "Error in File creation : "+ getDetails(status)
					Status = false;
				}

			}
		} catch (IOException i) {
			println " Error in File Creation" + i.getMessage()
		} catch (Exception e) {
			println "Error occured" + e.getMessage()
		}

		return Status;
	}

	/**
	 * Helper Method to determine the filename.
	 */
	def getfileName(def filePath) {
	def fileName;
		if (filePath.contains("\\")) {

			fileName = filePath.substring(filePath.lastIndexOf("\\") + 1,
					filePath.length());
		}else if (filePath.contains("/")) {

			fileName = filePath.substring(filePath.lastIndexOf("/") + 1,
					filePath.length());

		}else if (filePath.contains("\\")) {

			fileName = filePath.substring(filePath.lastIndexOf("\\") + 1,
					filePath.length());

		}
	
		return fileName;

	}
	
	/**
	 * Helper Method to create the Connection def
	 * @param chunk
	 * @param connection
	 * @param connectionParam
	 * @return
	 */
	HttpURLConnection getConnection(byte[] chunk, HttpURLConnection connection,
			def connectionParam) {

		try {
			URL url = new URL(connectionParam);

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

			// request property ..... for chunk size.
			DataOutputStream wr;

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

		} catch (IOException e) {
			println "Error occured white writing to connection"
					+ e.getMessage()
		}

		return connection;
	}
	/**
	 * Helper Method for Creation Of def for URL COnnection
	 * @param isFirst
	 * @param isLast
	 * @param chunk
	 * @param totalFileLength
	 * @return
	 */
	def getConnectionParameters (boolean isFirst,boolean isLast,byte[] chunk,long totalFileLength,long start, long end,int packetNo){
		StringBuffer buffer = new StringBuffer();
		try {
		
		def fileName = getfileName(filePath);
	   	def url1 = serverUrl+ LCM_UPLOAD_URL_V1
		
		def url2 = url1+fileName
		def urlReq = url2+"/contents"
		buffer.append(urlReq);
		
		
		List<String> opts = new ArrayList<String>();
		opts.add("isFirst=" + isFirst);
		opts.add("isLast=" + isLast);
		opts.add("chunkSize=" + chunk.length);
		opts.add("fileSize=" + totalFileLength);
		if(start !=-1 && end != -1){
			opts.add("startRange=" + start);
			opts.add("endRange=" + end);
			opts.add("chunkNo=" + packetNo);
		}

		
			buffer.append("?q="
					+ URLEncoder.encode(createJsonString(opts), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			println "Error in Encoding"+e.getMessage()
		}

		return buffer.toString();
	}
	
	 /**
	  * Helper Method for Creation of Json def
	  * @param options
	  * @return
	  */
	 String createJsonString(List<String> options) {String jsonString = null;
 		HashMap<String, Object> optMap = new HashMap<String, Object>(); 
    JSONObject jObj = null;
		String[] optArray;
		Boolean tmpBool = null;
		for (int i = 0; i < options.size(); i++) {
		
			if (options.get(i).indexOf("=") != -1) {
				
				def temp = options.get(i);
				optArray = temp.split("=");
				if (optArray[0].equalsIgnoreCase("clearData") || optArray[0].equalsIgnoreCase("isFirst")
						|| optArray[0].equalsIgnoreCase("isLast")) {
					if (optArray[1] != null && !optArray[1].isEmpty()) {
						tmpBool = Boolean.valueOf(optArray[1]);
						optMap.put(optArray[0], (Boolean) tmpBool);
					}
				} else if (optArray[0].equalsIgnoreCase("chunkSize") || optArray[0].equalsIgnoreCase("chunkNo")) {
					optMap.put(optArray[0], (Integer) Integer.parseInt(optArray[1]));
				}else if (optArray[0].equalsIgnoreCase("extDirPath")) {
					int pos = options.get(i).indexOf("=");
					if (pos != -1) {
						optMap.put(optArray[0], options.get(i).substring(pos + 1, options.get(i).length()));
					} else {
						optMap.put(optArray[0], (String) optArray[1]);
					}
				} else {
					optMap.put(optArray[0], (String) optArray[1]);
				}
			}

		}//for
		if (optMap.size() > 0) {
			try {
				jObj = new JSONObject(optMap);
				jsonString = jObj.toString();
			} catch (Exception e) {
				println "Error:" + e
			}
		}
		return jsonString;
	}
 
/**
 * Method to retrieve the error message
 * @param response
 * @return
 * @throws Exception
 */
	 def getDetails(def response) throws Exception {
		JSONObject json = new JSONObject(response);
		if (!JSONObject.NULL.equals(json.get("details")))
			return json.getString("details");
		else
			return "NA";
	}

}