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.sipfoundry.conference.ConfRecordThread.java

public void ProcessConfEnd(FreeSwitchEvent event, ConferenceTask conf) {
    String confName = event.getEventValue("conference-name");
    ConferenceBridgeItem item = ConferenceBridgeXML.getConferenceBridgeItem(confName);
    if (item != null) {
        String wavName = conf.getWavName();
        LOG.debug("ConfRecordThread::Finished conference recording of " + wavName);

        try {/*  w  w w. j  ava  2  s .  c o  m*/
            // Let FS finish any recording it may be doing
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        AuditWavFiles(new File(destName));

        // Use the conference name to find the conference mailbox server.
        String mboxServerAndPort = item.getMailboxServer();

        // Trigger the servlet on the voicemail server to read the WAV file
        // E.g. "http://s1.example.com:8085/recording/conference?test1_6737347.wav"
        try {
            String urlString = "http://" + mboxServerAndPort + "/recording/conference" + "?wn=" + wavName
                    + "&on=" + item.getOwnerName() + "&oi=" + item.getOwnerId() + "&bc="
                    + item.getBridgeContact();
            URL url = new URL(urlString);
            URLConnection urlC = url.openConnection();
            long contentLength = urlC.getContentLength();
        } catch (IOException e) {
            LOG.error("ConfRecordThread::Trigger error ", e);
        }
    }
}

From source file:de.anycook.upload.UserUploader.java

private byte[] getURLData(URL url) {
    try {/*from w ww  .  ja v a  2  s .c  o  m*/
        URLConnection c = url.openConnection();
        InputStream in = new BufferedInputStream(c.getInputStream());
        int contentLength = c.getContentLength();
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1)
                break;
            offset += bytesRead;
        }

        in.close();

        return data;

    } catch (IOException e) {
        logger.error("failed to save FBImage", e);
    }

    return new byte[0];
}

From source file:uk.ac.ebi.intact.dataexchange.cvutils.OboSlimBuilder.java

private void saveUrlToCache(URL url, File cachedFile) throws IOException {

    final URLConnection con = url.openConnection();
    final int downloadSize = con.getContentLength();

    System.out.println("Saving URL (" + downloadSize / 1024 + "K) to cache: " + cachedFile.getAbsolutePath());
    BufferedWriter out = new BufferedWriter(new FileWriter(cachedFile));

    out.close();/*from  w ww.java  2  s.com*/
    InputStream inputStream = con.getInputStream();

    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
    try {
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            out.write(inputLine + "\n");
    } finally {
        in.close();
        out.flush();
        out.close();
        inputStream.close();
    }
}

From source file:com.janoz.usenet.suppliers.impl.UrlBasedSupplier.java

@Override
public byte[] getData(NZB nzb) {
    if (nzb.getUrl() == null) {
        throw new LazyInitializationException("Unable to fetch data. URL missing.");
    }/*from   w  w w .j  a  v  a 2 s. c  om*/
    if (throttler != null) {
        throttler.throttle();
    }
    InputStream is = null;
    try {
        URLConnection connection = new URL(nzb.getUrl()).openConnection();
        is = connection.getInputStream();
        int contentLength = connection.getContentLength();
        ByteArrayOutputStream baos;
        if (contentLength != -1) {
            baos = new ByteArrayOutputStream(contentLength);
        } else {
            baos = new ByteArrayOutputStream(16384); // Pick some appropriate size
        }

        byte[] buf = new byte[512];
        while (true) {
            int len = is.read(buf);
            if (len == -1) {
                break;
            }
            baos.write(buf, 0, len);
        }
        return baos.toByteArray();
    } catch (MalformedURLException e) {
        LOG.error("Error in URL.", e);
        throw new LazyInitializationException("Error fetching NZB with URL  " + nzb.getUrl() + ".", e);
    } catch (IOException e) {
        LOG.error("IO error fetching lazy data.", e);
        throw new LazyInitializationException("IO error fetching NZB with URL  " + nzb.getUrl() + ".", e);
    } finally {
        if (throttler != null) {
            throttler.setThrottleForNextAction();
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                LOG.info("error closing stream.", e);
            }
        }
    }
}

From source file:com.datos.vfs.provider.url.UrlFileObject.java

/**
 * Returns the size of the file content (in bytes).
 *///w ww.j  a  va  2 s  . com
@Override
protected long doGetContentSize() throws Exception {
    final URLConnection conn = url.openConnection();
    final InputStream in = conn.getInputStream();
    try {
        return conn.getContentLength();
    } finally {
        in.close();
    }
}

From source file:org.josso.tooling.gshell.install.provider.maven2.MavenFileObject.java

@Override
protected long doGetContentSize() throws Exception {
    final URLConnection conn = uri.toURL().openConnection();
    final InputStream in = conn.getInputStream();
    try {// w  w  w . j a  v  a  2s.c om
        return conn.getContentLength();
    } finally {
        in.close();
    }
}

From source file:org.codehaus.mojo.license.model.LicenseRepository.java

protected boolean checkExists(URL url) throws IOException {
    URLConnection openConnection = url.openConnection();
    return openConnection.getContentLength() > 0;
}

From source file:javarestart.controllers.ApplicationController.java

@RequestMapping(value = "/{applicationName}", params = { "resource" }, method = RequestMethod.GET)
public void loadResource(@RequestParam(value = "resource") String resourceName,
        @PathVariable("applicationName") String applicationName, HttpServletResponse response)
        throws Exception {
    AppResourceProvider resourceProvider = getOrRegisterApp(applicationName);
    URLConnection resource = null;
    try {/*from   w w  w .  jav a  2s  .c  o m*/
        resource = resourceProvider.load(resourceName);
        resource.connect();
        response.setContentLength(resource.getContentLength());
        IOUtils.copy(resource.getInputStream(), response.getOutputStream());
        response.flushBuffer();
        logger.info("Class or resource loaded: " + resourceName);
    } catch (ResourceNotFoundException e) {
        logger.warning(e.toString());
        response.sendError(404);
    }
}

From source file:com.ebay.jetstream.application.dataflows.VisualDataFlow.java

public ByteBuffer getAsByteArray(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    InputStream in = connection.getInputStream();
    int contentLength = connection.getContentLength();
    ByteArrayOutputStream tmpOut;

    if (contentLength != -1) {
        tmpOut = new ByteArrayOutputStream(contentLength);
    } else {/* ww w .  j a va 2 s . co m*/
        tmpOut = new ByteArrayOutputStream(16384);
    }

    byte[] buf = new byte[BUF];
    while (true) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        tmpOut.write(buf, 0, len);
    }
    in.close();
    tmpOut.close();
    byte[] array = tmpOut.toByteArray();
    return ByteBuffer.wrap(array);
}

From source file:com.kryten2k35.otaupdater.tasks.UpdateDownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    mContext = getApplicationContext();//from w w  w.  j  a v a  2s. co m
    if (DEBUGGING)
        Log.d(TAG, "DownloadService started");
    remoteFileInfo = UpdaterApplication.getRemoteFileInfo();
    String filename = remoteFileInfo.getFilename();
    String fileUrl = remoteFileInfo.getDirectUrl();

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(filename.replaceAll("/", ""))
            .setContentText(getString(R.string.download_in_progress)).setSmallIcon(R.drawable.ic_notification)
            .setOngoing(true);

    Intent progressIntent = new Intent(DOWNLOAD_PROGRESS);

    try {
        InputStream input = null;

        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();

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

        String downloadLocation = Preferences.getDownloadLocation(mContext);
        File dir = new File(downloadLocation);
        File file = new File(downloadLocation + filename);
        dir.mkdirs();
        FileOutputStream fOut = new FileOutputStream(file);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        int percentDone = -1;

        if (DEBUGGING)
            Log.d(TAG, "DownloadService Downloading...");
        while ((count = input.read(data)) != -1 && !isCancelled) {
            total += count;
            // publishing the progress....
            int progress = (int) Math.round(total * 100 / fileLength);

            fOut.write(data, 0, count);

            if (percentDone != progress) {
                percentDone = progress;
                mBuilder.setProgress(100, progress, false);
                mNotifyManager.notify(0, mBuilder.build());
            }

            progressIntent.putExtra("progress", progress);
            progressIntent.putExtra("total", (int) total);
            sendBroadcast(progressIntent);
        }

        fOut.flush();
        fOut.close();
        input.close();
        mIsSuccessful = true;
    } catch (Exception e) {
        mIsSuccessful = false;
        Log.d(TAG, "Exception!", e);
    }

    if (mIsSuccessful) {
        if (isCancelled) {
            mBuilder.setContentText(getString(R.string.download_cancelled)).setProgress(0, 0, false)
                    .setOngoing(false);
            mNotifyManager.notify(0, mBuilder.build());
            sendBroadcast(new Intent(DOWNLOAD_CANCELLED));
        } else {
            mBuilder.setContentText(getString(R.string.download_complete)).setProgress(0, 0, false)
                    .setOngoing(false);
            mNotifyManager.notify(0, mBuilder.build());
            sendBroadcast(new Intent(DOWNLOAD_FINISHED));
        }
    }
}