Example usage for java.io BufferedInputStream close

List of usage examples for java.io BufferedInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:eu.esdihumboldt.hale.io.geoserver.AbstractResource.java

/**
 * @see eu.esdihumboldt.hale.io.geoserver.Resource#write(java.io.OutputStream)
 *//*from w w  w.  j  a v a2 s . co  m*/
@Override
public void write(OutputStream out) throws IOException {

    // unset unspecified variables by setting their value to null
    for (String var : this.allowedAttributes) {
        if (!this.attributes.containsKey(var)) {
            this.attributes.put(var, null);
        }
    }

    InputStream resourceStream = locateResource();
    if (resourceStream != null) {
        BufferedInputStream input = new BufferedInputStream(resourceStream);
        BufferedOutputStream output = new BufferedOutputStream(out);
        try {

            for (int b = input.read(); b >= 0; b = input.read()) {
                output.write(b);
            }
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                // ignore exception on close
            }
            try {
                output.close();
            } catch (IOException e) {
                // ignore exception on close
            }
        }
    }

}

From source file:com.wabacus.config.database.type.DB2.java

public byte[] getBlobValue(ResultSet rs, int iindex) throws SQLException {
    Blob blob = (Blob) rs.getBlob(iindex);
    if (blob == null)
        return null;
    BufferedInputStream bin = null;
    try {/*from www  .  jav a  2s .c  o  m*/
        bin = new BufferedInputStream(blob.getInputStream());
        return Tools.getBytesArrayFromInputStream(bin);
    } catch (Exception e) {
        log.error("?", e);
        return null;
    } finally {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:Main.java

public static String zip(String filename) throws IOException {
    BufferedInputStream origin = null;
    Integer BUFFER_SIZE = 20480;//from   w  w  w  .  j  a v a  2s .  co  m

    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        File flockedFilesFolder = new File(
                Environment.getExternalStorageDirectory() + File.separator + "FlockLoad");
        System.out.println("FlockedFileDir: " + flockedFilesFolder);
        String uncompressedFile = flockedFilesFolder.toString() + "/" + filename;
        String compressedFile = flockedFilesFolder.toString() + "/" + "flockZip.zip";
        ZipOutputStream out = new ZipOutputStream(
                new BufferedOutputStream(new FileOutputStream(compressedFile)));
        out.setLevel(9);
        try {
            byte data[] = new byte[BUFFER_SIZE];
            FileInputStream fi = new FileInputStream(uncompressedFile);
            System.out.println("Filename: " + uncompressedFile);
            System.out.println("Zipfile: " + compressedFile);
            origin = new BufferedInputStream(fi, BUFFER_SIZE);
            try {
                ZipEntry entry = new ZipEntry(
                        uncompressedFile.substring(uncompressedFile.lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }
            } finally {
                origin.close();
            }
        } finally {
            out.close();
        }
        return "flockZip.zip";
    }
    return null;
}

From source file:org.dataone.proto.trove.mn.service.v1.impl.MNStorageImpl.java

@Override
public Identifier create(Identifier pid, InputStream object, SystemMetadata sysmeta)
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
        InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
    try {/*from w ww .  java2  s . co m*/
        File systemMetadata = new File(dataoneCacheDirectory + File.separator + "meta" + File.separator
                + EncodingUtilities.encodeUrlPathSegment(pid.getValue()));
        TypeMarshaller.marshalTypeToFile(sysmeta, systemMetadata.getAbsolutePath());

        if (systemMetadata.exists()) {
            systemMetadata.setLastModified(sysmeta.getDateSysMetadataModified().getTime());
        } else {
            throw new ServiceFailure("1190", "SystemMetadata not found on FileSystem after create");
        }
        File objectFile = new File(dataoneCacheDirectory + File.separator + "object" + File.separator
                + EncodingUtilities.encodeUrlPathSegment(pid.getValue()));
        if (!objectFile.exists() && objectFile.createNewFile()) {
            objectFile.setReadable(true);
            objectFile.setWritable(true);
            objectFile.setExecutable(false);
        }

        if (object != null) {
            FileOutputStream objectFileOutputStream = new FileOutputStream(objectFile);
            BufferedInputStream inputStream = new BufferedInputStream(object);
            byte[] barray = new byte[SIZE];
            int nRead = 0;

            while ((nRead = inputStream.read(barray, 0, SIZE)) != -1) {
                objectFileOutputStream.write(barray, 0, nRead);
            }
            objectFileOutputStream.flush();
            objectFileOutputStream.close();
            inputStream.close();
        }
    } catch (FileNotFoundException ex) {
        throw new ServiceFailure("1190", ex.getCause().toString() + ":" + ex.getMessage());
    } catch (IOException ex) {
        throw new ServiceFailure("1190", ex.getMessage());
    } catch (JiBXException ex) {
        throw new InvalidSystemMetadata("1180", ex.getMessage());
    }
    return pid;
}

From source file:com.sharksharding.util.web.http.QueryViewServlet.java

/**
 * ????/*  w  w w  .  j  a v  a2  s  . com*/
 * 
 * @author gaoxianglong
 * 
 * @param path
 *            ?
 * 
 * @return byte[] ??
 */
protected byte[] initView(String path) {
    byte[] value = null;
    BufferedInputStream reader = null;
    try {
        reader = new BufferedInputStream(QueryViewServlet.class.getClassLoader().getResourceAsStream(path));
        value = new byte[reader.available()];
        reader.read(value);
    } catch (IOException e) {
        throw new FileNotFoundException("can not find config");
    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return value;
}

From source file:eionet.gdem.utils.Utils.java

/**
 *
 * @param f/*from   w w w.  jav a2 s  .  c om*/
 * @param algorithm
 * @return
 * @throws Exception
 */
public static String digest(File f, String algorithm) throws Exception {

    byte[] dstBytes = new byte[16];

    MessageDigest md;

    md = MessageDigest.getInstance(algorithm);

    BufferedInputStream in = null;

    int theByte = 0;
    try {
        in = new BufferedInputStream(new FileInputStream(f));
        while ((theByte = in.read()) != -1) {
            md.update((byte) theByte);
        }
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
    dstBytes = md.digest();
    md.reset();

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < dstBytes.length; i++) {
        Byte byteWrapper = new Byte(dstBytes[i]);
        int k = byteWrapper.intValue();
        String s = Integer.toHexString(k);
        if (s.length() == 1) {
            s = "0" + s;
        }
        buf.append(s.substring(s.length() - 2));
    }

    return buf.toString();
}

From source file:com.wabacus.config.database.type.DB2.java

public byte[] getBlobValue(ResultSet rs, String column) throws SQLException {
    Blob blob = (Blob) rs.getBlob(column);
    if (blob == null)
        return null;
    BufferedInputStream bin = null;
    try {//from   ww  w . ja  v a2s. co  m
        bin = new BufferedInputStream(blob.getInputStream());
        return Tools.getBytesArrayFromInputStream(bin);
    } catch (Exception e) {
        log.error("?" + column + "", e);
        return null;
    } finally {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.qut.middleware.metadata.source.impl.MetadataSourceBase.java

/**
 * Reads the provided input stream, calculates and updates an internal hash.
 * If the internal hash has changed, the byte array obtained from reading the
 * InputStream is passed to the processMetadata method, along with the
 * provided MetadataProcessor object.// w ww.ja va2s.  c  o  m
 * @param input Input stream to send 
 * @param processor
 * @throws IOException
 */
protected void readMetadata(InputStream input, MetadataProcessor processor) throws IOException {
    byte[] buf = new byte[BUFFER_LENGTH];
    long startTime = System.currentTimeMillis();

    // Pipe everything through a digest stream so we get a hash value at the end
    DigestInputStream digestInput = new DigestInputStream(input, this.getMessageDigestInstance());
    BufferedInputStream bufferedInput = new BufferedInputStream(digestInput);

    ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();

    this.logger.debug("Metadata source {} - going to read input stream", this.getLocation());
    int bytes = 0;
    while ((bytes = bufferedInput.read(buf)) != -1) {
        byteOutput.write(buf, 0, bytes);
    }

    bufferedInput.close();
    digestInput.close();
    byteOutput.close();

    long endTime = System.currentTimeMillis();

    byte[] document = byteOutput.toByteArray();
    byte[] hash = digestInput.getMessageDigest().digest();

    this.logger.debug("Metadata source {} - read {} bytes of metadata in {} ms",
            new Object[] { this.getLocation(), document.length, (endTime - startTime) });

    // If the document has changed, the hash will be updated, and then we go to process the new document
    if (this.updateDigest(hash)) {
        startTime = System.currentTimeMillis();
        this.logger.debug("Metadata source {} - updated. Going to process.", this.getLocation());
        this.processMetadata(document, processor);
        endTime = System.currentTimeMillis();
        this.logger.info("Metadata source {} - processed document and updated cache in {} ms",
                this.getLocation(), (endTime - startTime));
    } else {
        this.logger.info("Metadata source {} - has not been updated.", this.getLocation());
    }
}

From source file:org.anon.smart.smcore.test.channel.upload.TestUploadEvent.java

private String downloadFile(String file) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    String dwnFile = file + ".1";
    HttpGet httpget = new HttpGet("http://localhost:9020/errortenant/ErrorCases/DownloadEvent/" + file);
    HttpResponse response = httpclient.execute(httpget);
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {//from w w w .  j  a  v  a 2s  .co  m
            BufferedInputStream bis = new BufferedInputStream(instream);

            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(new File(projectHome + "/" + dwnFile)));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (RuntimeException ex) {
            httpget.abort();
            throw ex;
        } finally {
            instream.close();
        }
        httpclient.getConnectionManager().shutdown();
    }
    return dwnFile;
}

From source file:com.cloudseal.spring.client.namespace.CloudSealLogoutImageFilter.java

public void writeContent(HttpServletResponse response, String contentType, InputStream content)
        throws IOException {
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {/*from  w w w  .j ava2 s.  c  om*/
        input = new BufferedInputStream(content, DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length = 0;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        output.close();
        input.close();
    }
}