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.wymiwyg.wrhapi.test.BaseTests.java

@Test
public void testHeaderAddedInMessageBody() throws Exception {
    final String serverHeaderValue = "Ad-Hoc testing server";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, final Response response) throws HandlerException {

            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    try {

                        response.setHeader(HeaderName.SERVER, serverHeaderValue);
                    } catch (HandlerException ex) {
                        throw new RuntimeException(ex);
                    }//from w w w  .j  a  v a  2s  .  c  o  m
                    ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes());
                    out.write(bb);
                }
            });
        }
    }, serverBinding);

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

From source file:nl.openweb.hippo.umd.ui.ResourceServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String resourcePath = StringUtils.substringBefore(request.getPathInfo(), ";");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing request for resource {}.", resourcePath);
    }//from  w w  w .  j  a v a2  s  .c om

    URL resource = getResourceURL(resourcePath);

    if (resource == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource not found: {}", resourcePath);
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");

    URLConnection conn = resource.openConnection();
    long lastModified = conn.getLastModified();

    if (ifModifiedSince >= lastModified) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource: {} Not Modified.", resourcePath);
        }
        response.setStatus(304);
        return;
    }

    int contentLength = conn.getContentLength();

    prepareResponse(response, resource, lastModified, contentLength);

    OutputStream out = selectOutputStream(request, response);

    try {
        InputStream is = conn.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = is.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            is.close();
        }
    } finally {
        out.close();
    }

}

From source file:gr.iti.mklab.bubing.parser.ITIHTMLParser.java

public void processImageURL(URI pageUri, URI base, String imageUri, String altText)
        throws MalformedURLException, IOException {

    URI url = BURL.parse(imageUri);
    if (url != null) {
        URI resolved = base.resolve(url);
        String resolvedStr = resolved.toString();
        //avoid trying to index the same image multiple times
        if (!ItiAgent.UNIQUE_IMAGE_URLS.mightContain(resolvedStr)) {
            // Put it in the bloom filter even if it is not saved eventually
            // to avoid doing the same checks for the same image a second time
            ItiAgent.UNIQUE_IMAGE_URLS.put(resolvedStr);

            final URLConnection con = resolved.toURL().openConnection();

            if (Utils.checkContentHeaders(con.getContentLength(), con.getContentType())) {

                InputStream is = con.getInputStream();

                BufferedImage image = null;
                try {
                    image = ImageIO.read(is);
                } catch (IllegalArgumentException e) {
                    // this exception is probably thrown because of a greyscale jpeg image
                    System.out.println("Exception: " + e.getMessage() + " | Image: " + imageUri);
                    image = ImageIOGreyScale.read(is); // retry with the modified class
                } catch (MalformedURLException e) {
                    System.out.println("Malformed url exception. Url: " + imageUri);
                }/*from ww w.  j  av a2  s  . c om*/

                if (Utils.checkImage(image)) {

                    Image item = new Image();
                    item.setUrl(resolvedStr);
                    item.setTitle(altText);
                    item.setWidth(image.getWidth());
                    item.setHeight(image.getHeight());
                    item.setWebPageUrl(pageUri.toString());
                    item.setLastModifiedDate(new Date(con.getLastModified()));
                    item.setObjectId(new ObjectId());

                    try {
                        VisualIndexer.getInstance().indexAndStore(image, item);
                    } catch (Exception e) {
                        System.out.println("HTMLImageParser parse exeption: " + e);
                    }

                }
            }
        }
    }
}

From source file:com.sslexplorer.install.actions.InstallAction.java

private boolean installExtensions(HttpServletRequest request, List<WizardActionStatus> actionStatus,
        Map<String, String> extensionsToInstall, ActionForward fwd, TaskProgressBar overallProgress,
        TaskProgressBar atomicProgress) throws IOException {
    boolean forwardToLicense = false;
    int val = 7;
    request.setAttribute(TaskHttpServletRequest.ATTR_TASK_PROGRESS_HANDLED_EXTERNALLY, Boolean.TRUE);
    for (Iterator<Entry<String, String>> i = extensionsToInstall.entrySet().iterator(); i.hasNext();) {
        overallProgress.setValue(val++);
        atomicProgress.setValue(0);// w ww.  ja v a 2s.c om
        atomicProgress.setMinValue(0);
        atomicProgress.setMaxValue(100);
        atomicProgress.setValue(100);
        Entry<String, String> ext = i.next();
        atomicProgress.setNote(new BundleActionMessage("install",
                "taskProgress.install.atomic.installExtension.note", ext.getKey()));
        URLConnection con = ExtensionStore.getInstance().downloadExtension(ext.getKey(), ext.getValue());
        InputStream in = null;
        try {
            atomicProgress.setMaxValue(con.getContentLength());
            atomicProgress.setValue(0);
            ExtensionBundle bundle = null;
            in = con.getInputStream();
            in = new TaskInputStream(atomicProgress, in);
            if (ExtensionStore.getInstance().isExtensionBundleLoaded(ext.getKey())) {
                bundle = ExtensionStore.getInstance().updateExtension(ext.getKey(), in, request,
                        con.getContentLength());
                if (bundle.isContainsPlugin())
                    GlobalWarningManager.getInstance()
                            .addMultipleGlobalWarning(new GlobalWarning(GlobalWarning.MANAGEMENT_USERS,
                                    new BundleActionMessage("extensions",
                                            "extensionStore.message.extensionUpdatedRestartRequired"),
                                    DismissType.DISMISS_FOR_USER));
            } else {
                bundle = ExtensionStore.getInstance().installExtensionFromStore(ext.getKey(), in, request,
                        con.getContentLength());
                File licenseFile = bundle.getLicenseFile();
                final RepositoryStore repStore = RepositoryFactory.getRepository()
                        .getStore(ExtensionStore.ARCHIVE_STORE);
                if (licenseFile != null && licenseFile.exists()) {
                    forwardToLicense = true;
                    CoreUtil.requestLicenseAgreement(request.getSession(),
                            new LicenseAgreement(bundle.getName(), licenseFile,
                                    new ExtensionLicenseAgreementCallback(repStore, bundle, actionStatus),
                                    fwd));
                } else {
                    ExtensionStore.getInstance().postInstallExtension(bundle, request);
                    actionStatus.add(new WizardActionStatus(WizardActionStatus.COMPLETED_OK,
                            "installation.install.status.installedExtension", bundle.getName(),
                            bundle.getId()));
                }
            }

        } catch (CoreException ce) {
            log.error("Failed to install extension " + ext.getKey() + ".", ce);
            actionStatus.add(new WizardActionStatus(WizardActionStatus.COMPLETED_WITH_ERRORS,
                    "installation.install.status.failedToInstallExtension", ext.getKey(),
                    ce.getLocalizedMessage(request.getSession())));
        } catch (Exception e) {
            log.error("Failed to install extension " + ext.getKey() + ".", e);
            actionStatus.add(new WizardActionStatus(WizardActionStatus.COMPLETED_WITH_ERRORS,
                    "installation.install.status.failedToInstallExtension", ext.getKey(), e.getMessage()));
        } finally {
            Util.closeStream(in);
        }

    }
    return forwardToLicense;
}

From source file:org.wso2.emm.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);//from w  ww  .j a  va  2 s. c om
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}

From source file:org.owasp.jbrofuzz.update.StartUpdateChecker.java

/**
 * <p>/*from  ww w. jav a 2  s  .  c  o  m*/
 * Static method for getting the current online version of JBroFuzz.
 * </p>
 * 
 * <p>
 * This method makes a connection to the OWASP web site, checking for the
 * latest version number.
 * </p>
 * 
 * @return double of the version or 0.0 in case of an error
 * 
 * @author subere@uncon.org
 * @version 2.5
 * @since 1.3
 */
private static double getWebsiteVersion() {

    String response = "";
    BufferedReader instream = null;

    try {

        final URL url = new URL(JBroFuzzFormat.URL_WEBSITE);
        final URLConnection urlc;

        final boolean proxyEnabled = JBroFuzz.PREFS.getBoolean(JBroFuzzPrefs.UPDATE[0].getId(), false);
        if (proxyEnabled) {

            final String proxy = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[1].getId(), "");
            final int port = JBroFuzz.PREFS.getInt(JBroFuzzPrefs.UPDATE[2].getId(), -1);
            // A note here, proxy has no http:// or https://
            Proxy myProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, port));
            urlc = url.openConnection(myProxy);
            // Username:Password, yawn

            final boolean proxyReqAuth = JBroFuzz.PREFS.getBoolean(JBroFuzzPrefs.UPDATE[3].getId(), false);
            if (proxyReqAuth) {

                final String user = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[5].getId(), "");
                final String pass = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[6].getId(), "");
                final String encodedPassword = EncoderHashCore.encode(user + ":" + pass, "Base64");
                urlc.setRequestProperty("Proxy-Authorization", "Basic " + encodedPassword);
            }

        } else {

            urlc = url.openConnection();

        }
        urlc.setRequestProperty("User-Agent", "JBroFuzz/" + JBroFuzzFormat.VERSION);

        final int statusCode = ((HttpURLConnection) urlc).getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK) {

            instream = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

            // Typically returns -1
            final long contentLength = urlc.getContentLength();

            if (contentLength > Integer.MAX_VALUE) {
                return ZERO_VERSION;
            }

            int count;
            int limit = 0;
            final StringBuffer body = new StringBuffer(Character.MAX_VALUE);
            // 
            while (((count = instream.read()) != -1) && (limit < Character.MAX_VALUE)) {
                body.append((char) count);
                limit++;
            }
            instream.close();

            response = body.toString();

        } else {
            return ZERO_VERSION;
        } // else statement for a 200 response

    } catch (final IOException e) {
        return ZERO_VERSION;
    } finally {
        IOUtils.closeQuietly(instream);
    }

    if (!response.equalsIgnoreCase("")) {

        final Pattern pattern1 = Pattern.compile("Current version is (\\d.\\d)");
        final Matcher match1 = pattern1.matcher(response);
        if (match1.find()) {
            final String webVersion = match1.group().substring(19, 22);

            try {
                // Return the value, if found
                return Double.parseDouble(webVersion);

            } catch (final NumberFormatException e) {
                // Return 0.0 if an error occurs
                return ZERO_VERSION;

            }

        } else {
            return ZERO_VERSION;
        }
    }
    return ZERO_VERSION;
}

From source file:$.ResourceServlet.java

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String resourcePath = StringUtils.substringBefore(request.getPathInfo(), ";");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing request for resource {}.", resourcePath);
        }//from ww w  .j  a v a2 s.c  o m

        URL resource = getResourceURL(resourcePath);

        if (resource == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource not found: {}", resourcePath);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");

        URLConnection conn = resource.openConnection();
        long lastModified = conn.getLastModified();

        if (ifModifiedSince >= lastModified) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource: {} Not Modified.", resourcePath);
            }
            response.setStatus(304);
            return;
        }

        int contentLength = conn.getContentLength();

        prepareResponse(response, resource, lastModified, contentLength);

        OutputStream out = selectOutputStream(request, response);

        try {
            InputStream is = conn.getInputStream();
            try {
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = is.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                is.close();
            }
        } finally {
            out.close();
        }

    }

From source file:org.wso2.iot.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);/*from   w  w  w  .ja v  a  2  s .c  o m*/
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                        Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                        message);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                        Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                        message);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}

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

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*from  ww w.j a  v  a 2  s.c o  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) {
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        result = Result.FAILURE;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}