Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP request extractor//from ww w .java 2  s  . c  o  m
 *
 * @param urlToRead device URL
 * @return device type string
 * @throws IOException
 */
public static String getHTML(String urlToRead) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }

        conn.setRequestMethod("GET");
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public String getProcessImageURLFromGuvnor(String processId) {
    List<String> allPackages = getPackageNames();
    for (String pkg : allPackages) {
        // query the package to get a list of all processes in this package
        List<String> allProcessesInPackage = getAllProcessesInPackage(pkg);
        // check each process to see if it has the matching id set
        for (String process : allProcessesInPackage) {
            String processContent = getProcessSourceContent(pkg, process);
            Pattern p = Pattern.compile("<\\S*process[\\s\\S]*id=\"" + processId + "\"", Pattern.MULTILINE);
            Matcher m = p.matcher(processContent);
            if (m.find()) {
                try {
                    String imageBinaryURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/"
                            + getGuvnorSubdomain() + "/org.drools.guvnor.Guvnor/package/" + pkg + "/"
                            + getGuvnorSnapshotName() + "/" + URLEncoder.encode(processId, "UTF-8")
                            + "-image.png";

                    URL checkURL = new URL(imageBinaryURL);
                    HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
                    checkConnection.setRequestMethod("GET");
                    checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
                    checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
                    applyAuth(checkConnection);
                    checkConnection.connect();

                    if (checkConnection.getResponseCode() == 200) {
                        return imageBinaryURL;
                    }//from w ww .  ja v  a2 s.c o  m

                } catch (Exception e) {
                    logger.error("Could not read process image: " + e.getMessage());
                    throw new RuntimeException("Could not read process image: " + e.getMessage());
                }
            }
        }
    }
    logger.info("Did not find process image for: " + processId);
    return null;
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getAll(Context context) {
    // synchronized (Swingset.initPlaygroundLock) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {/* w w  w . ja  v a2 s  .  co  m*/
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground");
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    // all done
    Log.d(TAG, "   -> returned " + result);
    return playgrounds;
    // }
}

From source file:com.dawg6.d3api.server.D3IO.java

private <T> T readValue(ObjectMapper mapper, URL url, Class<T> clazz, int retries)
        throws JsonParseException, JsonMappingException, IOException {

    //      log.info("URL " + url);

    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);/*  w  w w.  j  a va 2s.c o  m*/
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(connectTimeout);
    c.setReadTimeout(readTimeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
    case 200:
    case 201:
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        try {
            mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            return mapper.readValue(sb.toString(), clazz);
        } catch (Exception e) {
            log.severe("JSON = " + sb.toString());
            log.log(Level.SEVERE, e.getMessage());

            return null;
        }

    case 408:
    case 504:
        log.info("HTTP Response: " + status + ", retries = " + retries + ", URL: " + url);
        errors++;
        onError(status);

        if (retries > 0) {
            retryAttempts++;
            onRetry();
            return readValue(mapper, url, clazz, retries - 1);
        } else
            return null;

    default:
        log.severe("HTTP Response: " + status + ", URL: " + url);
        return null;
    }
}

From source file:com.checkmarx.jenkins.CxWebService.java

private void checkServerConnectivity(URL url) throws AbortException {
    int seconds = CxConfig.getRequestTimeOutDuration();
    int milliseconds = seconds * 1000;

    try {/*from   w  w  w  .jav  a  2s  .  c om*/
        HttpURLConnection urlConn;
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setConnectTimeout(milliseconds);
        urlConn.setReadTimeout(milliseconds);
        urlConn.connect();
        if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new AbortException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS);
        }
    } catch (IOException e) {
        logger.debug(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS, e);
        throw new AbortException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS);
    }
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public boolean guvnorExists() {
    String checkURLStr = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
            + "/rest/packages/";

    try {/*from   w  w  w. ja v a 2  s  .  c  o  m*/
        URL checkURL = new URL(checkURLStr);
        HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
        checkConnection.setRequestMethod("GET");
        checkConnection.setRequestProperty("Accept", "application/atom+xml");
        checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
        checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
        applyAuth(checkConnection);
        checkConnection.connect();
        return (checkConnection.getResponseCode() == 200);
    } catch (Exception e) {
        logger.error("Error checking guvnor existence: " + e.getMessage());
        return false;
    }
}

From source file:com.pannous.es.reindex.MySearchResponseJson.java

protected HttpURLConnection createUrlConnection(String urlAsStr, int timeout)
        throws MalformedURLException, IOException {
    URL url = new URL(urlAsStr);
    //using proxy may increase latency
    HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
    hConn.setRequestProperty("User-Agent", "ElasticSearch reindex");
    hConn.setRequestProperty("Accept", "application/json");
    hConn.setRequestProperty("content-charset", "UTF-8");
    // hConn.setRequestProperty("Cache-Control", cacheControl);
    // suggest respond to be gzipped or deflated (which is just another compression)
    // http://stackoverflow.com/q/3932117
    hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    hConn.setConnectTimeout(timeout);//from  w w  w. j a v a  2 s .  c o  m
    hConn.setReadTimeout(timeout);
    return hConn;
}