下面列出了org.apache.http.HttpStatus#SC_BAD_GATEWAY 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void render(DriverRequest originalRequest, String content, Writer outWriter) throws IOException,
HttpErrorPage {
if (name != null) {
LOG.debug("Rendering fragment {} in page {}", name, page);
}
this.out = outWriter;
if (content == null) {
return;
}
// Pass 1. Remove esi comments
StringBuilder contentWithoutComments = new StringBuilder(Parameters.DEFAULT_BUFFER_SIZE);
parserComments.setHttpRequest(originalRequest);
parserComments.parse(content, contentWithoutComments);
// Pass 2. Process ESI
parser.setHttpRequest(originalRequest);
parser.parse(contentWithoutComments, this);
if (name != null && !this.found) {
throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Fragment " + name + " not found", "Fragment " + name
+ " not found");
}
}
/**
* 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 void render(DriverRequest originalRequest, String content, Writer out) throws IOException, HttpErrorPage {
if (name != null) {
LOG.debug("Rendering fragment {} in page {}", name, page);
}
this.futureOut = new FutureAppendableAdapter(out);
if (content == null) {
return;
}
try {
// Pass 1. Remove esi comments
StringBuilderFutureAppendable contentWithoutComments = new StringBuilderFutureAppendable();
parserComments.setHttpRequest(originalRequest);
parserComments.setData(DATA_EXECUTOR, this.executor);
parserComments.parse(content, contentWithoutComments);
CharSequence contentWithoutCommentsResult;
contentWithoutCommentsResult = contentWithoutComments.get();
// Pass 2. Process ESI
parser.setHttpRequest(originalRequest);
parser.setData(DATA_EXECUTOR, this.executor);
parser.parse(contentWithoutCommentsResult, this);
if (name != null && !this.found) {
throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Fragment " + name + " not found", "Fragment "
+ name + " not found");
}
this.futureOut.performAppends();
} catch (ExecutionException e) {
throw new IOException(e);
}
}
HttpResponse generateIncompleteResponseError(HttpResponse response,
Resource resource) {
int contentLength = Integer.parseInt(response.getFirstHeader(
"Content-Length").getValue());
HttpResponse error = new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_BAD_GATEWAY, "Bad Gateway");
error.setHeader("Content-Type", "text/plain;charset=UTF-8");
String msg = String.format("Received incomplete response "
+ "with Content-Length %d but actual body length %d",
contentLength, resource.length());
byte[] msgBytes = msg.getBytes();
error.setHeader("Content-Length", Integer.toString(msgBytes.length));
error.setEntity(new ByteArrayEntity(msgBytes));
return error;
}
public BackgroundException map(final Throwable failure, final StringBuilder buffer, final int statusCode) {
switch(statusCode) {
case HttpStatus.SC_UNAUTHORIZED:
return new LoginFailureException(buffer.toString(), failure);
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return new ProxyLoginFailureException(buffer.toString(), failure);
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_NOT_ACCEPTABLE:
return new AccessDeniedException(buffer.toString(), failure);
case HttpStatus.SC_CONFLICT:
return new ConflictException(buffer.toString(), failure);
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_GONE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
return new NotfoundException(buffer.toString(), failure);
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
case HttpStatus.SC_PAYMENT_REQUIRED:
return new QuotaException(buffer.toString(), failure);
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_NOT_IMPLEMENTED:
return new InteroperabilityException(buffer.toString(), failure);
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_GATEWAY_TIMEOUT:
return new ConnectionTimeoutException(buffer.toString(), failure);
case HttpStatus.SC_LOCKED:
return new LockedException(buffer.toString(), failure);
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case 429:
// Too Many Requests. Rate limiting
case 509:
// Bandwidth Limit Exceeded
return new RetriableAccessDeniedException(buffer.toString(), failure);
default:
return new InteroperabilityException(buffer.toString(), failure);
}
}
private boolean isInvalidGatewayStatus(int status) {
return status == HttpStatus.SC_BAD_GATEWAY || status == HttpStatus.SC_GATEWAY_TIMEOUT;
}
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;
}
}
public EsiSyntaxError(String message) {
super(HttpStatus.SC_BAD_GATEWAY, "ESI syntax error", message);
}
/**
* Perform rendering on a single url content, and append result to "writer". Automatically follows redirects
*
* @param pageUrl
* Address of the page containing the template
* @param incomingRequest
* originating request object
* @param renderers
* the renderers to use in order to transform the output
* @return The resulting response
* @throws IOException
* If an IOException occurs while writing to the writer
* @throws HttpErrorPage
* If an Exception occurs while retrieving the template
*/
public CloseableHttpResponse render(String pageUrl, IncomingRequest incomingRequest, Renderer... renderers)
throws IOException, HttpErrorPage {
DriverRequest driverRequest = new DriverRequest(incomingRequest, this, pageUrl);
// Replace ESI variables in URL
// TODO: should be performed in the ESI extension
String resultingPageUrl = VariablesResolver.replaceAllVariables(pageUrl, driverRequest);
String targetUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false);
String currentValue;
CloseableHttpResponse response;
// Retrieve URL
// Get from cache to prevent multiple request to the same url if
// multiple fragments are used.
String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl;
Pair<String, CloseableHttpResponse> cachedValue = incomingRequest.getAttribute(cacheKey);
// content and response were not in cache
if (cachedValue == null) {
OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, targetUrl, false);
headerManager.copyHeaders(driverRequest, outgoingRequest);
response = requestExecutor.execute(outgoingRequest);
int redirects = MAX_REDIRECTS;
try {
while (redirects > 0
&& this.redirectStrategy.isRedirected(outgoingRequest, response, outgoingRequest.getContext())) {
// Must consume the entity
EntityUtils.consumeQuietly(response.getEntity());
redirects--;
// Perform new request
outgoingRequest =
this.requestExecutor.createOutgoingRequest(
driverRequest,
this.redirectStrategy.getLocationURI(outgoingRequest, response,
outgoingRequest.getContext()).toString(), false);
this.headerManager.copyHeaders(driverRequest, outgoingRequest);
response = requestExecutor.execute(outgoingRequest);
}
} catch (ProtocolException e) {
throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Invalid response from server", e);
}
response = this.headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
currentValue = HttpResponseUtils.toString(response, this.eventManager);
// Cache
cachedValue = new ImmutablePair<>(currentValue, response);
incomingRequest.setAttribute(cacheKey, cachedValue);
}
currentValue = cachedValue.getKey();
response = cachedValue.getValue();
logAction("render", pageUrl, renderers);
// Apply renderers
currentValue = performRendering(pageUrl, driverRequest, response, currentValue, renderers);
response.setEntity(new StringEntity(currentValue, HttpResponseUtils.getContentType(response)));
return response;
}