Java Code Examples for java.net.URLConnection.getContentLength()

The following are Jave code examples for showing how to use getContentLength() of the java.net.URLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: OpenJSharp   File: MethodUtil.java   Source Code and License Vote up 6 votes
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
Example 2
Project: ObsidianSuite   File: Downloader.java   Source Code and License Vote up 6 votes
private void downloadZip(String link) throws MalformedURLException, IOException
{
	URL url = new URL(link);
	URLConnection conn = url.openConnection();
	InputStream is = conn.getInputStream();
	long max = conn.getContentLength();
	gui.setOutputText("Downloding file...");
	BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip")));
	byte[] buffer = new byte[32 * 1024];
	int bytesRead = 0;
	int in = 0;
	while ((bytesRead = is.read(buffer)) != -1) {
		in += bytesRead;
		fOut.write(buffer, 0, bytesRead);
	}
	fOut.flush();
	fOut.close();
	is.close();
	gui.setOutputText("Download Complete!");

}
 
Example 3
Project: jdk8u-jdk   File: AppletClassLoader.java   Source Code and License Vote up 6 votes
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();

    // Fixed #4507227: Slow performance to load
    // class and resources. [stanleyh]
    //
    // Use buffered input stream [stanleyh]
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
Example 4
Project: javaide   File: MethodUtil.java   Source Code and License Vote up 6 votes
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
Example 5
Project: incubator-netbeans   File: Pump.java   Source Code and License Vote up 5 votes
private void initPumping(URLConnection connection) throws IOException {
    final Date lastModif = new Date(connection.getLastModified());
    final URL realUrl = connection.getURL();
    final String accept = connection.getHeaderField("Accept-Ranges");
    final boolean acceptBytes = accept != null ? accept.contains("bytes"): false;
    final long length = connection.getContentLength();
    pumping.init(realUrl, length, lastModif, acceptBytes);
}
 
Example 6
Project: geomapapp   File: XMImage.java   Source Code and License Vote up 5 votes
private void saveSEGY(OutputStream out) throws IOException {
	if(image==null) throw new IOException("no image loaded");

	String mcsPath = PathUtil.getPath("PORTALS/MULTI_CHANNEL_PATH",
			MapApp.BASE_URL+"/data/portals/mcs/");

	URL url = URLFactory.url( mcsPath + line.getCruiseID().trim() + "/segy/" +
			line.getCruiseID().trim() +"-"+ 
			line.getID().trim() + ".segy" );
	URLConnection urlCon = url.openConnection();
	BufferedInputStream in = new BufferedInputStream(urlCon.getInputStream());
	int length = urlCon.getContentLength();

	// Create a JProgressBar + JDialog
	JDialog d = new JDialog((Frame)null, "Saving SEGY");
	JPanel p = new JPanel(new BorderLayout());
	p.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
	d.setLocationRelativeTo(null);
	JProgressBar pb = new JProgressBar(0,length);
	p.add(new JLabel("Saving " + (length / 1000000) + "mb segy file"), BorderLayout.NORTH);
	p.add(pb);
	d.getContentPane().add(p);

	d.pack();
	d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
	d.setVisible(true);

	byte[] b = new byte[16384];
	int read = in.read(b);
	while (read != -1) {
		out.write(b, 0, read);
		pb.setValue(pb.getValue() + read);
		pb.repaint();
		read = in.read(b);
	}

	out.flush();
	in.close();
	d.dispose();
}
 
Example 7
Project: elasticsearch_my   File: InstallPluginCommand.java   Source Code and License Vote up 5 votes
/** Downloads a zip from the url, into a temp file under the given temp dir. */
@SuppressForbidden(reason = "We use getInputStream to download plugins")
private Path downloadZip(Terminal terminal, String urlString, Path tmpDir) throws IOException {
    terminal.println(VERBOSE, "Retrieving zip from " + urlString);
    URL url = new URL(urlString);
    Path zip = Files.createTempFile(tmpDir, null, ".zip");
    URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
    int contentLength = urlConnection.getContentLength();
    try (InputStream in = new TerminalProgressInputStream(urlConnection.getInputStream(), contentLength, terminal)) {
        // must overwrite since creating the temp file above actually created the file
        Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
    }
    return zip;
}
 
Example 8
Project: Mire   File: FragmentAbout.java   Source Code and License Vote up 5 votes
@Override
protected String doInBackground(String... aurl)
{
	int count;
	try
	{
		URL url = new URL(aurl[0]);
		URLConnection conexion = url.openConnection();
		conexion.connect();

		int lenghtOfFile = conexion.getContentLength();
		Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

		InputStream input = new BufferedInputStream(url.openStream());
		OutputStream output = new FileOutputStream("/sdcard" + folder_mire + folder_update + "/mire.apk");

		byte data[] = new byte[1024];

		long total = 0;

		while ((count = input.read(data)) != -1) 
		{
			total += count;
			publishProgress("" + (int)((total*100) / lenghtOfFile));
			output.write(data, 0, count);
		}
		output.flush();
		output.close();
		input.close();
	} 
	catch (Exception e)
	{ }

	return null;
}
 
Example 9
Project: hippo   File: Attachment.java   Source Code and License Vote up 5 votes
public boolean download(PublishingPackage publishingPackage) {

        File file = new File(getFilePath());
        // The URIs have spaces and we need to encode them or we get a 505 error response
        String encodedUri = INDICATORS_URL + getUri().trim().replace(" ", "%20");
        try {
            if (file.exists() && file.length() > 0) {
                log.debug("File {} already exists, not downloading.", getFilePath());
                return true;
            }

            file.getParentFile().mkdirs();
            file.createNewFile();

            try (FileOutputStream fos = new FileOutputStream(file)) {
                URL url = new URL(encodedUri);
                log.debug("Downloading attachment from: " + url);

                URLConnection connection = url.openConnection();
                ReadableByteChannel websiteChannel = Channels.newChannel(connection.getInputStream());
                long bytesExpected = connection.getContentLength();
                FileChannel fileChannel = fos.getChannel();

                long bytesRead = 0;
                while (bytesRead < bytesExpected) {
                    long read = fileChannel.transferFrom(websiteChannel, bytesRead, DOWNLOAD_CHUNK_SIZE);
                    bytesRead += read;
                    log.debug("Downloaded {} Mb / {} Mb", getMb(bytesRead), getMb(bytesExpected));
                }
            }
            return true;
        } catch (Exception e) {
            migrationReport.report(publishingPackage.getUniqueIdentifier(), ATTACHMENT_NOT_AVAILABLE, encodedUri);
            file.delete(); // Attempt to delete the file as it may be partially downloaded
            return false;
        }
    }
 
Example 10
Project: Parabot-317-API-Minified-OS-Scape   File: NetUtil.java   Source Code and License Vote up 5 votes
public static boolean downloadFile(String url, String location) {
    try {

        final URLConnection connection = createURLConnection(url);

        final int  contentLength = connection.getContentLength();
        final File destination   = new File(location);

        if (destination.exists()) {
            final URLConnection savedFileConnection = destination.toURI().toURL().openConnection();
            if (savedFileConnection.getContentLength() == contentLength) {
                return true;
            }
        } else {
            final File parent = destination.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
        }

        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());

        final FileOutputStream fos = new FileOutputStream(destination);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();

    } catch (IOException exception) {
        exception.printStackTrace();
        return false;
    }

    System.out.println(url + "->" + location);
    return new File(location).exists();
}
 
Example 11
Project: myfaces-trinidad   File: ResourceLoaderTestCase.java   Source Code and License Vote up 5 votes
protected void doTestUnknownContentLength(
  URL url) throws IOException
{
  URLConnection conn = url.openConnection();
  long actualContentLength = conn.getContentLength();

  assertEquals("Invalid explicit content length",
               -1L, actualContentLength);
}
 
Example 12
Project: apache-tomcat-7.0.73-with-comment   File: SSIServletExternalResolver.java   Source Code and License Vote up 5 votes
@Override
public long getFileSize(String path, boolean virtual) throws IOException {
    long fileSize = -1;
    try {
        URLConnection urlConnection = getURLConnection(path, virtual);
        fileSize = urlConnection.getContentLength();
    } catch (IOException e) {
        // Ignore this. It will always fail for non-file based includes
    }
    return fileSize;
}
 
Example 13
Project: objectbox-java   File: NativeLibraryLoader.java   Source Code and License Vote up 5 votes
private static void checkUnpackLib(String filename) {
    String path = "/native/" + filename;
    URL resource = NativeLibraryLoader.class.getResource(path);
    if (resource == null) {
        System.err.println("Not available in classpath: " + path);
    } else {
        File file = new File(filename);
        try {
            URLConnection urlConnection = resource.openConnection();
            int length = urlConnection.getContentLength();
            long lastModified = urlConnection.getLastModified();
            if (!file.exists() || file.length() != length || file.lastModified() != lastModified) {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                try {
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
                    try {
                        IoUtils.copyAllBytes(in, out);
                    } finally {
                        IoUtils.safeClose(out);
                    }
                } finally {
                    IoUtils.safeClose(in);
                }
                if (lastModified > 0) {
                    file.setLastModified(lastModified);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 14
Project: lazycat   File: SSIServletExternalResolver.java   Source Code and License Vote up 5 votes
@Override
public long getFileSize(String path, boolean virtual) throws IOException {
	long fileSize = -1;
	try {
		URLConnection urlConnection = getURLConnection(path, virtual);
		fileSize = urlConnection.getContentLength();
	} catch (IOException e) {
		// Ignore this. It will always fail for non-file based includes
	}
	return fileSize;
}
 
Example 15
Project: incubator-netbeans   File: URLResourceRetriever.java   Source Code and License Vote up 4 votes
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
    
    URLConnection ucn = null;
    
    // loop until no more redirections are 
    for (;;) {
        if (Thread.currentThread().isInterrupted()) {
            return null;
        }
        if(proxy != null) {
            ucn = downloadURL.openConnection(proxy);
        } else {
            ucn = downloadURL.openConnection();
        }
        HttpURLConnection hucn = doConfigureURLConnection(ucn);

        if(Thread.currentThread().isInterrupted())
            return null;
    
        ucn.connect();

        int rc = hucn.getResponseCode();
        boolean isRedirect = 
                rc == HttpURLConnection.HTTP_MOVED_TEMP ||
                rc == HttpURLConnection.HTTP_MOVED_PERM;
        if (!isRedirect) {
            break;
        }

        String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
        URL newURL = new URL(addr);
        if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
            throw new ResourceRedirectException(newURL);
        }
        downloadURL = newURL;
    }

    ucn.setReadTimeout(10000);
    InputStream is = ucn.getInputStream();
    streamLength = ucn.getContentLength();
    effectiveURL = ucn.getURL();
    return is;
    
}
 
Example 16
Project: NBANDROID-V2   File: MavenDownloader.java   Source Code and License Vote up 4 votes
public static void downloadFully(URL url, File target) throws IOException {

        // We don't use the settings here explicitly, since HttpRequests picks up the network settings from studio directly.
        ProgressHandle handle = ProgressHandle.createHandle("Downloading " + url);
        try {
            URLConnection connection = url.openConnection();
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setInstanceFollowRedirects(true);
                ((HttpsURLConnection) connection).setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
                ((HttpsURLConnection) connection).setRequestProperty("Accept-Charset", "UTF-8");
                ((HttpsURLConnection) connection).setDoOutput(true);
                ((HttpsURLConnection) connection).setDoInput(true);
            }
            connection.setConnectTimeout(3000);
            connection.connect();
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                throw new FileNotFoundException();
            }
            handle.start(contentLength);
            OutputStream dest = new FileOutputStream(target);
            InputStream in = connection.getInputStream();
            int count;
            int done = 0;
            byte data[] = new byte[BUFFER_SIZE];
            while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
                done += count;
                handle.progress(done);
                dest.write(data, 0, count);
            }
            dest.close();
            in.close();
        } finally {
            handle.finish();
            if (target.length() == 0) {
                try {
                    target.delete();
                } catch (Exception e) {
                }
            }
        }
    }
 
Example 17
Project: incubator-netbeans   File: NetworkAccess.java   Source Code and License Vote up 4 votes
private SizedConnection createCallableNetwork (final URL url, final int timeout) {
    return new SizedConnection () {
        private int contentLength = -1;

        @Override
        public int getContentLength() {
            return contentLength;
        }

        @Override
        public InputStream call () throws Exception {
            URLConnection conn = url.openConnection ();
            conn.setConnectTimeout (timeout);
            conn.setReadTimeout(timeout);
            if(conn instanceof HttpsURLConnection){
                NetworkAccess.initSSL((HttpsURLConnection) conn);
            }

            // handle redirection here
            int redirCount = 0;
            URLConnection redir = conn;
            do {
               conn = redir;
               redir = checkRedirect(conn, timeout);
               redirCount++;
            } while (conn != redir && redirCount <= MAX_REDIRECTS);

            if (conn != redir) {
                throw new IOException("Too many redirects for " + url);
            }

            InputStream is = conn.getInputStream ();
            contentLength = conn.getContentLength();
            if (err.isLoggable(Level.FINE)) {
                Map <String, List <String>> map = conn.getHeaderFields();
                StringBuilder sb = new StringBuilder("Connection opened for:\n");
                sb.append("    Url: ").append(conn.getURL()).append("\n");
                for(String field : map.keySet()) {
                   sb.append("    ").append(field==null ? "Status" : field).append(": ").append(map.get(field)).append("\n");
                }
                sb.append("\n");
                err.log(Level.FINE, sb.toString());
            }
            return new BufferedInputStream (is);
        }
    };
}
 
Example 18
Project: PlayStoreParallelDownload   File: DownloadService.java   Source Code and License Vote up 4 votes
@Override
protected Void doInBackground(String... urls) {

    Log.d(TAG, "doInBackground: " + urls[0]);

    String url = urls[0];
    int position = Integer.valueOf(urls[1]);

    int count;
    try {

       // String root = Environment.getExternalStorageDirectory().toString();

        System.out.println("Downloading: " + url);
        URL urlFormed = new URL(url);

        URLConnection conection = urlFormed.openConnection();
        conection.connect();

        // getting file length
        int lenghtOfFile = conection.getContentLength();

        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(urlFormed.openStream(), 8192);

        // Output stream to write file

        //OutputStream output = new FileOutputStream(root+"temp.apk");
        byte data[] = new byte[1024];

        long total = 0;
        long download_percentage_old = 00;
        while ((count = input.read(data)) != -1) {
            total += count;

            // writing data to file
            //output.write(data, 0, count);
            long download_percentage_new = (100 * total) / lenghtOfFile;
            if (download_percentage_old != download_percentage_new) {
                download_percentage_old = download_percentage_new;
                Long values[] = new Long[]{download_percentage_old, Long.valueOf(position)};
                publishProgress(values);
            }
        }
        // flushing output
        //output.flush();

        // closing streams
        //output.close();
        input.close();
    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }
    return null;
}
 
Example 19
Project: CollegeDoc   File: Topics.java   Source Code and License Vote up 4 votes
/**
 * Downloading file in background thread
 */
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        File Directory = new File("/sdcard/College Doc/"+u+"/");
        // have the object build the directory structure, if needed.
        Directory.mkdirs();
        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        // getting file length
        int lenghtOfFile = conection.getContentLength();

        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream to write file
        OutputStream output = new FileOutputStream("/sdcard/College Doc/"+uri);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            publishProgress("" + (int) ((total * 100) / lenghtOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
        checkconnection();
        Toast.makeText(Topics.this, "downloading failed", Toast.LENGTH_SHORT).show();
    }

    return null;
}
 
Example 20
Project: imui-tutorial   File: MainActivity.java   Source Code and License Vote up 4 votes
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        // delete previous model first if available
        File fdelete = new File(MODEL_FILE);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                System.out.println("file Deleted.");
            } else {
                System.out.println("file not Deleted.");
            }
        }


        URL url = new URL(f_url[0]);

        URLConnection conection = url.openConnection();
        conection.connect();
        int lenghtOfFile = conection.getContentLength();
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream to write file
        OutputStream output = new FileOutputStream(MODEL_FILE);

        byte data[] = new byte[1024];
        long total = 0;
        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress("" + (int) ((total * 100) / lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();

    } catch (Exception e) {
        MainActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                alertDialog.setTitle("Invalid file.");
                alertDialog.setMessage("Click OK to enter a new server URL.");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                promptServerUrl();
                            }
                        });
                alertDialog.show();
            }
        });
    }

    return null;
}