Example usage for java.net HttpURLConnection getReadTimeout

List of usage examples for java.net HttpURLConnection getReadTimeout

Introduction

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

Prototype

public int getReadTimeout() 

Source Link

Document

Returns setting for read timeout.

Usage

From source file:org.rhq.modules.plugins.jbossas7.ASConnection.java

/**
 * Execute an operation against the domain api. This method is doing the
 * real work by talking to the remote server and sending JSON data, that
 * is obtained by serializing the operation.
 *
 * Please do not use this API , but execute()
 * @return JsonNode that describes the result
 * @param operation an Operation that should be run on the domain controller
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation)
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation, boolean)
 * @see #executeComplex(org.rhq.modules.plugins.jbossas7.json.Operation)
 *//*from   w w w .  j  ava 2s. co  m*/
public JsonNode executeRaw(Operation operation) {

    InputStream inputStream = null;
    BufferedReader br = null;
    InputStream es = null;
    HttpURLConnection conn = null;
    long t1 = System.currentTimeMillis();
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.addRequestProperty("Accept", "application/json");
        conn.setConnectTimeout(10 * 1000); // 10s
        conn.setReadTimeout(10 * 1000); // 10s

        if (conn.getReadTimeout() != 10 * 1000)
            log.warn("JRE uses a broken timeout mechanism - nothing we can do");

        OutputStream out = conn.getOutputStream();

        String json_to_send = mapper.writeValueAsString(operation);

        //check for spaces in the path which the AS7 server will reject. Log verbose error and
        // generate failure indicator.
        if ((operation != null) && (operation.getAddress() != null)
                && operation.getAddress().getPath() != null) {
            if (containsSpaces(operation.getAddress().getPath())) {
                Result noResult = new Result();
                String outcome = "- Path '" + operation.getAddress().getPath()
                        + "' in invalid as it cannot contain spaces -";
                if (verbose) {
                    log.error(outcome);
                }
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                JsonNode invalidPathResult = mapper.valueToTree(noResult);
                return invalidPathResult;
            }
        }

        if (verbose) {
            log.info("Json to send: " + json_to_send);
        }

        mapper.writeValue(out, operation);

        out.flush();
        out.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }

        if (inputStream != null) {

            br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            String outcome;
            JsonNode operationResult;
            if (builder.length() > 0) {
                outcome = builder.toString();
                operationResult = mapper.readTree(outcome);
                if (verbose) {
                    ObjectMapper om2 = new ObjectMapper();
                    om2.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
                    String tmp = om2.writeValueAsString(operationResult);
                    log.info(tmp);
                }
            } else {
                outcome = "- no response from server -";
                Result noResult = new Result();
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                operationResult = mapper.valueToTree(noResult);
            }
            return operationResult;
        } else {
            //if not properly authorized sends plugin exception for visual indicator in the ui.
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED
                    || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
                if (log.isDebugEnabled()) {
                    log.debug("[" + url + "] Response was empty and response code was " + responseCode + " "
                            + conn.getResponseMessage() + ".");
                }
                throw new InvalidPluginConfigurationException(
                        "Credentials for plugin to connect to AS7 management interface are invalid. Update Connection Settings with valid credentials.");
            } else {
                log.error("[" + url + "] Response was empty and response code was " + responseCode + " "
                        + conn.getResponseMessage() + ".");
            }
        }
    } catch (IllegalArgumentException iae) {
        log.error("Illegal argument " + iae);
        log.error("  for input " + operation);
    } catch (SocketTimeoutException ste) {
        log.error("Request to AS timed out " + ste.getMessage());
        conn.disconnect();
        Result failure = new Result();
        failure.setFailureDescription(ste.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(ste);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } catch (IOException e) {
        log.error("Failed to get data: " + e.getMessage());

        //the following code is in place to help keep-alive http connection re-use to occur.
        if (conn != null) {//on error conditions it's still necessary to read the response so JDK knows can reuse
            //the http connections behind the scenes.
            es = conn.getErrorStream();
            if (es != null) {
                BufferedReader dr = new BufferedReader(new InputStreamReader(es));
                String ignore = null;
                try {
                    while ((ignore = dr.readLine()) != null) {
                        //already reported error. just empty stream.
                    }
                    es.close();
                } catch (IOException e1) {
                    // ignore
                }
            }
        }

        Result failure = new Result();
        failure.setFailureDescription(e.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(e);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (es != null) {
            try {
                es.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        long t2 = System.currentTimeMillis();
        PluginStats stats = PluginStats.getInstance();
        stats.incrementRequestCount();
        stats.addRequestTime(t2 - t1);
    }

    return null;
}

From source file:org.comixwall.pffw.GraphsBase.java

/**
 * Run the controller task.//from   w  ww .  j  a  v a  2s.  c om
 * We fetch the graphs using secure http, or fall back to plain http if secure connection fails.
 * <p>
 * Note that the PFFW uses a self-signed server certificate. So the code should trust that certificate
 * and not reject the hostname.
 *
 * @return True on success, false on failure.
 */
@Override
public boolean executeTask() {
    Boolean retval = true;
    try {
        String output = controller.execute("symon", "RenderLayout", mLayout, mGraphWidth, mGraphHeight);

        JSONArray jsonArray = new JSONArray(output);
        mGraphsJsonObject = new JSONObject(jsonArray.get(0).toString());

        Iterator<String> it = mGraphsJsonObject.keys();
        while (it.hasNext()) {
            String title = it.next();
            String file = mGraphsJsonObject.getString(title);

            try {
                InputStream stream = null;

                try {
                    String outputGraph = controller.execute("symon", "GetGraph", file);
                    String base64Graph = new JSONArray(outputGraph).get(0).toString();
                    stream = new ByteArrayInputStream(Base64.decode(base64Graph, Base64.DEFAULT));

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.warning("SSH graph connection exception: " + e.toString());
                }

                // Try secure http if ssh fails
                if (stream == null) {
                    // 1540861800_404e00f4044d07242a77f802e457f774
                    String hash = file.substring(file.indexOf('_') + 1);

                    try {
                        // Using https here gives: CertPathValidatorException: Trust anchor for certification path not found.
                        // So we should trust the PFFW server crt and hostname
                        URL secureUrl = new URL("https://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpsURLConnection secureUrlConn = (HttpsURLConnection) secureUrl.openConnection();

                        // Tell the URLConnection to use a SocketFactory from our SSLContext
                        secureUrlConn.setSSLSocketFactory(sslContext.getSocketFactory());

                        // Install the PFFW host verifier
                        secureUrlConn.setHostnameVerifier(hostnameVerifier);

                        logger.finest("Using secure http: " + secureUrl.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        secureUrlConn.setConnectTimeout(5000);
                        secureUrlConn.setReadTimeout(5000);
                        logger.finest("Secure URL connection timeout values: "
                                + secureUrlConn.getConnectTimeout() + ", " + secureUrlConn.getReadTimeout());

                        stream = secureUrlConn.getInputStream();

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warning("Secure URL connection exception: " + e.toString());
                    }

                    // Try plain http if secure http fails
                    if (stream == null) {
                        // ATTENTION: Don't use try-catch here, catch in the outer exception handling
                        URL plainUrl = new URL("http://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpURLConnection plainUrlConn = (HttpURLConnection) plainUrl.openConnection();

                        logger.finest("Using plain http: " + plainUrlConn.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        plainUrlConn.setConnectTimeout(5000);
                        plainUrlConn.setReadTimeout(5000);
                        logger.finest("Plain URL connection timeout values: " + plainUrlConn.getConnectTimeout()
                                + ", " + plainUrlConn.getReadTimeout());

                        stream = plainUrlConn.getInputStream();
                    }
                }

                Bitmap bmp = BitmapFactory.decodeStream(stream);
                setBitmap(title, bmp);

            } catch (Exception e) {
                // We are especially interested in SocketTimeoutException, but catch all
                e.printStackTrace();
                logger.info("GraphsBase doInBackground exception: " + e.toString());
                // We should break out of while loop on exception, because all conn attempts have failed
                break;
            }
        }

        output = controller.execute("pf", "GetReloadRate");

        int timeout = Integer.parseInt(new JSONArray(output).get(0).toString());
        mRefreshTimeout = timeout < 10 ? 10 : timeout;

    } catch (Exception e) {
        e.printStackTrace();
        logger.warning("doInBackground exception: " + e.toString());
        retval = false;
    }
    return retval;
}