下面列出了org.apache.http.HttpStatus#SC_ACCEPTED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void report(AlexaMessage msg) {
try(Timer.Context ctxt = AlexaMetrics.startPostEventTimer()) {
HttpPost post = createPost(config.getEventEndpoint(), REPORT_CONTENT_TYPE);
post.setConfig(requestConfig);
String json = SerDer.serialize(msg);
logger.trace("proactively reporting {}", json);
post.setEntity(new StringEntity(json, StandardCharsets.UTF_8));
try(CloseableHttpClient client = httpClient()) {
try(CloseableHttpResponse response = client.execute(post)) {
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) {
if(disabledSkill500(response)) {
throw new SkillDisabledException();
}
if(disabledSkill403(response)) {
throw new SkillDisabledException();
}
logger.warn("proactive reporting of {} failed with status {}", msg, response.getStatusLine());
}
}
} catch(IOException e) {
AlexaMetrics.incPostEventFailed();
logger.warn("proactive reporting of {} failed", msg, e);
}
}
}
public EventResult notifyEvent(Incident incident) throws NotifyEventException {
try {
HttpRequestWithBody request = Unirest.post(eventApi)
.header("Accept", "application/json");
request.body(incident);
HttpResponse<JsonNode> jsonResponse = request.asJson();
log.debug(IOUtils.toString(jsonResponse.getRawBody()));
switch(jsonResponse.getStatus()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
return EventResult.successEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getPropertyValue(jsonResponse, "dedup_key"));
case HttpStatus.SC_BAD_REQUEST:
return EventResult.errorEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getArrayValue(jsonResponse, "errors"));
default:
return EventResult.errorEvent(String.valueOf(jsonResponse.getStatus()), "", IOUtils.toString(jsonResponse.getRawBody()));
}
} catch (UnirestException | IOException e) {
throw new NotifyEventException(e);
}
}
private static String textFromResponse(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
final int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
break;
default: {
final String errorInfo;
if (entity != null)
errorInfo = " -- " + EntityUtils.toString(entity);
else
errorInfo = "";
throw new IllegalStateException(
"Unexpected HTTP resource from service:"
+ response.getStatusLine().getStatusCode() + ":" +
response.getStatusLine().getReasonPhrase() + errorInfo);
}
}
if (entity == null)
throw new IllegalStateException("No HTTP resource from service");
return EntityUtils.toString(entity);
}
@Override
public ActionResult execute() {
String studentId = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_ID);
if (!studentId.equals(userInfo.id) && !isMasqueradeMode()) {
return new JsonResult("You are not authorized to update this student's profile.",
HttpStatus.SC_FORBIDDEN);
}
StudentProfileUpdateRequest updateRequest = getAndValidateRequestBody(StudentProfileUpdateRequest.class);
try {
StudentProfileAttributes studentProfile = sanitizeProfile(extractProfileData(studentId, updateRequest));
logic.updateOrCreateStudentProfile(
StudentProfileAttributes.updateOptionsBuilder(studentId)
.withShortName(studentProfile.shortName)
.withEmail(studentProfile.email)
.withGender(studentProfile.gender)
.withNationality(studentProfile.nationality)
.withInstitute(studentProfile.institute)
.withMoreInfo(studentProfile.moreInfo)
.build());
return new JsonResult(Const.StatusMessages.STUDENT_PROFILE_EDITED, HttpStatus.SC_ACCEPTED);
} catch (InvalidParametersException ipe) {
return new JsonResult(ipe.getMessage(), HttpStatus.SC_BAD_REQUEST);
}
}
public static byte[] post(String url, byte[] requestContent, Map<String, String> headerMap) throws IOException {
HttpPost httpPost = new HttpPost(url);
if (requestContent != null) {
HttpEntity httpEntity = new ByteArrayEntity(requestContent);
httpPost.setEntity(httpEntity);
}
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
HttpResponse response = httpclient.execute(httpPost);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_CREATED
|| responseCode == HttpStatus.SC_ACCEPTED || responseCode == HttpStatus.SC_NO_CONTENT) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
return EntityUtils.toByteArray(responseEntity);
}
} else if (responseCode == HttpStatus.SC_NOT_FOUND) {
throw new RpcException(RpcException.UNKNOWN_EXCEPTION, "not found service for url [" + url + "]");
} else if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
throw new RpcException(RpcException.NETWORK_EXCEPTION, "occur an exception at server end.");
} else {
throw new RpcException(RpcException.NETWORK_EXCEPTION, "Unknow HttpStatus Code");
}
return null;
}
private static JsonObject gsonFromResponse(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
final int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
break;
default: {
final String errorInfo;
if (entity != null)
errorInfo = " -- " + EntityUtils.toString(entity);
else
errorInfo = "";
throw new IllegalStateException(
"Unexpected HTTP resource from service:"
+ response.getStatusLine().getStatusCode() + ":" +
response.getStatusLine().getReasonPhrase() + errorInfo);
}
}
if (entity == null)
throw new IllegalStateException("No HTTP resource from service");
Reader r = new InputStreamReader(entity.getContent());
JsonObject jsonResponse = new Gson().fromJson(r, JsonObject.class);
EntityUtils.consume(entity);
return jsonResponse;
}
private Response doRequest(String input, String transform, String format,
MimeType contentType) throws Exception {
String transformURI = fServers.transformURI(input + "-" + transform + ".json").toString();
Response response = RestAssured.given()
.queryParam("refinejson", transformURI)
.header("Accept", contentType.toString() + ";q=1.0")
.contentType("text/csv")
.content(contentsAsBytes("inputs", input, "csv"))
.when().post();
Assert.assertEquals(HttpStatus.SC_ACCEPTED, response.getStatusCode());
String location = response.getHeader("location");
Assert.assertTrue(location != null);
/* Polls until ready. */
long start = System.currentTimeMillis();
do {
response = RestAssured.given()
.header("Accept", "text/turtle")
.header("Content-Type", "text/turtle")
.when().get(location);
if (System.currentTimeMillis() - start >= ASYNC_TIMEOUT) {
Assert.fail("Asynchronous call timed out.");
}
Thread.sleep(100);
} while (response.statusCode() == HttpStatus.SC_ACCEPTED);
return response;
}
private static String handleResponse(HttpResponse response, String methodName, boolean retry, int executionCount,
int retryCount, String uri) throws OnPremiseGatewayException {
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
return handleSuccessCase(response);
case HttpStatus.SC_CREATED:
return handleSuccessCase(response);
case HttpStatus.SC_ACCEPTED:
return handleSuccessCase(response);
case HttpStatus.SC_NOT_FOUND:
throw new OnPremiseGatewayException(NOT_FOUND_ERROR_MSG);
case HttpStatus.SC_UNAUTHORIZED:
throw new OnPremiseGatewayException(AUTH_ERROR_MSG);
case HttpStatus.SC_FORBIDDEN:
throw new OnPremiseGatewayException(AUTH_FORBIDDEN_ERROR_MSG);
default:
if (retry) {
handleDefaultCaseWithRetry(executionCount, response, retryCount, methodName, uri);
} else {
throw new OnPremiseGatewayException(
methodName + " request failed for URI: " + uri + " with HTTP error code : " + response);
}
}
return OnPremiseGatewayConstants.EMPTY_STRING;
}
private void checkResponseOK(final HttpResponse response) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
LOG.debug("Requested Veeam resource does not exist");
return;
}
if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ||
response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) &&
response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
LOG.debug("HTTP request failed, status code is " + response.getStatusLine().getStatusCode() + ", response is: " + response.toString());
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Got invalid API status code returned by the Veeam server");
}
}
private String evaluateResponse(HttpResponse httpResponse) throws DigitalOceanException {
int statusCode = httpResponse.getStatusLine().getStatusCode();
String response = "";
if (HttpStatus.SC_OK == statusCode
|| HttpStatus.SC_CREATED == statusCode
|| HttpStatus.SC_ACCEPTED == statusCode) {
response = httpResponseToString(httpResponse);
} else if (HttpStatus.SC_NO_CONTENT == statusCode) {
// in a way its always true from client perspective if there is no exception.
response = String.format(NO_CONTENT_JSON_STRUCT, statusCode);
}
if (statusCode >= 400 && statusCode < 510) {
String jsonStr = httpResponseToString(httpResponse);
log.debug("JSON Response: {}", jsonStr);
JsonObject jsonObj = null;
String errorMsg = StringUtils.EMPTY;
String id = StringUtils.EMPTY;
try {
jsonObj = JsonParser.parseString(jsonStr).getAsJsonObject();
id = jsonObj.get("id").getAsString();
errorMsg = jsonObj.get("message").getAsString();
} catch (JsonSyntaxException e) {
errorMsg =
"Digital Oceans server are on maintenance. Wait for official messages "
+ "from digital ocean itself. Such as 'Cloud Control Panel, API & Support Ticket System Unavailable'";
}
String errorMsgFull =
String.format(
"\nHTTP Status Code: %s\nError Id: %s\nError Message: %s", statusCode, id, errorMsg);
log.debug(errorMsgFull);
throw new DigitalOceanException(errorMsg, id, statusCode);
}
return response;
}
private void checkForError(HttpResponse response) {
if (response.getStatus() == HttpStatus.SC_ACCEPTED || response.getStatus() == HttpStatus.SC_OK)
return;
ErrorHandler errorHandler = errorHandlers.getOrDefault(response.getStatus(), new ErrorHandler());
errorHandler.publishError(response);
}
Action authorize() throws IOException {
AuthorizationContext context = getAuthCtx();
log.debug("AuthorizationContext : {}", context);
AuthorizationResponse authResponse = cores.getAuthorizationPlugin().authorize(context);
int statusCode = authResponse.statusCode;
if (statusCode == AuthorizationResponse.PROMPT.statusCode) {
@SuppressWarnings({"unchecked"})
Map<String, String> headers = (Map) getReq().getAttribute(AuthenticationPlugin.class.getName());
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) response.setHeader(e.getKey(), e.getValue());
}
if (log.isDebugEnabled()) {
log.debug("USER_REQUIRED {} {}", req.getHeader("Authorization"), req.getUserPrincipal());
}
sendError(statusCode,
"Authentication failed, Response code: " + statusCode);
if (shouldAudit(EventType.REJECTED)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.REJECTED, req, context));
}
return RETURN;
}
if (statusCode == AuthorizationResponse.FORBIDDEN.statusCode) {
if (log.isDebugEnabled()) {
log.debug("UNAUTHORIZED auth header {} context : {}, msg: {}", req.getHeader("Authorization"), context, authResponse.getMessage());
}
sendError(statusCode,
"Unauthorized request, Response code: " + statusCode);
if (shouldAudit(EventType.UNAUTHORIZED)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.UNAUTHORIZED, req, context));
}
return RETURN;
}
if (!(statusCode == HttpStatus.SC_ACCEPTED) && !(statusCode == HttpStatus.SC_OK)) {
log.warn("ERROR {} during authentication: {}", statusCode, authResponse.getMessage());
sendError(statusCode,
"ERROR during authorization, Response code: " + statusCode);
if (shouldAudit(EventType.ERROR)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.ERROR, req, context));
}
return RETURN;
}
if (shouldAudit(EventType.AUTHORIZED)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.AUTHORIZED, req, context));
}
return null;
}
private int computeStatus(int status) {
switch (status) {
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_PAYMENT_REQUIRED:
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_NOT_ACCEPTABLE:
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_CONFLICT:
case HttpStatus.SC_GONE:
case HttpStatus.SC_LENGTH_REQUIRED:
case HttpStatus.SC_PRECONDITION_FAILED:
case HttpStatus.SC_REQUEST_TOO_LONG:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
case HttpStatus.SC_EXPECTATION_FAILED:
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_METHOD_FAILURE:
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_LOCKED:
case HttpStatus.SC_FAILED_DEPENDENCY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_NOT_IMPLEMENTED:
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case HttpStatus.SC_GATEWAY_TIMEOUT:
case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
return 0;
case HttpStatus.SC_CONTINUE:
case HttpStatus.SC_SWITCHING_PROTOCOLS:
case HttpStatus.SC_PROCESSING:
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
case HttpStatus.SC_NO_CONTENT:
case HttpStatus.SC_RESET_CONTENT:
case HttpStatus.SC_PARTIAL_CONTENT:
case HttpStatus.SC_MULTI_STATUS:
case HttpStatus.SC_MULTIPLE_CHOICES:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_SEE_OTHER:
case HttpStatus.SC_NOT_MODIFIED:
case HttpStatus.SC_USE_PROXY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return 1;
default :
return 1;
}
}
/**
* {@inheritDoc}
*/
public SparkJobResult startJob(String data, Map<String, String> params) throws SparkJobServerClientException {
final CloseableHttpClient httpClient = buildClient();
try {
if (params == null || params.isEmpty()) {
throw new SparkJobServerClientException("The given params is null or empty.");
}
if (params.containsKey(ISparkJobServerClientConstants.PARAM_APP_NAME) &&
params.containsKey(ISparkJobServerClientConstants.PARAM_CLASS_PATH)) {
StringBuffer postUrlBuff = new StringBuffer(jobServerUrl);
postUrlBuff.append("jobs?");
int num = params.size();
for (String key : params.keySet()) {
postUrlBuff.append(key).append('=').append(params.get(key));
num--;
if (num > 0) {
postUrlBuff.append('&');
}
}
HttpPost postMethod = new HttpPost(postUrlBuff.toString());
postMethod.setConfig(getRequestConfig());
setAuthorization(postMethod);
if (data != null) {
StringEntity strEntity = new StringEntity(data);
strEntity.setContentEncoding("UTF-8");
strEntity.setContentType("text/plain");
postMethod.setEntity(strEntity);
}
HttpResponse response = httpClient.execute(postMethod);
String resContent = getResponseContent(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
return parseResult(resContent);
} else {
logError(statusCode, resContent, true);
}
} else {
throw new SparkJobServerClientException("The given params should contains appName and classPath");
}
} catch (Exception e) {
processException("Error occurs when trying to start a new job:", e);
} finally {
close(httpClient);
}
return null;
}
@Override
public void accepted(String message) {
this.message = message;
httpCode = HttpStatus.SC_ACCEPTED;
}
/**
* Submits the job to salt-api using the class function and args.
*
* @return the jid of the submitted job
* @throws HttpException
* if there was a communication failure with salt-api
* @throws InterruptedException
*/
protected String submitJob(SaltApiCapability capability, HttpClient client, String authToken, String minionId, Set<String> secureData) throws HttpException, IOException,
SaltApiException, SaltTargettingMismatchException, InterruptedException {
List<NameValuePair> params = Lists.newArrayList();
List<String> args = ArgumentParser.DEFAULT_ARGUMENT_SPLITTER.parse(function);
params.add(new BasicNameValuePair(SALT_API_FUNCTION_PARAM_NAME, args.get(0)));
params.add(new BasicNameValuePair(SALT_API_TARGET_PARAM_NAME, minionId));
List<NameValuePair> printableParams = Lists.newArrayList();
printableParams.addAll(params);
for (int i = 1; i < args.size(); i++) {
String value = args.get(i);
params.add(new BasicNameValuePair(SALT_API_ARGUMENTS_PARAM_NAME, value));
for (String s : secureData) {
value = StringUtils.replace(value, s, SECURE_OPTION_VALUE);
}
printableParams.add(new BasicNameValuePair(SALT_API_ARGUMENTS_PARAM_NAME, value));
}
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params, CHAR_SET_ENCODING);
postEntity.setContentEncoding(CHAR_SET_ENCODING);
postEntity.setContentType(REQUEST_CONTENT_TYPE);
HttpPost post = httpFactory.createHttpPost(saltEndpoint + MINION_RESOURCE);
post.setHeader(SALT_AUTH_TOKEN_HEADER, authToken);
post.setHeader(REQUEST_ACCEPT_HEADER_NAME, JSON_RESPONSE_ACCEPT_TYPE);
post.setEntity(postEntity);
logWrapper.debug("Submitting job with arguments [%s]", printableParams);
logWrapper.info("Submitting job with salt-api endpoint: [%s]", post.getURI());
HttpResponse response = retryExecutor.execute(logWrapper, client, post, numRetries, Predicates.<Integer>alwaysFalse());
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
try {
String entityResponse = extractBodyFromEntity(entity);
if (statusCode != HttpStatus.SC_ACCEPTED) {
throw new HttpException(String.format("Expected response code %d, received %d. %s",
HttpStatus.SC_ACCEPTED, statusCode, entityResponse));
} else {
logWrapper.debug("Received response for job submission = %s", response);
SaltInteractionHandler interactionHandler = capability.getSaltInteractionHandler();
SaltApiResponseOutput saltOutput = interactionHandler.extractOutputForJobSubmissionResponse(entityResponse);
if (saltOutput.getMinions().size() != 1) {
throw new SaltTargettingMismatchException(String.format(
"Expected minion delegation count of 1, was %d. Full minion string: (%s)", saltOutput
.getMinions().size(), saltOutput.getMinions()));
} else if (!saltOutput.getMinions().contains(minionId)) {
throw new SaltTargettingMismatchException(String.format(
"Minion dispatch mis-match. Expected:%s, was:%s", minionId, saltOutput.getMinions()
.toString()));
}
return saltOutput.getJid();
}
} finally {
closeResource(entity);
post.releaseConnection();
}
}