private void sendFile(InputStream in, URLConnection conn) throws IOException { conn.connect(); OutputStream out = conn.getOutputStream(); try { StreamUtils.copyStream(in, out, IO_BUFFER_SIZE); } finally { out.close(); } }
private static void putVMFiles(String remoteFilePath, String localFilePath) throws Exception { String serviceUrl = url.substring(0, url.lastIndexOf("sdk") - 1); String httpUrl = serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + datacenter + "&dsName=" + datastore; httpUrl = httpUrl.replaceAll("\\ ", "%20"); System.out.println("Putting VM File " + httpUrl); URL fileURL = new URL(httpUrl); HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); // Maintain session List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; // set the cookie in the new request header Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Length", "1024"); long fileLen = new File(localFilePath).length(); System.out.println("File size is: " + fileLen); conn.setChunkedStreamingMode((int) fileLen); OutputStream out = conn.getOutputStream(); InputStream in = new BufferedInputStream(new FileInputStream(localFilePath)); int bufLen = 9 * 1024; byte[] buf = new byte[bufLen]; byte[] tmp = null; int len = 0; while ((len = in.read(buf, 0, bufLen)) != -1) { tmp = new byte[len]; System.arraycopy(buf, 0, tmp, 0, len); out.write(tmp, 0, len); } in.close(); out.close(); conn.getResponseMessage(); conn.disconnect(); }
void writeVMDKFile(String absoluteFile, String string, long diskCapacity, String vmName) throws IOException { HttpURLConnection conn = getHTTPConnection(string); InputStream in = conn.getInputStream(); String fileName = localPath + "/" + vmName + "-" + absoluteFile; OutputStream out = new FileOutputStream(new File(fileName)); byte[] buf = new byte[102400]; int len = 0; long written = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); written = written + len; } System.out.println("Exported File " + vmName + "-" + absoluteFile + " : " + written); in.close(); out.close(); }