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:ubic.gemma.image.aba.AllenBrainAtlasServiceImpl.java

private void showHeader(URLConnection url) {

    this.infoOut.println("");
    this.infoOut.println("URL              : " + url.getURL().toString());
    this.infoOut.println("Content-Type     : " + url.getContentType());
    this.infoOut.println("Content-Length   : " + url.getContentLength());
    if (url.getContentEncoding() != null)
        this.infoOut.println("Content-Encoding : " + url.getContentEncoding());
}

From source file:org.spoutcraft.launcher.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;//from   www  .  j av  a  2 s  .co m
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * Test whether the getPort method returns the actual request port and not the one
 * included in the host-header//from w w  w . j  a va  2 s .  c o m
 * @throws Exception 
 */
@Test
public void testPort() throws Exception {
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            assertEquals(serverBinding.getPort(), request.getPort());
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.setRequestProperty("host", "foo:88");
        connection.setRequestProperty("FOO", "bar");
        connection.connect();
        // for the handler to be invoked, something of the response has to
        // be asked
        //assertEquals(headerValue, connection.getHeaderField("Cookie"));
        connection.getContentLength();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * set a "cookie" request header and expects the same value in the "cookie"
 * response header//from   w w  w . ja  v  a2  s  .  c om
 * 
 * @throws Exception
 */
@Test
public void testMultipleRequestHeader() throws Exception {
    final String headerValue = "bla blah";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testMultipleRequestHeader");

            String receivedHeaderValue = request.getHeaderValues(HeaderName.COOKIE)[0];
            response.setHeader(HeaderName.COOKIE, receivedHeaderValue);
            assertEquals(headerValue, receivedHeaderValue);
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.setRequestProperty("CoOkie", headerValue);
        connection.setRequestProperty("FOO", "bar");
        connection.connect();
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(headerValue, connection.getHeaderField("Cookie"));
        connection.getContentLength();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:fr.jayasoft.ivy.url.BasicURLHandler.java

public boolean isReachable(URL url, int timeout) {
    try {/*from w ww .j ava  2 s  .c o  m*/
        URLConnection con = url.openConnection();
        if (con instanceof HttpURLConnection) {
            int status = ((HttpURLConnection) con).getResponseCode();
            if (status == HttpStatus.SC_OK) {
                return true;
            }
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                Message.warn("Your proxy requires authentication.");
            } else if (String.valueOf(status).startsWith("4")) {
                Message.verbose(
                        "CLIENT ERROR: " + ((HttpURLConnection) con).getResponseMessage() + " url=" + url);
            } else if (String.valueOf(status).startsWith("5")) {
                Message.error(
                        "SERVER ERROR: " + ((HttpURLConnection) con).getResponseMessage() + " url=" + url);
            }
            Message.debug("HTTP response status: " + status + " url=" + url);
        } else {
            int contentLength = con.getContentLength();
            return contentLength > 0;
        }
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info(
                "You probably access the destination server through a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("Server access Error: " + e.getMessage() + " url=" + url);
    }
    return false;
}

From source file:org.cytoscape.app.internal.net.WebQuerier.java

/**
 * Given the unique app name used by the app store, query the app store for the 
 * download URL and download the app to the given directory.
 * /*from  ww  w  .  j  a v a  2 s  . com*/
 * If a file with the same name exists in the directory, it is overwritten.
 * 
 * @param appName The unique app name used by the app store
 * @param version The desired version, or <code>null</code> to obtain the latest release
 * @param directory The directory used to store the downloaded file
 * @param taskMonitor 
 */
public File downloadApp(WebApp webApp, String version, File directory, DownloadStatus status)
        throws AppDownloadException {

    List<WebApp.Release> compatibleReleases = getCompatibleReleases(webApp);

    if (compatibleReleases.size() > 0) {
        WebApp.Release releaseToDownload = null;

        if (version != null) {
            for (WebApp.Release compatibleRelease : compatibleReleases) {

                // Check if the desired version is found in the list of available versions
                if (compatibleRelease.getReleaseVersion()
                        .matches("(^\\s*|.*,)\\s*" + version + "\\s*(\\s*$|,.*)")) {
                    releaseToDownload = compatibleRelease;
                }
            }

            if (releaseToDownload == null) {
                throw new AppDownloadException("No release with the requested version " + version
                        + " was found for the requested app " + webApp.getFullName());
            }
        } else {
            releaseToDownload = compatibleReleases.get(compatibleReleases.size() - 1);
        }

        URL downloadUrl = null;
        try {
            downloadUrl = new URL(currentAppStoreUrl + releaseToDownload.getRelativeUrl());
        } catch (MalformedURLException e) {
            throw new AppDownloadException("Unable to obtain URL for version " + version
                    + " of the release for " + webApp.getFullName());
        }

        if (downloadUrl != null) {
            try {

                // Prepare to download
                URLConnection connection = streamUtil.getURLConnection(downloadUrl);
                InputStream inputStream = connection.getInputStream();
                long contentLength = connection.getContentLength();
                ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);

                File outputFile;
                try {
                    // Replace spaces with underscores
                    String outputFileBasename = webApp.getName().replaceAll("\\s", "_");

                    // Append version information
                    outputFileBasename += "-v" + releaseToDownload.getReleaseVersion();

                    // Strip disallowed characters
                    outputFileBasename = OUTPUT_FILENAME_DISALLOWED_CHARACTERS.matcher(outputFileBasename)
                            .replaceAll("");

                    // Append extension
                    outputFileBasename += ".jar";

                    // Output file has same name as app, but spaces and slashes are replaced with hyphens
                    outputFile = new File(directory.getCanonicalPath() + File.separator + outputFileBasename);

                    if (outputFile.exists()) {
                        outputFile.delete();
                    }

                    outputFile.createNewFile();

                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                    try {
                        FileChannel fileChannel = fileOutputStream.getChannel();

                        long currentDownloadPosition = 0;
                        long bytesTransferred;

                        TaskMonitor taskMonitor = status.getTaskMonitor();
                        do {
                            bytesTransferred = fileChannel.transferFrom(readableByteChannel,
                                    currentDownloadPosition, 1 << 14);
                            if (status.isCanceled()) {
                                outputFile.delete();
                                return null;
                            }
                            currentDownloadPosition += bytesTransferred;
                            if (contentLength > 0) {
                                double progress = (double) currentDownloadPosition / contentLength;
                                taskMonitor.setProgress(progress);
                            }
                        } while (bytesTransferred > 0);
                    } finally {
                        fileOutputStream.close();
                    }
                } finally {
                    readableByteChannel.close();
                }
                return outputFile;
            } catch (IOException e) {
                throw new AppDownloadException(
                        "Error while downloading app " + webApp.getFullName() + ", " + e.getMessage());
            }
        }
    } else {
        throw new AppDownloadException(
                "No available releases were found for the app " + webApp.getFullName() + ".");
    }
    return null;
}

From source file:de.mkrtchyan.recoverytools.FlashFragment.java

public void catchUpdates(final boolean ask) {
    mSwipeUpdater.setRefreshing(true);//www.jav  a 2 s  . c om
    final Thread updateThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                /** Check changes on server */
                final URL recoveryUrl = new URL(Constants.RECOVERY_SUMS_URL);
                URLConnection recoveryCon = recoveryUrl.openConnection();
                long recoveryListSize = recoveryCon.getContentLength(); //returns size of file on server
                long recoveryListLocalSize = RecoveryCollectionFile.length(); //returns size of local file
                if (recoveryListSize > 0) {
                    isRecoveryListUpToDate = recoveryListLocalSize == recoveryListSize;
                }
                final URL kernelUrl = new URL(Constants.KERNEL_SUMS_URL);
                URLConnection kernelCon = kernelUrl.openConnection();
                long kernelListSize = kernelCon.getContentLength();
                long kernelListLocalSize = KernelCollectionFile.length();
                if (kernelListSize > 0) {
                    isKernelListUpToDate = kernelListLocalSize == kernelListSize;
                }
            } catch (IOException e) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, R.string.check_connection, Toast.LENGTH_SHORT).show();
                    }
                });
                mActivity.addError(Constants.RASHR_TAG, e, false);
            }
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!isRecoveryListUpToDate || !isKernelListUpToDate) {
                        /** Counting current images */
                        final int img_count = mDevice.getStockRecoveryVersions().size()
                                + mDevice.getCwmRecoveryVersions().size()
                                + mDevice.getTwrpRecoveryVersions().size()
                                + mDevice.getPhilzRecoveryVersions().size()
                                + mDevice.getStockKernelVersions().size();
                        final URL recoveryURL;
                        final URL kernelURL;
                        try {
                            recoveryURL = new URL(Constants.RECOVERY_SUMS_URL);
                            kernelURL = new URL(Constants.KERNEL_SUMS_URL);
                        } catch (MalformedURLException e) {
                            return;
                        }
                        final Downloader RecoveryUpdater = new Downloader(mContext, recoveryURL,
                                RecoveryCollectionFile);
                        RecoveryUpdater.setOverrideFile(true);
                        RecoveryUpdater.setOnDownloadListener(new Downloader.OnDownloadListener() {
                            @Override
                            public void success(File file) {
                                mDevice.loadRecoveryList();
                                isRecoveryListUpToDate = true;
                                final Downloader KernelUpdater = new Downloader(mContext, kernelURL,
                                        KernelCollectionFile);
                                KernelUpdater.setOverrideFile(true);
                                KernelUpdater.setOnDownloadListener(new Downloader.OnDownloadListener() {
                                    @Override
                                    public void success(File file) {
                                        mDevice.loadKernelList();
                                        isKernelListUpToDate = true;
                                        /** Counting added images (after update) */
                                        final int new_img_count = (mDevice.getStockRecoveryVersions().size()
                                                + mDevice.getCwmRecoveryVersions().size()
                                                + mDevice.getTwrpRecoveryVersions().size()
                                                + mDevice.getPhilzRecoveryVersions().size()
                                                + mDevice.getStockKernelVersions().size()) - img_count;
                                        mActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (isAdded()) {
                                                    Toast.makeText(mActivity,
                                                            String.format(getString(R.string.new_imgs_loaded),
                                                                    new_img_count),
                                                            Toast.LENGTH_SHORT).show();
                                                }
                                                mSwipeUpdater.setRefreshing(false);
                                            }
                                        });
                                    }

                                    @Override
                                    public void failed(final Exception e) {
                                        Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                                        mSwipeUpdater.setRefreshing(false);
                                    }
                                });
                                KernelUpdater.execute();
                            }

                            @Override
                            public void failed(final Exception e) {
                                Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                                mSwipeUpdater.setRefreshing(false);
                            }
                        });
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (ask) {
                                    AlertDialog.Builder updateDialog = new AlertDialog.Builder(mContext);
                                    updateDialog.setTitle(R.string.update_available)
                                            .setMessage(R.string.lists_outdated)
                                            .setPositiveButton(R.string.update,
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Toast.makeText(mActivity, R.string.refresh_list,
                                                                    Toast.LENGTH_SHORT).show();
                                                            RecoveryUpdater.execute();
                                                        }
                                                    })
                                            .setNegativeButton(android.R.string.cancel,
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {

                                                        }
                                                    })
                                            .show();
                                } else {
                                    Toast.makeText(mActivity, R.string.refresh_list, Toast.LENGTH_SHORT).show();
                                    RecoveryUpdater.execute();
                                }
                            }
                        });
                    } else {
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, R.string.uptodate, Toast.LENGTH_SHORT).show();
                                mSwipeUpdater.setRefreshing(false);
                            }
                        });
                    }
                }
            });
        }
    });
    updateThread.start();
}

From source file:com.apache.ivy.BasicURLHandler.java

public URLInfo getURLInfo(URL url, int timeout) {
    // Install the IvyAuthenticator
    if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) {
        IvyAuthenticator.install();//from  w  w w  .  j av  a  2s  .c  om
    }

    URLConnection con = null;
    try {
        url = normalizeToURL(url);
        con = url.openConnection();
        con.setRequestProperty("User-Agent", "Apache Ivy/1.0");//+ Ivy.getIvyVersion());
        if (con instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) con;
            if (getRequestMethod() == URLHandler.REQUEST_METHOD_HEAD) {
                httpCon.setRequestMethod("HEAD");
            }
            if (checkStatusCode(url, httpCon)) {
                String bodyCharset = getCharSetFromContentType(con.getContentType());
                return new URLInfo(true, httpCon.getContentLength(), con.getLastModified(), bodyCharset);
            }
        } else {
            int contentLength = con.getContentLength();
            if (contentLength <= 0) {
                return UNAVAILABLE;
            } else {
                // TODO: not HTTP... maybe we *don't* want to default to ISO-8559-1 here?
                String bodyCharset = getCharSetFromContentType(con.getContentType());
                return new URLInfo(true, contentLength, con.getLastModified(), bodyCharset);
            }
        }
    } catch (UnknownHostException e) {
        // Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        // Message.info("You probably access the destination server through "
        //    + "a proxy server that is not well configured.");
    } catch (IOException e) {
        //Message.error("Server access error at url " + url, e);
    } finally {
        disconnect(con);
    }
    return UNAVAILABLE;
}

From source file:org.getobjects.appserver.publisher.GoResource.java

@Override
public void appendToResponse(final WOResponse _r, final WOContext _ctx) {
    URLConnection con = null;
    try {/*from w w  w  . j  a  v  a 2 s. c  o m*/
        con = this.url.openConnection();
    } catch (IOException coe) {
        log.warn("could not open connection to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* open stream */

    InputStream is = null;
    try {
        is = con.getInputStream();
    } catch (IOException ioe) {
        log.warn("could not open stream to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* transfer */

    try {
        String mimeType = con.getContentType();
        if (mimeType == null || "content/unknown".equals(mimeType))
            mimeType = mimeTypeForPath(this.url.getPath());

        if (mimeType == null)
            mimeType = "application/octet-stream";

        _r.setHeaderForKey(mimeType, "content-type");
        _r.setHeaderForKey("" + con.getContentLength(), "content-length");

        /* setup caching headers */

        Date now = new Date();
        GregorianCalendar cal = new GregorianCalendar();

        cal.setTime(new Date(con.getLastModified()));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "last-modified");

        cal.setTime(now);
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "date");

        cal.add(Calendar.SECOND, this.expirationIntervalForMimeType(mimeType));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "expires");

        /* start streaming */

        _r.enableStreaming();

        byte[] buffer = new byte[0xFFFF];
        for (int len; (len = is.read(buffer)) != -1;)
            _r.appendContentData(buffer, len);
    } catch (IOException e) {
        log.error("IO error trying to deliver resource: " + this.url, e);
        _r.setStatus(WOMessage.HTTP_STATUS_INTERNAL_ERROR);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.warn("could not close URL input stream: " + this.url, e);
        }
    }
}

From source file:org.getobjects.appserver.publisher.JoResource.java

@Override
public void appendToResponse(WOResponse _r, WOContext _ctx) {
    URLConnection con = null;
    try {//  ww  w.  j a v a 2 s .  co m
        con = this.url.openConnection();
    } catch (IOException coe) {
        log.warn("could not open connection to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* open stream */

    InputStream is = null;
    try {
        is = con.getInputStream();
    } catch (IOException ioe) {
        log.warn("could not open stream to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* transfer */

    try {
        String mimeType = con.getContentType();
        if (mimeType == null || "content/unknown".equals(mimeType))
            mimeType = mimeTypeForPath(this.url.getPath());

        if (mimeType == null)
            mimeType = "application/octet-stream";

        _r.setHeaderForKey(mimeType, "content-type");
        _r.setHeaderForKey("" + con.getContentLength(), "content-length");

        /* setup caching headers */

        Date now = new Date();
        GregorianCalendar cal = new GregorianCalendar();

        cal.setTime(new Date(con.getLastModified()));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "last-modified");

        cal.setTime(now);
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "date");

        cal.add(Calendar.SECOND, this.expirationIntervalForMimeType(mimeType));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "expires");

        /* start streaming */

        _r.enableStreaming();

        byte[] buffer = new byte[0xFFFF];
        for (int len; (len = is.read(buffer)) != -1;)
            _r.appendContentData(buffer, len);
    } catch (IOException e) {
        log.error("IO error trying to deliver resource: " + this.url, e);
        _r.setStatus(WOMessage.HTTP_STATUS_INTERNAL_ERROR);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.warn("could not close URL input stream: " + this.url, e);
        }
    }
}