Skip to content

Instantly share code, notes, and snippets.

@hartsock
Created July 8, 2014 18:53
Show Gist options
  • Save hartsock/b1d44677f2a5795489f5 to your computer and use it in GitHub Desktop.
Save hartsock/b1d44677f2a5795489f5 to your computer and use it in GitHub Desktop.
An example of putting a file onto a datastore...
@SuppressWarnings("unchecked")
void putVMFiles(String remoteFilePath, String localFilePath)
throws Exception {
String url = connection.getUrl();
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<String> cookies = (List<String>) headers.get("Set-cookie");
cookieValue = 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<String, List<String>> map = new HashMap<String, List<String>>();
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment