Example usage for org.springframework.web.multipart MultipartFile getBytes

List of usage examples for org.springframework.web.multipart MultipartFile getBytes

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getBytes.

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

From source file:com.orchestra.portale.controller.NewPoiController.java

@RequestMapping(value = "/insertpoi", method = RequestMethod.POST)
public ModelAndView insertPoi(@RequestParam Map<String, String> params,
        @RequestParam("file") MultipartFile[] files, @RequestParam("cover") MultipartFile cover,
        HttpServletRequest request) throws InterruptedException {

    CompletePOI poi = new CompletePOI();
    CompletePOI poitest = new CompletePOI();

    ModelAndView model = new ModelAndView("insertpoi");
    ModelAndView model2 = new ModelAndView("errorViewPoi");
    poitest = pm.findOneCompletePoiByName(params.get("name"));
    if (poitest != null && poitest.getName().toLowerCase().equals(params.get("name").toLowerCase())) {

        model2.addObject("err", "Esiste gi un poi chiamato " + params.get("name"));
        return model2;
    } else {/*from ww w .ja  v a  2  s  .c om*/
        poi.setName(params.get("name"));
        poi.setVisibility(params.get("visibility"));
        poi.setAddress(params.get("address"));
        double lat = Double.parseDouble(params.get("latitude"));
        double longi = Double.parseDouble(params.get("longitude"));
        poi.setLocation(new double[] { lat, longi });
        poi.setShortDescription(params.get("shortd"));
        int i = 1;
        ArrayList<String> categories = new ArrayList<String>();
        while (params.containsKey("category" + i)) {

            categories.add(params.get("category" + i));

            i = i + 1;
        }
        poi.setCategories(categories);

        ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

        //componente cover
        if (!cover.isEmpty()) {
            CoverImgComponent coverimg = new CoverImgComponent();
            coverimg.setLink("cover.jpg");
            listComponent.add(coverimg);
        }
        //componente galleria immagini
        ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
        if (files.length > 0) {
            ImgGalleryComponent img_gallery = new ImgGalleryComponent();

            i = 0;
            while (i < files.length) {
                ImgGallery img = new ImgGallery();

                Thread.sleep(100);
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
                String currentTimestamp = sdf.format(date);
                img.setLink("img_" + currentTimestamp + ".jpg");
                if (params.containsKey("credit" + (i + 1)))
                    img.setCredit(params.get("credit" + (i + 1)));

                i = i + 1;
                links.add(img);
            }
            img_gallery.setLinks(links);
            listComponent.add(img_gallery);
        }
        //componente contatti
        ContactsComponent contacts_component = new ContactsComponent();
        //Recapiti telefonici
        i = 1;
        boolean contacts = false;
        if (params.containsKey("tel" + i)) {
            ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>();

            while (params.containsKey("tel" + i)) {
                PhoneContact phone = new PhoneContact();
                if (params.containsKey("tel" + i)) {
                    phone.setLabel(params.get("desctel" + i));
                }
                phone.setNumber(params.get("tel" + i));
                phoneList.add(phone);
                i = i + 1;
            }
            contacts = true;
            contacts_component.setPhoneList(phoneList);
        }
        //Recapiti mail
        i = 1;
        if (params.containsKey("email" + i)) {
            ArrayList<EmailContact> emailList = new ArrayList<EmailContact>();

            while (params.containsKey("email" + i)) {
                EmailContact email = new EmailContact();
                if (params.containsKey("email" + i)) {
                    email.setLabel(params.get("descemail" + i));
                }
                email.setEmail(params.get("email" + i));
                emailList.add(email);
                i = i + 1;
            }
            contacts = true;
            contacts_component.setEmailsList(emailList);
        }
        //Recapiti fax
        i = 1;
        if (params.containsKey("fax" + i)) {
            ArrayList<FaxContact> faxList = new ArrayList<FaxContact>();

            while (params.containsKey("fax" + i)) {
                FaxContact fax = new FaxContact();
                if (params.containsKey("fax" + i)) {
                    fax.setLabel(params.get("descfax" + i));
                }
                fax.setFax(params.get("fax" + i));
                faxList.add(fax);
                i = i + 1;
            }
            contacts = true;
            contacts_component.setFaxList(faxList);
        }
        //Social predefiniti
        i = 1;
        if (params.containsKey("SN" + i)) {

            while (params.containsKey("SN" + i)) {
                if (params.get("SN" + i).equals("facebook")) {
                    contacts = true;
                    contacts_component.setFacebook(params.get("LSN" + i));
                }
                if (params.get("SN" + i).equals("twitter")) {
                    contacts = true;
                    contacts_component.setTwitter(params.get("LSN" + i));
                }
                if (params.get("SN" + i).equals("google")) {
                    contacts = true;
                    contacts_component.setGoogle(params.get("LSN" + i));
                }
                if (params.get("SN" + i).equals("skype")) {
                    contacts = true;
                    contacts_component.setSkype(params.get("LSN" + i));
                }
                i = i + 1;
            }
        }
        //Social personalizzati
        i = 1;
        if (params.containsKey("CSN" + i)) {
            ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>();

            while (params.containsKey("CSN" + i)) {
                GenericSocial social = new GenericSocial();
                contacts = true;
                social.setLabel(params.get("CSN" + i));
                social.setSocial(params.get("LCSN" + i));
                customsocial.add(social);
                i = i + 1;
            }
            contacts_component.setSocialList(customsocial);
        }
        if (contacts == true) {
            listComponent.add(contacts_component);
        }
        //DESCRIPTION COMPONENT
        i = 1;
        if (params.containsKey("par" + i)) {
            ArrayList<Section> list = new ArrayList<Section>();

            while (params.containsKey("par" + i)) {
                Section section = new Section();
                if (params.containsKey("titolo" + i)) {
                    section.setTitle(params.get("titolo" + i));
                }
                section.setDescription(params.get("par" + i));
                list.add(section);
                i = i + 1;

            }
            DescriptionComponent description_component = new DescriptionComponent();
            description_component.setSectionsList(list);
            listComponent.add(description_component);
        }
        //Orari
        i = 1;
        int k = 1;
        boolean ok = false;
        String gg = "";
        boolean[] aperto = new boolean[8];
        for (int z = 1; z <= 7; z++) {
            aperto[z] = false;
        }
        WorkingTimeComponent workingtime = new WorkingTimeComponent();
        if (params.containsKey("WD" + i + "start" + k + "H")) {

            ok = true;
            ArrayList<CompactWorkingDays> workingdays = new ArrayList<CompactWorkingDays>();

            while (params.containsKey("WD" + i)) {
                ArrayList<WorkingHours> Listwh = new ArrayList<WorkingHours>();
                k = 1;
                while (params.containsKey("WD" + i + "start" + k + "H")) {
                    WorkingHours wh = new WorkingHours();
                    wh.setStart(params.get("WD" + i + "start" + k + "H") + ":"
                            + params.get("WD" + i + "start" + k + "M"));
                    wh.setEnd(params.get("WD" + i + "end" + k + "H") + ":"
                            + params.get("WD" + i + "end" + k + "M"));
                    Listwh.add(wh);
                    k = k + 1;
                }
                CompactWorkingDays cwd = new CompactWorkingDays();
                cwd.setDays(params.get("WD" + i));
                cwd.setWorkinghours(Listwh);
                workingdays.add(cwd);
                i = i + 1;
            }
            int grn = 1;
            ArrayList<CompactWorkingDays> wdef = new ArrayList<CompactWorkingDays>();

            for (int z = 1; z <= 7; z++) {
                aperto[z] = false;
            }
            while (grn <= 7) {

                for (CompactWorkingDays g : workingdays) {

                    if (grn == 1 && g.getDays().equals("Luned")) {
                        aperto[1] = true;
                        wdef.add(g);
                    }
                    if (grn == 2 && g.getDays().equals("Marted")) {
                        aperto[2] = true;
                        wdef.add(g);
                    }
                    if (grn == 3 && g.getDays().equals("Mercoled")) {
                        aperto[3] = true;
                        wdef.add(g);
                    }
                    if (grn == 4 && g.getDays().equals("Gioved")) {
                        aperto[4] = true;
                        wdef.add(g);
                    }
                    if (grn == 5 && g.getDays().equals("Venerd")) {
                        aperto[5] = true;
                        wdef.add(g);
                    }
                    if (grn == 6 && g.getDays().equals("Sabato")) {
                        aperto[6] = true;
                        wdef.add(g);
                    }
                    if (grn == 7 && g.getDays().equals("Domenica")) {
                        aperto[7] = true;
                        wdef.add(g);
                    }

                }
                grn++;
            }
            workingtime.setWorkingdays(wdef);
            for (int z = 1; z <= 7; z++) {
                if (aperto[z] == false && z == 1)
                    gg = gg + " " + "Luned";
                if (aperto[z] == false && z == 2)
                    gg = gg + " " + "Marted";
                if (aperto[z] == false && z == 3)
                    gg = gg + " " + "Mercoled";
                if (aperto[z] == false && z == 4)
                    gg = gg + " " + "Gioved";
                if (aperto[z] == false && z == 5)
                    gg = gg + " " + "Venerd";
                if (aperto[z] == false && z == 6)
                    gg = gg + " " + "Sabato";
                if (aperto[z] == false && z == 7)
                    gg = gg + " " + "Domenica";
            }

            if (!gg.equals("")) {
                ok = true;
                workingtime.setWeekly_day_of_rest(gg);
            }
        }

        i = 1;
        String ggs = "";
        while (params.containsKey("RDA" + i)) {
            ggs = ggs + " " + params.get("RDA" + i);
            i = i + 1;
        }
        if (!ggs.equals("")) {
            ok = true;
            workingtime.setDays_of_rest(ggs);
        }
        if (ok) {
            listComponent.add(workingtime);
        }

        i = 1;
        if (params.containsKey("type" + i)) {

            PricesComponent pc = new PricesComponent();
            ArrayList<TicketPrice> tpList = new ArrayList<TicketPrice>();
            while (params.containsKey("type" + i)) {
                TicketPrice tp = new TicketPrice();
                tp.setType(params.get("type" + i));
                double dp = Double.parseDouble(params.get("price" + i));
                tp.setPrice(dp);
                tp.setType_description(params.get("typedesc" + i));
                tpList.add(tp);
                i = i + 1;
            }
            pc.setPrices(tpList);
            listComponent.add(pc);
        }

        i = 1;
        if (params.containsKey("SERV" + i)) {
            ArrayList<String> servList = new ArrayList<String>();
            while (params.containsKey("SERV" + i)) {
                servList.add(params.get("SERV" + i));
                i = i + 1;
            }
            ServicesComponent servicescomponent = new ServicesComponent();
            servicescomponent.setServicesList(servList);
            listComponent.add(servicescomponent);
        }
        poi.setComponents(listComponent);

        pm.savePoi(poi);

        CompletePOI poi2 = (CompletePOI) pm.findOneCompletePoiByName(poi.getName());

        for (int z = 0; z < files.length; z++) {
            MultipartFile file = files[z];

            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                HttpSession session = request.getSession();
                ServletContext sc = session.getServletContext();

                File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator
                        + "img" + File.separator + poi2.getId());
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

            } catch (Exception e) {
                return model;
            }
        }
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }

        return model;
    }
}

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

/**
 * Amr upload image and form data/* w  ww .j  a  v a2  s  .  com*/
 *
 */
@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:org.iti.agrimarket.administration.view.AddCategoryController.java

/**
 * Amr upload image and form data/*from   ww  w .  jav  a  2s .co m*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/addcategory")
public String addCategory(@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);

    Category category = new Category();
    category.setNameAr(nameAr);
    category.setNameEn(nameEn);
    Category parentCategory = categoryService.getCategory(parentCategoryId);

    category.setCategory(parentCategory);

    category.setSoundUrl("/to be continue");
    int res = categoryService.addCategory(category);

    if (!file.isEmpty()) {
        String fileName = category.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.CATEGORY_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

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

            stream.close();
            category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + fileName + ext);
            categoryService.updateCategory(category);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong
            return "redirect:/admin/categories_page.htm";
        }

    } else {

        category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + "default_category.jpg");
        categoryService.updateCategory(category);

    }

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

From source file:mx.edu.um.mateo.inventario.web.ProductoController.java

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    if (bindingResult.hasErrors()) {
        log.error("Hubo algun error en la forma, regresando");
        return "inventario/producto/edita";
    }/*from  ww  w . j a  v a  2s.c o m*/

    try {
        if (archivo != null && !archivo.isEmpty()) {
            log.debug("SUBIENDO ARCHIVO: {}", archivo.getOriginalFilename());
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.actualiza(producto, usuario);
    } catch (IOException e) {
        log.error("No se pudo actualizar el producto", e);
        errors.rejectValue("imagenes", "problema.con.imagen.message",
                new String[] { archivo.getOriginalFilename() }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/edita";
    } catch (ConstraintViolationException e) {
        log.error("No se pudo actualizar el producto", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/edita";
    }

    redirectAttributes.addFlashAttribute("message", "producto.actualizado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() });

    return "redirect:/inventario/producto/ver/" + producto.getId();
}

From source file:dicky.controlleradmin.ProductAdminController.java

@RequestMapping(value = "prosesInsert", method = RequestMethod.POST)
public String prosesInsert(HttpServletRequest request, HttpSession session, ModelMap modelMap,
        @RequestParam("fileUpload") MultipartFile[] fileUpload) throws ServletException, IOException {

    if (fileUpload != null && fileUpload.length > 0) {
        for (MultipartFile file : fileUpload) {
            String lokasiUpload = tujuanUpload(session).getAbsolutePath();

            System.out.println("Saving file: " + file.getOriginalFilename());
            Product product = new Product();
            product.setIdProduct(request.getParameter("idproduct"));
            product.setNameProduct(request.getParameter("nama"));
            String price = request.getParameter("price");
            product.setPrice(new BigDecimal(price));
            String idkategori = request.getParameter("idkategori");
            Kategori findId = kategoriService.findId(idkategori);
            product.setKategori(findId);
            product.setFilename(file.getOriginalFilename());
            product.setFiledata(file.getBytes());
            File tujuan = new File(lokasiUpload + File.separator + file.getOriginalFilename());
            file.transferTo(tujuan);//  ww  w .  ja  va  2  s  .  c  o  m
            productService.create(product);
            modelMap.put("products", productService.findAll());

        }
    }

    return "redirect:../product.html";
}

From source file:com.glaf.jbpm.web.rest.MxJbpmDeployResource.java

@POST
@Path("deploy")
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
@ResponseBody//from   w w  w  . ja  v a2 s.c  o m
public byte[] deploy(@Context HttpServletRequest request) {
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, Object> paramMap = RequestUtils.getParameterMap(req);
    if (LogUtils.isDebug()) {
        logger.debug(paramMap);
    }
    int status_code = 0;
    String cause = null;
    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        String filename = mFile.getOriginalFilename();
        long filesize = mFile.getSize();
        if (filename == null || filesize <= 0) {
            continue;
        }
        if (filename.endsWith(".jar") || filename.endsWith(".zip")) {
            JbpmContext jbpmContext = null;
            MxJbpmProcessDeployer deployer = new MxJbpmProcessDeployer();
            try {
                jbpmContext = ProcessContainer.getContainer().createJbpmContext();
                if (jbpmContext != null && jbpmContext.getSession() != null) {
                    deployer.deploy(jbpmContext, mFile.getBytes());
                    status_code = 200;
                }
            } catch (Exception ex) {
                if (jbpmContext != null) {
                    jbpmContext.setRollbackOnly();
                }
                status_code = 500;
                throw new JbpmException(ex);
            } finally {
                com.glaf.jbpm.context.Context.close(jbpmContext);
            }
        }
    }

    Map<String, Object> jsonMap = new java.util.HashMap<String, Object>();
    if (status_code == 200) {
        jsonMap.put("statusCode", 200);
        jsonMap.put("message", "???");
    } else if (status_code == 401) {
        jsonMap.put("statusCode", 401);
        jsonMap.put("message", "????");
    } else if (status_code == 500) {
        jsonMap.put("statusCode", 500);
        jsonMap.put("message", "?????");
        jsonMap.put("cause", cause);
    } else {
        jsonMap.put("statusCode", status_code);
        jsonMap.put("message", "??????");
    }

    JSONObject jsonObject = new JSONObject(jsonMap);

    try {
        return jsonObject.toString().getBytes("UTF-8");
    } catch (IOException e) {
        return jsonObject.toString().getBytes();
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddExperimentWizardController.java

@Override
protected ModelAndView processFinish(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception {
    log.debug("Processing measuration form - adding new measuration");
    ModelAndView mav = new ModelAndView("redirect:/experiments/my-experiments.html");

    mav.addObject("userIsExperimenter", auth.userIsExperimenter());

    AddExperimentWizardCommand data = (AddExperimentWizardCommand) command;

    Experiment experiment;/*from www .  j a v  a 2s . c om*/

    log.debug("Checking the permission level.");
    if (!auth.userIsExperimenter()) {
        log.debug("User is not experimenter - unable to add experiment. Returning MAV.");
        mav.setViewName("redirect:experiments/userNotExperimenter");
        return mav;
    }

    log.debug("Creating new Measuration object");
    experiment = new Experiment();

    // This assignment is commited only when new experiment is being created
    log.debug("Setting the owner to the logged user.");
    experiment.setPersonByOwnerId(personDao.getLoggedPerson());

    log.debug("Setting the group, which is the new experiment being added into.");
    ResearchGroup researchGroup = new ResearchGroup();
    researchGroup.setResearchGroupId(data.getResearchGroup());
    experiment.setResearchGroup(researchGroup);

    log.debug("Setting Weather object - ID " + data.getWeather());
    Weather weather = new Weather();
    weather.setWeatherId(data.getWeather());
    experiment.setWeather(weather);

    log.debug("Setting Scenario object - ID " + data.getScenario());
    Scenario scenario = new Scenario();
    scenario.setScenarioId(data.getScenario());
    experiment.setScenario(scenario);

    log.debug("Setting Person object (measured person) - ID " + data.getSubjectPerson());
    Person subjectPerson = new Person();
    subjectPerson.setPersonId(data.getSubjectPerson());
    experiment.setPersonBySubjectPersonId(subjectPerson);

    Date startDate = ControllerUtils.getDateFormatWithTime()
            .parse(data.getStartDate() + " " + data.getStartTime());
    experiment.setStartTime(new Timestamp(startDate.getTime()));
    log.debug("Setting start date - " + startDate);

    Date endDate = ControllerUtils.getDateFormatWithTime().parse(data.getEndDate() + " " + data.getEndTime());
    experiment.setEndTime(new Timestamp(endDate.getTime()));
    log.debug("Setting end date - " + endDate);

    log.debug("Setting the temperature - " + data.getTemperature());
    experiment.setTemperature(Integer.parseInt(data.getTemperature()));

    log.debug("Setting the weather note - " + data.getWeatherNote());
    experiment.setEnvironmentNote(data.getWeatherNote());

    log.debug("Started setting the Hardware objects");
    int[] hardwareArray = data.getHardware();
    Set<Hardware> hardwareSet = new HashSet<Hardware>();
    for (int hardwareId : hardwareArray) {
        System.out.println("hardwareId " + hardwareId);
        Hardware tempHardware = hardwareDao.read(hardwareId);
        hardwareSet.add(tempHardware);
        tempHardware.getExperiments().add(experiment);
        log.debug("Added Hardware object - ID " + hardwareId);
    }
    log.debug("Setting Hardware list to Measuration object");
    experiment.setHardwares(hardwareSet);

    log.debug("Started setting the Person objects (coExperimenters)");
    int[] coExperimentersArray = data.getCoExperimenters();
    Set<Person> coExperimenterSet = new HashSet<Person>();
    for (int personId : coExperimentersArray) {
        Person tempExperimenter = personDao.read(personId);
        coExperimenterSet.add(tempExperimenter);
        tempExperimenter.getExperiments().add(experiment);
        log.debug("Added Person object - ID " + tempExperimenter.getPersonId());
    }
    log.debug("Setting Person list to Measuration object");
    experiment.setPersons(coExperimenterSet);

    log.debug("Setting private/public access");
    experiment.setPrivateExperiment(data.isPrivateNote());
    float samplingRate = Float.parseFloat(data.getSamplingRate());
    Digitization digitization = digitizationDao.getDigitizationByParams(samplingRate, -1, "NotKnown");
    if (digitization == null) {
        digitization = new Digitization();
        digitization.setFilter("NotKnown");
        digitization.setGain(-1);
        digitization.setSamplingRate(samplingRate);
        digitizationDao.create(digitization);
    }

    experiment.setDigitization(digitization);
    experiment.setArtifact(artifactDao.read(1));
    experiment.setElectrodeConf(electrodeConfDao.read(1));
    experiment.setSubjectGroup(subjectGroupDao.read(1)); //default subject group

    if (data.getMeasurationId() > 0) { // editing existing measuration
        log.debug("Saving the Measuration object to database using DAO - update()");
        experimentDao.update(experiment);
    } else { // creating new measuration
        log.debug("Saving the Measuration object to database using DAO - create()");
        experimentDao.create(experiment);
    }

    //  log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
    //     experiment.setExperimentId(addDataCommand.getMeasurationId());

    log.debug("Creating new Data object.");
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) httpServletRequest;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);
        if (file.getOriginalFilename().endsWith(".zip")) {
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
            ZipEntry en = zis.getNextEntry();
            while (en != null) {
                if (en.isDirectory()) {
                    en = zis.getNextEntry();
                    continue;
                }
                DataFile dataFile = new DataFile();
                dataFile.setExperiment(experiment);
                String name[] = en.getName().split("/");
                dataFile.setFilename(name[name.length - 1]);
                data.setFileDescription(data.getFileDescription());
                dataFile.setFileContent(Hibernate.createBlob(zis));
                String[] partOfName = en.getName().split("[.]");
                dataFile.setMimetype(partOfName[partOfName.length - 1]);
                dataFileDao.create(dataFile);
                en = zis.getNextEntry();
            }
        } else {
            DataFile dataFile = new DataFile();
            dataFile.setExperiment(experiment);

            log.debug("Original name of uploaded file: " + file.getOriginalFilename());
            String filename = file.getOriginalFilename().replace(" ", "_");
            dataFile.setFilename(filename);

            log.debug("MIME type of the uploaded file: " + file.getContentType());
            if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                int index = filename.lastIndexOf(".");
                dataFile.setMimetype(filename.substring(index));
            } else {
                dataFile.setMimetype(file.getContentType());
            }

            log.debug("Parsing the sapmling rate.");
            dataFile.setDescription(data.getFileDescription());

            log.debug("Setting the binary data to object.");
            dataFile.setFileContent(Hibernate.createBlob(file.getBytes()));

            dataFileDao.create(dataFile);
            log.debug("Data stored into database.");
        }
    }

    log.debug("Returning MAV object");
    return mav;
}

From source file:com.goodhuddle.huddle.service.impl.MemberServiceImpl.java

@Override
public ImportMembersResults importMembers(MultipartFile multipartFile, Long[] tagIds) {
    final ImportMembersResults results = new ImportMembersResults();
    results.setSuccess(true);//from  w  ww .j  a  v  a2 s.c o  m

    try {
        final Huddle huddle = huddleService.getHuddle();

        if (!multipartFile.isEmpty()) {

            File file = fileStore.getTempFile(fileStore.createTempFile(multipartFile.getBytes()));

            final CSVReader reader = new CSVReader(new FileReader(file));
            if (reader.readNext() != null) {
                // skipped header row

                final List<Tag> tags = new ArrayList<>();
                if (tagIds != null) {
                    for (Long tagId : tagIds) {
                        tags.add(tagRepository.findByHuddleAndId(huddle, tagId));
                    }
                }

                boolean done = false;
                while (!done) {
                    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
                    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    done = txTemplate.execute(new TransactionCallback<Boolean>() {

                        @Override
                        public Boolean doInTransaction(TransactionStatus status) {
                            try {
                                int i = 0;
                                String[] nextLine;
                                while ((nextLine = reader.readNext()) != null) {
                                    String email = nextLine[0];
                                    String firstName = nextLine[1];
                                    String lastName = nextLine[2];
                                    String postCode = nextLine[3];
                                    String phone = nextLine[4];

                                    Member member = memberRepository.findByHuddleAndEmailIgnoreCase(huddle,
                                            email);
                                    if (member != null) {
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        List<Tag> memberTags = member.getTags();
                                        if (memberTags == null) {
                                            memberTags = new ArrayList<>();
                                        }
                                        outer: for (Tag tag : tags) {
                                            for (Tag memberTag : memberTags) {
                                                if (memberTag.getId() == member.getId()) {
                                                    break outer;
                                                }
                                            }
                                            memberTags.add(tag);
                                        }
                                        member.setTags(memberTags);
                                        memberRepository.save(member);
                                        results.setNumUpdated(results.getNumUpdated() + 1);
                                    } else {
                                        member = new Member();
                                        member.setHuddle(huddle);
                                        member.setEmail(email);
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        member.setTags(tags);
                                        memberRepository.save(member);
                                        results.setNumImported(results.getNumImported() + 1);
                                    }

                                    if (i++ > 30) {
                                        return false;
                                    }
                                }
                                return true;
                            } catch (IOException e) {
                                log.error("Error importing file: " + e, e);
                                results.setSuccess(false);
                                results.setErrorMessage("Error importing file: " + e);
                                return true;
                            }
                        }
                    });
                }

            }

        } else {
            log.info("Empty file was uploaded");
            results.setSuccess(false);
            results.setErrorMessage("Empty file was uploaded");
        }
    } catch (IOException e) {
        results.setSuccess(false);
        results.setErrorMessage("Error uploading file: " + e);
    }

    return results;
}

From source file:com.baidu.gcrm.materials.web.MaterialsAction.java

/**
 * //  w w  w  . j  ava2s .c o m
 * 
 * @return
 */
@RequestMapping("/doUploadFile")
@ResponseBody
public Object doUploadFile(MultipartHttpServletRequest multipartRequest, HttpServletResponse response) {
    Iterator<String> it = multipartRequest.getFileNames();
    MultipartFile mpf = null;
    while (it.hasNext()) {
        String fileName = it.next();
        mpf = multipartRequest.getFile(fileName);
        log.debug("===" + fileName + "upload to local sever");
    }

    //
    Attachment attachment = new Attachment();
    attachment.setFieldName(mpf.getName());
    attachment.setName(mpf.getOriginalFilename());
    attachment.setCustomerNumber(-1L);
    attachment.setId(-1L);
    attachment.setTempUrl("");
    //attachment.setType(-1);
    attachment.setUrl("");
    //   attachment.setExit(false);
    try {
        attachment.setBytes(mpf.getBytes());
    } catch (IOException e) {
        log.error("=====" + e.getMessage());
        attachment.setMessage("failed");
        return attachment;
    }

    if (!StringUtils.isEmpty(mpf.getOriginalFilename())) {
        if (mpf.getOriginalFilename().endsWith(".exe")) {
            attachment.setMessage("materials.extension.error");//I18N?code
        } else {
            if (matericalsService.uploadFile(attachment)) {
                attachment.setMessage("success");
            } else {
                attachment.setMessage("failed");
            }
        }
    }

    //?
    String userAgent = multipartRequest.getHeader("user-agent").toLowerCase();
    if (userAgent.indexOf("msie 6") != -1 || userAgent.indexOf("msie 7") != -1
            || userAgent.indexOf("msie 8") != -1 || userAgent.indexOf("msie 9") != -1) {
        return JSONObject.toJSONString(attachment);

    }
    return attachment;
}

From source file:edu.uiowa.icts.bluebutton.controller.ClinicalDocumentController.java

@RequestMapping(value = "save.html", method = RequestMethod.POST)
public String save(@RequestParam("person.personId") Integer person_personId,
        @Valid @ModelAttribute("clinicalDocument") ClinicalDocument clinicalDocument, BindingResult result, // must immediately follow bound object
        @RequestParam("file") MultipartFile document, Model model) throws IOException {
    if (document.isEmpty()) {
        result.addError(new FieldError("clinicalDocument", "document", "may not be empty"));
    }// w  w w  .  j  a va 2 s.c om
    if (result.hasErrors()) {
        model.addAttribute("personList", bluebuttonDaoService.getPersonService().list());
        return "/bluebutton/clinicaldocument/edit";
    } else {
        clinicalDocument.setPerson(bluebuttonDaoService.getPersonService().findById(person_personId));
        clinicalDocument.setDocument(document.getBytes());
        clinicalDocument.setName(document.getOriginalFilename());
        clinicalDocument.setDateUploaded(new Date());
        bluebuttonDaoService.getClinicalDocumentService().saveOrUpdate(clinicalDocument);
        return "redirect:/clinicaldocument/confirm?clinicalDocumentId="
                + clinicalDocument.getClinicalDocumentId();
    }
}