Example usage for java.net URLConnection getContentLength

List of usage examples for java.net URLConnection getContentLength

Introduction

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

Prototype

public int getContentLength() 

Source Link

Document

Returns the value of the content-length header field.

Usage

From source file:org.grycap.gpf4med.util.URLUtils.java

/**
 * Reads any kind of data (including binary) from a URL and writes them to a local file. This method 
 * uses a buffer to read the remote file. It's designed with performance in mind.
 * @param source Source URL.//from w  w w . ja v  a  2 s .  c  o m
 * @param destination Destination file.
 * @throws IOException If an input/output error occurs.
 */
private static void downloadBinary(final URLConnection source, final File destination) throws IOException {
    checkArgument(source != null, "Uninitialized source");
    checkArgument(destination != null, "Uninitialized destination");
    InputStream in = null;
    OutputStream out = null;
    try {
        FileUtils.forceMkdir(destination.getParentFile());
        in = new BufferedInputStream(source.getInputStream());
        out = new FileOutputStream(destination);
        final int contentLength = source.getContentLength();
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        int totalBytesRead = 0;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        if (totalBytesRead != contentLength) {
            try {
                destination.delete();
            } catch (Exception ignore) {
            }
            throw new IOException(
                    "Only read " + totalBytesRead + " bytes; Expected " + contentLength + " bytes");
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception ignore) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:org.apache.sling.osgi.obr.Resource.java

public static Resource create(URL file) throws IOException {
    JarInputStream jar = null;/*  w  w w. j a  v a2  s .c  om*/
    try {
        URLConnection conn = file.openConnection();
        jar = new JarInputStream(conn.getInputStream());
        Manifest manifest = jar.getManifest();
        if (manifest == null) {
            throw new IOException(file + " is not a valid JAR file: Manifest not first entry");
        }
        return new Resource(file, manifest.getMainAttributes(), conn.getContentLength());
    } finally {
        IOUtils.closeQuietly(jar);
    }
}

From source file:com.viettel.dms.download.DownloadFile.java

/**
 * Download file with urlConnection/* w ww. j a  v a 2s.  c  o m*/
 * @author : BangHN
 * since : 1.0
 */
public static void downloadWithURLConnection(String url, File output, File tmpDir) {
    BufferedOutputStream os = null;
    BufferedInputStream is = null;
    File tmp = null;
    try {
        VTLog.i("Download ZIPFile", "Downloading url :" + url);

        tmp = File.createTempFile("download", ".tmp", tmpDir);
        URL urlDownload = new URL(url);
        URLConnection cn = urlDownload.openConnection();
        cn.addRequestProperty("session", HTTPClient.sessionID);
        cn.setConnectTimeout(CONNECT_TIMEOUT);
        cn.setReadTimeout(READ_TIMEOUT);
        cn.connect();
        is = new BufferedInputStream(cn.getInputStream());
        os = new BufferedOutputStream(new FileOutputStream(tmp));
        //cp nht dung lng tp tin request
        fileSize = cn.getContentLength();
        //vn c tr?ng hp khng c ContentLength
        if (fileSize < 0) {
            //mc nh = 4 MB
            fileSize = 4 * 1024 * 1024;
        }
        copyStream(is, os);
        tmp.renameTo(output);
        tmp = null;
    } catch (IOException e) {
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        throw new RuntimeException(e);
    } catch (Exception e) {
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        throw new RuntimeException(e);
    } finally {
        if (tmp != null) {
            try {
                tmp.delete();
                tmp = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (is != null) {
            try {
                is.close();
                is = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (os != null) {
            try {
                os.close();
                os = null;
            } catch (Exception ignore) {
                ;
            }
        }
    }
}

From source file:org.gwtwidgets.server.spring.test.BaseTest.java

protected String readResource(String resource) throws Exception {
    URL url = getClass().getClassLoader().getResource(resource);
    if (url == null)
        url = ClassLoader.getSystemResource(resource);
    if (url == null)
        url = ClassLoader.getSystemClassLoader().getResource(resource);
    URLConnection conn = url.openConnection();
    byte[] b = new byte[conn.getContentLength()];
    InputStream in = conn.getInputStream();
    in.read(b);//www  . ja v a 2  s  .  c  o m
    in.close();
    return new String(b, "UTF-8");
}

From source file:org.eclipse.ecr.web.framework.io.URLConnectionMessageBodyWriter.java

@Override
public long getSize(URLConnection conn, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
    return conn.getContentLength();
}

From source file:org.apache.logging.log4j.core.selector.TestClassLoader.java

@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {
    final String path = name.replace('.', '/').concat(".class");
    final URL resource = super.getResource(path);
    if (resource == null) {
        throw new ClassNotFoundException(name);
    }/*  ww w. j a va  2 s  .c  o  m*/
    try {
        final URLConnection uc = resource.openConnection();
        final int len = uc.getContentLength();
        final InputStream in = new BufferedInputStream(uc.getInputStream());
        final byte[] bytecode = new byte[len];
        try {
            IOUtils.readFully(in, bytecode);
        } finally {
            Closer.closeSilently(in);
        }
        return defineClass(name, bytecode, 0, bytecode.length);
    } catch (final IOException e) {
        Throwables.rethrow(e);
        return null; // unreachable
    }
}

From source file:org.moyrax.javascript.shell.Global.java

private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException {
    int chunkLength;
    InputStream is = null;// w  w  w.j  a v a  2  s  . c om
    try {
        if (!urlIsFile) {
            URL urlObj = new URL(filePath);
            URLConnection uc = urlObj.openConnection();
            is = uc.getInputStream();
            chunkLength = uc.getContentLength();
            if (chunkLength <= 0)
                chunkLength = 1024;
            if (charCoding == null) {
                String type = uc.getContentType();
                if (type != null) {
                    charCoding = getCharCodingFromType(type);
                }
            }
        } else {
            File f = new File(filePath);

            long length = f.length();
            chunkLength = (int) length;
            if (chunkLength != length)
                throw new IOException("Too big file size: " + length);

            if (chunkLength == 0) {
                return "";
            }

            is = new FileInputStream(f);
        }

        Reader r;
        if (charCoding == null) {
            r = new InputStreamReader(is);
        } else {
            r = new InputStreamReader(is, charCoding);
        }
        return readReader(r, chunkLength);

    } finally {
        if (is != null)
            is.close();
    }
}

From source file:com.nominanuda.web.mvc.URLStreamer.java

public HttpResponse handle(HttpRequest request) throws IOException {
    URL url = getURL(request);/*from w ww. ja v  a 2 s  . com*/
    URLConnection conn = url.openConnection();
    conn.connect();
    int len = conn.getContentLength();
    InputStream is = conn.getInputStream();
    String ce = conn.getContentEncoding();
    String ct = determineContentType(url, conn);
    if (len < 0) {
        byte[] content = ioHelper.readAndClose(is);
        is = new ByteArrayInputStream(content);
        len = content.length;
    }
    StatusLine statusline = httpCoreHelper.statusLine(SC_OK);
    HttpResponse resp = new BasicHttpResponse(statusline);
    resp.setEntity(new InputStreamEntity(is, len));
    httpCoreHelper.setContentType(resp, ct);
    httpCoreHelper.setContentLength(resp, len);//TODO not needed ??
    if (ce != null) {
        httpCoreHelper.setContentEncoding(resp, ce);
    }
    return resp;
}

From source file:org.jcodec.common.io.HttpRAInputStream.java

public HttpRAInputStream(URL url) throws IOException {
    this.url = url;
    URLConnection connection = url.openConnection();
    is = connection.getInputStream();/*from w  w w.j  a v  a 2s.  co  m*/
    length = connection.getContentLength();
}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Attempt to download the icon specified by the given URL.  If the resource at the URL
 * has a content type of image/*, the binary data for this resource will be downloaded.
 *
 * @param iconUrlStr URL of the image resource to access
 * @return the binary data and content type of the image resource at the given URL, null
 * if the URL is invalid, the resource does not have a content type starting with image/, or
 * on some other failure./*from   w  ww  .  j a  v a2 s . com*/
 */
public static final @Nullable IconInfo getIconInfo(String iconUrlStr) {
    if (!StringUtils.hasLength(iconUrlStr)) {
        log.debug("No icon url exists.");
        return null;
    }
    URL iconUrl = null;
    try {
        // Need to encode any invalid characters before creating the URL object
        iconUrl = new URL(UriUtils.encodeHttpUrl(iconUrlStr, "UTF-8"));
    } catch (MalformedURLException ex) {
        log.debug("Malformed icon URL string: {}", iconUrlStr, ex);
        return null;
    } catch (UnsupportedEncodingException ex) {
        log.debug("Unable to encode icon URL string: {}", iconUrlStr, ex);
        return null;
    }

    // Open a connection with the given URL
    final URLConnection conn;
    final InputStream inputStream;
    try {
        conn = iconUrl.openConnection();
        inputStream = conn.getInputStream();
    } catch (IOException ex) {
        log.debug("Unable to open connection to URL: {}", iconUrlStr, ex);
        return null;
    }

    String contentType = conn.getContentType();
    int sizeBytes = conn.getContentLength();

    try {
        // Make sure the resource has an appropriate content type
        if (!conn.getContentType().startsWith("image/")) {
            log.debug("Resource at URL {} does not have a content type of image/*.", iconUrlStr);
            return null;
            // Make sure the resource is not too large
        } else if (sizeBytes > MAX_ICON_SIZE_BYTES) {
            log.debug("Image resource at URL {} is too large: {}", iconUrlStr, sizeBytes);
            return null;
        } else {
            // Convert the resource to a byte array
            byte[] iconBytes = ByteStreams.toByteArray(new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return inputStream;
                }
            });
            return new IconInfo(iconBytes, contentType);
        }
    } catch (IOException e) {
        log.debug("Error reading resource data.", e);
        return null;
    } finally {
        Closeables.closeQuietly(inputStream);
    }
}