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:com.unboundid.scim.marshal.json.JsonUnmarshaller.java

/**
 * {@inheritDoc}//  www. j  av a2  s .co m
 */
public void bulkUnmarshal(final File file, final BulkConfig bulkConfig, final BulkContentHandler handler)
        throws SCIMException {
    // First pass: ensure the number of operations is less than the max,
    // and save the failOnErrrors value.
    final AtomicInteger failOnErrorsValue = new AtomicInteger(-1);
    final BulkContentHandler preProcessHandler = new BulkContentHandler() {
        @Override
        public void handleFailOnErrors(final int failOnErrors) {
            failOnErrorsValue.set(failOnErrors);
        }
    };
    try {
        final FileInputStream fileInputStream = new FileInputStream(file);
        try {
            final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            try {
                final JsonBulkParser jsonBulkParser = new JsonBulkParser(bufferedInputStream, bulkConfig,
                        preProcessHandler);
                jsonBulkParser.setSkipOperations(true);
                jsonBulkParser.unmarshal();
            } finally {
                bufferedInputStream.close();
            }
        } finally {
            fileInputStream.close();
        }
    } catch (IOException e) {
        Debug.debugException(e);
        throw new ServerErrorException("Error pre-processing bulk request: " + e.getMessage());
    }

    int failOnErrors = failOnErrorsValue.get();
    if (failOnErrors != -1) {
        handler.handleFailOnErrors(failOnErrors);
    }

    // Second pass: Parse fully.
    try {
        final FileInputStream fileInputStream = new FileInputStream(file);
        try {
            final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            try {
                final JsonBulkParser jsonBulkParser = new JsonBulkParser(bufferedInputStream, bulkConfig,
                        handler);
                jsonBulkParser.unmarshal();
            } finally {
                bufferedInputStream.close();
            }
        } finally {
            fileInputStream.close();
        }
    } catch (IOException e) {
        Debug.debugException(e);
        throw new ServerErrorException("Error parsing bulk request: " + e.getMessage());
    }
}

From source file:com.naryx.tagfusion.cfm.tag.net.ftp.cfFTPData.java

public void uploadFile(File fileLocal, String remoteFile) {
    if (!ftpclient.isConnected()) {
        errorText = "not connected";
        succeeded = false;/*  w  w  w.  j ava 2s .  c  om*/
        return;
    }

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    try {

        ftpclient.setAutodetectUTF8(true);

        fis = new FileInputStream(fileLocal);
        bis = new BufferedInputStream(fis);
        ftpclient.storeFile(remoteFile, bis);
        bis.close();

        errorCode = ftpclient.getReplyCode();
        succeeded = FTPReply.isPositiveCompletion(errorCode);

    } catch (Exception e) {
        errorCode = ftpclient.getReplyCode();
        errorText = e.getMessage();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
        setStatusData();
    }
}

From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.GeekIncLogoDownloadService.java

private void saveAndResizeFile(File tmpFile, File outFile, int requiredSize)
        throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(tmpFile);
    BufferedInputStream bfis = new BufferedInputStream(fis);

    // Recherche de la taille sans charger entirement l'image
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;/*from w ww.  jav a 2  s.  c  o  m*/
    BitmapFactory.decodeStream(bfis, null, o);

    // Calcule la bonne mise  l'chelle en cherchant la puissance de 2 la
    // plus proche
    int scale = 1;
    while (o.outWidth / scale / 2 >= requiredSize && o.outHeight / scale / 2 >= requiredSize)
        scale *= 2;

    // Mise  l'chelle !
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;

    bfis.close();
    fis.close();

    fis = new FileInputStream(tmpFile);
    bfis = new BufferedInputStream(fis);
    Bitmap bmp = BitmapFactory.decodeStream(bfis, null, o2);
    bfis.close();

    FileOutputStream fout = new FileOutputStream(outFile);
    BufferedOutputStream bout = new BufferedOutputStream(fout);
    bmp.compress(Bitmap.CompressFormat.PNG, 90, bout);
    bout.close();
    fout.close();
}

From source file:com.cloud.storage.template.VhdProcessor.java

private boolean checkCompressed(String fileName) throws IOException {

    FileInputStream fin = null;//from w w  w.  j av  a2s  .  c  o  m
    BufferedInputStream bin = null;
    CompressorInputStream cin = null;

    try {
        fin = new FileInputStream(fileName);
        bin = new BufferedInputStream(fin);
        cin = new CompressorStreamFactory().createCompressorInputStream(bin);

    } catch (CompressorException e) {
        s_logger.warn(e.getMessage());
        return false;

    } catch (FileNotFoundException e) {
        s_logger.warn(e.getMessage());
        return false;
    } finally {
        if (cin != null)
            cin.close();
        else if (bin != null)
            bin.close();
    }
    return true;
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public OriHttpPage getPost(HttpClient client, String action, NameValuePair[] data) {
    PostMethod post = new PostMethod(action);

    post.setRequestBody(data);//from  w  ww.  jav  a2  s  . c  o  m

    try {

        int c = client.executeMethod(post);

        BufferedInputStream remoteBIS = new BufferedInputStream(post.getResponseBodyAsStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);
        byte[] buf = new byte[1024];
        int bytesRead = 0;
        while (bytesRead >= 0) {
            baos.write(buf, 0, bytesRead);
            bytesRead = remoteBIS.read(buf);
        }
        remoteBIS.close();
        byte[] content = baos.toByteArray();
        //        byte[] content=get.getResponseBody();

        ConnResponse conRes = new ConnResponse(post.getResponseHeader("Content-type").getValue(), null, 0, 0,
                post.getStatusCode());
        return new OriHttpPage(action, content, conRes, Constants.CHARTSET_DEFAULT);
    } catch (IOException ioe) {
        log.warn("Caught IO Exception: " + ioe.getMessage(), ioe);
        ioe.printStackTrace();
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(null, null);
    }
}

From source file:com.stimulus.archiva.extraction.MessageExtraction.java

private void writeAttachment(Part p, String filename) {
    filename = getFilename(filename, "attachment.att");
    File attachFile = new File(Config.getFileSystem().getViewPath() + File.separatorChar + filename);
    OutputStream os = null;/*from w  ww. ja v  a 2  s . c o  m*/
    InputStream is = null;
    try {
        logger.debug("writing attachment {filename='" + attachFile.getAbsolutePath() + "'}");
        os = new BufferedOutputStream(new FileOutputStream(attachFile));
        is = p.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        int c = 0;
        while ((c = bis.read()) != -1) {
            os.write(c);
        }
        os.close();
        bis.close();
        Config.getFileSystem().getTempFiles().markForDeletion(attachFile);
    } catch (Exception ex) {
        logger.error("failed to write attachment {filename='" + attachFile + "'}", ex);
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.shmsoft.dmass.main.ActionStaging.java

private boolean downloadUri(String[] dirs) throws Exception {
    boolean anyDownload = false;
    File downloadDirFile = new File(ParameterProcessing.DOWNLOAD_DIR);
    if (downloadDirFile.exists()) {
        Util.deleteDirectory(downloadDirFile);
    }//from www  .j a  va 2 s  .com
    new File(ParameterProcessing.DOWNLOAD_DIR).mkdirs();

    List<DownloadItem> downloadItems = new ArrayList<>();

    for (String dir : dirs) {
        URI uri = null;

        String path;
        String savePath;
        try {
            uri = new URI(dir);
            path = uri.getPath();
            path = StringUtils.replace(path, "/", "");
            savePath = ParameterProcessing.DOWNLOAD_DIR + "/" + path;

            DownloadItem di = new DownloadItem();
            di.uri = uri;
            di.file = dir;
            di.savePath = savePath;

            downloadItems.add(di);
        } catch (URISyntaxException e) {
            History.appendToHistory("Incorrect URI syntax, skipping that: " + uri);
            continue;
        }
    }

    setDownloadState(downloadItems.size());

    for (DownloadItem di : downloadItems) {
        try {
            if (interrupted) {
                return anyDownload;
            }

            setProcessingFile(di.uri.toString());

            URL url = new URL(di.file);
            URLConnection con = url.openConnection();
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            FileOutputStream out = new FileOutputStream(di.savePath);
            History.appendToHistory("Download from " + di.uri + " to " + di.savePath);
            int i;
            byte[] bytesIn = new byte[1024];
            while ((i = in.read(bytesIn)) >= 0) {
                out.write(bytesIn, 0, i);
            }
            out.close();
            in.close();
            anyDownload = true;

            File downloadedFile = new File(di.savePath);
            totalSize += downloadedFile.length();

            progress(1);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
    return anyDownload;
}

From source file:jhttpp2.Jhttpp2HTTPSession.java

/**
 * Small webserver for local files in {app}/htdocs
 * /*from  w  w w  .  j  ava2s. c  om*/
 * @since 0.4.04
 */
public void file_handler() throws IOException {
    if (!server.www_server) {
        sendErrorMSG(500, "The jHTTPp2 built-in WWW server module is disabled.");
        return;
    }
    String filename = in.url;
    if (filename.equals("/"))
        filename = "index.html"; // convert / to index.html
    else if (filename.startsWith("/"))
        filename = filename.substring(1);
    if (filename.endsWith("/"))
        filename += "index.html"; // add index.html, if ending with /
    File file = new File("htdocs/" + filename); // access only files in
    // "htdocs"
    if (!file.exists() || !file.canRead() // be sure that we can read the
    // file
            || filename.indexOf("..") != -1 // don't allow ".." !!!
            || file.isDirectory()) { // dont't read if it's a directory
        sendErrorMSG(404, "The requested file /" + filename + " was not found or the path is invalid.");
        return;
    }
    int pos = filename.lastIndexOf("."); // MIME type of the specified file
    String content_type = "text/plain"; // all unknown content types will be
    // marked as text/plain
    if (pos != -1) {
        String extension = filename.substring(pos + 1);
        if (extension.equalsIgnoreCase("htm") || (extension.equalsIgnoreCase("html")))
            content_type = "text/html; charset=iso-8859-1";
        else if (extension.equalsIgnoreCase("jpg") || (extension.equalsIgnoreCase("jpeg")))
            content_type = "image/jpeg";
        else if (extension.equalsIgnoreCase("gif"))
            content_type = "image/gif";
        else if (extension.equalsIgnoreCase("png"))
            content_type = "image/png";
        else if (extension.equalsIgnoreCase("css"))
            content_type = "text/css";
        else if (extension.equalsIgnoreCase("pdf"))
            content_type = "application/pdf";
        else if (extension.equalsIgnoreCase("ps") || extension.equalsIgnoreCase("eps"))
            content_type = "application/postscript";
        else if (extension.equalsIgnoreCase("xml"))
            content_type = "text/xml";
    }
    sendHeader(200, content_type, file.length());
    endHeader();
    BufferedInputStream file_in = new BufferedInputStream(new FileInputStream(file));
    byte[] buffer = new byte[4096];
    int a = file_in.read(buffer);
    while (a != -1) { // read until EOF
        out.write(buffer, 0, a);
        a = file_in.read(buffer);
    }
    out.flush();
    file_in.close(); // finished!
}

From source file:VentanaPrincipal.java

private void subirFichero() throws IOException {
    String directorio = lblRuta.getText();
    cliente.changeWorkingDirectory(directorio);
    cliente.setFileType(FTP.BINARY_FILE_TYPE);

    JFileChooser chooser = new JFileChooser();
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        BufferedInputStream in = new BufferedInputStream(
                new FileInputStream(chooser.getSelectedFile().getAbsolutePath()));
        cliente.storeFile(chooser.getSelectedFile().getName(), in);
        listFicheros.add(chooser.getSelectedFile().getName() + "- Fichero");
        in.close();
        lblMens.setText("Documento subido con xito");
    }/*from w w w  .  j  av  a2s . c  o  m*/
}

From source file:sys.core.manager.RecursosManager.java

public void viewArchivo(String archivo) {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/force-download");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + archivo + "\"");
    ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext()
            .getBean("applicationMBean");
    byte[] buf = new byte[1024];
    try {/*from  w ww.java2s.  com*/
        File file = new File(applicationMBean.getRutaArchivos() + archivo);
        long length = file.length();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        ServletOutputStream out = response.getOutputStream();
        response.setContentLength((int) length);
        while ((in != null) && ((length = in.read(buf)) != -1)) {
            out.write(buf, 0, (int) length);
        }
        in.close();
        out.close();
    } catch (Exception exc) {
        logger.error(exc);
    }
}