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.gsr.myschool.server.reporting.bilan.ConvocationReportController.java

@RequestMapping(method = RequestMethod.GET, value = "/convocationReport", produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)/*ww w  . ja v a  2 s  .  co  m*/
public void generateExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

        response.addHeader("Content-Disposition", "attachment; filename=convocation_report.pdf");

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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.//from w ww.j a  va2  s  .c o m
 * @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:mobisocial.nfcserver.handler.HttpFileHandler.java

public int handleNdef(NdefMessage[] ndefMessages) {
    URI page = null;//w ww. j a  v a  2  s  . c  om
    NdefRecord firstRecord = ndefMessages[0].getRecords()[0];
    if (UriRecord.isUri(firstRecord)) {
        page = UriRecord.parse(firstRecord).getUri();
    }

    try {
        if (page != null && (page.getScheme().startsWith("http"))) {
            System.out.println("trying to get " + page);
            if (page.getPath() == null || !page.toString().contains(".")) {
                return NDEF_PROPAGATE;
            }

            try {
                String extension = page.toString().substring(page.toString().lastIndexOf(".") + 1);
                if (!MimeTypeHandler.MIME_EXTENSIONS.containsValue(extension)) {
                    return NDEF_PROPAGATE;
                }

                // Download content
                System.out.println("Downloading " + extension + " file.");
                HttpGet httpGet = new HttpGet(page);
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity entity = httpResponse.getEntity();
                InputStream content = entity.getContent();

                File fileOut = new File("nfcfiles/" + System.currentTimeMillis() + "." + extension);
                fileOut.getParentFile().mkdirs();
                FileOutputStream fileOutStream = new FileOutputStream(fileOut);
                BufferedOutputStream buffered = new BufferedOutputStream(fileOutStream);
                byte[] buf = new byte[1024];
                while (true) {
                    int r = content.read(buf);
                    if (r <= 0)
                        break;
                    buffered.write(buf, 0, r);
                }
                buffered.close();
                fileOutStream.close();

                MimeTypeHandler.openFile(fileOut);
                return NDEF_CONSUME;
            } catch (Exception e) {
                e.printStackTrace();
                return NDEF_PROPAGATE;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error launching page", e);
    }
    return NDEF_PROPAGATE;
}

From source file:com.rapleaf.hank.storage.HdfsPartitionRemoteFileOps.java

@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
    Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
    File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
    LOG.info("Copying remote file " + source + " to local file " + destination);
    InputStream inputStream = getInputStream(remoteSourceRelativePath);
    FileOutputStream fileOutputStream = new FileOutputStream(destination);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    // Use copyLarge (over 2GB)
    try {/* w ww .  j a v a  2 s  .  c  om*/
        IOUtils.copyLarge(inputStream, bufferedOutputStream);
        bufferedOutputStream.flush();
        fileOutputStream.flush();
    } finally {
        inputStream.close();
        bufferedOutputStream.close();
        fileOutputStream.close();
    }
}

From source file:it.geosolutions.imageio.plugins.exif.EXIFUtilities.java

/**
 * This method will update the image referred by the specified inputStream, by replacing
 * the underlying EXIF with the one represented by the specified {@link EXIFMetadata} instance.
 * Write the result to the specified {@link OutputStream}.
 * //from   w ww  .  ja va 2s.  c  o m
 * @param outputStream the stream where to write the result
 * @param inputStream the input stream referring to the original image to be copied back to the
 *   output
 * @param exif the {@link EXIFMetadata} instance containing updated exif to replace the one
 *   contained into the input image. 
 * @param previousEXIFLength 
 *   the length of the previous EXIF marker. 
 *   It is needed in order to understand the portion of the input image to be copied back to 
 *   the output
 * @throws IOException
 */
private static void updateStream(final OutputStream outputStream, final FileImageInputStreamExt inputStream,
        final EXIFMetadata exif, final int previousEXIFLength) throws IOException {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    try {

        // Setup a new byteArrayOutputStream on top of the Exif object 
        baos = initializeExifStream(exif, null);

        // Update this outputStream by copying bytes from the original image 
        // referred by the inputStream, but inserting updated EXIF 
        // instead of copying it from the original image
        bos = new BufferedOutputStream(outputStream, DEFAULT_BUFFER_SIZE);
        updateFromStream(bos, baos, inputStream, previousEXIFLength);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (Throwable t) {
                // Eat exception on close
            }
        }
        if (baos != null) {
            try {
                baos.close();
            } catch (Throwable t) {
                // Eat exception on close
            }
        }
    }

}

From source file:org.iti.agrimarket.view.UpdateOfferController.java

/**
 * upload image and form data//w  w w .j a v a2  s .  c o  m
 *
 */
@RequestMapping(method = RequestMethod.POST, value = { "/updateoffer.htm" })
public String updateOffer(@RequestParam("description") String description,
        @RequestParam("quantity") float quantity, @RequestParam("quantityunit") int quantityunit,
        @RequestParam("unitprice") int unitprice, @RequestParam("price") float price,
        @RequestParam("mobile") String mobile, @RequestParam("governerate") String governerate,
        @RequestParam("product") int product, @RequestParam("file") MultipartFile file,
        @RequestParam("offerId") int offerId, @ModelAttribute("user") User userFromSession,
        RedirectAttributes redirectAttributes, Model model, HttpServletRequest request) {

    System.out.println("product id PPPPPPPPPPPPPPPPPPPPPP:" + product);

    UserOfferProductFixed userOfferProductFixed = offerService.findUserOfferProductFixed(offerId);
    if (userOfferProductFixed != null) {
        userOfferProductFixed.setDescription(description);
        userOfferProductFixed.setPrice(price);
        userOfferProductFixed.setQuantity(quantity);
        userOfferProductFixed.setProduct(productService.getProduct(product));
        userOfferProductFixed.setUnitByUnitId(unitService.getUnit(quantityunit));
        userOfferProductFixed.setUnitByPricePerUnitId(unitService.getUnit(unitprice));
        userOfferProductFixed.setUser(userFromSession);
        userOfferProductFixed.setUserLocation(governerate);
        userOfferProductFixed.setUserPhone(mobile);

        offerService.updateOffer(userOfferProductFixed);

    }
    if (!file.isEmpty()) {

        String fileName = userOfferProductFixed.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();

            System.out.println(new String(bytes));
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.OFFER_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                    new File(Constants.IMAGE_PATH + Constants.USER_PATH + fileName + ext)));
            stream.write(bytes);
            stream.close();
            userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + fileName + ext);
            System.out.println("image url" + userOfferProductFixed.getImageUrl());

            offerService.updateOffer(userOfferProductFixed);

        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            offerService.deleteOffer(userOfferProductFixed.getId()); // delete the category if something goes wrong

            redirectAttributes.addFlashAttribute("message", "You failed to upload  because the file was empty");
            return "redirect:/web/updateoffer.htm";
        }

    } else {
        redirectAttributes.addFlashAttribute("message", "You failed to upload  because the file was empty");
    }

    //User user =  userService.getUserByEmail(userFromSession.getMail());
    //           model.addAttribute("user", user);
    User oldUser = (User) request.getSession().getAttribute("user");
    if (oldUser != null) {
        User user = userService.getUserEager(oldUser.getId());
        request.getSession().setAttribute("user", user);
        model.addAttribute("user", user);
    }

    return "profile";
}

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  a2s  .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:edu.wustl.xipHost.caGrid.RetrieveNBIASecuredTest.java

@Test
public void test() throws Exception {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    Login login = new GridLogin();
    String userName = "<JIRAusername>";
    String password = "<JIRApassword>";
    DcmFileFilter dcmFilter = new DcmFileFilter();
    login.login(userName, password);/*  w ww . java  2  s  .  c o  m*/
    GlobusCredential globusCred = login.getGlobusCredential();
    boolean isConnectionSecured = login.isConnectionSecured();
    logger.debug("Acquired NBIA GlobusCredential. Connection secured = " + isConnectionSecured);
    if (!isConnectionSecured) {
        fail("Unable to acquire NBIA GlobusCredential. Check username and password.");
        return;
    }
    NCIACoreServiceClient client = new NCIACoreServiceClient(gridServiceUrl, globusCred);
    client.setAnonymousPrefered(false);
    TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID("1.3.6.1.4.1.9328.50.1.4718");
    TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference(),
            globusCred);
    InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor(), globusCred);
    ZipInputStream zis = new ZipInputStream(istream);
    ZipEntryInputStream zeis = null;
    BufferedInputStream bis = null;
    File importDir = new File("./test-content/NBIA5");
    if (!importDir.exists()) {
        importDir.mkdirs();
    } else {
        File[] files = importDir.listFiles(dcmFilter);
        for (int j = 0; j < files.length; j++) {
            File file = files[j];
            file.delete();
        }
    }
    while (true) {
        try {
            zeis = new ZipEntryInputStream(zis);
        } catch (EOFException e) {
            break;
        } catch (IOException e) {
            logger.error(e, e);
        }
        String unzzipedFile = null;
        try {
            unzzipedFile = importDir.getCanonicalPath();
        } catch (IOException e) {
            logger.error(e, e);
        }
        logger.debug(" filename: " + zeis.getName());
        bis = new BufferedInputStream(zeis);
        byte[] data = new byte[8192];
        int bytesRead = 0;
        String retrievedFilePath = unzzipedFile + File.separator + zeis.getName();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(retrievedFilePath));
            while ((bytesRead = (bis.read(data, 0, data.length))) != -1) {
                bos.write(data, 0, bytesRead);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            logger.error(e, e);
        }
    }
    try {
        zis.close();
        tclient.destroy();
    } catch (IOException e) {
        logger.error(e, e);
    }
    File[] retrievedFiles = importDir.listFiles(dcmFilter);
    int numbOfRetreivedFiles = retrievedFiles.length;
    assertEquals("Number of retrieved files should be 2 but is. " + numbOfRetreivedFiles, numbOfRetreivedFiles,
            2);
    //Assert file names. They should be equal to items' SeriesInstanceUIDs
    Map<String, File> mapRetrievedFiles = new HashMap<String, File>();
    for (int i = 0; i < numbOfRetreivedFiles; i++) {
        File file = retrievedFiles[i];
        mapRetrievedFiles.put(file.getName(), file);
    }
    boolean retrievedFilesCorrect = false;
    if (mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4716.dcm")
            && mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4720.dcm")) {
        retrievedFilesCorrect = true;
    }
    assertTrue("Retrieved files are not as expected.", retrievedFilesCorrect);
}

From source file:net.sf.nmedit.nomad.core.service.initService.ExplorerLocationMemory.java

public void shutdown() {
    Enumeration<TreeNode> nodes = Nomad.sharedInstance().getExplorer().getRoot().children();

    List<FileContext> locations = new ArrayList<FileContext>();
    TempDir tempDir = TempDir.generalTempDir();
    File userPatches = tempDir.getTempFile("patches");
    String canonicalPatches = null;
    try {/*from w w  w  .  j a v  a 2s .c o  m*/
        canonicalPatches = userPatches.getCanonicalPath();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    while (nodes.hasMoreElements()) {
        TreeNode node = nodes.nextElement();
        if (node instanceof FileContext) {
            FileContext fc = (FileContext) node;
            try {
                if (!fc.getFile().getCanonicalPath().equals(canonicalPatches))
                    locations.add(fc);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Properties p = new Properties();
    writeProperties(p, locations);

    File file = getTempFile();

    BufferedOutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        p.store(out, "this file is generated, do not edit it");
    } catch (IOException e) {
        // ignore
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:org.ktunaxa.referral.server.mvc.UploadGeometryController.java

private URL unzipShape(byte[] fileContent) throws IOException {
    String tempDir = System.getProperty("java.io.tmpdir");

    URL url = null;//from www. java  2  s  .  c o m
    ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileContent));
    try {
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            log.info("Extracting: " + entry);
            String name = tempDir + "/" + entry.getName();
            tempFiles.add(name);
            if (name.endsWith(".shp")) {
                url = new URL("file://" + name);
            }
            int count;
            byte[] data = new byte[BUFFER];
            // write the files to the disk
            deleteFileIfExists(name);
            FileOutputStream fos = new FileOutputStream(name);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);
            try {
                while ((count = zin.read(data, 0, BUFFER)) != -1) {
                    destination.write(data, 0, count);
                }
                destination.flush();
            } finally {
                destination.close();
            }
        }
    } finally {
        zin.close();
    }
    if (url == null) {
        throw new IllegalArgumentException("Missing .shp file");
    }
    return url;
}