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:org.openmrs.module.reportingsummary.web.controller.summary.GenerateSummariesController.java

@RequestMapping(method = RequestMethod.POST)
public void process(final @RequestParam(required = true, value = "template") MultipartFile template,
        final HttpServletResponse response) throws IOException, EvaluationException {

    PatientDataSetDefinition definition = new PatientDataSetDefinition();

    definition.addColumn("id", new PatientIdDataDefinition(), StringUtils.EMPTY, new ObjectFormatter());

    ListConverter listConverter = new ListConverter();
    listConverter.setMaxNumberOfItems(1);

    PatientIdentifierDataDefinition preferredIdentifier = new PatientIdentifierDataDefinition();
    definition.addColumn("identifier", preferredIdentifier, StringUtils.EMPTY, listConverter);

    definition.addColumn("name", new PreferredNameDataDefinition(), StringUtils.EMPTY,
            new ObjectFormatter("{familyName}, {givenName}"));

    AgeDataDefinition ageOnDate = new AgeDataDefinition();
    ageOnDate.addParameter(new Parameter("effectiveDate", "effective date", Date.class));
    definition.addColumn("age", ageOnDate, "effectiveDate=${currentDate}", new AgeConverter());

    definition.addColumn("birthdate", new BirthdateDataDefinition(), StringUtils.EMPTY,
            new BirthdateConverter("dd-MMM-yyyy"));
    definition.addColumn("gender", new GenderDataDefinition(), StringUtils.EMPTY, new ObjectFormatter());

    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setName("Test Report");
    reportDefinition.addDataSetDefinition("PatientDataSetDefinition", definition, null);

    final ReportDesign design = new ReportDesign();
    design.setName("Test Report Design With Excel Template Renderer");
    design.setReportDefinition(reportDefinition);
    design.setRendererType(ExcelTemplateRenderer.class);

    Properties properties = new Properties();
    properties.put("repeatingSections", "sheet:1,dataset:PatientDataSetDefinition");
    design.setProperties(properties);//w w w . j a va  2 s .  c  o  m

    ReportDesignResource resource = new ReportDesignResource();
    resource.setName("excel-template.xls");
    Properties props = new Properties();
    InputStream inputStream = template.getInputStream();
    resource.setContents(IOUtils.toByteArray(inputStream));
    IOUtils.closeQuietly(inputStream);
    design.addResource(resource);

    ExcelTemplateRenderer renderer = new ExcelTemplateRenderer() {
        public ReportDesign getDesign(String argument) {
            return design;
        }
    };

    ReportDefinitionService rs = Context.getService(ReportDefinitionService.class);
    ReportData data = rs.evaluate(reportDefinition, prepareEvaluationContext());

    CsvReportRenderer csvReportRenderer = new CsvReportRenderer();
    csvReportRenderer.render(data, "output:csv", System.out);

    File file = File.createTempFile("excel", "summary");
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
    renderer.render(data, "output:xls", bufferedOutputStream);
    bufferedOutputStream.close();

    response.setHeader("Content-Disposition", "attachment; filename=patient-summary.xls");
    response.setContentType("application/vnd.ms-excel");
    response.setContentLength((int) file.length());

    FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
    if (file.delete())
        log.info("Temporary file deleted!");
}

From source file:au.com.addstar.SpigotDirectDownloader.java

public boolean downloadUpdate(ResourceInfo info, File file, Long timeOut)
        throws InvalidDownloadException, ConnectionFailedException {
    try {//from w w  w.j  ava2  s . c  o  m
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        Resource resource = api.getResourceManager().getResourceById(info.id, spigotUser);
        if (info.premium && !owned.contains(resource.getResourceId())) {
            return false;
        }
        Page page = webClient.getPage(resource.getDownloadURL());
        webClient.waitForBackgroundJavaScript(timeOut); // todo need to add check for need purchase or no auth.
        BufferedInputStream in = new java.io.BufferedInputStream(
                page.getEnclosingWindow().getEnclosedPage().getWebResponse().getContentAsStream());
        java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
        java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
        byte[] data = new byte[1024];
        int x;
        while ((x = in.read(data, 0, 1024)) >= 0) {
            bout.write(data, 0, x);
        }
        bout.close();
        in.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Plugin plugin = Plugin.checkDownloadedVer(file);
    if (plugin == null || plugin.getVersion() == null) {
        FileUtils.deleteQuietly(file);
        if (timeOut < 15000L && info.external) {
            downloadUpdate(info, file, timeOut + 5000L);
        }
        throw new InvalidDownloadException("File did not contain a plugin.yml");
    }
    return true;
}

From source file:eu.scape_project.archiventory.container.ZipContainer.java

/**
 * Extracts a zip entry (file entry)/*from  w  w w. j  a  va 2  s .  com*/
 * @param zipIn
 * @param filePath
 * @throws IOException
 */
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
    byte[] bytesIn = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = zipIn.read(bytesIn)) != -1) {
        bos.write(bytesIn, 0, read);
    }
    bos.close();
    if ((new File(filePath).exists())) {
        String id = filePath.replaceFirst("[0-9]{10,30}", "");
        //id = id.replace(this.tmpDirName"/tmp", "");
        // key-value pair
        this.put(filePath, filePath);
    }
}

From source file:fr.shywim.antoinedaniel.sync.AppState.java

/**
 * Save the AppState to a file.//from w  w w .  j  a va2  s  . c  o m
 *
 * @param context a context.
 */
public void save(Context context) {
    if (changed) {
        File privDir = context.getFilesDir();
        File appState = new File(privDir, FILE_NAME);

        try {
            byte[] bytes = getAsByteArray();
            if (appState.exists() || (!appState.exists() && appState.createNewFile())) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(appState));
                bos.write(bytes);
                bos.flush();
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.fhaes.fhsamplesize.view.SSIZCurveChart.java

/**
 * Save chart as PDF file. Requires iText library.
 * //from   w w  w  .ja va  2s  .c  om
 * @param chart JFreeChart to save.
 * @param fileName Name of file to save chart in.
 * @param width Width of chart graphic.
 * @param height Height of chart graphic.
 * @throws Exception if failed.
 * @see <a href="http://www.lowagie.com/iText">iText</a>
 */
@SuppressWarnings("deprecation")
public static void writeAsPDF(File fileToSave, int width, int height) throws Exception {

    if (chart != null) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(fileToSave.getAbsolutePath()));

            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            Document document = new Document(pagesize, 50, 50, 50, 50);
            try {
                PdfWriter writer = PdfWriter.getInstance(document, out);
                document.addAuthor("JFreeChart");
                document.open();

                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());

                Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
                chart.draw(g2, r2D, null);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
            } finally {
                document.close();
            }
        } finally {
            if (out != null)
                out.close();
        }
    }
}

From source file:org.iti.agrimarket.administration.view.AddProductController.java

/**
 * Amr upload image and form data//from   w  ww .jav a 2 s.co m
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/addproduct")
public String addproduct(@RequestParam("nameAr") String nameAr, @RequestParam("nameEn") String nameEn,
        @RequestParam("parentCategoryId") int parentCategoryId, @RequestParam("file") MultipartFile file) {

    System.out.println("save user func ---------");
    System.out.println("full Name :" + nameAr);

    Product product = new Product();
    product.setNameAr(nameAr);

    product.setNameEn(nameEn);
    Category parentCategory = categoryService.getCategory(parentCategoryId);

    product.setCategory(parentCategory);

    product.setSoundUrl("/to be continue");

    int res = productService.addProduct(product);

    if (!file.isEmpty()) {
        String fileName = product.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.PRODUCT_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.PRODUCT_PATH + fileName)));
            stream.write(bytes);

            stream.close();
            product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + fileName + ext);
            productService.updateProduct(product);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            productService.deleteProduct(product.getId()); // delete the category if something goes wrong
            return "redirect:/admin/products_page.htm";
        }

    } else {

        product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + "default_category.jpg");
        productService.updateProduct(product);

    }

    return "redirect:/admin/products_page.htm";
}

From source file:com.castlemock.web.basis.manager.FileManager.java

/**
 * The method uploads a list of MultipartFiles to the server. The output file directory is configurable and can be
 * configured in the main property file under the key "temp.file.directory"
 * @param files The list of files that should be uploaded
 * @return Returns the uploaded files as a list of files. The files have the new server path.
 * @throws IOException Throws an exception if the upload fails.
 *///www.  j  ava2  s  .c  o  m
public List<File> uploadFiles(final List<MultipartFile> files) throws IOException {
    final File fileDirectory = new File(tempFilesFolder);

    if (!fileDirectory.exists()) {
        fileDirectory.mkdirs();
    }

    final List<File> uploadedFiles = new ArrayList<File>();
    LOGGER.debug("Starting uploading files");
    for (MultipartFile file : files) {
        if (file.getOriginalFilename().isEmpty()) {
            continue;
        }

        LOGGER.debug("Uploading file: " + file.getOriginalFilename());
        final File serverFile = new File(
                fileDirectory.getAbsolutePath() + File.separator + file.getOriginalFilename());
        final byte[] bytes = file.getBytes();
        final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        try {
            stream.write(bytes);
            uploadedFiles.add(serverFile);
        } finally {
            stream.close();
        }
    }
    return uploadedFiles;
}

From source file:edu.jhuapl.graphs.controller.GraphObject.java

public void writeChartAsHighResolutionTIFF(OutputStream out, String dir, int graphWidth, int graphHeight,
        int resolution) throws IOException {

    try {/*from w  ww.ja  v  a 2 s  .c  o  m*/
        // Source file will be a png file
        String source = getImageFileName();
        if (!source.contains(".png")) {
            source = source + ".png";
        }

        // Create png file object
        File pngFile = new File(dir, source);

        System.out.println("Creating png file: " + pngFile.getAbsolutePath());

        // Write a high resolution PNG file
        BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(pngFile));
        writeChartAsHighResolutionPNG(out1, graphWidth, graphHeight, resolution);
        out1.close();

        // Set resolution for Tiff file
        TIFFEncodeParam param = new TIFFEncodeParam();
        // Create {X,Y}Resolution fields.
        TIFFField fieldXRes = new TIFFField(0x11A, TIFFField.TIFF_RATIONAL, 1,
                new long[][] { { resolution, 1 } });
        TIFFField fieldYRes = new TIFFField(0x11B, TIFFField.TIFF_RATIONAL, 1,
                new long[][] { { resolution, 1 } });
        param.setExtraFields(new TIFFField[] { fieldXRes, fieldYRes });

        // Encode a tiff file
        RenderedOp src = JAI.create("fileload", pngFile.getAbsolutePath());
        TIFFImageEncoder encoder = new TIFFImageEncoder(out, param);
        encoder.encode(src);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/singleSave", method = RequestMethod.POST)
public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file,
        @RequestParam("desc") String desc) {
    System.out.println("File Description:" + desc);
    String fileName = null;//  ww  w.ja v  a 2s . c om
    if (!file.isEmpty()) {
        try {
            fileName = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            BufferedOutputStream buffStream = new BufferedOutputStream(
                    new FileOutputStream(new File("C:/cp/" + fileName)));
            buffStream.write(bytes);
            buffStream.close();
            return "You have successfully uploaded " + fileName;
        } catch (Exception e) {
            return "You failed to upload " + fileName + ": " + e.getMessage();
        }
    } else {
        return "Unable to upload. File is empty.";
    }
}

From source file:net.sf.sahi.util.Utils.java

public static byte[] getBytes(final InputStream in, final int contentLength) throws IOException {
    BufferedInputStream bin = new BufferedInputStream(in, BUFFER_SIZE);

    if (contentLength != -1) {
        int totalBytesRead = 0;
        byte[] buffer = new byte[contentLength];
        while (totalBytesRead < contentLength) {
            int bytesRead = -1;
            try {
                bytesRead = bin.read(buffer, totalBytesRead, contentLength - totalBytesRead);
            } catch (EOFException e) {
            }/*w w w . j  a va  2  s  .c om*/
            if (bytesRead == -1) {
                break;
            }
            totalBytesRead += bytesRead;
        }
        return buffer;
    } else {
        ByteArrayOutputStream byteArOut = new ByteArrayOutputStream();
        BufferedOutputStream bout = new BufferedOutputStream(byteArOut);
        try {
            int totalBytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while (true) {
                int bytesRead = -1;
                try {
                    bytesRead = bin.read(buffer);
                } catch (EOFException e) {
                }
                if (bytesRead == -1) {
                    break;
                }
                bout.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
            }
        } catch (SocketTimeoutException ste) {
            ste.printStackTrace();
        }
        bout.flush();
        bout.close();
        return byteArOut.toByteArray();
    }
}