下面列出了org.apache.http.HttpStatus#SC_INTERNAL_SERVER_ERROR 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean disabledSkill500(CloseableHttpResponse response) throws IOException {
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return false;
}
HttpEntity entity = null;
try {
entity = response.getEntity();
Map<String, Object> body = JSON.fromJson(EntityUtils.toString(entity, StandardCharsets.UTF_8), ERR_TYPE);
String msg = (String) body.get("message");
boolean disabled = StringUtils.containsIgnoreCase(msg, "SkillIdentifier");
if(disabled) {
logger.warn("disabled skill due to 500 error with body {}", body);
}
return disabled;
} finally {
consumeQuietly(entity);
}
}
@Override
public boolean shouldRetry(Exception ex, RequestMessage request,
ResponseMessage response, int retries) {
if (ex instanceof ClientException) {
String errorCode = ((ClientException) ex).getErrorCode();
if (errorCode.equals(ClientErrorCode.CONNECTION_TIMEOUT)
|| errorCode.equals(ClientErrorCode.SOCKET_TIMEOUT)) {
return true;
}
}
if (response != null) {
int statusCode = response.getStatusCode();
if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
|| statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
return true;
}
}
return false;
}
public Credentials getUserFromAuthToken(String token) throws DAOException {
AuthTokenUtils.AuthToken authToken;
try {
authToken = new AuthTokenUtils.AuthToken(keyManager.getSymmetricKey(),token);
} catch (AuthenticationException e) {
throw new DAOException(HttpStatus.SC_INTERNAL_SERVER_ERROR,"internal error");
}
if(authToken.isExpired()) throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"Expired");
Query q = new QueryBuilder().select().from(Credentials.class).where(Credentials.AUTH_TOKEN_KEY,OPERAND.EQ,token).build();
TransientObject to = ObjectUtils.get1stOrNull(dao.query(q));
if(to!=null){
return new ServerCredentials(to);
} else {
throw new DAOException(HttpStatus.SC_BAD_REQUEST,"invalid auth token");
}
}
public void testHeadersFilteredWhenError500() throws Exception {
Properties properties = new Properties();
properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
HttpResponse response =
new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
"Internal Server Error");
response.addHeader("Content-type", "Text/html;Charset=UTF-8");
response.addHeader("Transfer-Encoding", "dummy");
HttpEntity httpEntity = new StringEntity("Error", "UTF-8");
response.setEntity(httpEntity);
mockConnectionManager.setResponse(response);
Driver driver = createMockDriver(properties, mockConnectionManager);
CloseableHttpResponse driverResponse;
try {
driverResponse = driver.proxy("/", request.build());
fail("We should get an HttpErrorPage");
} catch (HttpErrorPage e) {
driverResponse = e.getHttpResponse();
}
int statusCode = driverResponse.getStatusLine().getStatusCode();
assertEquals("Status code", HttpStatus.SC_INTERNAL_SERVER_ERROR, statusCode);
assertFalse("Header 'Transfer-Encoding'", driverResponse.containsHeader("Transfer-Encoding"));
}
private JsonResult joinCourseForStudent(String regkey) {
StudentAttributes student;
try {
student = logic.joinCourseForStudent(regkey, userInfo.id);
} catch (EntityDoesNotExistException ednee) {
return new JsonResult(ednee.getMessage(), HttpStatus.SC_NOT_FOUND);
} catch (EntityAlreadyExistsException eaee) {
return new JsonResult(eaee.getMessage(), HttpStatus.SC_BAD_REQUEST);
} catch (InvalidParametersException ipe) {
return new JsonResult(ipe.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
sendJoinEmail(student.course, student.name, student.email, false);
return new JsonResult("Student successfully joined course", HttpStatus.SC_OK);
}
/**
* May throw {@link ProxyServiceException} based on response statuses.
*/
private void mayThrowProxyServiceException(final HttpResponse httpResponse) {
final StatusLine status = httpResponse.getStatusLine();
if (HttpStatus.SC_UNAUTHORIZED == status.getStatusCode()
|| HttpStatus.SC_PAYMENT_REQUIRED == status.getStatusCode()
|| HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED == status.getStatusCode()
|| HttpStatus.SC_INTERNAL_SERVER_ERROR <= status.getStatusCode()) {
throw new ProxyServiceException(httpResponse);
}
}
/**
* Returns whether a failed request should be retried according to the given request context. In the following
* circumstances, the request will fail directly without consulting this method:
* <ul>
* <li>if it has already reached the max retry limit,
* <li>if the request contains non-repeatable content,
* <li>if any RuntimeException or Error is thrown when executing the request.
* </ul>
*
* @param exception the exception from the failed request, represented as a BceClientException object.
* @param retriesAttempted the number of times the current request has been attempted.
* @return true if the failed request should be retried.
*/
protected boolean shouldRetry(BceClientException exception, int retriesAttempted) {
// Always retry on client exceptions caused by IOException
if (exception.getCause() instanceof IOException) {
logger.debug("Retry for IOException.");
return true;
}
// Only retry on a subset of service exceptions
if (exception instanceof BceServiceException) {
BceServiceException e = (BceServiceException) exception;
/*
* For 500 internal server errors and 503 service unavailable errors and 502 service bad gateway, we want to retry, but we need to use
* an exponential back-off strategy so that we don't overload a server with a flood of retries.
*/
if (e.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
logger.debug("Retry for internal server error.");
return true;
}
if (e.getStatusCode() == HttpStatus.SC_BAD_GATEWAY) {
logger.debug("Retry for bad gateway.");
return true;
}
if (e.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
logger.debug("Retry for service unavailable.");
return true;
}
String errorCode = e.getErrorCode();
if (ErrorCode.REQUEST_EXPIRED.equals(errorCode)) {
logger.debug("Retry for request expired.");
return true;
}
}
return false;
}
@Override
public boolean isValidEndPoint(final URL url) {
Assert.notNull(this.httpClient);
HttpEntity entity = null;
try (final CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
final int responseCode = response.getStatusLine().getStatusCode();
for (final int acceptableCode : this.acceptableCodes) {
if (responseCode == acceptableCode) {
LOGGER.debug("Response code from server matched {}.", responseCode);
return true;
}
}
LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was {}",
responseCode);
if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
final String value = response.getStatusLine().getReasonPhrase();
LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(),
value);
}
entity = response.getEntity();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
EntityUtils.consumeQuietly(entity);
}
return false;
}
private void throwProxyExceptionForStatus(HttpResponse httpResponse) {
final StatusLine status = httpResponse.getStatusLine();
if (HttpStatus.SC_UNAUTHORIZED == status.getStatusCode()
|| HttpStatus.SC_PAYMENT_REQUIRED == status.getStatusCode()
|| HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED == status.getStatusCode()
|| HttpStatus.SC_INTERNAL_SERVER_ERROR <= status.getStatusCode()) {
throw new ProxyServiceException(httpResponse);
}
}
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;
}
@Override
public ActionResult execute() {
String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID);
String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME);
try {
logic.moveFeedbackSessionToRecycleBin(feedbackSessionName, courseId);
} catch (InvalidParametersException | EntityDoesNotExistException e) {
return new JsonResult(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
FeedbackSessionAttributes recycleBinFs = logic.getFeedbackSessionFromRecycleBin(feedbackSessionName, courseId);
return new JsonResult(new FeedbackSessionData(recycleBinFs));
}
public ResultInfo setErrorDesc(String errorDesc) {
if (this.errorCode == null) {
this.errorCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
}
this.errorDescription = errorDesc;
return this;
}
private CloseableHttpResponse getResource(String url) throws HttpErrorPage {
String result = resources.get(url);
if (result == null) {
throw new HttpErrorPage(HttpStatus.SC_NOT_FOUND, "Not found", "The page: " + url + " does not exist");
}
try {
return new HttpResponseBuilder().status(HttpStatus.SC_OK).reason("OK").entity(result).build();
} catch (UnsupportedEncodingException e) {
throw new HttpErrorPage(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.toString(), e.toString());
}
}
/**
* Given the result of trying to fetch the robots.txt file, decide how long until we retry (or
* refetch) it again.
*
* @param statusCode
* @return interval to wait, in milliseconds.
*/
private long calcRobotsFetchRetryDelay(int statusCode) {
if (statusCode == HttpStatus.SC_OK) {
return 12L * 60 * 60 * 1000;
} else if (statusCode == HttpStatus.SC_NOT_FOUND) {
return 24L * 60 * 60 * 1000;
} else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return 1L * 60 * 60 * 1000;
} else {
// Other errors usually indicate that the server is miss-configured,
// and we really want to treat it as a "not found" (even though we
// don't currently).
return 24L * 60 * 60 * 1000;
}
}
/**
* This sends a PUT request to the server and unmarshals the JSON result.
*
* @param urlSuffix the path, to which the request should be sent
* @param request the data, which should be sent to the server (mapped to JSON)
* @param returnType the class to which the JSON result should be mapped; if null,
* no mapping is tried and null is returned.
* @return the mapped result of the request
* @throws IndegoException in case of any unexpected event
*/
private <T> T doPutRequest (String urlSuffix, Object request, Class<? extends T> returnType)
throws IndegoException
{
try {
HttpPut httpRequest = new HttpPut(baseUrl + urlSuffix);
httpRequest.setHeader("x-im-context-id", session.getContextId());
String json = mapper.writeValueAsString(request);
httpRequest.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpClient.execute(httpRequest);
if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR ) {
throw new IndegoInvalidCommandException("The request failed with error: "
+ response.getStatusLine().toString());
}
if ( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK ) {
throw new IndegoAuthenticationException("The request failed with error: "
+ response.getStatusLine().toString());
}
String responseContents = EntityUtils.toString(response.getEntity());
if ( returnType == null ) {
return null;
}
else {
T result = mapper.readValue(responseContents, returnType);
return result;
}
}
catch (IOException ex) {
throw new IndegoException(ex);
}
}
@Override
public ActionResult execute() {
String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID);
String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME);
FeedbackSessionUpdateRequest updateRequest =
getAndValidateRequestBody(FeedbackSessionUpdateRequest.class);
try {
FeedbackSessionAttributes updateFeedbackSession = logic.updateFeedbackSession(
FeedbackSessionAttributes.updateOptionsBuilder(feedbackSessionName, courseId)
.withInstructions(updateRequest.getInstructions())
.withStartTime(updateRequest.getSubmissionStartTime())
.withEndTime(updateRequest.getSubmissionEndTime())
.withGracePeriod(updateRequest.getGracePeriod())
.withSessionVisibleFromTime(updateRequest.getSessionVisibleFromTime())
.withResultsVisibleFromTime(updateRequest.getResultsVisibleFromTime())
.withIsClosingEmailEnabled(updateRequest.isClosingEmailEnabled())
.withIsPublishedEmailEnabled(updateRequest.isPublishedEmailEnabled())
.build());
return new JsonResult(new FeedbackSessionData(updateFeedbackSession));
} catch (InvalidParametersException ipe) {
throw new InvalidHttpRequestBodyException(ipe.getMessage(), ipe);
} catch (EntityDoesNotExistException ednee) {
return new JsonResult(ednee.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
}
/**
* Send a moveTo call to a remote machine
*
* @param place the four-tuple of the place we are heading to
* @param agent the MobileAgent that is moving
* @return status of operation including body if successful
*/
public EmissaryResponse outboundMoveTo(final String place, final IMobileAgent agent) {
String url = null;
// Move to actions can be load-balanced out to
// a virtual IP address:port if so configured
if (VIRTUAL_MOVETO_ADDR != null) {
url = VIRTUAL_MOVETO_PROTOCOL + "://" + VIRTUAL_MOVETO_ADDR + "/";
} else {
url = KeyManipulator.getServiceHostURL(place);
}
url += CONTEXT + "/MoveTo.action";
final HttpPost method = new HttpPost(url);
method.setHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(PLACE_NAME, place));
nvps.add(new BasicNameValuePair(MOVE_ERROR_COUNT, Integer.toString(agent.getMoveErrorCount())));
final DirectoryEntry[] iq = agent.getItineraryQueueItems();
for (int j = 0; j < iq.length; j++) {
nvps.add(new BasicNameValuePair(ITINERARY_ITEM, iq[j].getKey()));
}
try {
// This is an 8859_1 String
final String agentData = PayloadUtil.serializeToString(agent.getPayloadForTransport());
nvps.add(new BasicNameValuePair(AGENT_SERIAL, agentData));
} catch (IOException iox) {
// TODO This will probably need looked at when redoing the moveTo
logger.error("Cannot serialize agent data", iox);
BasicHttpResponse response =
new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Cannot serialize agent data");
response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
return new EmissaryResponse(response);
}
method.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("8859_1")));
// Add a cookie to the outbound header if we are posting
// to the virtual IP for load balancing
if (VIRTUAL_MOVETO_ADDR != null) {
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, KeyManipulator.getServiceClassname(place));
cookie.setDomain(VIRTUAL_MOVETO_ADDR.substring(0, VIRTUAL_MOVETO_ADDR.indexOf(":")));
cookie.setPath(COOKIE_PATH);
return send(method, cookie);
}
return send(method);
}
private static int translateErrorCode(int retCode, int errorCode) {
int libErrorCode = retCode;
if (errorCode > 0) {
if (retCode == 3) {
// 二级错误字段【验签失败】
switch (errorCode) {
case 1: // 无效TOKEN,被吊销
libErrorCode = LibResultCode.OAUTH_TOKEN_REVOKED;
break;
case 2: // 请求重放
libErrorCode = LibResultCode.OAUTH_NONCE_USED;
break;
case 3: // access_token不存在
libErrorCode = LibResultCode.OAUTH_TOKEN_REJECTED;
break;
case 4: // access_token超时
libErrorCode = LibResultCode.OAUTH_TOKEN_EXPIRED;
break;
case 5: // oauth 版本不对
libErrorCode = LibResultCode.OAUTH_VERSION_REJECTED;
break;
case 6: // 签名方法不对
libErrorCode = LibResultCode.OAUTH_SIGNATURE_METHOD_REJECTED;
break;
case 7: // 参数错
libErrorCode = LibResultCode.OAUTH_PARAMETER_REJECTED;
break;
case 9: // 验证签名失败
libErrorCode = LibResultCode.OAUTH_SIGNATURE_INVALID;
break;
case 10: // 网络错误
libErrorCode = LibResultCode.NET_ISSUE;
break;
case 11: // 参数长度不对
libErrorCode = LibResultCode.OAUTH_PARAMETER_REJECTED;
break;
case 8:
case 12:
case 13:
case 14:
case 15: // 处理失败
libErrorCode = LibResultCode.SC_INTERNAL_SERVER_ERROR;
break;
}
} else if (retCode == 4) {
// 二级错误字段【发表接口】
switch (errorCode) {
case 4: // 表示有过多脏话
libErrorCode = LibResultCode.API_MB_CONTENT_ILLEGAL;
break;
case 5: // 禁止访问,如城市,uin黑名单限制等
libErrorCode = LibResultCode.API_MB_PERMISSION_ACCESS_DENIED;
break;
case 6: // 删除时:该记录不存在。发表时:父节点已不存在
libErrorCode = LibResultCode.API_MB_ITEM_NOT_EXIST;
break;
case 8: // 内容超过最大长度:420字节 (以进行短url处理后的长度计)
libErrorCode = LibResultCode.API_MB_CONTENT_OVER_LENGTH;
break;
case 9: // 包含垃圾信息:广告,恶意链接、黑名单号码等
libErrorCode = LibResultCode.API_MB_CONTENT_ILLEGAL;
break;
case 10: // 发表太快,被频率限制
libErrorCode = LibResultCode.API_MB_INVOKE_RATE_TOO_QUICK;
break;
case 11: // 源消息已删除,如转播或回复时
libErrorCode = LibResultCode.API_MB_TWEET_NOT_EXIST;
break;
case 12: // 源消息审核中
libErrorCode = LibResultCode.API_MB_ITEM_REVIEWING;
break;
case 13: // 重复发表
libErrorCode = LibResultCode.API_MB_TWEET_REPEAT;
break;
}
}
} else {
switch (retCode) {
case 1: // 参数错误
libErrorCode = HttpStatus.SC_BAD_REQUEST;
break;
case 2: // 频率受限
libErrorCode = LibResultCode.API_MB_RATE_LIMITED;
break;
case 3: // 鉴权失败
libErrorCode = HttpStatus.SC_UNAUTHORIZED;
break;
case 4: // 服务器内部错误
libErrorCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
break;
}
}
return libErrorCode;
}
private static boolean isInternalServerError(ApiException e) {
return e.getCode() >= HttpStatus.SC_INTERNAL_SERVER_ERROR;
}
/**
* HttpResponseException with 500 internal server error status.
*
* @param message exception message
*/
public HttpServerErrorException(String message) {
super(HttpStatus.SC_INTERNAL_SERVER_ERROR, message);
}