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:net.sf.markov4jmeter.testplangenerator.util.Configuration.java

/**
 * Loads the key/value pairs from a specified properties file.
 *
 * @param filename  name of the properties file to be loaded.
 *
 * @throws FileNotFoundException//from w w w. j  a v  a 2s . c  o  m
 *     in case the denoted file does not exist.
 * @throws IOException
 *     if any error while reading occurs.
 * @throws NullPointerException
 *     if <code>null</code> is passed as filename.
 */
public void load(final String filename) throws FileNotFoundException, IOException {

    // might throw a FileNotFoundException;
    final FileInputStream fileInputStream = new FileInputStream(filename);

    final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

    try {

        // might throw an IO- or IllegalArgumentException;
        this.load(bufferedInputStream);

    } finally {

        if (bufferedInputStream != null) {

            try {

                bufferedInputStream.close();

            } catch (final IOException ex) {

                // ignore IOException, since this is the "finally" block;
                // TODO: error message could be written into log-file;
            }
        }
    }
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private void doDownloadUrlToFile(URL downloadURL, File downloadFile) throws Exception {
    HttpClient client = createHttpClient(downloadURL);
    HttpMethod getRequest = new GetMethod(downloadURL.toString());
    try {//  w  w  w .  j av  a  2s.  c o  m
        int status = -1;
        for (int attempts = 0; attempts < MAX_ATTEMPTS && status != HTTP_SUCCESS_CODE; attempts++)
            status = client.executeMethod(getRequest);
        if (status != HTTP_SUCCESS_CODE)
            throw new Exception("Got " + status + " status trying to download file " + downloadURL.toString()
                    + " to " + downloadFile.toString());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(downloadFile));
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            out.write(block, 0, bytes);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        throw e;
    } finally {
        getRequest.releaseConnection();
    }
}

From source file:Thumbnail.java

public void doWork(String[] args) {
    try {//from   ww  w  . ja  v  a 2 s  .  c om
        byte[] bytes = new byte[50000];

        FileInputStream fs = new FileInputStream(args[2]);
        BufferedInputStream bis = new BufferedInputStream(fs);
        bis.read(bytes);

        ID id = new ID();
        id.nail_id = Integer.parseInt(args[0]);
        id.acc_id = Integer.parseInt(args[1]);

        statement = connection.prepareStatement("INSERT INTO thumbnail VALUES(?,?,?,?, 0, now())");

        statement.setInt(1, id.nail_id);
        statement.setInt(2, id.acc_id);
        statement.setBytes(3, bytes);
        statement.setObject(4, id);

        int i = statement.executeUpdate();
        System.out.println("Rows updated = " + i);

        bis.close();
        fs.close();
        statement.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:JarBuilder.java

/** Adds the file to the given path and name
 *
 * @param file     the file to be added//  ww  w  .  ja va 2s  .  co  m
 * @param parent   the directory to the path in which the file is to be added
 * @param fileName the name of the file in the archive
 */
public void addFile(File file, String parent, String fileName) throws IOException {
    byte data[] = new byte[2048];

    FileInputStream fi = new FileInputStream(file.getAbsolutePath());
    BufferedInputStream origin = new BufferedInputStream(fi, 2048);

    JarEntry entry = new JarEntry(makeName(parent, fileName));
    _output.putNextEntry(entry);

    int count = origin.read(data, 0, 2048);
    while (count != -1) {
        _output.write(data, 0, count);
        count = origin.read(data, 0, 2048);
    }

    origin.close();
}

From source file:DatabaseListener.java

/**
 * <p>Calculate and return an absolute pathname to the XML file to contain
 * our persistent storage information.</p>
 *
 * @return Absolute path to XML file./*  w w w.ja  va2  s  .com*/
 * @throws Exception if an input/output error occurs
 */
private String calculatePath() throws Exception {

    // Can we access the database via file I/O?
    String path = context.getRealPath(pathname);
    if (path != null) {
        return (path);
    }

    // Does a copy of this file already exist in our temporary directory
    File dir = (File) context.getAttribute("javax.servlet.context.tempdir");
    File file = new File(dir, "struts-example-database.xml");
    if (file.exists()) {
        return (file.getAbsolutePath());
    }

    // Copy the static resource to a temporary file and return its path
    InputStream is = context.getResourceAsStream(pathname);
    BufferedInputStream bis = new BufferedInputStream(is, 1024);
    FileOutputStream os = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
    byte buffer[] = new byte[1024];
    while (true) {
        int n = bis.read(buffer);
        if (n <= 0) {
            break;
        }
        bos.write(buffer, 0, n);
    }
    bos.close();
    bis.close();
    return (file.getAbsolutePath());

}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * @param req servlet request/* w  w w.j a  va 2s  .c om*/
 * @param resp servlet response
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    URL url = getURL(req, req.getParameter("uri"));
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(true);
    con.setAllowUserInteraction(false);
    con.setUseCaches(false);

    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    // pass along all appropriate HTTP headers
    Enumeration headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hname = (String) headerNames.nextElement();
        if (!unproxiedHeaders.contains(hname.toLowerCase())) {
            con.addRequestProperty(hname, req.getHeader(hname));
        }
    }
    con.connect();

    // read POST data from incoming request, write to outgoing request
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    // read result headers of POST, write to response
    Map<String, List<String>> headers = con.getHeaderFields();
    for (String key : headers.keySet()) {
        if (key != null) { // TODO: why is this check necessary!
            List<String> header = headers.get(key);
            if (header.size() > 0)
                resp.setHeader(key, header.get(0));
        }
    }

    // read result data of POST, write out to response
    in = new BufferedInputStream(con.getInputStream());
    out = new BufferedOutputStream(resp.getOutputStream());
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    con.disconnect();
}

From source file:nl.phanos.liteliveresultsclient.LoginHandler.java

public void getZip() throws Exception {
    String url = "https://www.atletiek.nu/feeder.php?page=exportstartlijstentimetronics&event_id=" + nuid
            + "&forceAlleenGeprinteLijsten=1";
    System.out.println(url);/*from www .j a  va  2  s.c om*/
    HttpGet request = new HttpGet(url);

    request.setHeader("User-Agent", USER_AGENT);
    request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.setHeader("Accept-Language", "en-US,en;q=0.5");
    request.setHeader("Cookie", getCookies());

    HttpResponse response = client.execute(request);
    int responseCode = response.getStatusLine().getStatusCode();

    System.out.println("Response Code : " + responseCode);
    //System.out.println(convertStreamToString(response.getEntity().getContent())); 
    BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
    String filePath = "tmp.zip";
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
    int inByte;
    while ((inByte = bis.read()) != -1) {
        bos.write(inByte);
    }
    bis.close();
    bos.close();

    // set cookies
    setCookies(response.getFirstHeader("Set-Cookie") == null ? ""
            : response.getFirstHeader("Set-Cookie").toString());
    request.releaseConnection();
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected static String getFileXmlVersion(File f) throws IOException {
    String ret = null;//w  w  w.ja v  a  2s.c o  m
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
    byte[] bb = new byte[255];
    bis.read(bb);
    String buff = new String(bb);
    buff = buff.substring(buff.indexOf("<?"));
    buff = buff.substring(0, buff.indexOf("?>") + 2);
    String header = buff;
    int versionPos = header.indexOf("version=");
    if (versionPos >= 0) {
        String s = header.substring(versionPos + 8);
        if (s.startsWith("\"")) {
            ret = s.substring(1, s.indexOf('"', 1));
        } else if (s.startsWith("'")) {
            ret = s.substring(1, s.indexOf('\'', 1));
        } else {
            s = s.substring(0, s.length() - 2).trim();
            if (s.indexOf(' ') > 0) {
                ret = s.substring(0, s.indexOf(' '));
            } else {
                ret = s;
            }
        }
    } else {
        ret = (new InputStreamReader(new FileInputStream(f))).getEncoding();
    }
    bis.close();
    logger.debug("version=" + ret);
    return ret;
}

From source file:it.eng.spagobi.analiticalmodel.execution.service.PrintNotesAction.java

public void doService() {
    logger.debug("IN");

    ExecutionInstance executionInstance;
    executionInstance = getContext().getExecutionInstance(ExecutionInstance.class.getName());
    String executionIdentifier = new BIObjectNotesManager()
            .getExecutionIdentifier(executionInstance.getBIObject());
    Integer biobjectId = executionInstance.getBIObject().getId();
    List globalObjNoteList = null;
    try {/*from   w w  w .  java2  s  .c o m*/
        globalObjNoteList = DAOFactory.getObjNoteDAO().getListExecutionNotes(biobjectId, executionIdentifier);
    } catch (EMFUserError e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    } catch (Exception e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    }
    //mantains only the personal notes and others one only if they have PUBLIC status
    List objNoteList = new ArrayList();
    UserProfile profile = (UserProfile) this.getUserProfile();
    String userId = (String) profile.getUserId();
    for (int i = 0, l = globalObjNoteList.size(); i < l; i++) {
        ObjNote objNote = (ObjNote) globalObjNoteList.get(i);
        if (objNote.getIsPublic()) {
            objNoteList.add(objNote);
        } else if (objNote.getOwner().equalsIgnoreCase(userId)) {
            objNoteList.add(objNote);
        }
    }

    String outputType = "PDF";
    RequestContainer requestContainer = getRequestContainer();
    SourceBean sb = requestContainer.getServiceRequest();
    outputType = (String) sb.getAttribute(SBI_OUTPUT_TYPE);
    if (outputType == null)
        outputType = "PDF";

    String templateStr = getTemplateTemplate();

    //JREmptyDataSource conn=new JREmptyDataSource(1);
    //Connection conn = getConnection("SpagoBI",getHttpSession(),profile,obj.getId().toString());      
    JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(objNoteList);

    HashedMap parameters = new HashedMap();
    parameters.put("PARAM_OUTPUT_FORMAT", outputType);
    parameters.put("TITLE", executionInstance.getBIObject().getLabel());

    UUIDGenerator uuidGen = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    String executionId = uuid_local.toString();
    executionId = executionId.replaceAll("-", "");
    //Creta etemp file
    String dirS = System.getProperty("java.io.tmpdir");
    File dir = new File(dirS);
    dir.mkdirs();
    String fileName = "notes" + executionId;
    OutputStream out = null;
    File tmpFile = null;
    try {
        tmpFile = File.createTempFile(fileName, "." + outputType, dir);
        out = new FileOutputStream(tmpFile);
        StringBufferInputStream sbis = new StringBufferInputStream(templateStr);
        logger.debug("compiling report");
        JasperReport report = JasperCompileManager.compileReport(sbis);
        //report.setProperty("", )
        logger.debug("filling report");
        JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, datasource);
        JRExporter exporter = null;
        if (outputType.equalsIgnoreCase("PDF")) {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRPdfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRPdfExporter();
        } else {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRRtfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRRtfExporter();
        }

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        logger.debug("exporting report");
        exporter.exportReport();

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        return;
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("Error closing output", e);
        }
    }

    String mimeType;
    if (outputType.equalsIgnoreCase("RTF")) {
        mimeType = "application/rtf";
    } else {
        mimeType = "application/pdf";
    }

    HttpServletResponse response = getHttpResponse();
    response.setContentType(mimeType);
    response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
    response.setContentLength((int) tmpFile.length());
    try {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
    } catch (Exception e) {
        logger.error("Error while writing the content output stream", e);
    } finally {
        tmpFile.delete();
    }

    logger.debug("OUT");

}

From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public List<String> getFilesExists(List<String> fileNames) {
    List<String> ret = new ArrayList<String>();
    try {/*from  www .j  a v a 2  s  .c om*/
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn;
        ftpClient.enterLocalPassiveMode();
        for (String nombre : fileNames) {
            buffIn = new BufferedInputStream(ftpClient
                    .retrieveFileStream(params.get("remoteRetreiveFiles") + REMOTE_SEPARATOR + nombre));//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 150) {
                System.out.println("Archivo obtenido exitosamente");
                buffIn.close();
                ret.add(nombre);
            } else {
                System.out.println(
                        "No se pudo obtener el archivo: " + nombre + ", codigo:" + ftpClient.getReplyCode());
            }
        }

        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    return ret;
}