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:asciidoc.maven.plugin.AbstractAsciiDocMojo.java

private void unzipEntry(ZipFile zipfile, ZipEntry zipEntry, File outputDir) throws IOException {
    if (zipEntry.isDirectory()) {
        createDir(new File(outputDir, zipEntry.getName()));
        return;/* w w  w  .  j a v a 2 s. c om*/
    }
    File outputFile = new File(outputDir, zipEntry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }
    if (getLog().isDebugEnabled())
        getLog().debug("Extracting " + zipEntry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(zipEntry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

From source file:com.gsr.myschool.server.reporting.convocation.ConvocationController.java

@RequestMapping(value = "test", method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)/* ww  w  .java2s  .com*/
public void generateReportTest(@RequestParam String niveauId, @RequestParam String sessionId,
        HttpServletResponse response) {
    ReportDTO dto = convocationService.generateConvocationTest(Long.valueOf(niveauId), Long.valueOf(sessionId));
    try {
        response.addHeader("Content-Disposition", "attachment; filename=convocation.pdf");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] result = reportService.generatePdf(dto);

        outputStream.write(result, 0, result.length);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vmware.bdd.cli.auth.LoginClientImplTest.java

public LoginTestTemplate(final String expectedUserName, final String expectedPassword, final int responseCode,
        final String sessionId) {

    httpHandler = new HttpHandler() {
        @Override//from  ww  w  . ja  va  2 s.  com
        public void handle(HttpExchange httpExchange) throws IOException {
            Headers headers = httpExchange.getRequestHeaders();

            Assert.assertEquals("application/x-www-form-urlencoded; charset=UTF-8",
                    headers.getFirst("Content-Type"));
            Assert.assertEquals("POST", httpExchange.getRequestMethod());

            InputStream reqStream = httpExchange.getRequestBody();

            Reader reader = new InputStreamReader(reqStream);

            StringBuilder sb = new StringBuilder();

            char[] tmp = new char[16];
            int count = reader.read(tmp);
            while (count > 0) {
                sb.append(tmp, 0, count);
                count = reader.read(tmp);
            }

            //            String val = URLDecoder.decode(sb.toString(), "UTF-8");

            List<NameValuePair> namePasswordPairs = URLEncodedUtils.parse(sb.toString(),
                    Charset.forName("UTF-8"));
            Assert.assertEquals(namePasswordPairs.get(0).getValue(), expectedUserName);
            Assert.assertEquals(namePasswordPairs.get(1).getValue(), expectedPassword);

            if (sessionId != null) {
                Headers responseHeaders = httpExchange.getResponseHeaders();
                responseHeaders.set(LoginClientImpl.SET_COOKIE_HEADER,
                        "JSESSIONID=" + sessionId + "; Path=/serengeti; Secure");
            }

            String response = "LoginClientImplTest";
            httpExchange.sendResponseHeaders(responseCode, response.length());

            BufferedOutputStream os = new BufferedOutputStream(httpExchange.getResponseBody());

            os.write(response.getBytes());
            os.close();

        }
    };
}

From source file:io.github.blindio.prospero.core.browserdrivers.phantomjs.AbstractUnarchiver.java

protected void extract(ArchiveInputStream arcInStream) throws IOException {
    ArchiveEntry entry = null;//  w  ww.j  a  v  a2  s  . co  m

    /** Read the tar entries using the getNextEntry method **/

    while ((entry = (ArchiveEntry) arcInStream.getNextEntry()) != null) {

        System.out.println("Extracting: " + entry.getName());

        /** If the entry is a directory, create the directory. **/

        if (entry.isDirectory()) {

            File f = new File(getDestDirectory() + SystemUtils.FILE_SEPARATOR + entry.getName());
            f.mkdirs();
        }
        /**
         * If the entry is a file,write the decompressed file to the disk
         * and close destination stream.
         **/
        else {
            int count;
            byte data[] = new byte[BUFFER];

            FileOutputStream fos = new FileOutputStream(
                    getDestDirectory() + SystemUtils.FILE_SEPARATOR + entry.getName());
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = arcInStream.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.close();
        }
    }

    /** Close the input stream **/

    arcInStream.close();
    System.out.println("untar completed successfully!!");
}

From source file:org.khmeracademy.btb.auc.pojo.service.impl.UploadImage_serviceimpl.java

@Override
public Image upload(int pro_id, List<MultipartFile> files) {
    Image uploadImage = new Image();
    if (files.isEmpty()) {

    } else {//w w  w  .j  av  a 2 s  .  c  o  m

        //            if(folder=="" || folder==null)
        //                folder = "default";
        String UPLOAD_PATH = "/opt/project/default";
        String THUMBNAIL_PATH = "/opt/project/thumnail/";

        java.io.File path = new java.io.File(UPLOAD_PATH);
        java.io.File thum_path = new java.io.File(THUMBNAIL_PATH);
        if (!path.exists())
            path.mkdirs();
        if (!thum_path.exists()) {
            thum_path.mkdirs();
        }

        List<String> names = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
            try {
                byte[] bytes = file.getBytes();
                Files.copy(file.getInputStream(), Paths.get(UPLOAD_PATH, fileName)); //copy path name to server
                try {
                    //TODO: USING THUMBNAILS TO RESIZE THE IMAGE

                    Thumbnails.of(UPLOAD_PATH + "/" + fileName).forceSize(640, 640).toFiles(thum_path,
                            Rename.NO_CHANGE);
                } catch (Exception ex) {
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(new File(THUMBNAIL_PATH + fileName)));
                    stream.write(bytes);
                    stream.close();
                }
                names.add(fileName); // add file name
                imRepo.upload(pro_id, fileName); // upload path to database
            } catch (Exception e) {

            }
        }
        uploadImage.setProjectPath("/resources/");
        uploadImage.setServerPath(UPLOAD_PATH);
        uploadImage.setNames(names);
        uploadImage.setMessage("File has been uploaded successfully!!!");
    }
    return uploadImage;
}

From source file:de.thorstenberger.examServer.dao.xml.AbstractJAXBDao.java

/**
 * Serializes the object into xml. Will wrap any exception into a {@link RuntimeException}.
 *
 * @param obj/*from w  ww. ja va2s . c o  m*/
 *            the object to save.
 * @throws RuntimeException
 *             wrapping {@link JAXBException} of {@link IOException}
 */
synchronized protected void save(final Object obj) {
    log.debug(String.format("Trying to save xml package to file '%s'", workingPath + "/" + xmlFileName));
    final String txId = startTransaction();
    Marshaller marshaller = null;
    try {

        marshaller = JAXBUtils.getJAXBMarshaller(jc);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        final BufferedOutputStream bos = new BufferedOutputStream(
                getFRM().writeResource(txId, this.xmlFileName));
        marshaller.marshal(obj, bos);

        bos.close();
        commitTransaction(txId);
    } catch (final JAXBException e) {
        rollback(txId, e);
        throw new RuntimeException(e);
    } catch (final IOException e) {
        rollback(txId, e);
        throw new RuntimeException(e);
    } catch (final ResourceManagerException e) {
        rollback(txId, e);
        throw new RuntimeException(e);
    } catch (RuntimeException e) {
        rollback(txId, e);
        throw e;
    } finally {
        if (marshaller != null)
            JAXBUtils.releaseJAXBMarshaller(jc, marshaller);
    }
}

From source file:eu.planets_project.pp.plato.services.characterisation.DROIDIntegration.java

/**
 * Tries to identify the given <param>data</param> and <param>filename</param>.
 * - throws an exception if it is not possible to create a temporary file.
 * /*from w w w  .j ava  2  s . c  o m*/
 * @param filename
 * @param data
 * @return {@link IdentificationFile}
 * @throws Exception
 */
public IdentificationFile identify(String filename, byte[] data) throws Exception {
    String filebody = filename;
    String suffix = "";
    int bodyEnd = filename.lastIndexOf(".");
    if (bodyEnd >= 0) {
        filebody = filename.substring(0, bodyEnd);
        suffix = filename.substring(bodyEnd);
    }
    File tempFile = File.createTempFile(filebody + System.nanoTime(), suffix);
    tempFile.deleteOnExit();
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
    out.write(data);
    out.close();

    return droid.identify(tempFile.getCanonicalPath());
}

From source file:edu.vt.middleware.crypt.signature.SignatureCliTest.java

/**
 * @param  partialLine  Partial command line.
 * @param  pubKey  Public key file.//from w  ww . j  av a 2 s.  c o  m
 * @param  privKey  Private key file.
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "cli", "signature" }, dataProvider = "testdata")
public void testSignatureCli(final String partialLine, final String pubKey, final String privKey)
        throws Exception {
    final String pubKeyPath = KEY_DIR_PATH + pubKey;
    final String privKeyPath = KEY_DIR_PATH + privKey;
    final PrintStream oldStdOut = System.out;
    try {
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outStream));

        // Compute signature and verify it
        String fullLine = partialLine + " -sign " + " -key " + privKeyPath + " -in " + TEST_PLAINTEXT;
        logger.info("Testing signature CLI sign operation with command line:\n\t" + fullLine);
        SignatureCli.main(CliHelper.splitArgs(fullLine));

        final String sig = outStream.toString();
        Assert.assertTrue(sig.length() > 0);

        // Write signature out to file for use in verify step
        new File(TEST_OUTPUT_DIR).mkdir();

        final File sigFile = new File(TEST_OUTPUT_DIR + "sig.out");
        final BufferedOutputStream sigOs = new BufferedOutputStream(new FileOutputStream(sigFile));
        try {
            sigOs.write(outStream.toByteArray());
        } finally {
            sigOs.close();
        }
        outStream.reset();

        // Verify signature
        fullLine = partialLine + " -verify " + sigFile + " -key " + pubKeyPath + " -in " + TEST_PLAINTEXT;
        logger.info("Testing signature CLI verify operation with command " + "line:\n\t" + fullLine);
        SignatureCli.main(CliHelper.splitArgs(fullLine));

        final String result = outStream.toString();
        AssertJUnit.assertTrue(result.indexOf("SUCCESS") != -1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Restore STDOUT
        System.setOut(oldStdOut);
    }
}

From source file:com.sqli.liferay.imex.util.xml.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  .j  a va 2 s . 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:com.peadargrant.filecheck.web.controllers.CheckController.java

@RequestMapping(method = RequestMethod.POST)
public String performCheck(@RequestParam(value = "assignment", required = true) String assignmentCode,
        @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {

    String assignmentsUrl = serverEnvironment.getPropertyAsString("assignmentsUrl");
    model.addAttribute("assignmentsUrl", assignmentsUrl);

    // bail out if the file is empty
    if (file.isEmpty()) {
        model.addAttribute("message", "file.was.empty");
        return "error";
    }/*from w  w w  .jav  a2  s  .  co m*/

    // input stream from file 
    byte[] bytes = file.getBytes();
    String name = file.getOriginalFilename();

    // write to temp dir
    String filePath = System.getProperty("java.io.tmpdir") + "/" + name;
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
    stream.write(bytes);
    stream.close();

    // load file
    File inputFile = new File(filePath);

    // get assignment
    Assignment assignment = this.getAssignmentForCode(assignmentCode);
    if (assignment == null) {
        return "assignmentNotFound";
    }
    model.addAttribute(assignment);

    // GUI report table model
    SummaryTableModel summaryTableModel = new SummaryTableModel();
    ReportTableModel reportTableModel = new ReportTableModel(summaryTableModel);

    // checker
    Checker checker = new Checker();
    checker.setReport(reportTableModel);
    checker.runChecks(inputFile, assignment);

    // details for output
    model.addAttribute("fileName", name);
    model.addAttribute("startTime", new java.util.Date());
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    model.addAttribute("remoteIP", ipAddress);

    // final outcome
    model.addAttribute("outcome", summaryTableModel.getFinalOutcome());
    Color finalOutcomeColor = summaryTableModel.getFinalOutcome().getSaturatedColor();
    model.addAttribute("colourr", finalOutcomeColor.getRed());
    model.addAttribute("colourg", finalOutcomeColor.getGreen());
    model.addAttribute("colourb", finalOutcomeColor.getBlue());

    // transformer for parsing tables
    FileCheckWebTableTransformer transformer = new FileCheckWebTableTransformer();

    // summary table headings
    List<String> summaryColumns = transformer.getColumnHeaders(summaryTableModel);
    model.addAttribute("summaryColumns", summaryColumns);

    // summary table
    List summaryContents = transformer.getTableContents(summaryTableModel);
    model.addAttribute("summary", summaryContents);

    // detail table headings
    List<String> detailColumns = transformer.getColumnHeaders(reportTableModel);
    model.addAttribute("detailColumns", detailColumns);

    // detail report table
    List detailContents = transformer.getTableContents(reportTableModel);
    model.addAttribute("detail", detailContents);

    // delete the uploaded file
    inputFile.delete();

    // Return results display
    return "check";
}