Java Code Examples for org.apache.http.HttpStatus#SC_BAD_GATEWAY

The following examples show how to use org.apache.http.HttpStatus#SC_BAD_GATEWAY . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EsiRenderer.java    From esigate with Apache License 2.0 6 votes vote down vote up
@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");
    }
}
 
Example 2
Source File: DefaultRetryPolicy.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: EsiRenderer.java    From esigate with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 4
Source File: BasicHttpCache.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 5
Source File: HttpResponseExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
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);
    }
}
 
Example 6
Source File: HttpTransportClient.java    From vk-java-sdk with MIT License 4 votes vote down vote up
private boolean isInvalidGatewayStatus(int status) {
    return status == HttpStatus.SC_BAD_GATEWAY || status == HttpStatus.SC_GATEWAY_TIMEOUT;
}
 
Example 7
Source File: HttpRequestHandler.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
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;
    }
}
 
Example 8
Source File: EsiSyntaxError.java    From esigate with Apache License 2.0 4 votes vote down vote up
public EsiSyntaxError(String message) {
    super(HttpStatus.SC_BAD_GATEWAY, "ESI syntax error", message);
}
 
Example 9
Source File: Driver.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}