Example usage for java.io BufferedInputStream available

List of usage examples for java.io BufferedInputStream available

Introduction

In this page you can find the example usage for java.io BufferedInputStream available.

Prototype

public synchronized int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:eu.planets_project.tb.gui.backing.DownloadManager.java

/**
 * //from   w  w w. jav a 2  s  .  c o m
 * @return
 * @throws IOException
 */
public String downloadExportedExperiment(String expExportID, String downloadName) {
    FacesContext ctx = FacesContext.getCurrentInstance();

    // Decode the file name (might contain spaces and on) and prepare file object.
    try {
        expExportID = URLDecoder.decode(expExportID, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    File file = expCache.getExportedFile(expExportID);

    HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

    // Check if file exists and can be read:
    if (!file.exists() || !file.isFile() || !file.canRead()) {
        return "fileNotFound";
    }

    // Get content type by filename.
    String contentType = new MimetypesFileTypeMap().getContentType(file);

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open the file:
        input = new BufferedInputStream(new FileInputStream(file));
        int contentLength = input.available();

        // Initialise the servlet response:
        response.reset();
        response.setContentType(contentType);
        response.setContentLength(contentLength);
        response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\"");
        output = new BufferedOutputStream(response.getOutputStream());

        // Write file out:
        for (int data; (data = input.read()) != -1;) {
            output.write(data);
        }

        // Flush the stream:
        output.flush();

        // Tell Faces that we're finished:
        ctx.responseComplete();

    } catch (IOException e) {
        // Something went wrong?
        e.printStackTrace();

    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
    return "success";
}

From source file:com.aionengine.gameserver.cache.HTMLCache.java

public String loadFile(File file) {
    if (isLoadable(file)) {
        BufferedInputStream bis = null;
        try {//  w w  w.  jav  a  2  s.c o m
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] raw = new byte[bis.available()];
            bis.read(raw);

            String content = new String(raw, HTMLConfig.HTML_ENCODING);
            String relpath = getRelativePath(HTML_ROOT, file);

            size += content.length();

            String oldContent = cache.get(relpath);
            if (oldContent == null)
                loadedFiles++;
            else
                size -= oldContent.length();

            cache.put(relpath, content);

            return content;
        } catch (Exception e) {
            log.warn("Problem with htm file:", e);
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }

    return null;
}

From source file:edu.ku.brc.helpers.HTTPGetter.java

/**
 * Performs a "generic" HTTP request and fill member variable with results
 * use "getDigirResultsetStr" to get the results as a String
 *
 * @param url URL to be executed/*from w w  w .ja  v  a2  s .  co m*/
 * @param fileCache the file to place the results
 * @return returns an error code
 */
public byte[] doHTTPRequest(final String url, final File fileCache) {
    byte[] bytes = null;
    Exception excp = null;
    status = ErrorCode.NoError;

    // Create an HttpClient with the MultiThreadedHttpConnectionManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());

    GetMethod method = null;
    try {
        method = new GetMethod(url);

        //log.debug("getting " + method.getURI()); //$NON-NLS-1$
        httpClient.executeMethod(method);

        // get the response body as an array of bytes
        long bytesRead = 0;
        if (fileCache == null) {
            bytes = method.getResponseBody();
            bytesRead = bytes.length;

        } else {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileCache));
            bytes = new byte[4096];
            InputStream ins = method.getResponseBodyAsStream();
            BufferedInputStream bis = new BufferedInputStream(ins);
            while (bis.available() > 0) {
                int numBytes = bis.read(bytes);
                if (numBytes > 0) {
                    bos.write(bytes, 0, numBytes);
                    bytesRead += numBytes;
                }
            }

            bos.flush();
            bos.close();

            bytes = null;
        }

        log.debug(bytesRead + " bytes read"); //$NON-NLS-1$

    } catch (ConnectException ce) {
        excp = ce;
        log.error(String.format("Could not make HTTP connection. (%s)", ce.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (HttpException he) {
        excp = he;
        log.error(String.format("Http problem making request.  (%s)", he.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (IOException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (java.lang.IllegalArgumentException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (Exception e) {
        excp = e;
        log.error("Error: " + e); //$NON-NLS-1$
        status = ErrorCode.Error;

    } finally {
        // always release the connection after we're done
        if (isThrowingErrors && status != ErrorCode.NoError) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HTTPGetter.class, excp);
        }

        if (method != null)
            method.releaseConnection();
        //log.debug("Connection released"); //$NON-NLS-1$
    }

    if (listener != null) {
        if (status == ErrorCode.NoError) {
            listener.completed(this);
        } else {
            listener.completedWithError(this, status);
        }
    }

    return bytes;
}

From source file:com.aionemu.gameserver.cache.HTMLCache.java

public String loadFile(File file) {
    if (isLoadable(file)) {
        BufferedInputStream bis = null;
        try {/*  w ww  .j a  v  a 2s.c o m*/
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] raw = new byte[bis.available()];
            bis.read(raw);

            String content = new String(raw, HTMLConfig.HTML_ENCODING);
            String relpath = getRelativePath(HTML_ROOT, file);

            size += content.length();

            String oldContent = cache.get(relpath);
            if (oldContent == null) {
                loadedFiles++;
            } else {
                size -= oldContent.length();
            }

            cache.put(relpath, content);

            return content;
        } catch (Exception e) {
            log.warn("Problem with htm file:", e);
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }

    return null;
}

From source file:org.b3log.symphony.processor.CaptchaProcessor.java

/**
 * Loads captcha./*w w w.j ava2  s  .  c  o  m*/
 */
private synchronized void loadCaptchas() {
    LOGGER.trace("Loading captchas....");

    try {
        captchas = new Image[CAPTCHA_COUNT];

        ZipFile zipFile;

        if (RuntimeEnv.LOCAL == Latkes.getRuntimeEnv()) {
            final InputStream inputStream = SymphonyServletListener.class.getClassLoader()
                    .getResourceAsStream("captcha_static.zip");
            final File file = File.createTempFile("b3log_captcha_static", null);
            final OutputStream outputStream = new FileOutputStream(file);

            IOUtils.copy(inputStream, outputStream);
            zipFile = new ZipFile(file);

            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        } else {
            final URL captchaURL = SymphonyServletListener.class.getClassLoader()
                    .getResource("captcha_static.zip");

            zipFile = new ZipFile(captchaURL.getFile());
        }

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();

        int i = 0;

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();

            final BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    zipFile.getInputStream(entry));
            final byte[] captchaCharData = new byte[bufferedInputStream.available()];

            bufferedInputStream.read(captchaCharData);
            bufferedInputStream.close();

            final Image image = IMAGE_SERVICE.makeImage(captchaCharData);

            image.setName(entry.getName().substring(0, entry.getName().lastIndexOf('.')));

            captchas[i] = image;

            i++;
        }

        zipFile.close();
    } catch (final Exception e) {
        LOGGER.error("Can not load captchs!");

        throw new IllegalStateException(e);
    }

    LOGGER.trace("Loaded captch images");
}

From source file:org.chiba.xml.xforms.ui.UploadTest.java

/**
 * Tests ui element state./*from ww  w . j ava2 s. c  o  m*/
 *
 * @throws Exception if any error occurred during the test.
 */
public void testUploadBase64() throws Exception {
    Upload upload = (Upload) this.chibaBean.getContainer().lookup("upload-base64");
    upload.getTarget().addEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    String filename = "UploadTest.xhtml";
    String mediatype = "application/xhtml+xml";

    BufferedInputStream bis = new BufferedInputStream(getClass().getResourceAsStream(filename));
    byte[] data = new byte[bis.available()];
    bis.read(data);
    upload.setValue(data, filename, mediatype);
    upload.getTarget().removeEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    assertEquals(new String(data), new String(Base64.decodeBase64(((String) upload.getValue()).getBytes())));
    assertEquals(filename, upload.getFilename().getValue());
    assertEquals(mediatype, upload.getMediatype().getValue());

    ModelItem modelItem = upload.getModel().getInstance(upload.getInstanceId())
            .getModelItem(upload.getLocationPath());
    assertEquals(filename, modelItem.getFilename());
    assertEquals(mediatype, modelItem.getMediatype());

    assertEquals("upload-base64", this.valueChangedListener.getId());
}

From source file:org.chiba.xml.xforms.ui.UploadTest.java

/**
 * Tests ui element state.//from   ww  w  .  ja  v a2  s.  c om
 *
 * @throws Exception if any error occurred during the test.
 */
public void testUploadHex() throws Exception {
    Upload upload = (Upload) this.chibaBean.getContainer().lookup("upload-hex");
    upload.getTarget().addEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    String filename = "UploadTest.xhtml";
    String mediatype = "application/xhtml+xml";

    BufferedInputStream bis = new BufferedInputStream(getClass().getResourceAsStream(filename));
    byte[] data = new byte[bis.available()];
    bis.read(data);
    upload.setValue(data, filename, mediatype);
    upload.getTarget().removeEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    assertEquals(new String(data), new String(Hex.decodeHex(((String) upload.getValue()).toCharArray())));
    assertEquals(filename, upload.getFilename().getValue());
    assertEquals(mediatype, upload.getMediatype().getValue());

    ModelItem modelItem = upload.getModel().getInstance(upload.getInstanceId())
            .getModelItem(upload.getLocationPath());
    assertEquals(filename, modelItem.getFilename());
    assertEquals(mediatype, modelItem.getMediatype());

    assertEquals("upload-hex", this.valueChangedListener.getId());
}

From source file:com.esri.arcgisruntime.sample.choosecameracontroller.MainActivity.java

/**
 * Copy the given file from the app's assets folder to the app's cache directory.
 *
 * @param fileName as String/*from   ww  w.ja  v  a2 s. co m*/
 */
private void copyFileFromAssetsToCache(String fileName) {
    AssetManager assetManager = getApplicationContext().getAssets();
    File file = new File(getCacheDir() + File.separator + fileName);
    if (!file.exists()) {
        try {
            BufferedInputStream bis = new BufferedInputStream(assetManager.open(fileName));
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(getCacheDir() + File.separator + fileName));
            byte[] buffer = new byte[bis.available()];
            int read = bis.read(buffer);
            while (read != -1) {
                bos.write(buffer, 0, read);
                read = bis.read(buffer);
            }
            bos.close();
            bis.close();
            Log.i(TAG, fileName + " copied to cache.");
        } catch (Exception e) {
            Log.e(TAG, "Error writing " + fileName + " to cache. " + e.getMessage());
        }
    } else {
        Log.i(TAG, fileName + " already in cache.");
    }
}

From source file:com.l2jfree.gameserver.cache.HtmCache.java

public String loadFile(File file) {
    if (isLoadable(file)) {
        BufferedInputStream bis = null;
        try {/*from   w  ww  . ja v a  2 s. c o m*/
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] raw = new byte[bis.available()];
            bis.read(raw);

            String content = new String(raw, "UTF-8");
            String relpath = Util.getRelativePath(Config.DATAPACK_ROOT, file);

            _size += content.length();

            String oldContent = _cache.get(relpath);
            if (oldContent == null)
                _loadedFiles++;
            else
                _size -= oldContent.length();

            _cache.put(relpath, content);

            return content;
        } catch (Exception e) {
            _log.warn("Problem with htm file:", e);
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }

    return null;
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public byte[] readDataToByteArray(URL url) throws Exception {

    byte[] data = null;

    if (!isSetup())
        setup();/* w w  w  .  j  ava 2  s  .c  o  m*/

    GetMethod method = new GetMethod(url.toString());

    try {
        int statusCode = client.executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {

            BufferedInputStream inputStream = new BufferedInputStream(method.getResponseBodyAsStream());
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream(inputStream.available());

            byte[] tmpBuf = new byte[1000];
            int bytesRead;

            while ((bytesRead = inputStream.read(tmpBuf, 0, tmpBuf.length)) != -1) {
                byteStream.write(tmpBuf, 0, bytesRead);
            }

            inputStream.close();
            data = byteStream.toByteArray();
        } else {
            log.warn("HttpStatus statusCode:" + statusCode);
            log.warn("HttpStatus.SC_OK:" + HttpStatus.SC_OK);
        }

    } catch (Exception e) {
        log.warn("Exception:" + e.getMessage(), e);
        throw new Exception(e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return data;
}