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:at.medevit.elexis.ehc.core.internal.EhcCoreServiceTest.java

private File createTempFile(String string) throws IOException {
    File ret = File.createTempFile("test_", ".tmp");
    if (ret != null) {
        try (FileOutputStream output = new FileOutputStream(ret)) {
            BufferedInputStream input = new BufferedInputStream(getClass().getResourceAsStream(string));
            IOUtils.copy(input, output);
            input.close();
        }//from w ww  . ja  v a 2  s . c  o  m
    }
    return ret;
}

From source file:com.sec.ose.osi.util.tools.FileOperator.java

public static void copyFile(File pSource, File pDest) throws FileNotFoundException {

    if (pSource == null)
        throw new FileNotFoundException("Source file is not found");

    if (pSource.exists() == false)
        throw new FileNotFoundException(pSource.getPath());

    if (pDest == null)
        throw new FileNotFoundException("Report file is not found");

    BufferedInputStream bi = null;
    BufferedOutputStream bo = null;

    try {/*w w w.  ja v  a2s .c o  m*/
        bi = new BufferedInputStream(new FileInputStream(pSource)); // FileNotFoundExeption
        bo = new BufferedOutputStream(new FileOutputStream(pDest));

        byte buffer[] = new byte[BUF_SIZE];

        int readByte = 0;

        while ((readByte = bi.read(buffer)) != -1) { // IOException
            bo.write(buffer, 0, readByte);

        }

    } catch (FileNotFoundException e) {
        log.warn(e);
        throw e;
    } catch (IOException e) {
        log.warn(e);
    } finally {

        if (bo != null) {
            try {
                bo.flush();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.warn(e);
            }
            try {
                bo.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.warn(e);
            }

            bo = null;
        }
        if (bi != null) {
            try {
                bi.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.warn(e);
            }
            bi = null;
        }
    }

}

From source file:it.eng.spagobi.kpi.service.KpiExporterAction.java

/**
 * This action is called by the user who wants to export the result of a Kpi in PDF
 * /*from w  w w  . j a  v a  2s  .  co  m*/
 */

public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws Exception {

    File tmpFile = null;
    logger.debug("IN");
    HttpServletRequest httpRequest = getHttpRequest();
    HttpSession session = httpRequest.getSession();

    this.freezeHttpResponse();

    try {
        // get KPI result
        List<KpiResourceBlock> listKpiBlocks = (List<KpiResourceBlock>) session.getAttribute("KPI_BLOCK");

        //List<KpiResourceBlock> listKpiBlocks=executeKpi(objectId);

        // recover BiObject Name
        Object idObject = serviceRequest.getAttribute(SpagoBIConstants.OBJECT_ID);
        if (idObject == null) {
            logger.error("Document id not found");
            return;
        }

        Integer id = Integer.valueOf(idObject.toString());
        BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(id);
        String docName = document.getName();

        //Recover user Id
        HashedMap parameters = new HashedMap();
        String userId = null;
        Object userIdO = serviceRequest.getAttribute("user_id");
        if (userIdO != null)
            userId = userIdO.toString();

        it.eng.spagobi.engines.exporters.KpiExporter exporter = new KpiExporter();
        tmpFile = exporter.getKpiReportPDF(listKpiBlocks, document, userId);

        String outputType = "PDF";

        String mimeType = "application/pdf";

        logger.debug("Report exported succesfully");

        HttpServletResponse response = getHttpResponse();
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
        response.setContentLength((int) tmpFile.length());

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
        logger.debug("OUT");

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {

        tmpFile.delete();

    }
}

From source file:pl.lewica.util.FileUtil.java

public static boolean fetchAndSaveImage(String sourceUrl, String destinationPath, boolean overwrite)
        throws IOException {
    File destinationFile = new File(destinationPath);
    if (destinationFile.exists() && !overwrite) {
        return false;
    }//from ww w  . j  a  v  a  2  s  .c o m

    BufferedInputStream bis = null;
    FileOutputStream fos = null;

    try {
        URL url = new URL(sourceUrl);
        // See http://stackoverflow.com/questions/3498643/dalvik-message-default-buffer-size-used-in-bufferedinputstream-constructor-it/7516554#7516554
        int bufferSize = 8192;
        bis = new BufferedInputStream(url.openStream(), bufferSize);
        ByteArrayBuffer bab = new ByteArrayBuffer(50);

        int current = 0;
        while ((current = bis.read()) != -1) {
            bab.append((byte) current);
        }

        fos = new FileOutputStream(destinationFile);
        fos.write(bab.toByteArray());
        fos.close();
    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioe) {
                // This issue can be safely skipped but there's no harm in logging it
                Log.w("FileUtil", "Unable to close file output stream for " + sourceUrl);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
                // This issue can be safely skipped but there's no harm in logging it
                Log.w("FileUtil", "Unable to close buffered input stream for " + sourceUrl);
            }
        }
    }

    return true;
}

From source file:cn.vlabs.clb.server.web.FileInfo.java

public String getSHA256() throws IOException {
    File file = this.getFile();
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] temp = new byte[1024];
    int size = 0;
    while ((size = in.read(temp)) != -1) {
        out.write(temp, 0, size);/*from  w ww .ja  va 2 s  . c  o  m*/
    }
    in.close();

    byte[] content = out.toByteArray();

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(content);
        String output = Hex.encodeHexString(hash);
        System.out.println(output);
        return output;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:dk.deck.resolver.util.ZipUtils.java

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
        return;// w  w w.  ja  v  a2s.  c o m
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    // log.debug("Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

From source file:it.eng.spagobi.kpi.service.KpiXmlExporterAction.java

/**
 * This action is called by the user who wants to export the result of a Kpi in XML
 * //from w  w  w.  j a va 2s  .c o m
 */

public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws Exception {

    File tmpFile = null;
    logger.debug("IN");
    HttpServletRequest httpRequest = getHttpRequest();
    HttpSession session = httpRequest.getSession();

    this.freezeHttpResponse();

    try {
        // get KPI result
        List<KpiResourceBlock> listKpiBlocks = (List<KpiResourceBlock>) session.getAttribute("KPI_BLOCK");
        String title = (String) session.getAttribute("TITLE");
        String subtitle = (String) session.getAttribute("SUBTITLE");
        if (title == null)
            title = "";
        if (subtitle == null)
            subtitle = "";

        // recover BiObject Name
        Object idObject = serviceRequest.getAttribute(SpagoBIConstants.OBJECT_ID);
        if (idObject == null) {
            logger.error("Document id not found");
            return;
        }

        Integer id = Integer.valueOf(idObject.toString());
        BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(id);
        String docName = document.getName();

        //Recover user Id
        HashedMap parameters = new HashedMap();
        String userId = null;
        Object userIdO = serviceRequest.getAttribute("user_id");
        if (userIdO != null)
            userId = userIdO.toString();

        it.eng.spagobi.engines.exporters.KpiExporter exporter = new KpiExporter();
        tmpFile = exporter.getKpiExportXML(listKpiBlocks, document, userId);

        String outputType = "XML";

        String mimeType = "text/xml";

        logger.debug("Report exported succesfully");

        HttpServletResponse response = getHttpResponse();
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
        response.setContentLength((int) tmpFile.length());

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
        logger.debug("OUT");

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {

        tmpFile.delete();

    }
}

From source file:com.athena.dolly.websocket.client.test.WebSocketClient.java

public void sendFile(File file) throws Exception {
    // Send 10 messages and wait for responses
    System.out.println("WebSocket Client sending file ->" + file.getAbsolutePath());
    //for (int i = 0; i < 10; i++) {
    //    ch.writeAndFlush(new TextWebSocketFrame("Message #" + i));
    //}//from   w w w.j a v  a 2 s  . co  m

    ch.writeAndFlush(new TextWebSocketFrame(file.getAbsolutePath()));

    // Binary File Data Send
    byte[] buf = new byte[65536];
    int len = 0;

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

    while ((len = bis.read(buf)) != -1) {
        ch.write(new BinaryWebSocketFrame(Unpooled.copiedBuffer(buf, 0, len)));
    }

    ch.flush();
    System.out.println("File send succeed");

    bis.close();

    // Ping
    System.out.println("WebSocket Client sending ping");
    ch.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));

}

From source file:com.ibm.dbwkl.helper.CryptionModule.java

/**
 * @param path// w w w . jav a2s. c  o m
 * @return byte Array with the encrypted password
 * @throws IOException
 */
public String readPassfile(String path) throws IOException {
    String encryptedPassword;
    byte[] passbytes;

    if (path != null) {
        if (path.length() != 0) {
            this.passpath = path;
        }
    }

    File passfile = new File(this.passpath);
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(passfile));
    passbytes = new byte[(int) passfile.length()];
    bis.read(passbytes);
    bis.close();

    encryptedPassword = new String(passbytes, "UTF8");

    return encryptedPassword;
}

From source file:com.teasoft.teavote.util.Signature.java

/**
 * Signs a given sql backup digitally. The file to sign is modified by
 * prepending the public key to it. The resultant file is digitally signed.
 * The public key is removed and a caution message and the digital signature
 * is written at the top of the file./*from   ww w.  j  a va  2 s  . co  m*/
 *
 * In verifying the file, the caution message and digital signature must be
 * replaced with the public key
 *
 * @param pathToData
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws InvalidKeySpecException
 */
public void signData(String pathToData) throws FileNotFoundException, IOException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
    String pathToDuplicate = new ConfigLocation().getConfigPath() + File.separator + "duplicate.sql";
    try ( //Create a copy of the file
            FileInputStream originalFileIs = new FileInputStream(pathToData)) {
        File duplicateFile = new File(pathToDuplicate);
        try (FileOutputStream fos = new FileOutputStream(duplicateFile)) {
            fos.write(IOUtils.toByteArray(originalFileIs));
            //fos.flush();
            originalFileIs.close();
        }
    }

    byte[] buffer = new byte[1024];
    int nRead = 0;

    java.security.Signature dsa = java.security.Signature.getInstance("SHA1withDSA", "SUN");
    dsa.initSign(getPrivateKey());
    FileInputStream fis = new FileInputStream(pathToData);
    BufferedInputStream bufin = new BufferedInputStream(fis);
    int len;
    while ((len = bufin.read(buffer)) >= 0) {
        dsa.update(buffer, 0, len);
    }
    ;
    bufin.close();
    byte[] realSig = dsa.sign();

    //Create file starting with the signature
    String sigString = "-- " + Base64.encodeBase64String(realSig);
    String caution = "-- CAUTION: THIS FILE IS DIGITALLY SIGNED. DO NOT MODIFY IT. ANY CHANGE WILL RENDER IT UNRESTORABLE";

    FileOutputStream signedDataFw = new FileOutputStream(pathToData);
    signedDataFw.write("--\n".getBytes());
    signedDataFw.write((caution + "\n").getBytes());
    signedDataFw.write((sigString + "\n").getBytes());
    signedDataFw.write("--\n".getBytes());
    signedDataFw.write("\n".getBytes());
    //Write data to file.
    File duplicateFile = new File(pathToDuplicate);
    FileInputStream duplicateFileReader = new FileInputStream(duplicateFile);

    while ((nRead = duplicateFileReader.read(buffer)) != -1) {
        signedDataFw.write(buffer, 0, nRead);
    }
    //signedDataFw.flush();
    signedDataFw.close();
    duplicateFileReader.close();
    duplicateFile.delete();
}