Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

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

Prototype

@Override
public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte to this buffered output stream.

Usage

From source file:eu.esdihumboldt.hale.io.geoserver.AbstractResource.java

/**
 * @see eu.esdihumboldt.hale.io.geoserver.Resource#write(java.io.OutputStream)
 */// w ww. j  a v a 2  s.  c  o  m
@Override
public void write(OutputStream out) throws IOException {

    // unset unspecified variables by setting their value to null
    for (String var : this.allowedAttributes) {
        if (!this.attributes.containsKey(var)) {
            this.attributes.put(var, null);
        }
    }

    InputStream resourceStream = locateResource();
    if (resourceStream != null) {
        BufferedInputStream input = new BufferedInputStream(resourceStream);
        BufferedOutputStream output = new BufferedOutputStream(out);
        try {

            for (int b = input.read(); b >= 0; b = input.read()) {
                output.write(b);
            }
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                // ignore exception on close
            }
            try {
                output.close();
            } catch (IOException e) {
                // ignore exception on close
            }
        }
    }

}

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:org.iti.agrimarket.view.UserController.java

@RequestMapping(value = { "/uprofile.htm" }, method = RequestMethod.POST)
public String updateUserProfile(@RequestParam(value = "fullName", required = true) String fullName,
        @RequestParam(value = "mobile", required = true) String mobil,
        @RequestParam(value = "governerate", required = true) String governerate,
        @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,
        Locale locale, Model model) {
    System.out.println("hhhhhhhhhhhhhhhhhhhhhh" + file.getName());

    String language = locale.getLanguage();
    locale = LocaleContextHolder.getLocale();
    User user = (User) request.getSession().getAttribute("user");
    if (user != null) {
        user.setFullName(fullName);//from   w  w  w .ja  v  a2 s  .c o m
        user.setGovernerate(governerate);
        if (file != null) {
            try {
                user.setImage(file.getBytes());
                byte[] image = user.getImage();

                MagicMatch match = null;
                try {
                    match = Magic.getMagicMatch(image);
                } catch (MagicParseException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (MagicMatchNotFoundException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (MagicException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                }
                String ext = null;
                if (match != null)
                    ext = "." + match.getExtension();

                File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH);
                if (!parentDir.isDirectory()) {
                    parentDir.mkdirs();
                }
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                        new File(Constants.IMAGE_PATH + Constants.USER_PATH + file.getOriginalFilename())));
                stream.write(image);
                stream.close();
                user.setImageUrl(
                        Constants.IMAGE_PRE_URL + Constants.USER_PATH + file.getOriginalFilename() + ext);

            } catch (IOException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        user.setMobile(mobil);
        int res = userService.updateUser(user);
        if (res != 0) {

            request.getSession().setAttribute("user", user);
        }
        model.addAttribute("user", user);
    }
    model.addAttribute("lang", locale);

    return "profile";
}

From source file:net.sourceforge.fenixedu.util.sibs.SibsOutgoingPaymentFile.java

public void save(final File destinationFile) {
    BufferedOutputStream outputStream = null;
    try {/* w w w . j  a v a 2 s.co m*/
        outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile));
        outputStream.write(render().getBytes());
        outputStream.flush();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Pull specified Version of Tomcat from Internet Download Site ...
 *
 * @param GENERATION_LOGGER Logger/*w  w w.j a  v a  2s. co m*/
 * @param tomcatInstance    POJO
 */
protected static boolean pullTomcatVersionFromApacheMirror(GenerationLogger GENERATION_LOGGER,
        TomcatAvailableArchives tomcatAvailableArchives, TomcatInstance tomcatInstance) {
    /**
     * First determine the Latest Release based upon our Short name.
     */
    TomcatArchive tomcatArchive = tomcatAvailableArchives
            .getAvailableArchiveByShortName(tomcatInstance.getTomcatVersion());
    if (tomcatArchive == null || tomcatArchive.getShortVersion() == null) {
        GENERATION_LOGGER.error("Unable to determine a Download Archive for Tomcat Version: "
                + tomcatInstance.getTomcatVersion() + ", Notify Engineering to Support new Version of Tomcat!");
        return false;
    }
    tomcatInstance.setTomcatArchive(tomcatArchive); // Set a Reference to archive used.
    /**
     * Now check to see if the Artifact has already been pulled?
     */
    if (validateTomcatDownloadedVersion(GENERATION_LOGGER, tomcatInstance, false)) {
        GENERATION_LOGGER.info("Using previously Downloaded Archive: " + tomcatArchive.getName() + ".zip");
        return true;
    }
    /**
     * Proceed to Pull Archive ...
     */
    GENERATION_LOGGER.info("Pulling Tomcat Version from Apache Mirror ...");

    URL url = null;
    URLConnection con = null;
    int i;
    try {
        /**
         * Construct the Apache Mirror URL to Pull Tomcat Instance.
         * Assume a V8 version ...
         */
        String tcHeadVersion;
        if (tomcatInstance.getTomcatVersion().startsWith("v8")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_8_MIRROR_HEAD;
        } else if (tomcatInstance.getTomcatVersion().startsWith("v9")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_9_MIRROR_HEAD;
        } else {
            GENERATION_LOGGER.error("Unable to determine a Download URL for Tomcat Version: "
                    + tomcatInstance.getTomcatVersion()
                    + ", Notify Engineering to Support new Version of Tomcat!");
            return false;
        }
        /**
         * Now construct the URL to use to Pull over Internet.
         */
        url = new URL(tomcatAvailableArchives.getApacheMirrorHeadUrl() + "/" + tcHeadVersion + "/v"
                + tomcatArchive.getShortVersion() + "/bin/" + tomcatArchive.getName() + ".zip");
        GENERATION_LOGGER.info("Using URL for Downloading Artifact: " + url.toString());

        con = url.openConnection();
        BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(tomcatInstance.getDestinationFolder().getAbsolutePath() + File.separator
                        + tomcatArchive.getName() + ".zip"));
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
        bis.close();
        GENERATION_LOGGER.info("Successfully Pulled Tomcat Version from Apache Mirror ...");
        return true;
    } catch (MalformedInputException malformedInputException) {
        malformedInputException.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
    /**
     * Indicate a Failure has Occurred
     */
    return false;
}

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

/**
 * Amr upload image and form data/*from w ww  . ja v  a  2s  .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.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   www. j a  va  2 s  .  co m
            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//from w  w w  .  jav a  2  s  .  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:com.awstrainers.devcourse.sdkdemos.S3Test.java

private File createTempFile() throws IOException {
    BufferedOutputStream out = null;
    try {/*from   w w w.j a  v a2  s.  c  o m*/
        File file = File.createTempFile("s3test" + UUID.randomUUID(), ".txt");

        byte[] zeroes = new byte[1024];
        out = new BufferedOutputStream(new FileOutputStream(file));
        for (int i = 0; i < 100; i++) {
            out.write(zeroes);
        }
        return file;
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:com.oakesville.mythling.util.HttpHelper.java

private void writeRequestBytes(OutputStream os) throws IOException {
    BufferedOutputStream bos = null;
    try {/*from w  w  w  .  j  av  a 2 s. c o m*/
        bos = new BufferedOutputStream(os);
        bos.write(postContent);
    } finally {
        if (bos != null)
            bos.close();
    }
}