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:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public void activate(final Context context, final SignedObj obj) {
    Runnable r = new Runnable() {
        @Override/*  www . ja  v  a2  s  .co m*/
        public void run() {
            byte[] bytes = obj.getRaw();
            if (bytes == null) {
                Pair<JSONObject, byte[]> p = splitRaw(obj.getJson());
                //                content = p.first;
                bytes = p.second;
            }

            /*AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bytes.length, AudioTrack.MODE_STATIC);
            track.write(bytes, 0, bytes.length);
            try { // TODO: hack.
            Thread.sleep(500);
             } catch (InterruptedException e) {
             }
            track.play();
            */
            /****/

            File file = new File(getTempFilename());
            try {
                OutputStream os = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                bos.write(bytes, 0, bytes.length);
                bos.flush();
                bos.close();

                copyWaveFile(getTempFilename(), getFilename());
                deleteTempFile();

                MediaPlayer mp = new MediaPlayer();

                mp.setDataSource(getFilename());
                mp.prepare();
                mp.start();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    if (context instanceof Activity) {
        ((Activity) context).runOnUiThread(r);
    } else {
        r.run();
    }
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFile(Object context, URI uri, File file, boolean reuse, IDownloadListener listener) {
    BufferedInputStream strm = null;
    if (listener != null) {
        listener.onBegin(context, file);
    }//  w  w w . j ava  2s  .  c  om
    try {
        HttpClient client = ApplicationEx.getInstance().getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            long total = (int) entity.getContentLength();
            long position = 0;
            if (!(file.exists() && reuse && file.length() == total)) {
                if (file.exists()) {
                    file.delete();
                }
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(entity.getContent());
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] bytes = new byte[2048];
                    for (int c = in.read(bytes); c != -1; c = in.read(bytes)) {
                        out.write(bytes, 0, c);
                        position += c;
                        if (listener != null) {
                            if (!listener.onUpdate(context, position, total)) {
                                throw new DownloadCanceledException();
                            }
                        }
                    }

                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
            if (listener != null) {
                listener.onDone(context, file);
            }
        } else {
            String message = "Failed to download URL " + uri.toString() + " due error " + status.getStatusCode()
                    + " " + status.getReasonPhrase();
            throw new Exception(message);
        }
    } catch (DownloadCanceledException ex) {
        if (listener != null) {
            listener.onCanceled(context, file);
        }
    } catch (Exception ex) {
        if (listener != null) {
            listener.onFailed(context, file, ex);
        }
    } finally {
        if (strm != null) {
            try {
                strm.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.br.uepb.controller.MedicaoController.java

@RequestMapping(value = "/home/medicao.html", method = RequestMethod.POST)
public ModelAndView medicaoPost(HttpServletRequest request, Model model,
        @ModelAttribute("uploadItem") UploadItem uploadItem) {

    String login = request.getSession().getAttribute("login").toString();

    SessaoBusiness sessao = GerenciarSessaoBusiness.getSessaoBusiness(login);
    MedicoesBusiness medicoesBusiness = new MedicoesBusiness();
    LoginDomain loginDomain = sessao.getLoginDomain();

    ModelAndView modelAndView = new ModelAndView();
    String mensagem = "";
    String status = "";

    @SuppressWarnings("deprecation")
    String uploadRootPath = request.getRealPath(File.separator);

    File uploadRootDir = new File(uploadRootPath);

    // Cria o diretrio se no existir
    if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();/*from   ww  w.j av a  2  s .c o m*/
    }
    CommonsMultipartFile fileData = uploadItem.getFileData();

    // Nome do arquivo cliente
    String name = fileData.getOriginalFilename();

    if (name != null && name.length() > 0) {
        try {
            // Create the file on server
            File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(fileData.getBytes());
            stream.close();
            // Salvou o arquivo xml

            String tipo_dispositivo = uploadItem.getTipo_dispositivo();
            String arquivo = serverFile.toString();

            if (tipo_dispositivo.equals("2")) { // oximetro
                modelAndView.addObject("tipoDispositivo", 2);
                if (medicoesBusiness.medicaoOximetro(arquivo, login)) {
                    //medicoesBusiness.medicaoOximetro(arquivo);
                    mensagem = "Medio Oximetro cadastrada com sucesso!";
                    status = "0";

                    MedicaoOximetroDomain oximetro = medicoesBusiness
                            .listaUltimaMedicaoOximetro(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", oximetro);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);

                } else {
                    mensagem = "Erro ao cadastrar Oximetro arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("1")) { // balanca
                modelAndView.addObject("tipoDispositivo", 1);
                if (medicoesBusiness.medicaoBalanca(arquivo, login)) {
                    mensagem = "Medio Balana cadastrada com sucesso!";
                    status = "0";

                    MedicaoBalancaDomain balanca = medicoesBusiness
                            .listaUltimaMedicaoBalanca(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", balanca);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Balana arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("3")) { // pressao
                modelAndView.addObject("tipoDispositivo", 3);
                if (medicoesBusiness.medicaoPressao(arquivo, login)) {
                    mensagem = "Medio Presso cadastrada com sucesso!";
                    status = "0";

                    MedicaoPressaoDomain pressao = medicoesBusiness
                            .listaUltimaMedicaoPressao(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", pressao);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Presso arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("0")) { // icg
                modelAndView.addObject("tipoDispositivo", 0);
                if (medicoesBusiness.medicaoIcg(arquivo, login)) {
                    mensagem = "Medio ICG cadastrada com sucesso!";
                    status = "0";

                    MedicaoIcgDomain icg = medicoesBusiness
                            .listaUltimaMedicaoIcg(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", icg);

                } else {
                    mensagem = "Erro ao cadastrar ICG arquivo XML!";
                    status = "1";
                }
            } else {
                mensagem = "Erro ao cadastrar arquivo XML!";
                status = "1";
            }

        } catch (Exception e) {
            mensagem = "Erro ao cadastrar arquivo XML!";
            status = "1";
        }
    } else {
        mensagem = "O arquivo no foi informado ou est vazio";
        status = "1";
    }

    if (status == "1") {
        modelAndView.addObject("tipoDispositivo", null);
        modelAndView.addObject("oximetro", null);
        modelAndView.addObject("balanca", null);
        modelAndView.addObject("pressao", null);
        modelAndView.addObject("icg", null);
    }

    model.addAttribute("mensagem", mensagem);
    model.addAttribute("status", status);
    modelAndView.setViewName("home/medicao");
    return modelAndView;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

public static void unzip(String sourceFile, String destDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(sourceFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry = null;// w w w  .  j  a v  a2 s .c o m

    int BUFFER_SIZE = 4096;
    while ((entry = zis.getNextEntry()) != null) {
        String dst = destDir + File.separator + entry.getName();
        if (entry.isDirectory()) {
            createDir(destDir, entry);
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];

        // write the file to the disk
        FileOutputStream fos = new FileOutputStream(dst);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        // close the output streams
        dest.flush();
        dest.close();
    }

    zis.close();
}

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

/**
 * Amr upload image and form data/*  ww w .j  a v a 2  s  . c o m*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/addoffer")
public String addOffer(@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, @ModelAttribute("user") User userFromSession,
        @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes,
        HttpServletRequest request, HttpServletResponse response) {

    if (userFromSession == null) {
        return "login";
    } else {

        user = userFromSession;
    }

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

    UserOfferProductFixed userOfferProductFixed = new UserOfferProductFixed();

    userOfferProductFixed.setDescription(description);
    userOfferProductFixed.setPrice(price);
    userOfferProductFixed.setRecommended(Boolean.FALSE);

    userOfferProductFixed.setQuantity(quantity);
    userOfferProductFixed.setProduct(productService.getProduct(product));
    userOfferProductFixed.setUnitByUnitId(unitService.getUnit(quantityunit));
    userOfferProductFixed.setUnitByPricePerUnitId(unitService.getUnit(unitprice));
    userOfferProductFixed.setUser(userService.getUser(user.getId()));
    userOfferProductFixed.setUserLocation(governerate);
    userOfferProductFixed.setUserPhone(mobile);
    userOfferProductFixed.setStartDate(new Date());

    int res = offerService.addOffer(userOfferProductFixed);

    if (!file.isEmpty()) {

        String fileName = userOfferProductFixed.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.OFFER_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

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

            stream.close();
            userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.OFFER_PATH + fileName + ext);
            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/addoffer.htm";
        }

    } else {

        userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.OFFER_PATH + "default_offer.jpg");

        offerService.updateOffer(userOfferProductFixed);

    }

    User oldUser = (User) request.getSession().getAttribute("user");
    if (oldUser != null) {
        User user = userService.getUserEager(oldUser.getId());
        request.getSession().setAttribute("user", user);
    }
    return "redirect:/web/offers.htm";
}

From source file:com.clarionmedia.infinitum.internal.caching.RestResponseCache.java

@Override
protected void writeValueToDisk(File file, RestResponse data) throws IOException {
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
    outputStream.write(data.getStatusCode());
    byte[] headerData = getHeaderData(data.getHeaders());
    outputStream.write(headerData.length);
    outputStream.write(headerData);/*w w w  .j  ava2  s.  c  o  m*/
    outputStream.write(data.getResponseData());
    outputStream.close();
}

From source file:com.card.loop.xyz.controller.LearningObjectController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam(value = "title") String title, @RequestParam("author") String author,
        @RequestParam("description") String description, @RequestParam("file") MultipartFile file,
        @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {//from  w  ww .j a v  a 2s.  c  om
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.UPLOAD_BASE_PATH + file.getOriginalFilename());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningObject lo = new LearningObject();
            System.out.println(title);
            System.out.println(author);
            System.out.println(description);

            lo.setTitle(title);
            lo.setUploadedBy(author);
            lo.setDateUpload(new Date());
            lo.setDescription(description);
            lo.setStatus(0);
            lo.setDownloads(0);
            lo.setRating(1);

            System.out.println("UPLOAD LO FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }

    return "redirect:/developer-update";
}

From source file:org.iti.agrimarket.service.ProductRestController.java

/**
 * Responsible for adding new product/*  w w  w.j av  a2s.co m*/
 *
 * @param paramJsoncontains Json object of the product's data, and parent
 * category id
 * @param user Name of the user sending the request
 * @param key Encrypted key using the user's key
 * @param file The image of the product
 * @return Json {"success":1} if added successfully or status code with the
 * error
 */
@RequestMapping(value = Constants.ADD_PRODUCT_URL, method = RequestMethod.POST)
public Response addProduct(@RequestBody String paramJson) {

    //Parse the parameter
    Product product = paramExtractor.getParam(paramJson, Product.class);

    //Validate product
    if (product == null
            || ((product.getNameAr() == null || product.getNameAr().isEmpty())
                    && (product.getNameEn() == null || product.getNameEn().isEmpty()))
            || ((product.getNameAr() != null && product.getNameAr().length() > 44)
                    || (product.getNameEn() != null && product.getNameEn().length() > 44))) {
        logger.error(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }

    Integer parentCategory = product.getCategory().getId();

    //Check that parent category exists
    Category category = categorySrevice.getCategory(parentCategory);
    if (category == null) {
        logger.error(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }
    product.setCategory(category);

    //Add product
    productService.addProduct(product);

    //Use the generated id to form the image name
    String name = product.getId() + String.valueOf(new Date().getTime());

    //Save image
    if (product.getImage() != null) {
        try {
            byte[] bytes = product.getImage();
            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 + name)));
            stream.write(bytes);
            stream.close();

            //Set the image url in the db
            product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + name + ext);
            productService.updateProduct(product);
        } catch (Exception e) {
            logger.error(e.getMessage());

            productService.deleteProduct(product.getId()); // delete the offer if something goes wrong
            return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
        }
    } else {
        logger.error(Constants.IMAGE_UPLOAD_ERROR);

        productService.deleteProduct(product.getId()); //also here should delete the offer  
        return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
    }
    return Response.ok(Constants.SUCCESS_JSON, MediaType.APPLICATION_JSON).build();
}

From source file:web.diva.server.model.profileplot.ProfilePlotImgeGenerator.java

@SuppressWarnings("CallToPrintStackTrace")
public String toPdfFile(File userFolder, String url) {
    try {// ww w. jav  a  2  s  . c  o  m
        BufferedImage pdfImage = image;

        DOMImplementation domImpl = new SVGDOMImplementation();
        String svgNS = "http://www.w3.org/2000/svg";
        SVGDocument svgDocument = (SVGDocument) domImpl.createDocument(svgNS, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(svgDocument);
        svgGenerator.setSVGCanvasSize(new Dimension(pdfImage.getWidth(), pdfImage.getHeight()));
        svgGenerator.setPaint(Color.WHITE);
        svgGenerator.drawImage(pdfImage, 0, 0, null);
        File pdfFile = new File(userFolder, dataset.getName() + "_Profile_Plot" + ".pdf");
        if (!pdfFile.exists()) {
            pdfFile.createNewFile();
        } else {
            pdfFile.delete();
            pdfFile.createNewFile();
        }
        // write the svg file
        File svgFile = new File(pdfFile.getAbsolutePath() + ".temp");
        OutputStream outputStream = new FileOutputStream(svgFile);
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        Writer out = new OutputStreamWriter(bos, "UTF-8");

        svgGenerator.stream(out, true /* use css */);
        outputStream.flush();
        outputStream.close();
        bos.close();
        System.gc();
        String svgURI = svgFile.toURI().toString();
        TranscoderInput svgInputFile = new TranscoderInput(svgURI);

        OutputStream outstream = new FileOutputStream(pdfFile);
        bos = new BufferedOutputStream(outstream);
        TranscoderOutput output = new TranscoderOutput(bos);
        Transcoder pdfTranscoder = new PDFTranscoder();
        pdfTranscoder.addTranscodingHint(PDFTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, 0.084666f);
        pdfTranscoder.transcode(svgInputFile, output);
        outstream.flush();
        outstream.close();
        bos.close();
        System.gc();
        return url + userFolder.getName() + "/" + pdfFile.getName();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";

}

From source file:edu.stanford.mobisocial.dungbeetle.obj.action.PlayAllAudioAction.java

public void playNextSong() {
    if (c.isAfterLast()) {
        c.close();/* ww  w.  j a  v a  2s.  c  om*/
        alert.dismiss();
        return;
    }

    try {
        final JSONObject objData = new JSONObject(c.getString(c.getColumnIndex(DbObject.JSON)));
        Runnable r = new Runnable() {
            @Override
            public void run() {

                Log.w("PlayAllAudioAction", objData.optString("feedName"));
                byte bytes[] = Base64.decode(objData.optString(VoiceObj.DATA), Base64.DEFAULT);

                File file = new File(getTempFilename());
                try {
                    OutputStream os = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(os);
                    bos.write(bytes, 0, bytes.length);
                    bos.flush();
                    bos.close();

                    copyWaveFile(getTempFilename(), getFilename());
                    deleteTempFile();

                    mp = new MediaPlayer();

                    mp.setDataSource(getFilename());
                    mp.setOnCompletionListener(new OnCompletionListener() {

                        public void onCompletion(MediaPlayer m) {
                            Log.w("PlayAllAudioAction", "finished");
                            c.moveToNext();
                            playNextSong();
                        }
                    });
                    mp.prepare();
                    mp.start();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        if (context instanceof Activity) {
            ((Activity) context).runOnUiThread(r);
        } else {
            r.run();
        }
    } catch (Exception e) {
    }

}