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.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void downloadAndInstall(String url, String archiveFileName, Path installPath,
        IProgressMonitor monitor) throws IOException {
    Exception error = null;//from  w  w w  .j a  v a 2s  .c o m
    for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) {
        try {
            URL dl = new URL(url);
            Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$
            Files.createDirectories(dlDir);
            Path archivePath = dlDir.resolve(archiveFileName);
            URLConnection conn = dl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING);

            boolean isWin = Platform.getOS().equals(Platform.OS_WIN32);

            // extract
            ArchiveInputStream archiveIn = null;
            try {
                String compressor = null;
                String archiver = null;
                if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.BZIP2;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                    compressor = CompressorStreamFactory.GZIP;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.XZ;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                    archiver = ArchiveStreamFactory.ZIP;
                }

                InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                if (compressor != null) {
                    in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                }
                archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                        .getNextEntry()) {
                    if (entry.isDirectory()) {
                        continue;
                    }

                    // Magic file for git tarballs
                    Path path = Paths.get(entry.getName());
                    if (path.endsWith("pax_global_header")) { //$NON-NLS-1$
                        continue;
                    }

                    // Strip the first directory of the path
                    Path entryPath;
                    switch (path.getName(0).toString()) {
                    case "i586":
                    case "i686":
                        // Cheat for Intel
                        entryPath = installPath.resolve(path);
                        break;
                    default:
                        entryPath = installPath.resolve(path.subpath(1, path.getNameCount()));
                    }

                    Files.createDirectories(entryPath.getParent());

                    if (entry instanceof TarArchiveEntry) {
                        TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                        if (tarEntry.isLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount()));
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath));
                        } else if (tarEntry.isSymbolicLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, linkPath);
                        } else {
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                        if (!isWin && !tarEntry.isSymbolicLink()) {
                            int mode = tarEntry.getMode();
                            Files.setPosixFilePermissions(entryPath, toPerms(mode));
                        }
                    } else {
                        Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } finally {
                if (archiveIn != null) {
                    archiveIn.close();
                }
            }
            return;
        } catch (IOException | CompressorException | ArchiveException e) {
            error = e;
            // retry
        }
    }

    // out of retries
    if (error instanceof IOException) {
        throw (IOException) error;
    } else {
        throw new IOException(error);
    }
}

From source file:net.rptools.maptool.client.WebDownloader.java

/**
 * Read the data at the given URL. This method should not be called on the EDT.
 * //from   w w  w.  ja  v a2  s  .  co m
 * @return File pointer to the location of the data, file will be deleted at program end
 */
public String read() throws IOException {
    URLConnection conn = url.openConnection();

    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);

    // Send the request.
    conn.connect();

    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new ByteArrayOutputStream();

        int buflen = 1024 * 30;
        int bytesRead = 0;
        byte[] buf = new byte[buflen];

        for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {
            bytesRead += nRead;
            out.write(buf, 0, nRead);
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    return out != null ? new String(out.toByteArray()) : null;
}

From source file:jp.classmethod.aws.InstanceMetadataFactoryBean.java

private Reader createUserDataReader() throws IOException, MalformedURLException {
    URLConnection conn = new URL(USER_DATA_URL).openConnection();
    conn.setReadTimeout(TIMEOUT);
    conn.setConnectTimeout(TIMEOUT);
    conn.connect();// w  w  w. ja va 2  s.co m
    return new BufferedReader(new InputStreamReader(conn.getInputStream()));
}

From source file:net.sf.zekr.engine.network.NetworkController.java

public InputStream openSteam(String uri, int timeout) throws URISyntaxException, IOException {
    URL url = new URL(uri);
    URLConnection conn = url.openConnection(getProxy(uri));
    conn.setReadTimeout(timeout);
    conn.setUseCaches(true);/*  w w w .j  a  v  a 2  s.  c  o m*/
    return conn.getInputStream();
}

From source file:ar.com.zauber.common.image.impl.JREImageRetriver.java

/**
 * @param uc {@link URLConnection} a preparar.
 */// ww w  .jav  a  2 s.  c om
private void prepare(final URLConnection uc) {
    uc.setAllowUserInteraction(false);
    uc.setReadTimeout(timeout * 1000);
    if (userAgent != null) {
        uc.setRequestProperty("User-Agent", userAgent);
    }
}

From source file:org.seasar.uruma.eclipath.ProjectRefresher.java

protected void sendRequest(URL url) {
    URLConnection conn;
    InputStream is = null;//  w  ww. j  a  v a  2 s  .  co m
    try {
        conn = url.openConnection();
        conn.setReadTimeout(TIMEOUT_TIME);
        conn.connect();
        is = conn.getInputStream();
    } catch (IOException ex) {
        throw new PluginRuntimeException("Failed to send request. : " + url.toExternalForm(), ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
    return;
}

From source file:com.cnaude.purpleirc.Utilities.UpdateChecker.java

private String updateCheck(String mode) {
    String message;/*from w w w .j a  v a  2 s.  c  o  m*/
    try {
        URL url = new URL("http://h.cnaude.org:8081/job/PurpleIRC-forge/lastStableBuild/api/json");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "PurpleIRC-forge Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONObject obj = (JSONObject) JSONValue.parse(response);
        if (obj.isEmpty()) {
            return plugin.LOG_HEADER_F + " No files found, or Feed URL is bad.";
        }

        newVersion = obj.get("number").toString();
        String downloadUrl = obj.get("url").toString();
        plugin.logDebug("newVersionTitle: " + newVersion);
        newBuild = Integer.valueOf(newVersion);
        if (newBuild > currentBuild) {
            message = plugin.LOG_HEADER_F + " Latest dev build: " + newVersion + " is out!"
                    + " You are still running build: " + currentVersion;
            message = message + plugin.LOG_HEADER_F + " Update at: " + downloadUrl;
        } else if (currentBuild > newBuild) {
            message = plugin.LOG_HEADER_F + " Dev build: " + newVersion + " | Current build: " + currentVersion;
        } else {
            message = plugin.LOG_HEADER_F + " No new version available";
        }
    } catch (IOException | NumberFormatException e) {
        message = plugin.LOG_HEADER_F + " Error checking for latest dev build: " + e.getMessage();
    }
    return message;
}

From source file:org.apache.htrace.util.TestHTracedProcess.java

private String doGet(final URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(TIMEOUT);
    connection.setReadTimeout(TIMEOUT);
    connection.connect();//from   www . j  a v  a 2s  .  c om
    StringBuffer sb = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    try {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            sb.append(line);
        }
    } finally {
        reader.close();
    }
    return sb.toString();
}

From source file:se.blinfo.session.client.SessionClient.java

private String call(String path) {
    URL sessionServiceUrl;/* ww w  . j av  a  2  s. c  om*/
    try {
        sessionServiceUrl = new URL(baseUrl + path);
        URLConnection yc;
        try {
            yc = sessionServiceUrl.openConnection();
            yc.setConnectTimeout(5 * 1000); //5 sekunder
            yc.setReadTimeout(5 * 1000);
            yc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String response = in.readLine();
            in.close();
            return response;
        } catch (IOException ex) {
            Logger.getLogger(SessionClient.class.getName()).log(Level.SEVERE, "Kunde inte hmta data", ex);
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(SessionClient.class.getName()).log(Level.SEVERE, "Ogiltig url", ex);
    }
    return "";
}

From source file:com.zoffcc.applications.aagtl.ImageManager.java

public void DownloadFromUrl(String imageURL, String fileName) { // this is
                                                                // the downloader method
    try {//  w w w  .j  a  v  a 2s .  c  o m
        URL url = new URL(imageURL);
        File file = new File(fileName);

        //long startTime = System.currentTimeMillis();
        //Log.d("ImageManager", "download begining");
        //Log.d("ImageManager", "download url:" + url);
        //Log.d("ImageManager", "downloaded file name:" + fileName);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(10000);
        ucon.setReadTimeout(7000);

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is, HTMLDownloader.large_buffer_size);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(HTMLDownloader.default_buffer_size);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
        //Log.d("ImageManager", "download ready in"
        //      + ((System.currentTimeMillis() - startTime) / 1000)
        //      + " sec");

    } catch (SocketTimeoutException e2) {
        Log.d("ImageManager", "Connectiont timout: " + e2);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e);
    }

}