private void writeToFile(String target, String operation, byte[] contents) throws IOException {
String targetUrl = target == null ?
String.format("%s?op=%s&user.name=%s", url, operation, username) :
String.format("%s/%s?op=%s&user.name=%s", trimUrl(url), target, operation, username);
HttpEntityEnclosingRequestBase method = getWriteMethod(operation, targetUrl);
int responseCode;
HttpResponse response = null;
try {
response = httpClient.execute(method);
StatusLine status = response.getStatusLine();
responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 307) {
throw new IOException(String.format("Error returned from server. Status: %s - %s", responseCode, status.getReasonPhrase()));
}
} catch (IOException e) {
method.abort();
throw e;
} finally {
method.releaseConnection();
}
try {
Header redirectUrl = response.getFirstHeader("Location");
if (redirectUrl == null) {
throw new IOException(String.format("Location header, indicating data node location, is null. Cannot continue appending to %s.", url));
}
method = getWriteMethod(operation, redirectUrl.getValue());
method.setEntity(new ByteArrayEntity(contents));
response = httpClient.execute(method);
StatusLine status = response.getStatusLine();
responseCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
if (responseCode != 200 && responseCode != 201) {
throw new IOException(String.format("Error returned from server. Status: %s - %s; %s", responseCode, status.getReasonPhrase(), readResponse(entity)));
}
} catch (IOException e) {
method.abort();
throw e;
} finally {
method.releaseConnection();
}
}