Example usage for java.net URLConnection setConnectTimeout

List of usage examples for java.net URLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net URLConnection setConnectTimeout.

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:de.thejeterlp.bukkit.updater.Updater.java

/**
 * Index:/*from w  ww.  j  a  va2 s. co m*/
 * 0: downloadUrl
 * 1: name
 * 2: releaseType
 *
 * @return
 */
protected String[] read() {
    debug("Method: read()");
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() == 0)
            return null;
        Map<?, ?> map = (Map) array.get(array.size() - 1);
        String downloadUrl = (String) map.get("downloadUrl");
        String name = (String) map.get("name");
        String releaseType = (String) map.get("releaseType");
        return new String[] { downloadUrl, name, releaseType };
    } catch (Exception e) {
        main.getLogger().severe("Error on trying to check remote versions. Error: " + e);
        return null;
    }
}

From source file:com.concentricsky.android.khanacademy.util.CaptionManager.java

/**
 * Get a {@link WebResourceResponse} with subtitles for the video with the given youtube id.
 * /*  ww  w.j a v  a  2 s  .c  om*/
 * The response contains a UTF-8 encoded json object with the subtitles received 
 * from universalsubtitles.org. 
 * 
 * @param youtubeId The youtube id of the video whose subtitles we need.
 * @return The {@link WebResourceResponse} with the subtitles, or {@code null} in case of error or if none are found.
 */
public WebResourceResponse fetchRawCaptionResponse(String youtubeId) {
    Log.d(LOG_TAG, "fetchRawCaptionResponse");
    String youtube_url = "http://www.youtube.com/watch?v=" + youtubeId;
    try {
        URL url = new URL(String.format(subtitleFormat, youtube_url, "en"));
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setUseCaches(true);
        InputStream in = null;
        try {
            in = connection.getInputStream();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            //various exceptions including at least ConnectException and UnknownHostException can happen if we're offline
        }

        return in == null ? null : new WebResourceResponse("application/json", "UTF-8", in);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.dataconservancy.dcs.ingest.services.ExternalContentStager.java

private void stageExternalFile(DcsFile file) {

    List<DcsEvent> eventsToAdd = new ArrayList<DcsEvent>();

    URL fileUrl;//  w w  w  .  java  2 s  . c  o  m
    try {
        fileUrl = new URL(encodeTagId(file.getSource()));
    } catch (MalformedURLException e) {
        throw new RuntimeException(
                String.format("Invalid file content url in file %s: %s", file.getId(), file.getSource()));
    }

    HashMap<String, String> metadata = new HashMap<String, String>();

    if (file.getName() == null) {
        file.setName(getFileName(fileUrl));
    }

    /* Stage the content */
    InputStream stream = null;
    StagedFile staged = null;
    try {
        InputStream src = null;
        if (file.getSource().contains("file:"))
            src = fileUrl.openStream();
        else if (file.getSource().contains("http:") || file.getSource().contains("https:")) {
            String loginPassword = this.acrUser + ":" + this.acrPassword;
            String encoded = new sun.misc.BASE64Encoder().encode(loginPassword.getBytes());
            URLConnection conn = fileUrl.openConnection();
            conn.setConnectTimeout(15 * 1000);
            conn.setReadTimeout(15 * 1000);
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            src = conn.getInputStream();
        }
        stream = fixityFilter(src, metadata, eventsToAdd);
        staged = ingest.getFileContentStager().add(stream, metadata);
        // file.setSource(staged.getReferenceURI());
        // TODO : Directly setting the access URI due to Reference URI resolving issues for large collections
        file.setSource(staged.getAccessURI());
    } catch (IOException e) {
        throw new RuntimeException("Error getting content from " + fileUrl.toString());
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                log.error("Error while downloading file", e);
            }
        }
    }

    /*
     * Add digest and download events to the staged content's sip, as well
     * as fixity values themselves
     */
    updateStagedSip(staged.getSipRef(), fileUrl, metadata, eventsToAdd);

}

From source file:com.github.beat.signer.pdf_signer.TSAClient.java

private byte[] getTSAResponse(byte[] request) throws IOException {
    LOGGER.debug("Opening connection to TSA server");

    // FIXME: support proxy servers
    URLConnection connection = tsaInfo.getTsaUrl().openConnection();
    connection.setDoOutput(true);//from www .j  av a  2  s . com
    connection.setDoInput(true);
    connection.setReadTimeout(CONNECT_TIMEOUT);
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setRequestProperty("Content-Type", "application/timestamp-query");

    // TODO set accept header

    LOGGER.debug("Established connection to TSA server");

    String username = tsaInfo.getUsername();
    char[] password = tsaInfo.getPassword();
    if (StringUtils.isNotBlank(username) && password != null) {
        // FIXME this most likely wrong, e.g. set correct request property!
        // connection.setRequestProperty(username, password);
    }

    // read response
    sendRequest(request, connection);

    LOGGER.debug("Waiting for response from TSA server");

    byte[] response = getResponse(connection);

    LOGGER.debug("Received response from TSA server");

    return response;
}

From source file:com.bt.heliniumstudentapp.UpdateClass.java

@Override
protected String doInBackground(Void... Void) {
    try {//  ww  w.  j a  va  2s .c o m
        URLConnection connection = new URL(HeliniumStudentApp.URL_UPDATE_CHANGELOG).openConnection();

        connection.setConnectTimeout(HeliniumStudentApp.TIMEOUT_CONNECT);
        connection.setReadTimeout(HeliniumStudentApp.TIMEOUT_READ);

        connection.setRequestProperty("Accept-Charset", HeliniumStudentApp.CHARSET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + HeliniumStudentApp.CHARSET);

        connection.connect();

        final Scanner line = new Scanner(connection.getInputStream()).useDelimiter("\\A");
        final String html = line.hasNext() ? line.next() : "";

        ((HttpURLConnection) connection).disconnect();

        if (((HttpURLConnection) connection).getResponseCode() == 200)
            return html;
        else
            return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.gmail.bleedobsidian.itemcase.Updater.java

/**
 * Query ServerMods API for project variables.
 *
 * @return If successful or not./*w ww. j ava 2s.  c  om*/
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}

From source file:org.ambraproject.service.search.SolrHttpServiceImpl.java

/**
 * @inheritDoc//from   ww w  . j  av a2 s .  c o  m
 */
public Document makeSolrRequestForRss(String queryString) throws SolrException {

    if (solrUrl == null || solrUrl.isEmpty()) {
        setSolrUrl(config.getString(URL_CONFIG_PARAM));
    }

    queryString = "?" + queryString;

    URL url;
    String urlString = solrUrl + queryString;
    log.debug("Making Solr http request to " + urlString);
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new SolrException("Bad Solr Url: " + urlString, e);
    }

    InputStream urlStream = null;
    Document doc = null;
    try {
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.connect();
        urlStream = connection.getInputStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(urlStream);
    } catch (IOException e) {
        throw new SolrException("Error connecting to the Solr server at " + solrUrl, e);
    } catch (ParserConfigurationException e) {
        throw new SolrException("Error configuring parser xml parser for solr response", e);
    } catch (SAXException e) {
        throw new SolrException("Solr Returned bad XML for url: " + urlString, e);
    } finally {
        //Close the input stream
        if (urlStream != null) {
            try {
                urlStream.close();
            } catch (IOException e) {
                log.error("Error closing url stream to Solr", e);
            }
        }
    }

    return doc;
}

From source file:org.codice.ddf.admin.sources.utils.RequestUtils.java

/**
 * Attempts to open a connection to a URL.
 *
 * <p>Possible Error Codes to be returned - {@link
 * org.codice.ddf.admin.common.report.message.DefaultMessages#CANNOT_CONNECT}
 *
 * @param urlField {@link UrlField} containing the URL to connect to
 * @return a {@link Report} containing no messages on success, or containing {@link
 *     org.codice.ddf.admin.api.report.ErrorMessage}s on failure.
 *///from   w  w  w .  ja v a  2 s .co  m
public Report<Void> endpointIsReachable(UrlField urlField) {
    URLConnection urlConnection = null;
    try {
        urlConnection = new URL(urlField.getValue()).openConnection();
        urlConnection.setConnectTimeout(CLIENT_TIMEOUT_MILLIS);
        urlConnection.connect();
        LOGGER.debug("Successfully reached {}.", urlField);
    } catch (IOException e) {
        LOGGER.debug("Failed to reach {}, returning an error.", urlField, e);
        return Reports.from(cannotConnectError(urlField.getPath()));
    } finally {
        try {
            if (urlConnection != null) {
                urlConnection.getInputStream().close();
            }
        } catch (IOException e) {
            LOGGER.debug("Error closing connection stream.");
        }
    }
    return Reports.emptyReport();
}

From source file:org.onebusaway.transit_data_federation.util.RestApiLibrary.java

public String getContentsOfUrlAsString(URL requestUrl) throws IOException {
    BufferedReader br = null;/*from  w ww  .  jav  a  2  s.com*/
    InputStream inStream = null;
    URLConnection conn = null;

    try {
        conn = requestUrl.openConnection();
        conn.setConnectTimeout(connectionTimeout);
        conn.setReadTimeout(readTimeout);
        inStream = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(inStream));
        StringBuilder output = new StringBuilder();

        int cp;
        while ((cp = br.read()) != -1) {
            output.append((char) cp);
        }

        return output.toString();
    } catch (IOException ioe) {
        String url = requestUrl != null ? requestUrl.toExternalForm() : "url unavailable";
        log.error("Error getting contents of url: " + url);
        throw ioe;
    } finally {
        try {
            if (br != null)
                br.close();
            if (inStream != null)
                inStream.close();
        } catch (IOException ioe2) {
            log.error("Error closing connection");
        }
    }

}

From source file:org.infoglue.common.util.RemoteCacheUpdater.java

/**
 * This method post information to an URL and returns a string.It throws
 * an exception if anything goes wrong./*from   ww w  . j a  va 2s .c om*/
 * (Works like most 'doPost' methods)
 * 
 * @param urlAddress The address of the URL you would like to post to.
 * @param inHash The parameters you would like to post to the URL.
 * @return The result of the postToUrl method as a string.
 * @exception java.lang.Exception
 */

private String postToUrl(String urlAddress, Hashtable inHash) throws Exception {
    URL url = new URL(urlAddress);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(3000);
    urlConn.setReadTimeout(3000);
    urlConn.setAllowUserInteraction(false);
    urlConn.setDoOutput(true);
    urlConn.setDoInput(true);
    urlConn.setUseCaches(false);
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true);
    String argString = "";
    if (inHash != null) {
        argString = toEncodedString(inHash);
    }
    printout.print(argString);
    printout.flush();
    printout.close();
    InputStream inStream = null;
    inStream = urlConn.getInputStream();
    InputStreamReader inStreamReader = new InputStreamReader(inStream);
    BufferedReader buffer = new BufferedReader(inStreamReader);
    StringBuffer strbuf = new StringBuffer();
    String line;
    while ((line = buffer.readLine()) != null) {
        strbuf.append(line);
    }
    String readData = strbuf.toString();
    buffer.close();
    return readData;
}