下面列出了org.apache.http.HttpStatus#SC_NO_CONTENT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 正しい認証情報を使用してすべてのユーザがアクセス可能なコレクションに対して$batchをした場合処理が受付けられること.
* batchの実行順
* 1.POST(登録)
* 2.GET(一覧取得)
* 3.GET(取得)
* 4.PUT(更新)
* 5.DELETE(削除)
*/
@Test
public final void 正しい認証情報を使用してすべてのユーザがアクセス可能なコレクションに対して$batchをした場合処理が受付けられること() {
// 認証トークン取得
String[] tokens = accountAuth();
// ※本テストではACLをSetupのデフォルト値から変更しているため、実際はREAD_WRITE権限は持っていない。
String token = tokens[READ_WRITE];
// ACL設定
String path = String.format("%s/%s/%s", TEST_CELL1, BOX_NAME, COL_NAME);
DavResourceUtils.setACLPrivilegeAllForAllUser(TEST_CELL1, MASTER_TOKEN, HttpStatus.SC_OK, path, "none");
// READとWRITE→全てOK
TResponse res = UserDataUtils.batch(TEST_CELL1, BOX_NAME, COL_NAME, BOUNDARY, TEST_BODY,
token, HttpStatus.SC_ACCEPTED);
// 期待するレスポンスコード
int[] expectedCodes = new int[] {HttpStatus.SC_CREATED,
HttpStatus.SC_OK,
HttpStatus.SC_OK,
HttpStatus.SC_NO_CONTENT,
HttpStatus.SC_NO_CONTENT };
// レスポンスボディのチェック(ステータス)
checkBatchResponseBody(res, expectedCodes);
}
@Override
public ODataEntityUpdateResponse<E> execute() {
final InputStream input = getPayload();
((HttpEntityEnclosingRequestBase) request).setEntity(URIUtils.buildInputStreamEntity(odataClient, input));
try {
final HttpResponse httpResponse = doExecute();
final ODataEntityUpdateResponseImpl response =
new ODataEntityUpdateResponseImpl(odataClient, httpClient, httpResponse);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
response.close();
}
return response;
} finally {
IOUtils.closeQuietly(input);
}
}
@Override
public final void onSuccess(final int statusCode, final Header[] headers, final String responseString) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
Runnable parser = new Runnable() {
@Override
public void run() {
try {
final JSON_TYPE jsonResponse = parseResponse(responseString, false);
postRunnable(new Runnable() {
@Override
public void run() {
onSuccess(statusCode, headers, responseString, jsonResponse);
}
});
} catch (final Throwable t) {
Log.d(LOG_TAG, "parseResponse thrown an problem", t);
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, t, responseString, null);
}
});
}
}
};
if (!getUseSynchronousMode() && !getUsePoolThread()) {
new Thread(parser).start();
} else {
// In synchronous mode everything should be run on one thread
parser.run();
}
} else {
onSuccess(statusCode, headers, null, null);
}
}
@Override
public void onSuccess(final int statusCode, final Header[] headers, final String responseBody) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
new Thread(new Runnable() {
@Override
public void run() {
try {
final JSON_TYPE jsonResponse = parseResponse(responseBody);
postRunnable(new Runnable() {
@Override
public void run() {
onSuccess(statusCode, headers, responseBody, jsonResponse);
}
});
} catch (final Throwable t) {
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, t, responseBody, null);
}
});
}
}
}).start();
} else {
onSuccess(statusCode, headers, null, null);
}
}
@Override
public JsonNode parseResponse(HttpResponse httpResponse) throws AppException {
Transaction context = Transaction.getInstance();
try {
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_NO_CONTENT) {
if(context.get(MODE).equals(MODE_GRANT_ACCESS)) {
LOG.debug("Granted permission to organization: '"+context.get("orgName")+"'");
} else {
LOG.debug("Removed permission from organization: '"+context.get("orgName")+"'");
}
} else {
LOG.error("Received status code: " + httpResponse.getStatusLine().getStatusCode());
try {
LOG.error("Received response: " + EntityUtils.toString(httpResponse.getEntity()));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
throw new AppException("Failure granting/deleting permission to/from organization: '"+context.get("orgName")+"'. Mode: '"+context.get(MODE)+"'",
ErrorCode.ACCESS_ORGANIZATION_ERR);
}
} finally {
try {
((CloseableHttpResponse)httpResponse).close();
} catch (Exception ignore) { }
}
return null;
}
@Override
public final void onSuccess(final int statusCode, final Header[] headers, final String responseString) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
Runnable parser = new Runnable() {
@Override
public void run() {
try {
final JSON_TYPE jsonResponse = parseResponse(responseString, false);
postRunnable(new Runnable() {
@Override
public void run() {
onSuccess(statusCode, headers, responseString, jsonResponse);
}
});
} catch (final Throwable t) {
Log.d(LOG_TAG, "parseResponse thrown an problem", t);
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, t, responseString, null);
}
});
}
}
};
if (!getUseSynchronousMode() && !getUsePoolThread()) {
new Thread(parser).start();
} else {
// In synchronous mode everything should be run on one thread
parser.run();
}
} else {
onSuccess(statusCode, headers, null, null);
}
}
@Override
public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
new Thread(new Runnable() {
@Override
public void run() {
try {
final Object jsonResponse = parseResponse(responseBytes);
postRunnable(new Runnable() {
@Override
public void run() {
if (jsonResponse instanceof JSONObject) {
onSuccess(statusCode, headers, (JSONObject) jsonResponse);
} else if (jsonResponse instanceof JSONArray) {
onSuccess(statusCode, headers, (JSONArray) jsonResponse);
} else {
onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null);
}
}
});
} catch (final JSONException ex) {
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, ex, (JSONObject) null);
}
});
}
}
}).start();
} else {
onSuccess(statusCode, headers, new JSONObject());
}
}
@Override
public final void onSuccess(final int statusCode, final Header[] headers, final String responseString) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
new Thread(new Runnable() {
@Override
public void run() {
try {
final JSON_TYPE jsonResponse = parseResponse(responseString, false);
postRunnable(new Runnable() {
@Override
public void run() {
onSuccess(statusCode, headers, responseString, jsonResponse);
}
});
} catch (final Throwable t) {
Log.d(LOG_TAG, "parseResponse thrown an problem", t);
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, t, responseString, null);
}
});
}
}
}).start();
} else {
onSuccess(statusCode, headers, null, null);
}
}
/**
* Please see list of status codes and their meaning:
* <br><br>
* 204 No Content: URN is in database. No further information asked.<br>
* 301 Moved Permanently: The given URN is replaced with a newer version.
* This newer version should be used instead.<br>
* 404 Not Found: The given URN is not registered in system.<br>
* 410 Gone: The given URN is registered in system but marked inactive.<br>
*
* @return the status code of the request
*/
public Optional<Date> register(MCRPIRegistrationInfo urn) {
String url = getBaseServiceURL(urn);
CloseableHttpResponse response = MCRHttpsClient.head(url);
StatusLine statusLine = response.getStatusLine();
if (statusLine == null) {
LOGGER.warn("HEAD request for {} returns no status line.", url);
return Optional.empty();
}
int headStatus = statusLine.getStatusCode();
String identifier = urn.getIdentifier();
switch (headStatus) {
case HttpStatus.SC_NO_CONTENT:
LOGGER.info("URN {} is in database. No further information asked.", identifier);
LOGGER.info("Performing update of url.");
return update(urn);
case HttpStatus.SC_NOT_FOUND:
LOGGER.info("The given URN {} is not registered in system.", identifier);
return registerNew(urn);
case HttpStatus.SC_MOVED_PERMANENTLY:
LOGGER.warn("The given URN {} is replaced with a newer version. \n "
+ "This newer version should be used instead.", identifier);
break;
case HttpStatus.SC_GONE:
LOGGER.warn("The given URN {} is registered in system but marked inactive.", identifier);
break;
default:
LOGGER.warn("Could not handle request for urnInfo {} Status code {}.", identifier, headStatus);
break;
}
return Optional.empty();
}
@Override
public void onSuccess(final int statusCode, final Header[] headers, final String responseBody) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
new Thread(new Runnable() {
@Override
public void run() {
try {
final Object jsonResponse = parseResponse(responseBody);
postRunnable(new Runnable() {
@Override
public void run() {
if (jsonResponse instanceof JSONObject) {
onSuccess(statusCode, headers, (JSONObject) jsonResponse);
} else if (jsonResponse instanceof JSONArray) {
onSuccess(statusCode, headers, (JSONArray) jsonResponse);
} else if (jsonResponse instanceof String) {
onSuccess(statusCode, headers, (String) jsonResponse);
} else {
onFailure(new JSONException("Unexpected type " + jsonResponse.getClass().getName()), (JSONObject) null);
}
}
});
} catch (final JSONException ex) {
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(ex, (JSONObject) null);
}
});
}
}
}).start();
} else {
onSuccess(statusCode, headers, new JSONObject());
}
}
@Override
public final void onSuccess(final int statusCode, final Header[] headers, final String responseString) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
Runnable parser = new Runnable() {
@Override
public void run() {
try {
final JSON_TYPE jsonResponse = parseResponse(responseString, false);
postRunnable(new Runnable() {
@Override
public void run() {
onSuccess(statusCode, headers, responseString, jsonResponse);
}
});
} catch (final Throwable t) {
Log.d(LOG_TAG, "parseResponse thrown an problem", t);
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, t, responseString, null);
}
});
}
}
};
if (!getUseSynchronousMode()) {
new Thread(parser).start();
} else {
// In synchronous mode everything should be run on one thread
parser.run();
}
} else {
onSuccess(statusCode, headers, null, null);
}
}
public static Result noContent() {
return new Result(HttpStatus.SC_NO_CONTENT);
}
/**
* RtPlugin upgrade with properties ok.
* @throws Exception If something goes wrong.
*/
@Test
public void upgradeOk() throws Exception {
new ListedPlugins(
new AssertRequest(
new Response(
HttpStatus.SC_NO_CONTENT
)
),
URI.create("http://localhost/plugins"),
DOCKER
).pullAndInstall(
"vieus/sshfs",
"sshfs",
Json.createArrayBuilder().add(
Json.createObjectBuilder()
.add("Name", "network")
.add("Description", "")
.add("Value", "host")
).build()
);
final JsonArray properties = Json.createArrayBuilder().add(
Json.createObjectBuilder()
.add("Name", "mount")
.add("Description", "")
.add("Value", "/data")
).build();
final Plugin plugin = new RtPlugin(
Json.createObjectBuilder().build(),
new AssertRequest(
new Response(
HttpStatus.SC_NO_CONTENT
),
new Condition(
"Method should be a POST",
req -> "POST".equals(req.getRequestLine().getMethod())
),
new Condition(
"Resource path must be /{name}/upgrade?remote=test",
req -> req.getRequestLine().getUri()
.endsWith("/sshfs/upgrade?remote=test")
),
new Condition(
"upgrade() must send JsonArray request body",
req -> {
JsonObject payload =
new ArrayPayloadOf(req).next();
return "mount".equals(payload.getString("Name"))
&& "/data".equals(payload.getString("Value"));
}
)
),
URI.create("http://localhost/plugins/sshfs"),
DOCKER
);
plugin.upgrade("test", properties);
}
@Override
public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) {
if (statusCode != HttpStatus.SC_NO_CONTENT) {
Runnable parser = new Runnable() {
@Override
public void run() {
try {
final Object jsonResponse = parseResponse(responseBytes);
postRunnable(new Runnable() {
@Override
public void run() {
// In RFC5179 a null value is not a valid JSON
if (!useRFC5179CompatibilityMode && jsonResponse == null) {
onSuccess(statusCode, headers, (String) jsonResponse);
} else if (jsonResponse instanceof JSONObject) {
onSuccess(statusCode, headers, (JSONObject) jsonResponse);
} else if (jsonResponse instanceof JSONArray) {
onSuccess(statusCode, headers, (JSONArray) jsonResponse);
} else if (jsonResponse instanceof String) {
// In RFC5179 a simple string value is not a valid JSON
if (useRFC5179CompatibilityMode) {
onFailure(statusCode, headers, (String) jsonResponse, new JSONException("Response cannot be parsed as JSON data"));
} else {
onSuccess(statusCode, headers, (String) jsonResponse);
}
} else {
onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null);
}
}
});
} catch (final JSONException ex) {
postRunnable(new Runnable() {
@Override
public void run() {
onFailure(statusCode, headers, ex, (JSONObject) null);
}
});
}
}
};
if (!getUseSynchronousMode() && !getUsePoolThread()) {
new Thread(parser).start();
} else {
// In synchronous mode everything should be run on one thread
parser.run();
}
} else {
onSuccess(statusCode, headers, new JSONObject());
}
}
@Override
public void close() throws IOException {
try {
if(close.get()) {
log.warn(String.format("Skip double close of stream %s", this));
return;
}
if(null != canceled.get()) {
return;
}
if(overall.getLength() <= 0) {
final StoregateApiClient client = session.getClient();
final HttpPut put = new HttpPut(location);
put.addHeader(HttpHeaders.CONTENT_RANGE, "bytes */0");
final HttpResponse response = client.getClient().execute(put);
try {
switch(response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
final FileMetadata result = new JSON().getContext(FileMetadata.class).readValue(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8),
FileMetadata.class);
overall.setVersion(new VersionId(result.getId()));
case HttpStatus.SC_NO_CONTENT:
break;
default:
throw new StoregateExceptionMappingService().map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(),
EntityUtils.toString(response.getEntity())));
}
}
catch(BackgroundException e) {
throw new IOException(e);
}
finally {
EntityUtils.consume(response.getEntity());
}
}
}
finally {
close.set(true);
}
}
private boolean checkTaskStatus(final HttpResponse response) throws IOException {
final Task task = parseTaskResponse(response);
for (int i = 0; i < 120; i++) {
final HttpResponse taskResponse = get("/tasks/" + task.getTaskId());
final Task polledTask = parseTaskResponse(taskResponse);
if (polledTask.getState().equals("Finished")) {
final HttpResponse taskDeleteResponse = delete("/tasks/" + task.getTaskId());
if (taskDeleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
LOG.warn("Operation failed for veeam task id=" + task.getTaskId());
}
if (polledTask.getResult().getSuccess().equals("true")) {
Pair<String, String> pair = getRelatedLinkPair(polledTask.getLink());
if (pair != null) {
String url = pair.first();
String type = pair.second();
String path = url.replace(apiURI.toString(), "");
if (type.equals("RestoreSession")) {
for (int j = 0; j < 120; j++) {
HttpResponse relatedResponse = get(path);
RestoreSession session = parseRestoreSessionResponse(relatedResponse);
if (session.getResult().equals("Success")) {
return true;
}
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {
}
}
throw new CloudRuntimeException("Related job type: " + type + " was not successful");
}
}
return true;
}
throw new CloudRuntimeException("Failed to assign VM to backup offering due to: " + polledTask.getResult().getMessage());
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
LOG.debug("Failed to sleep while polling for Veeam task status due to: ", e);
}
}
return false;
}
/**
* Checks if a response message contains a body.
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
&& responseCode != HttpStatus.SC_NO_CONTENT
&& responseCode != HttpStatus.SC_NOT_MODIFIED;
}
/**
* Checks if a response message contains a body.
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
&& responseCode != HttpStatus.SC_NO_CONTENT
&& responseCode != HttpStatus.SC_NOT_MODIFIED;
}
/**
* Checks if a response message contains a body.
*
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
&& responseCode != HttpStatus.SC_NO_CONTENT
&& responseCode != HttpStatus.SC_NOT_MODIFIED;
}
/**
* Checks if a response message contains a body.
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
&& responseCode != HttpStatus.SC_NO_CONTENT
&& responseCode != HttpStatus.SC_NOT_MODIFIED;
}