Example usage for java.net HttpURLConnection HTTP_GATEWAY_TIMEOUT

List of usage examples for java.net HttpURLConnection HTTP_GATEWAY_TIMEOUT

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_GATEWAY_TIMEOUT.

Prototype

int HTTP_GATEWAY_TIMEOUT

To view the source code for java.net HttpURLConnection HTTP_GATEWAY_TIMEOUT.

Click Source Link

Document

HTTP Status-Code 504: Gateway Timeout.

Usage

From source file:org.okj.im.core.service.QQHttpService.java

/**
 * ?//from   www. ja  v a  2 s . c om
 * @param conn
 * @return
 */
protected boolean checkResponseCode(final HttpURLConnection conn) {
    boolean success = false;

    //?false;
    if (conn == null) {
        return false;
    }

    try {
        InputStream is = conn.getInputStream();
        if (is == null) {
            return false;
        }

        InputStream isrs = conn.getErrorStream();
        if (isrs != null) {
            return false;
        }

        int status = conn.getResponseCode();
        switch (status) {
        case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
            LogUtils.warn(LOGGER, "! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
            LogUtils.warn(LOGGER, "?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
            LogUtils.warn(LOGGER, "WebQQ?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
            LogUtils.warn(LOGGER, "??! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_OK:
            LogUtils.warn(LOGGER, "Connect OK! status{0}", status);
            success = true;
        }
    } catch (IOException ex) {
        LogUtils.error(LOGGER, "??", ex);
    }
    return success;
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK./*from  w w w.j a  v  a2  s  .  c o m*/
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

From source file:com.leafhut.open_source.VerifyReceipt.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {

    // Set up logger
    LoggerService logger = serviceProvider.getLoggerService(VerifyReceipt.class);

    String startMessage = "Processing receipt...";
    logger.info(startMessage);/* ww  w  .  jav  a2s.  c o  m*/

    HttpService http;
    try {
        http = serviceProvider.getHttpService();
    } catch (ServiceNotActivatedException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        logger.error(exceptionLogMessage);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    if (http == null) {

        String failureReason = "HTTP Service is null.";
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Fetch parameters sent via POST
    String encodedReceipt = null;
    try {

        JSONObject jsonObj = new JSONObject(request.getBody());

        if (!jsonObj.isNull(kReceiptParameter)) {

            encodedReceipt = jsonObj.getString(kReceiptParameter);
        }

    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Invalid or missing parameter.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Create JSON representation of receipt
    JSONObject validationBodyJSON = new JSONObject();
    try {
        validationBodyJSON.put(kReceiptValidationKey, encodedReceipt);
    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Could not create JSON for receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }
    String validationBodyString = validationBodyJSON.toString();

    // create the HTTP request
    PostRequest req;
    try {
        req = new PostRequest(validationServerURL, validationBodyString);
    } catch (MalformedURLException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Invalid URL for receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailingURLStringKey, validationServerURL);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Send the request. This method call will not return until the server returns.
    // note that this method may throw AccessDeniedException if the URL is whitelisted or rate limited,
    // or TimeoutException if the server took too long to return
    HttpResponse response;
    try {
        response = http.post(req);
    } catch (AccessDeniedException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "HTTP request refused by StackMob custom code environment.";
        String suggestionMessage = "Check rate limiting, whitelisting, and blacklisting in the StackMob custom code environment.";
        logger.error(exceptionLogMessage);
        logger.error(failureReason);
        logger.debug(suggestionMessage);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_FORBIDDEN);
        errorMap.put(kErrorDescriptionKey, kErrorCode403Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);
        errorMap.put(kRecoverySuggestionKey, suggestionMessage);

        return new ResponseToProcess(HttpURLConnection.HTTP_FORBIDDEN, errorMap);

    } catch (TimeoutException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "HTTP request to receipt validation server timed out.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_GATEWAY_TIMEOUT);
        errorMap.put(kErrorDescriptionKey, kErrorCode504Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_GATEWAY_TIMEOUT, errorMap);
    }

    if (response == null) {

        String failureReason = "Response from receipt validation server is null.";
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Parse the response from the server
    JSONObject serverResponseJSON;

    try {
        serverResponseJSON = new JSONObject(response.getBody());
    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Could not parse JSON response from receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    int validationStatus = -1;
    try {
        if (!serverResponseJSON.isNull(kValidationResponseStatusKey)) {

            validationStatus = serverResponseJSON.getInt(kValidationResponseStatusKey);
        }
    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Missing or invalid status code from receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Take action based on receipt validation
    if (validationStatus == 0) {

        //
        // Receipt is valid
        //
        // This is where you could take any server-side actions that were required to fulfill the purchase.
        // See the StackMob custom code documentation for more details:
        // https://developer.preview.stackmob.com/tutorials/custom%20code
        //

    } else {

        //
        // Receipt is invalid
        //

        String failureReason = "Invalid receipt.";
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_PAYMENT_REQUIRED);
        errorMap.put(kErrorDescriptionKey, kErrorCode402Description);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_PAYMENT_REQUIRED, errorMap);
    }

    // Send human-readable server response to calling client
    // Note: The parsing below is brittle (depends on there never being more than two layers of JSON).
    //       This probably should be generalized using recursion.
    Map<String, Object> returnMap = new HashMap<String, Object>();

    Iterator<?> keys = serverResponseJSON.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        try {
            if (serverResponseJSON.get(key) instanceof JSONObject) {

                JSONObject nestedJSON = (JSONObject) serverResponseJSON.get(key);

                Iterator<?> nestedKeys = nestedJSON.keys();
                while (nestedKeys.hasNext()) {

                    String nestedKey = (String) nestedKeys.next();
                    Object nestedValue = nestedJSON.get(nestedKey);
                    returnMap.put(nestedKey, nestedValue.toString());

                }
            } else {

                Object value = serverResponseJSON.get(key);
                returnMap.put(key, value.toString());
            }

        } catch (JSONException e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
    }

    String finishMessage = "Receipt is valid.";
    logger.info(finishMessage);
    return new ResponseToProcess(HttpURLConnection.HTTP_OK, returnMap);
}

From source file:hudson.FilePathTest.java

@Issue("JENKINS-26196")
@Test/*  w w  w  . j av  a 2 s.  c  om*/
public void installIfNecessarySkipsDownloadWhenErroneous() throws Exception {
    File tmp = temp.getRoot();
    final FilePath d = new FilePath(tmp);
    d.child(".timestamp").touch(123000);
    final HttpURLConnection con = mock(HttpURLConnection.class);
    final URL url = someUrlToZipFile(con);
    when(con.getResponseCode()).thenReturn(HttpURLConnection.HTTP_GATEWAY_TIMEOUT);
    when(con.getResponseMessage()).thenReturn("Gateway Timeout");
    when(con.getInputStream()).thenThrow(new ConnectException());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String message = "going ahead";
    assertFalse(d.installIfNecessaryFrom(url, new StreamTaskListener(baos), message));
    verify(con).setIfModifiedSince(123000);
    String log = baos.toString();
    assertFalse(log, log.contains(message));
    assertTrue(log, log.contains("504 Gateway Timeout"));
}