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:at.alladin.rmbt.android.util.AsyncHtmlContentRetriever.java

@Override
protected List<Object> doInBackground(String... params) {
    List<Object> result = new ArrayList<Object>();
    URL url;/*from   w w w  .  jav a 2 s. co  m*/
    URLConnection connection;
    try {
        url = new URL(params[0]);
        connection = url.openConnection();
        connection.setConnectTimeout(3000);
        connection.connect();
    } catch (Exception e) {
        result.add(-1);
        result.add(null);
        return result;
    }

    String htmlContent = "";
    HttpGet httpGet = new HttpGet(params[0]);
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response;
    int statusCode = -1;

    try {
        response = httpClient.execute(httpGet);
        statusCode = response.getStatusLine().getStatusCode();
        System.out.println("response code: " + statusCode);
        /*
         * load HTML:
         */
        /*
        HttpEntity entity = response.getEntity();
        if (entity != null) {
           InputStream inputStream = entity.getContent();
           htmlContent = convertToString(inputStream);
        }
        */
    } catch (Exception e) {
        result.add(-1);
        result.add(null);
        return result;
    }

    result.add(statusCode);
    result.add(htmlContent);

    return result;
}

From source file:org.tupelo_schneck.electric.ted.ImportIterator.java

public ImportIterator(final Options options, final byte mtu, final int count) throws IOException {
    this.timeZone = options.recordTimeZone;
    this.cal = new GregorianCalendar(this.timeZone);
    this.mtu = mtu;
    this.useVoltage = options.voltage;
    URL url;/* ww w .  j a v  a 2s  . co  m*/
    try {
        url = new URL(
                options.gatewayURL + "/history/rawsecondhistory.raw?INDEX=1&MTU=" + mtu + "&COUNT=" + count);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    URLConnection urlConnection = url.openConnection();
    urlConnection.setConnectTimeout(60000);
    urlConnection.setReadTimeout(60000);
    urlConnection.connect();
    urlStream = urlConnection.getInputStream();
    urlConnection.setReadTimeout(1000);
    getNextLine();

    // skip the first timestamp, in case we see only part of multiple values
    if (!closed) {
        Triple first = nextFromLine();
        Triple next = first;
        while (next != null && next.timestamp == first.timestamp) {
            next = nextFromLine();
        }
        pushback = next;

        if (Util.inDSTOverlap(timeZone, first.timestamp)) {
            int now = (int) (System.currentTimeMillis() / 1000);
            if (now < first.timestamp - 1800)
                inDSTOverlap = 1;
            else
                inDSTOverlap = 2;
        }
        previousTimestamp = first.timestamp;
    }
}

From source file:com.adito.extensions.store.ExtensionStoreDescriptor.java

private void loadDocument() throws IOException, JDOMException {

    URLConnection conx = descriptor.openConnection();
    conx.setConnectTimeout(ExtensionStore.CONNECT_TIMEOUT);
    conx.setReadTimeout(ExtensionStore.READ_TIMEOUT);

    InputStream in = null;/*w w  w.j  a v a 2  s . co  m*/
    try {

        in = conx.getInputStream();

        SAXBuilder sax = new SAXBuilder();
        document = sax.build(in);

        if (!document.getRootElement().getName().equalsIgnoreCase("applications")) {
            throw new JDOMException("Application root element must be <applications>");
        }

        store = document.getRootElement().getAttribute("store").getValue();
        if (store == null) {
            throw new JDOMException("<applications> element requires attribute 'store'");
        }
    } finally {
        Util.closeStream(in);
    }
}

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

public String getContentsOfUrlAsString(URL requestUrl) throws Exception {
    URLConnection conn = requestUrl.openConnection();
    conn.setConnectTimeout(connectionTimeout);
    conn.setReadTimeout(readTimeout);//from w w  w .  java2 s  . co m
    InputStream inStream = conn.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream));

    StringBuilder output = new StringBuilder();

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

    br.close();
    inStream.close();
    return output.toString();
}

From source file:samza.examples.rss.system.RssFeed.java

/**
 * Reads the url and queues the data/*from  w w  w. j  a v a  2  s.c  om*/
 *
 * @param feedDetail feedDetails object
 * @return set of all article urls that were read from the feed
 * @throws IOException                          when it cannot connect to the url or the url is malformed
 * @throws com.sun.syndication.io.FeedException when it cannot reed the feed.
 */
protected Set<String> queueFeedEntries(FeedDetails feedDetail, List<Datum> dataQueue)
        throws IOException, FeedException {
    URL feedUrl = new URL(feedDetail.getUrl());
    URLConnection connection = feedUrl.openConnection();
    connection.setConnectTimeout(this.timeOut);
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new InputStreamReader(connection.getInputStream()));
    Set<String> batch = Sets.newConcurrentHashSet();
    for (Object entryObj : feed.getEntries()) {
        SyndEntry entry = (SyndEntry) entryObj;
        ObjectNode nodeEntry = this.serializer.deserialize(entry);
        nodeEntry.put(RSS_KEY, feedDetail.getUrl());
        String entryId = determineId(nodeEntry);
        batch.add(entryId);
        Datum datum = new Datum(nodeEntry, entryId, DateTime.now());
        JsonNode published = nodeEntry.get(DATE_KEY);
        if (published != null) {
            try {
                DateTime date = RFC3339Utils.parseToUTC(published.asText());
                if (date.isAfter(this.publishedSince) && (!seenBefore(entryId, feedDetail.getUrl()))) {
                    dataQueue.add(datum);
                    log.debug("Added entry, {}, to provider queue.", entryId);
                }
            } catch (Exception e) {
                log.trace("Failed to parse date from object node, attempting to add node to queue by default.");
                if (!seenBefore(entryId, feedDetail.getUrl())) {
                    dataQueue.add(datum);
                    log.debug("Added entry, {}, to provider queue.", entryId);
                }
            }
        } else {
            log.debug("No published date present, attempting to add node to queue by default.");
            if (!seenBefore(entryId, feedDetail.getUrl())) {
                dataQueue.add(datum);
                log.debug("Added entry, {}, to provider queue.", entryId);
            }
        }
    }
    return batch;
}

From source file:org.omegat.core.spellchecker.DictionaryManager.java

/**
 * installs a remote dictionary by downloading the corresponding zip file
 * from the net and by installing the aff and dic file to the dictionary
 * directory.//from  www  .ja v  a  2 s  . c  om
 *
 * @param langCode
 *            : the language code (xx_YY)
 */
public void installRemoteDictionary(String langCode) throws MalformedURLException, IOException {
    String from = Preferences.getPreference(Preferences.SPELLCHECKER_DICTIONARY_URL) + "/" + langCode + ".zip";

    // Dirty hack for the French dictionary. Since it is named
    // fr_FR_1-3-2.zip, we remove the "_1-3-2" portion
    // [ 2138846 ] French dictionary cannot be downloaded and installed
    int pos = langCode.indexOf("_1-3-2", 0);
    if (pos != -1) {
        langCode = langCode.substring(0, pos);
    }
    List<String> expectedFiles = Arrays.asList(langCode + OConsts.SC_AFFIX_EXTENSION,
            langCode + OConsts.SC_DICTIONARY_EXTENSION);

    URL url = new URL(from);
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(TIMEOUT_MS);
    conn.setReadTimeout(TIMEOUT_MS);
    try (InputStream in = conn.getInputStream()) {
        List<String> extracted = StaticUtils.extractFromZip(in, dir, expectedFiles::contains);
        if (!expectedFiles.containsAll(extracted)) {
            throw new FileNotFoundException("Could not extract expected files from zip; expected: "
                    + expectedFiles + ", extracted: " + extracted);
        }
    } catch (IllegalArgumentException ex) {
        throw new FlakyDownloadException(ex);
    }
}

From source file:org.apache.streams.rss.provider.RssStreamProviderTask.java

/**
 * Reads the url and queues the data//from   w w  w  .ja v  a2  s. c om
 * @param feedUrl rss feed url
 * @return set of all article urls that were read from the feed
 * @throws IOException when it cannot connect to the url or the url is malformed
 * @throws FeedException when it cannot reed the feed.
 */
@VisibleForTesting
protected Set<String> queueFeedEntries(URL feedUrl) throws IOException, FeedException {
    Set<String> batch = Sets.newConcurrentHashSet();
    URLConnection connection = feedUrl.openConnection();
    connection.setConnectTimeout(this.timeOut);
    connection.setConnectTimeout(this.timeOut);
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new InputStreamReader(connection.getInputStream()));
    for (Object entryObj : feed.getEntries()) {
        SyndEntry entry = (SyndEntry) entryObj;
        ObjectNode nodeEntry = this.serializer.deserialize(entry);
        nodeEntry.put(RSS_KEY, this.rssFeed);
        String entryId = determineId(nodeEntry);
        batch.add(entryId);
        StreamsDatum datum = new StreamsDatum(nodeEntry);
        try {
            JsonNode published = nodeEntry.get(DATE_KEY);
            if (published != null) {
                try {
                    DateTime date = RFC3339Utils.parseToUTC(published.asText());
                    if (date.isAfter(this.publishedSince)
                            && (!this.perpetual || !seenBefore(entryId, this.rssFeed))) {
                        this.dataQueue.put(datum);
                        LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                    }
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.trace(
                            "Failed to parse date from object node, attempting to add node to queue by default.");
                    if (!this.perpetual || !seenBefore(entryId, this.rssFeed)) {
                        this.dataQueue.put(datum);
                        LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                    }
                }
            } else {
                LOGGER.debug("No published date present, attempting to add node to queue by default.");
                if (!this.perpetual || !seenBefore(entryId, this.rssFeed)) {
                    this.dataQueue.put(datum);
                    LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                }
            }
        } catch (InterruptedException ie) {
            LOGGER.error("Interupted Exception.");
            Thread.currentThread().interrupt();
        }
    }
    return batch;
}

From source file:de.matzefratze123.heavyspleef.util.Updater.java

public void query() {
    URL url;/*from   ww w . j a  v a 2 s  . co m*/

    try {
        url = new URL(API_HOST + API_QUERY + PROJECT_ID);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return;
    }

    try {
        URLConnection conn = url.openConnection();

        conn.setConnectTimeout(6000);
        conn.addRequestProperty("User-Agent", "HeavySpleef-Updater (by matzefratze123)");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String query = reader.readLine();

        JSONArray array = (JSONArray) JSONValue.parse(query);

        String version = null;

        if (array.size() > 0) {

            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            fileTitle = (String) latest.get(API_TITLE_VALUE);
            fileName = (String) latest.get(API_NAME_VALUE);
            downloadUrl = (String) latest.get(API_LINK_VALUE);

            String[] parts = fileTitle.split(" v");
            if (parts.length >= 2) {
                version = parts[1];
            }

            checkVersions(version);
            done = true;
        }
    } catch (IOException e) {
        Logger.severe("Failed querying the curseforge api: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:net.naonedbus.rest.controller.RestController.java

/**
 * Lire un flux Json.// w w w.  j  a  v a 2 s.c om
 * 
 * @param url
 *            L'url
 * @return Le fulx Json au format string
 * @throws IOException
 */
protected String readJsonFromUrl(final URL url) throws IOException {
    if (DBG)
        Log.d(LOG_TAG, "readJsonFromUrl " + url.toString());

    final URLConnection conn = url.openConnection();
    conn.setConnectTimeout(TIMEOUT);
    conn.setReadTimeout(TIMEOUT);
    conn.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());

    final InputStreamReader comReader = new InputStreamReader(conn.getInputStream());
    final String source = IOUtils.toString(comReader);
    IOUtils.closeQuietly(comReader);

    return source;
}

From source file:IntergrationTest.OCSPIntegrationTest.java

private void setTimeout(URLConnection conn) {
    conn.setConnectTimeout(10 * 1000);
    conn.setReadTimeout(10 * 1000);

}