import org.json.JSONObject import groovy.json.JsonSlurper // EPM Instance Variables serverUrl="https://instancename.pbcs.us2.oraclecloud.com" pbcsDomain="a123456" pbcsUserName="user@somedomain.com" pbcsPassword="password" apiVersion="" // Setup User Credentials and Authorization Header userCredentials = pbcsDomain + "." + pbcsUserName + ":" + pbcsPassword basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes()) // ***************************** // ** Common Helper Functions ** // ***************************** // Fetch Response Function from the Common Helper Functions 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(); } // Fetch Job Status from Response Function from the Common Helper Functions 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.detail } // Fetch Ping URL from Response 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 } // Execute Request Function from the Common Helper Functions 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; } // Get Job Status 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 } } } // Get LCM Versions Function from the Common Helper Functions 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" apiVersion = it.version } } else { println "Error occurred while listing versions" if (object.details != null) println "Error details: " + object.details } } // List Files Function from the Common Helper Functions 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 } } // Send Request Function from the Common Helper Functions 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(); println "STATUS CODE: " + statusCode 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; } // Upload File Function from the Common Helper Functions def uploadFile(dir,fileName) { final int DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; int packetNo = 1; boolean status = true; byte[] lastChunk = null; File f = new File(dir + 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(dir + 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 { println "\r" + "Status: " + status println "\r" + "Bytes Read: " + totalbytesRead; println "\r" + "File Size: " + totalFileSize; 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 downloadFile(dir,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 = dir + filename; 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); } outputStream.close() 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(); } // ****************************** // ** Call the Functions Above ** // ****************************** getLCMVersions(); /* Do not comment this line out as it retrieves the API version. */ // listFiles(); // uploadFile("C:\\temp\\","Test_File.txt"); downloadFile("C:\\temp\\Downloaded_File\\","Test_File.txt"); // End null