Example usage for java.net URLConnection setReadTimeout

List of usage examples for java.net URLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

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

Usage

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);
    InputStream inStream = conn.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream));

    StringBuilder output = new StringBuilder();

    int cp;// ww  w  .jav a  2s  .com
    while ((cp = br.read()) != -1) {
        output.append((char) cp);
    }

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

From source file:ubic.gemma.core.loader.protein.biomart.BiomartEnsemblNcbiFetcher.java

/**
 * Submit a xml query to biomart service return the returned data as a bufferedreader
 *
 * @param urlToRead Biomart configured URL
 * @return BufferedReader Stream to read data from
 *///from   ww  w  .j  a v  a 2 s. c  o m
private BufferedReader readBioMart(URL urlToRead) {
    URLConnection conn;
    try {
        conn = urlToRead.openConnection();
        conn.setReadTimeout(1000 * READ_TIMEOUT_SECONDS);
        conn.setDoOutput(true);
        // try (Writer writer = new OutputStreamWriter( conn.getOutputStream() );) {
        // writer.write( data );
        // writer.flush();
        return new BufferedReader(new InputStreamReader(conn.getInputStream()));
        // }
    } catch (IOException e) {
        log.error(e);
        throw new RuntimeException(e);
    }
}

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  ww w.  j a  va  2 s .  c  o  m
 *
 * @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:net.naonedbus.rest.controller.RestController.java

/**
 * Lire un flux Json.//from   ww w  . ja  va2  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);

}

From source file:es.prodevelop.gvsig.mini.tasks.yours.YOURSFunctionality.java

@Override
public boolean execute() {
    try {/*  w w w. ja va 2 s  . c o m*/
        final Point ini = (Point) route.getStartPoint().clone();
        final Point end = (Point) route.getEndPoint().clone();

        final String routeString = route.toYOURS(ini, end);

        log.log(Level.FINE, routeString);

        /* Define the URL we want to load data from. */
        URL parseURL = new URL(routeString);
        /* Open a connection to that URL. */
        if (this.isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        URLConnection urlconnec = parseURL.openConnection();

        urlconnec.setRequestProperty("X-Yours-client", "gvSIG");
        urlconnec.setReadTimeout(30000);
        /* Define InputStreams to read from the URLConnection. */
        InputStream is = urlconnec.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            if (isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);
        }

        res = route.fromYOURS(baf.toByteArray());
    } catch (IOException e) {
        res = TaskHandler.NO_RESPONSE;
    } catch (Exception e) {
        res = TaskHandler.ERROR;
        log.log(Level.SEVERE, "", e);
    } finally {
        // handler.sendEmptyMessage(map.ROUTE_SUCCEEDED);

        try {
            // if (res == -1) {
            // handler.sendEmptyMessage(map.ROUTE_CANCELED);
            if (res == -2) {
                res = TaskHandler.NO_RESPONSE;
            } else if (res == -3) {
                res = TaskHandler.BAD_RESPONSE;
            } else if (res == 1) {
                res = TaskHandler.FINISHED;
                if (route.getState() == Tags.ROUTE_WITH_START_AND_PASS_POINT) {
                    route.setState(Tags.ROUTE_WITH_N_POINT);
                } else if (route.getState() == Tags.ROUTE_WITH_START_POINT) {
                    route.setState(Tags.ROUTE_WITH_2_POINT);
                }
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "", e);
        } finally {
            // super.stop();
        }
        return true;
    }

}

From source file:com.adito.rss.FeedManager.java

protected void loadAvailable() throws IOException {
    URL location = new URL(baseLocation, "index.txt");

    availableFeeds.clear();//w  w w.  j  a  v  a  2  s  .c om
    URLConnection conx = location.openConnection();
    conx.setConnectTimeout(CONNECT_TIMEOUT);
    conx.setReadTimeout(READ_TIMEOUT);

    if (log.isInfoEnabled()) {
        log.info("Retrieving RSS feeds index from " + location);
    }
    InputStream inputStream = null;
    try {
        inputStream = conx.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            availableFeeds.add(line);
        }
    } finally {
        Util.closeStream(inputStream);
    }
    if (log.isInfoEnabled())
        log.info("There are " + availableFeeds.size() + " available feeds");
}

From source file:io.s4.latin.adapter.TwitterFeedListener.java

public void connectAndRead() throws Exception {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);

    String userPassword = userid + ":" + password;
    System.out.println("connect to " + connection.getURL().toString() + " ...");

    String encoded = EncodingUtil.getAsciiString(Base64.encodeBase64(EncodingUtil.getAsciiBytes(userPassword)));
    connection.setRequestProperty("Authorization", "Basic " + encoded);
    connection.setRequestProperty("Accept-Charset", "utf-8,ISO-8859-1");
    connection.connect();//ww  w  .  j  a v a2  s. c  o  m
    System.out.println("Connect OK!");
    System.out.println("Reading TwitterFeed ....");
    Long startTime = new Date().getTime();
    InputStream is = connection.getInputStream();
    Charset utf8 = Charset.forName("UTF-8");

    InputStreamReader isr = new InputStreamReader(is, utf8);
    BufferedReader br = new BufferedReader(isr);

    String inputLine = null;

    while ((inputLine = br.readLine()) != null) {
        if (inputLine.trim().length() == 0) {
            blankCount++;
            continue;
        }
        messageCount++;
        messageQueue.add(inputLine);
        if (messageCount % 500 == 0) {
            Long currentTime = new Date().getTime();
            System.out.println("Lines processed: " + messageCount + "\t ( " + blankCount + " empty lines ) in "
                    + (currentTime - startTime) / 1000 + " seconds. Reading "
                    + messageCount / ((currentTime - startTime) / 1000) + " rows/second");
        }
    }
}

From source file:org.openintents.updatechecker.UpdateChecker.java

public void checkForUpdate(String link) {

    mLatestVersion = -1;//w w w.  j  ava2 s.c  om
    mComment = null;
    mNewApplicationId = null;
    mLatestVersionName = null;

    try {
        Log.d(TAG, "Looking for version at " + link);

        if (mLatestVersion > 0 || mLatestVersionName != null) {
            return;
        } else {
            URL u = new URL(link);
            URLConnection connection = u.openConnection();
            connection.setReadTimeout(CONNECTION_TIMEOUT);
            Object content = connection.getContent();
            if (content instanceof InputStream) {
                InputStream is = (InputStream) content;

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                String firstLine = reader.readLine();
                if (firstLine != null && firstLine.indexOf("<") >= 0) {

                    parseVeeCheck(link);
                } else {
                    parseTxt(firstLine, reader);
                }

            } else {
                Log.d(TAG, "Unknown server format: " + ((String) content).substring(0, 100));
            }
        }
    } catch (MalformedURLException e) {
        Log.v(TAG, "MalformedURLException", e);
    } catch (IOException e) {
        Log.v(TAG, "IOException", e);
    } catch (Exception e) {
        Log.v(TAG, "Exception", e);
    }

}

From source file:com.varaneckas.hawkscope.plugins.twitter.TwitterClient.java

/**
 * Gets an 24x24 image for User//  w  w  w. j  av a  2s  .  c o m
 * 
 * @param user
 * @return
 */
public Image getUserImage(final User user) {
    if (user == null) {
        return getTwitterIcon();
    }
    if (!userImages.containsKey(user.getName())) {
        final Configuration cfg = ConfigurationFactory.getConfigurationFactory().getConfiguration();
        Image i = null;
        try {
            if (!cfg.isHttpProxyInUse()) {
                i = new Image(Display.getCurrent(), user.getProfileImageURL().openStream());
            } else {
                Proxy p = new Proxy(Type.HTTP,
                        InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort()));
                URLConnection con = user.getProfileImageURL().openConnection(p);
                con.setReadTimeout(3000);
                i = new Image(Display.getCurrent(), con.getInputStream());
            }
            i = new Image(Display.getCurrent(), i.getImageData().scaledTo(24, 24));
            userImages.put(user.getName(), i);
        } catch (final IOException e) {
            log.warn("Failed getting user icon: " + user.getName(), e);
            return getTwitterIcon();
        }
    }
    return userImages.get(user.getName());
}