Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

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

Usage

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

/**
 * Handles the HTTP <code>POST</code> method.
 * @param req servlet request//from   w  ww.j a v a  2 s.  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:com.nkapps.billing.controllers.BankStatementController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadPost(@RequestParam("file") MultipartFile uploadedFile, ModelMap map,
        HttpServletRequest request) {/*ww  w .j av  a  2 s  . c o m*/
    try {
        File file = null;
        /**
         * Upload file
         */
        //            FileItemFactory factory = new DiskFileItemFactory();
        //            ServletFileUpload upload = new ServletFileUpload(factory);
        //            List<FileItem> formItems = upload.parseRequest(request);
        //            Iterator iterator = formItems.iterator();
        //            while(iterator.hasNext()){
        //                FileItem item = (FileItem) iterator.next();
        //                if(!item.isFormField()){
        //                    File uploadedFile = new File(item.getName());
        //                    
        //                    String filePath = bankStatementService.getUploadDir() + File.separator + uploadedFile.getName();
        //                    file = new File(filePath);
        //                    item.write(file);    
        //                    break;
        //                }
        //            }
        String filePath = bankStatementService.getUploadDir() + File.separator
                + uploadedFile.getOriginalFilename();
        file = new File(filePath);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
        stream.write(uploadedFile.getBytes());
        stream.close();

        String messages;
        if (file.getName().endsWith(".xls")) { // for payment manual, excel file

            String ip = authService.getClientIp(request);
            if (!authService.isAllowedByPropertyIp("bank_statement_payment_manual_allowed_ips", ip)) {
                throw new Exception(messageSource.getMessage("upload.you_have_not_privelege_to_upload_excel",
                        null, LocaleContextHolder.getLocale()));
            }
            /**
             * Parse and Save
             */
            Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue();
            String issuerIp = authService.getClientIp(request);
            paymentService.parseAndSavePaymentManual(file, issuerSerialNumber, issuerIp);
            /**
             * Backup and Release uploads
             */
            bankStatementService.backupAndRelease(file, null);
            messages = messageSource.getMessage("upload.file_successfull_uploded", null,
                    LocaleContextHolder.getLocale());

        } else {
            /**
             * Extract file
             */
            File extractedFile = bankStatementService.extractedFile(file);

            /**
             * Parse and Save
             */
            Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue();
            String issuerIp = authService.getClientIp(request);
            messages = bankStatementService.parseAndSave(extractedFile, issuerSerialNumber, issuerIp);

            /**
             * Backup and Release uploads
             */
            bankStatementService.backupAndRelease(file, extractedFile);
            if (messages.isEmpty()) {
                messages = messageSource.getMessage("upload.file_successfull_uploded", null,
                        LocaleContextHolder.getLocale());
            } else {
                messages = messageSource.getMessage("upload.file_successfull_uploded", null,
                        LocaleContextHolder.getLocale()) + "<br/>" + messages;
            }

        }
        map.put("info", messages);

    } catch (Exception e) {
        logger.error(e.getMessage());
        map.put("reason", e.getMessage().replace("\n", ";").replace("\r", ";"));
    }
    return "bankstatement/upload";
}

From source file:com.cloudera.recordbreaker.learnstructure.test.GenerateRandomData.java

/**
 *///from  ww w  . j  a va 2s  . c  o  m
public void generateData(boolean encodeJson, File outfile, int numRecords) throws IOException {
    Schema schema = ReflectData.get().getSchema(TestRecord.class);
    DatumWriter dout = new ReflectDatumWriter(schema);

    if (encodeJson) {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outfile));
        try {
            Encoder encoder = EncoderFactory.get().jsonEncoder(schema, (OutputStream) out);
            for (int i = 0; i < numRecords; i++) {
                TestRecord tr = new TestRecord();
                dout.write(tr, encoder);
            }
            encoder.flush();
        } finally {
            out.close();
        }
    } else {
        DataFileWriter out = new DataFileWriter(dout);
        try {
            out.create(schema, outfile);
            for (int i = 0; i < numRecords; i++) {
                TestRecord tr = new TestRecord();
                out.append(tr);
            }
        } finally {
            out.close();
        }
    }
}

From source file:net.sf.jvifm.ui.ZipLister.java

private File extractToTemp(FileObject fileObject) {
    String basename = fileObject.getName().getBaseName();
    File tempFile = null;/*w w w  . j  av  a 2s. c  o  m*/
    try {
        String tmpPath = System.getProperty("java.io.tmpdir");
        tempFile = new File(FilenameUtils.concat(tmpPath, basename));

        byte[] buf = new byte[4096];
        BufferedInputStream bin = new BufferedInputStream(fileObject.getContent().getInputStream());
        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(tempFile));
        while (bin.read(buf, 0, 1) != -1) {
            bout.write(buf, 0, 1);
        }
        bout.close();
        bin.close(); // by barney
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return tempFile;
}

From source file:ebay.dts.client.FileTransferActions.java

public void downloadFile2(String fileName, String jobId, String fileReferenceId) throws EbayConnectorException {

    String callName = "downloadFile";

    try {//from  w  w w  . j  a  va 2  s . c  o  m

        FileTransferServicePort port = call.setFTSMessageContext(callName);
        com.ebay.marketplace.services.DownloadFileRequest request = new com.ebay.marketplace.services.DownloadFileRequest();
        request.setFileReferenceId(fileReferenceId);
        request.setTaskReferenceId(jobId);
        DownloadFileResponse response = port.downloadFile(request);
        if (response.getAck().equals(AckValue.SUCCESS)) {
            logger.debug(AckValue.SUCCESS.toString());
        } else {
            logger.error(response.getErrorMessage().getError().get(0).getMessage());
            throw new EbayConnectorException(response.getErrorMessage().getError().get(0).getMessage());
        }

        FileAttachment attachment = response.getFileAttachment();
        DataHandler dh = attachment.getData();

        try {
            InputStream in = dh.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(new GZIPInputStream(in));
            FileOutputStream fo = new FileOutputStream(new File(fileName)); // "C:/myDownLoadFile.gz"
            BufferedOutputStream bos = new BufferedOutputStream(fo);
            int bytes_read = 0;
            byte[] dataBuf = new byte[4096];
            while ((bytes_read = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, bytes_read);
            }
            bis.close();
            bos.flush();
            bos.close();
            logger.info("File attachment has been saved successfully to " + fileName);

        } catch (IOException e) {
            logger.error("Exception caught while trying to save the attachement");
            throw new EbayConnectorException("Exception caught while trying to save the attachement", e);
        }

    } catch (Exception e) {
        throw new EbayConnectorException("Exception caught while trying to save the attachement", e);
    }

}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

private void dumpToFile(URL url) {
    File externalStorage = Environment.getExternalStorageDirectory();
    if (!externalStorage.canWrite())
        return;// w ww.j a  v  a  2s . c  o m

    String fn = null;

    String[] f = url.toString().split("/");
    fn = f[f.length - 1].split("\\?")[0];
    Log.w("--------------", fn);

    String base = String.format("%s/dreamDroid/xml", externalStorage);
    File file = new File(String.format("%s/%s", base, fn));
    BufferedOutputStream bos = null;
    try {
        (new File(base)).mkdirs();
        file.createNewFile();
        bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(mBytes);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.feilong.tools.net.filetransfer.FTPUtil.java

@Override
protected boolean _downRemoteSingleFile(String remoteSingleFile, String filePath) throws Exception {
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));
    boolean success = ftpClient.retrieveFile(remoteSingleFile, bufferedOutputStream);

    bufferedOutputStream.flush();//from   w w  w . j a v a  2s  .  c o  m
    bufferedOutputStream.close();
    return success;
}

From source file:org.pegadi.webapp.view.FileView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // get the file from the map
    File file = (File) map.get("file");

    // check if it exists
    if (file == null || !file.exists() || !file.canRead()) {
        log.warn("Error reading: " + file);
        try {/*w  ww .  j a  v  a 2  s .  c om*/
            response.sendError(404);
        } catch (IOException e) {
            log.error("Could not write to response", e);
        }
        return;
    }
    // give some info in the response
    response.setContentType(getServletContext().getMimeType(file.getAbsolutePath()));
    // files does not change so often, allow three days caching
    response.setHeader("Cache-Control", "max-age=259200");
    response.setContentLength((int) file.length());

    // start writing to the response
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
        out = new BufferedOutputStream(response.getOutputStream());
        in = new BufferedInputStream(new FileInputStream(file));
        int c = in.read();
        while (c != -1) {
            out.write(c);
            c = in.read();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:it.readbeyond.minstrel.unzipper.Unzipper.java

private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters)
        throws IOException, JSONException {

    // store the zip entries to decompress
    List<String> list = new ArrayList<String>();

    // store the zip entries actually decompressed
    List<String> decompressed = new ArrayList<String>();

    // open input zip file
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // open destination directory, creating it if needed    
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdirs();/*from   w  w  w.ja  va2  s .c o m*/

    // extract all files
    if (mode.equals(ARGUMENT_MODE_ALL)) {
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            list.add(zipFileEntries.nextElement().getName());
        }
    }

    // extract all files except audio and video
    // (determined by file extension)
    if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) {
        String[] excludeExtensions = JSONArrayToStringArray(
                parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            if (!isFile(lower, excludeExtensions)) {
                list.add(name);
            }
        }
    }

    // extract all small files
    // maximum size is passed in args parameter
    // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE
    if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) {
        long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            if (ze.getSize() <= maximum_size) {
                list.add(ze.getName());
            }
        }
    }

    // extract only the requested files
    if (mode.equals(ARGUMENT_MODE_SELECTED)) {
        String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES));
        for (String entry : entries) {
            ZipEntry ze = zipFile.getEntry(entry);
            if (ze != null) {
                list.add(entry);
            }
        }
    }

    // extract all "structural" files
    if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) {
        String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            boolean extract = isFile(lower, extensions);
            if (extract) {
                list.add(name);
            }
        }
    }

    // NOTE list contains only valid zip entries
    // perform unzip
    for (String currentEntry : list) {
        ZipEntry entry = zipFile.getEntry(currentEntry);
        File destFile = new File(unzipDestinationDirectory, currentEntry);

        File destinationParent = destFile.getParentFile();
        destinationParent.mkdirs();

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int numberOfBytesRead;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
                dest.write(data, 0, numberOfBytesRead);
            }
            dest.flush();
            dest.close();
            is.close();
            fos.close();
            decompressed.add(currentEntry);
        }
    }

    zipFile.close();
    return stringify(decompressed);
}

From source file:de.rallye.images.ImageRepository.java

private void scalePicture(File src, String pictureHash, PictureSize size) throws IOException {
    lock.writeLock().lock();//from   w  w  w . j  a v a 2  s.c o m
    try {
        Dimension d = size.getDimension();

        BufferedImage base = ImageIO.read(src);

        BufferedImage out = ImageScaler.scaleImage(base, d);

        File f = getFile(pictureHash, size);

        if (size == PictureSize.Mini || size == PictureSize.Thumbnail) {
            ByteArrayOutputStream bStream = new ByteArrayOutputStream();
            ImageIO.write(out, "jpg", bStream);

            if (size == PictureSize.Thumbnail) {
                thumbCache.put(pictureHash, bStream.toByteArray());
            } else if (size == PictureSize.Mini) {
                miniCache.put(pictureHash, bStream.toByteArray());
            }

            ByteArrayInputStream iStream = new ByteArrayInputStream(bStream.toByteArray());
            BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(f));
            copy(iStream, outStream);
            iStream.close();
            outStream.close();

            bStream.close();
        } else {
            ImageIO.write(out, "jpg", f);
        }

        logger.info("Scaled {} to {} from ({}x{})", pictureHash, size, base.getWidth(), base.getHeight());
    } finally {
        lock.writeLock().unlock();
    }
}