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.eclipse.hudson.plugins.PluginInstallationJob.java

private File download(URL src) throws IOException {
    URLConnection con;
    if ((proxyConfig != null) && (proxyConfig.name != null)) {
        con = proxyConfig.openUrl(src);/*w w w . ja va 2s.  c  om*/
    } else {
        con = src.openConnection();
    }
    int total = con.getContentLength();
    CountingInputStream in = new CountingInputStream(con.getInputStream());
    byte[] buf = new byte[8192];
    int len;

    File dst = getDestination();
    File tmp = new File(dst.getPath() + ".tmp");
    OutputStream out = new FileOutputStream(tmp);

    try {
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len);
            //job.status = job.new Installing(total == -1 ? -1 : in.getCount() * 100 / total);
        }
    } catch (IOException e) {
        throw new IOException("Failed to load " + src + " to " + tmp, e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }

    if (total != -1 && total != tmp.length()) {
        throw new IOException("Inconsistent file length: expected " + total + " but only got " + tmp.length());
    }

    return tmp;
}

From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java

public void commitResponse(final String path, final Resource resource, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // determine properties of the resource being served back
    final URLConnection resourceConn = resource.getURL().openConnection();
    applyHeaders(path, response, resourceConn.getContentLength(), resourceConn.getLastModified());

    // stream back to response
    RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/" + path);
    rd.include(request, response);/*from w w w . j a v  a  2 s .c o m*/
}

From source file:org.jenkinsci.plugins.mber.FileDownloadCallable.java

@Override
public JSONObject invoke(final File file, final VirtualChannel channel) {
    InputStream istream = null;/* w w w . j a va2s. c o m*/
    OutputStream ostream = null;
    try {
        this.fileName = file.getName();
        // Avoid I/O errors by setting attributes on the connection before getting data from it.
        final String redirectedURL = followRedirects(this.url);
        final URLConnection connection = new URL(redirectedURL).openConnection();
        connection.setUseCaches(false);

        // Track expected bytes vs. downloaded bytes so we can retry corrupt downloads.
        final long expectedByteCount = connection.getContentLength();
        istream = connection.getInputStream();
        ostream = new LoggingOutputStream(new FilePath(file).write(), this, expectedByteCount);
        final long downloadedByteCount = IOUtils.copyLarge(istream, ostream);

        if (downloadedByteCount < expectedByteCount) {
            final long missingByteCount = expectedByteCount - downloadedByteCount;
            return MberJSON.failed(String.format("Missing %d bytes in %s", missingByteCount, this.fileName));
        }

        return MberJSON.success();
    } catch (final LoggingInterruptedException e) {
        return MberJSON.aborted(e);
    } catch (final Exception e) {
        return MberJSON.failed(e);
    } finally {
        // Close the input and output streams so other build steps can access those files.
        IOUtils.closeQuietly(istream);
        IOUtils.closeQuietly(ostream);
    }
}

From source file:ch.trustserv.soundbox.plugins.portals.jamendoplugin.JamendoPlugin.java

/**
 *
 * @param jamendoSong//from ww w.j a  v  a  2s.  com
 * @param reciever
 */
private void getStreamFromSong(final JamendoSong jamendoSong, final String reciever) {
    URL streamLink = null;
    try {
        streamLink = new URL("http://api.jamendo.com/get2/stream/track/redirect/?id=" + jamendoSong.getId()
                + "&streamencoding=mp31");
    } catch (MalformedURLException ex) {
        Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
    }
    ServiceReference ref = cx.getServiceReference(EventAdmin.class.getName());

    if (ref != null) {
        EventAdmin eventAdmin = (EventAdmin) cx.getService(ref);
        Dictionary properties = new Hashtable();
        try {
            URLConnection con = streamLink.openConnection();
            jamendoSong.setContentLength(con.getContentLength());
            properties.put("stream", new BufferedInputStream(con.getInputStream()));
            properties.put("song", jamendoSong);
        } catch (IOException ex) {
            Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }
        Event reportGeneratedEvent = null;
        switch (reciever) {
        case GETSTREAMFROMSONGFORDOWNLOADER:
            reportGeneratedEvent = new Event(STREAMFROMSONGFORDOWNLOADER, properties);
            break;
        case GETSTREAMFROMSONGFORPLAYER:
            reportGeneratedEvent = new Event(STREAMFROMSONGFORPLAYER, properties);
            break;
        }
        eventAdmin.sendEvent(reportGeneratedEvent);
    }
}

From source file:com.almunt.jgcaap.systemupdater.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    String urlToDownload = "http://download.jgcaap.xyz/files/oneplusone/cm-13.0/"
            + intent.getStringExtra("url");
    filename = intent.getStringExtra("url");
    String newfilename = filename.replace("zip", "temp");
    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
    try {/*from   w w  w  . j a  va2s.c om*/
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        // download the file
        InputStream input = new BufferedInputStream(connection.getInputStream());
        File tempDir = new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/");
        tempDir.mkdir();
        //make a folder for downloading files
        OutputStream output = new FileOutputStream(
                Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/" + newfilename);
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        File temp = new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/nd");
        //temp file is created in case of an error
        while ((count = input.read(data)) != -1 && continuedownload) {
            total += count;
            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress", (int) total);
            resultData.putInt("total", fileLength);
            resultData.putString("filename", filename);
            resultData.putBoolean("error", false);
            receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
            if (temp.exists()) {
                continuedownload = false;
                temp.delete();
            }
        }
        output.flush();
        output.close();
        input.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
        Bundle resultData = new Bundle();
        resultData.putInt("progress", 0);
        resultData.putInt("total", 1);
        resultData.putString("filename", filename);
        resultData.putBoolean("error", true);
        resultData.putString("errordetails", e.getMessage());
        receiver.send(UPDATE_PROGRESS, resultData);
    }
    String dir = Environment.getExternalStorageDirectory() + File.separator + "JgcaapUpdates";
    // copy downloaded file if download is successful
    if (continuedownload) {
        try {
            if (new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/" + newfilename)
                    .length() > 1000)
                copy(new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/" + newfilename),
                        new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/" + filename));

        } catch (IOException e) {
            e.printStackTrace();
        }
        Bundle resultData = new Bundle();
        resultData.putInt("progress", 100);
        receiver.send(UPDATE_PROGRESS, resultData);
    }
    //clear the temporary folder
    File deletefolder = new File(dir + "/temp");
    if (deletefolder.exists()) {
        File[] contents = deletefolder.listFiles();
        if (contents != null) {
            for (File f : contents) {
                f.delete();
            }
        }
    }
    deletefolder.delete();
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

/**
 * getDataResourceStream - gets an InputStream and Content-Length of a DataResource
 *
 * @param dataResource/*from w ww .ja va 2s .  co  m*/
 * @param https
 * @param webSiteId
 * @param locale
 * @param contextRoot
 * @return Map containing 'stream': the InputStream and 'length' a Long containing the content-length
 * @throws IOException
 * @throws GeneralException
 */
public static Map<String, Object> getDataResourceStream(GenericValue dataResource, String https,
        String webSiteId, Locale locale, String contextRoot, boolean cache)
        throws IOException, GeneralException {
    if (dataResource == null) {
        throw new GeneralException("Cannot stream null data resource!");
    }

    String dataResourceTypeId = dataResource.getString("dataResourceTypeId");
    String dataResourceId = dataResource.getString("dataResourceId");
    Delegator delegator = dataResource.getDelegator();

    // first text based data
    if (dataResourceTypeId.endsWith("_TEXT") || "LINK".equals(dataResourceTypeId)) {
        String text = "";

        if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
            text = dataResource.getString("objectInfo");
        } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
            GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText")
                    .where("dataResourceId", dataResourceId).cache(cache).queryOne();
            if (electronicText != null) {
                text = electronicText.getString("textData");
            }
        } else {
            throw new GeneralException("Unsupported TEXT type; cannot stream");
        }

        byte[] bytes = text.getBytes();
        return UtilMisc.toMap("stream", new ByteArrayInputStream(bytes), "length", Long.valueOf(bytes.length));

        // object (binary) data
    } else if (dataResourceTypeId.endsWith("_OBJECT")) {
        byte[] bytes = new byte[0];
        GenericValue valObj;

        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            valObj = EntityQuery.use(delegator).from("ImageDataResource")
                    .where("dataResourceId", dataResourceId).cache(cache).queryOne();
            if (valObj != null) {
                bytes = valObj.getBytes("imageData");
            }
        } else if ("VIDEO_OBJECT".equals(dataResourceTypeId)) {
            valObj = EntityQuery.use(delegator).from("VideoDataResource")
                    .where("dataResourceId", dataResourceId).cache(cache).queryOne();
            if (valObj != null) {
                bytes = valObj.getBytes("videoData");
            }
        } else if ("AUDIO_OBJECT".equals(dataResourceTypeId)) {
            valObj = EntityQuery.use(delegator).from("AudioDataResource")
                    .where("dataResourceId", dataResourceId).cache(cache).queryOne();
            if (valObj != null) {
                bytes = valObj.getBytes("audioData");
            }
        } else if ("OTHER_OBJECT".equals(dataResourceTypeId)) {
            valObj = EntityQuery.use(delegator).from("OtherDataResource")
                    .where("dataResourceId", dataResourceId).cache(cache).queryOne();
            if (valObj != null) {
                bytes = valObj.getBytes("dataResourceContent");
            }
        } else {
            throw new GeneralException("Unsupported OBJECT type [" + dataResourceTypeId + "]; cannot stream");
        }

        return UtilMisc.toMap("stream", new ByteArrayInputStream(bytes), "length", Long.valueOf(bytes.length));

        // file data
    } else if (dataResourceTypeId.endsWith("_FILE") || dataResourceTypeId.endsWith("_FILE_BIN")) {
        String objectInfo = dataResource.getString("objectInfo");
        if (UtilValidate.isNotEmpty(objectInfo)) {
            File file = DataResourceWorker.getContentFile(dataResourceTypeId, objectInfo, contextRoot);
            return UtilMisc.toMap("stream", new ByteArrayInputStream(FileUtils.readFileToByteArray(file)),
                    "length", Long.valueOf(file.length()));
        } else {
            throw new GeneralException(
                    "No objectInfo found for FILE type [" + dataResourceTypeId + "]; cannot stream");
        }

        // URL resource data
    } else if ("URL_RESOURCE".equals(dataResourceTypeId)) {
        String objectInfo = dataResource.getString("objectInfo");
        if (UtilValidate.isNotEmpty(objectInfo)) {
            URL url = new URL(objectInfo);
            if (url.getHost() == null) { // is relative
                String newUrl = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
                if (!newUrl.endsWith("/")) {
                    newUrl = newUrl + "/";
                }
                newUrl = newUrl + url.toString();
                url = new URL(newUrl);
            }

            URLConnection con = url.openConnection();
            return UtilMisc.toMap("stream", con.getInputStream(), "length",
                    Long.valueOf(con.getContentLength()));
        } else {
            throw new GeneralException("No objectInfo found for URL_RESOURCE type; cannot stream");
        }
    }

    // unsupported type
    throw new GeneralException(
            "The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in getDataResourceStream");
}

From source file:com.barchart.netty.server.http.handlers.TestStaticResourceHandler.java

@Test
public void testClasspathNotCached() throws Exception {

    final HttpGet get = new HttpGet("http://localhost:" + port + "/classpath/test.css");
    final HttpResponse response = client.execute(get);

    final URLConnection conn = getClass().getResource("/files/test.css").openConnection();

    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(conn.getContentLength(),
            Integer.parseInt(response.getFirstHeader(HttpHeaders.CONTENT_LENGTH).getValue()));
    assertTrue(IOUtils.contentEquals(conn.getInputStream(), response.getEntity().getContent()));

}

From source file:com.knowarth.portlet.downloadinterceptor.DownloadInterceptorPortlet.java

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws IOException {
    //Setting out email parameters
    String emailAdd = resourceRequest.getParameter("emailAddress");
    String visitorName = resourceRequest.getParameter("visitorName");
    String cmpName = resourceRequest.getParameter("companyName");
    String phoneNumber = resourceRequest.getParameter("phoneNumber");
    String comments = resourceRequest.getParameter("comments");

    //Getting the preferences and reading URL Location reading from edit mode
    PortletPreferences prefs = resourceRequest.getPreferences();
    String resourceurl = prefs.getValue("resourceurl", "");
    String caseStudyName = prefs.getValue("caseStudyName", "");
    String receiveEmailAdd = prefs.getValue("receiverEmailAdd", "");
    //emailBodyContent Return the template stored in preferences edit mode.
    String emailBodyContent = prefs.getValue("emailBodyTemplate", "");
    String emailsubj = prefs.getValue("emailSubjectTemplate", "");
    String resExtension = prefs.getValue("ResourceExtension", "");
    String body = StringUtil.replace(emailBodyContent,
            new String[] { "[$VISITOR_NAME$]", "[$COMPANY_NAME$]", "[$EMAIL_ADDRESS$]", "[$PHONE_NUMBER$]",
                    "[$COMMENTS$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, cmpName, emailAdd, phoneNumber, comments, caseStudyName });

    //Setting out body and email parameters
    String subject = StringUtil.replace(emailsubj, new String[] { "[$VISITOR_NAME$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, caseStudyName });
    //code for sending email
    try {/*from ww w.j a  va  2 s  . c  o m*/
        InternetAddress fromAddress = new InternetAddress(emailAdd);
        InternetAddress toAddress = new InternetAddress(receiveEmailAdd);

        MailMessage mailMessage = new MailMessage(fromAddress, toAddress, subject, body, true);
        MailServiceUtil.sendEmail(mailMessage);

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        _log.error("Error Sending Message", e);
    } finally {
        //For Downloading a resource

        String contentDisposition = "attachment; filename=" + caseStudyName + "." + resExtension;
        OutputStream out = resourceResponse.getPortletOutputStream();

        //LInk for resource URL Goes here. Uncomment it out for dynamic location and comment out the static link
        URL url = new URL(resourceurl);
        URLConnection conn = url.openConnection();
        resourceResponse.setContentType(conn.getContentType());
        resourceResponse.setContentLength(conn.getContentLength());
        resourceResponse.setCharacterEncoding(conn.getContentEncoding());
        resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600");

        // open the stream and put it into BufferedReader
        InputStream stream = conn.getInputStream();
        int c;
        while ((c = stream.read()) != -1) {
            out.write(c);
        }
        out.flush();
        out.close();
        stream.close();

    }

}

From source file:de.damdi.fitness.activity.settings.sync.WgerImageDownloader.java

/**
 * /*from w  w w.  java2 s . c  o m*/
 * @param urlToDownload
 *            the url
 * @return the name of the downloaded image. This name can be different from
 *         the original name if there's already a file with the same name.
 */
private String downloadImageToSyncedImagesFolder(String urlToDownload) {
    try {
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100%
        // progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());

        // create output folder
        String outputFolder = mContext.getFilesDir().toString() + "/" + IDataProvider.SYNCED_IMAGES_FOLDER;
        (new File(outputFolder)).mkdir();
        String imageName = new File(urlToDownload).getName();
        String outputPath = outputFolder + "/" + imageName;

        // skip files that already exist
        if ((new File(outputPath)).exists()) {
            Log.e(TAG, "already such a file: " + outputPath);
            Log.e(TAG, "Will SKIP this file.");
            return imageName;
        }
        OutputStream output = new FileOutputStream(outputPath);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress", (int) (total * 100 / fileLength));
            // receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }

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

        return imageName;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:deincraftlauncher.IO.download.Downloader.java

public void prepare() { //generating: fileName, totalSize, 

    preparing = true;/*w  ww  . jav a2  s .  c  om*/

    prepareThread = new Thread() {
        @Override
        public void run() {

            try {
                target = new URL(link);

                URLConnection targetCon = target.openConnection();

                totalSize = targetCon.getContentLength();

                String raw = targetCon.getHeaderField("Content-Disposition");

                if (raw != null && raw.contains("=")) {
                    fileName = raw.split("=")[1];
                    fileName = fileName.split(";")[0];
                } else {
                    fileName = "Unbekannt";
                }

                fileName = fileName.replaceAll("\"", "");

                System.out.println("Prepared Download: size: " + totalSize + " name=" + fileName);
                prepared = true;
                preparing = false;

                onPrepared.call(instance);

            } catch (MalformedURLException ex) {
                Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };

    prepareThread.start();

}