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.balero.controllers.UploadController.java

/**
 * Upload file on server//from  w w  w.  j  ava 2s. c o  m
 *
 * @param file HTML <input type="file"> content
 * @param baleroAdmin Magic cookie
 * @return home view
 */
@RequestMapping(method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file,
        @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin,
        HttpServletRequest request) {

    // Security
    UsersAuth security = new UsersAuth();
    security.setCredentials(baleroAdmin, UsersDAO);
    boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword());
    if (!securityFlag)
        return "hacking";

    String inputFileName = file.getOriginalFilename();

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

            // Creating the directory to store file
            //String rootPath = System.getProperty("catalina.home");
            File dir = new File("../webapps/media/uploads");
            if (!dir.exists())
                dir.mkdirs();

            String[] ext = new String[9];
            // Add your extension here
            ext[0] = ".jpg";
            ext[1] = ".png";
            ext[2] = ".bmp";
            ext[3] = ".jpeg";

            for (int i = 0; i < ext.length; i++) {
                int intIndex = inputFileName.indexOf(ext[i]);
                if (intIndex == -1) {
                    System.out.println("File extension is not valid");
                } else {
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                }
            }

            System.out.println("You successfully uploaded file");

        } catch (Exception e) {
            System.out.println("You failed to upload => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload because the file was empty.");
    }

    String referer = request.getHeader("Referer");
    return "redirect:" + referer;

}

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

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

    CompletePOI poi = pm.getCompletePoiById(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }/*from www .ja va2s . c o m*/
    }
    ModelAndView model = new ModelAndView("editedpoi");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    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));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 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("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        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;
        }
    }
    if (!cover.isEmpty()) {
        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;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java

@Atomic
public void updateAcademicServiceRequestTemplate(org.fenixedu.commons.i18n.LocalizedString name,
        org.fenixedu.commons.i18n.LocalizedString description, java.lang.Boolean active,
        MultipartFile documentTemplateFile, Model model) throws IOException {

    getAcademicServiceRequestTemplate(model).setName(name);
    getAcademicServiceRequestTemplate(model).setDescription(description);
    getAcademicServiceRequestTemplate(model).setActive(active);

    if (!documentTemplateFile.isEmpty()) {
        DocumentTemplateFile oldFile = getAcademicServiceRequestTemplate(model).getDocumentTemplateFile();
        oldFile.delete();/*from  w ww .ja v a 2  s  . c  o  m*/

        DocumentTemplateFile.create(getAcademicServiceRequestTemplate(model),
                documentTemplateFile.getOriginalFilename(), documentTemplateFile.getBytes());
    }
}

From source file:com.devoxx.watson.AskDevoxxController.java

private File storeTmpFile(MultipartFile file) throws FileException {
    // check if all form parameters are provided
    if (file == null) {
        throw new FileException("MultipartFile File Required");
    }/* w  w  w .j  a v a 2 s.  c o  m*/
    // create our destination folder, if it not exists
    log.info("Storing: tmpFileStorageLocation:" + tmpFileStorageLocation + ":");
    File uploadPath = new File(tmpFileStorageLocation);

    // Now do something with file...
    File tmpFile;
    try {
        tmpFile = File.createTempFile("devoxx-speechtext", UUID.randomUUID().toString() + ".ogg", uploadPath);
        log.info(tmpFile.getAbsolutePath());
        FileOutputStream tempFileOutputStream = new FileOutputStream(tmpFile);
        FileCopyUtils.copy(file.getBytes(), tempFileOutputStream);
    } catch (IOException e) {
        log.fatal("Can not save file tmpFile", e);
        throw new FileException("Can not save file tmpFile", e);
    }
    return tmpFile;
}

From source file:edu.sampleu.kew.krad.controller.IngesterController.java

@RequestMapping(method = RequestMethod.POST, params = "methodToCall=upload")
public ModelAndView upload(@ModelAttribute("KualiForm") IngesterForm ingesterForm, BindingResult result,
        HttpServletRequest request, HttpServletResponse response) {

    List<File> tempFiles = new ArrayList<File>();

    try {/*from w ww  .  ja  v a  2  s.  c  o m*/

        List<XmlDocCollection> collections = new ArrayList<XmlDocCollection>();

        for (MultipartFile file : ingesterForm.getFiles()) {
            if (file == null || StringUtils.isBlank(file.getOriginalFilename())) {
                continue;
            }

            // ok, we have to copy it to *another* file because Struts doesn't give us a File
            // reference (which itself is not a bad abstraction) and XmlDocs based on ZipFile
            // can't be constructed without a file reference.
            FileOutputStream fos = null;
            File temp = null;
            try {
                temp = File.createTempFile("ingester", null);
                tempFiles.add(temp);
                fos = new FileOutputStream(temp);
                fos.write(file.getBytes());
            } catch (IOException ioe) {
                GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                        KEWConstants.ERROR_INGESTER_COPY_FILE, file.getOriginalFilename(),
                        ExceptionUtils.getFullStackTrace(ioe));
                continue;
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException ioe) {
                        //                   //LOG.error("Error closing temp file output stream: " + temp, ioe);
                    }
                }
            }
            if (file.getOriginalFilename().toLowerCase().endsWith(".zip")) {
                try {
                    collections.add(new ZipXmlDocCollection(temp));
                } catch (IOException ioe) {
                    GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                            KEWConstants.ERROR_INGESTER_LOAD_FILE, file.getOriginalFilename());
                }
            } else if (file.getOriginalFilename().endsWith(".xml")) {
                collections.add(new FileXmlDocCollection(temp, file.getOriginalFilename()));
            } else {
                GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                        KEWConstants.ERROR_INGESTER_EXTRANEOUS_FILE, file.getOriginalFilename());
            }
        }

        if (collections.size() == 0) {
            String message = "No valid files to ingest";
            GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                    KEWConstants.ERROR_INGESTER_NO_VALID_FILES);
        } else {
            // wrap in composite collection to make transactional
            CompositeXmlDocCollection compositeCollection = new CompositeXmlDocCollection(collections);
            int totalProcessed = 0;
            List<XmlDocCollection> c = new ArrayList<XmlDocCollection>(1);
            c.add(compositeCollection);
            try {
                Collection<XmlDocCollection> failed = CoreApiServiceLocator.getXmlIngesterService().ingest(c,
                        GlobalVariables.getUserSession().getPrincipalId());
                boolean txFailed = failed.size() > 0;
                if (txFailed) {
                    GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                            KEWConstants.ERROR_INGESTER_FAILED);
                }
                for (XmlDocCollection collection1 : collections) {
                    List<? extends XmlDoc> docs = collection1.getXmlDocs();
                    for (XmlDoc doc1 : docs) {
                        if (doc1.isProcessed()) {
                            if (!txFailed) {
                                totalProcessed++;
                                GlobalVariables.getMessageMap().putInfoForSectionId(
                                        KEWConstants.INGESTER_SECTION_ID, KEWConstants.INFO_INGESTER_SUCCESS,
                                        doc1.getName(), doc1.getProcessingMessage());
                                //                                   messages.add("Ingested xml doc: " + doc1.getName() + (doc1.getProcessingMessage() == null ? "" : "\n" + doc1.getProcessingMessage()));
                            } else {
                                GlobalVariables.getMessageMap().putErrorForSectionId(
                                        KEWConstants.INGESTER_SECTION_ID,
                                        KEWConstants.ERROR_INGESTER_ROLLEDBACK, doc1.getName(),
                                        doc1.getProcessingMessage());
                                //                                   messages.add("Rolled back doc: " + doc1.getName() + (doc1.getProcessingMessage() == null ? "" : "\n" + doc1.getProcessingMessage()));
                            }
                        } else {
                            GlobalVariables.getMessageMap().putErrorForSectionId(
                                    KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_FAILED_XML,
                                    doc1.getName(), doc1.getProcessingMessage());
                            //                               messages.add("Failed to ingest xml doc: " + doc1.getName() + (doc1.getProcessingMessage() == null ? "" : "\n" + doc1.getProcessingMessage()));
                        }
                    }
                }
            } catch (Exception e) {
                //                   String message = "Error during ingest";
                //LOG.error(message, e);
                //                   messages.add(message + ": " + e  + ":\n" + ExceptionUtils.getFullStackTrace(e));
                GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                        KEWConstants.ERROR_INGESTER_DURING_INJECT, ExceptionUtils.getFullStackTrace(e));
            }
            if (totalProcessed == 0) {
                //                   String message = "No xml docs ingested";
                GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,
                        KEWConstants.ERROR_INGESTER_NO_XMLS);
            }
        }
    } finally {
        if (tempFiles.size() > 0) {
            for (File tempFile : tempFiles) {
                if (!tempFile.delete()) {
                    //LOG.warn("Error deleting temp file: " + tempFile);
                }
            }
        }
    }

    //       request.setAttribute("messages", messages);
    return getUIFModelAndView(ingesterForm);
}

From source file:com.oak_yoga_studio.controller.CustomerController.java

@RequestMapping(value = "/updateProfile", method = RequestMethod.POST)
public String updateUser(@Valid Customer customerUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Customer) session.getAttribute("loggedUser")).getId();
        Customer customer = customerService.getCustomerById(Id);

        customer.setFirstName(customerUpdate.getFirstName());
        customer.setLastName(customerUpdate.getLastName());
        //System.out.println("Date of Birth" + customerUpdate.getDateOfBirth());
        //customer.setDateOfBirth(customerUpdate.getDateOfBirth());
        customer.setEmail(customerUpdate.getEmail());

        try {/*from  w w w . ja  v  a 2 s. c  o m*/

            if (file.getBytes().length != 0) {
                customer.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        customerService.updateCustomer(Id, customer);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/editProfile";
}

From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java

private CfpSpeakerImage processPicture(MultipartFile picture, BindingResult bindingResult) {
    CfpSpeakerImage cfpSpeakerImage = null;
    byte[] pictureData = null;

    try {// www . jav  a  2  s .  c  o m
        pictureData = picture.getBytes();
    } catch (IOException e) {
        LOGGER.error("Error processing Image.", e);
        bindingResult
                .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image."));
        return null;
    }

    if (pictureData != null && picture.getSize() > 0) {

        ByteArrayInputStream bais = new ByteArrayInputStream(pictureData);
        BufferedImage image;
        try {
            image = ImageIO.read(bais);
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult
                    .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image."));
            return null;
        }

        if (image == null) {
            //FIXME better way?
            final String fileSizeFormatted = FileUtils.byteCountToDisplaySize(picture.getSize());
            LOGGER.warn(String.format("Cannot parse file '%s' (Content Type: %s; Size: %s) as image.",
                    picture.getOriginalFilename(), picture.getContentType(), fileSizeFormatted));
            bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile",
                    String.format(
                            "Did you upload a valid image? We cannot parse file '%s' (Size: %s) as image file.",
                            picture.getOriginalFilename(), fileSizeFormatted)));
            return null;
        }

        int imageHeight = image.getHeight();
        int imageWidth = image.getWidth();

        if (imageHeight < 360 && imageWidth < 360) {
            bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", String.format(
                    "Your image '%s' (%sx%spx) is too small. Please provide an image of at least 360x360px.",
                    picture.getOriginalFilename(), imageWidth, imageHeight)));
        }

        cfpSpeakerImage = new CfpSpeakerImage();

        cfpSpeakerImage.setFileData(pictureData);
        cfpSpeakerImage.setFileModified(new Date());
        cfpSpeakerImage.setFileSize(picture.getSize());
        cfpSpeakerImage.setName(picture.getOriginalFilename());
        cfpSpeakerImage.setType(picture.getContentType());

        return cfpSpeakerImage;
    }

    return null;
}

From source file:com.abixen.platform.core.service.impl.LayoutServiceImpl.java

@Override
public Layout changeIcon(Long id, MultipartFile iconFile) throws IOException {
    Layout layout = findLayout(id);/*from  w w w.  j a v  a2s.co m*/
    File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + layout.getIconFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }
    }
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime()).replaceAll("\"", "s")
            .replaceAll("/", "a").replace(".", "sde");
    File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + newIconFileName);
    FileOutputStream out = new FileOutputStream(newIconFile);
    out.write(iconFile.getBytes());
    out.close();
    layout.setIconFileName(newIconFileName);
    updateLayout(layout);
    return findLayout(id);
}

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

@RequestMapping(value = "/insertevent", method = RequestMethod.POST)
public ModelAndView insertPoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam("file") MultipartFile[] files, @RequestParam("cover") MultipartFile cover)
        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  .j  av a2 s .  c  om
        poi.setName(params.get("name"));
        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"));
        poi.setStart_date(params.get("datai"));
        poi.setEnd_date(params.get("dataf"));
        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>();
        CoverImgComponent coverimg = new CoverImgComponent();
        //componente cover
        if (!cover.isEmpty()) {

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

            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;

        EventsDateComponent workingtime = new EventsDateComponent();
        if (params.containsKey("WD" + i + "start" + k + "H")) {
            ArrayList<EventsDates> workingdays = new ArrayList<EventsDates>();

            while (params.containsKey("WD" + i)) {
                ArrayList<EventsHours> Listwh = new ArrayList<EventsHours>();
                k = 1;
                while (params.containsKey("WD" + i + "start" + k + "H")) {
                    EventsHours wh = new EventsHours();
                    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;
                }
                EventsDates cwd = new EventsDates();
                cwd.setDate(params.get("WD" + i));
                cwd.setHours(Listwh);
                workingdays.add(cwd);
                i = i + 1;
            }

            workingtime.setDates(workingdays);
            listComponent.add(workingtime);
        }
        /*
        LinkedPoiComponent lpc = new LinkedPoiComponent();
        ArrayList<LinkedPoi> alp = new ArrayList<LinkedPoi>();
        i=1;
        while (params.containsKey("mot"+i)) {
         k=1;
         ArrayList<String> apoi = new ArrayList<String>();
         while(params.containsKey("COL"+i+"-"+k)){
             apoi.add(params.get("COL"+i+"-"+k));
             k++;
         }
         LinkedPoi lp= new LinkedPoi();
         lp.setDescription(params.get("mot"+i));
         lp.setIdlist(apoi);
         alp.add(lp);
         i++;
        }
        lpc.setLinked(alp);
        if(params.containsKey("mot1")) {
         listComponent.add(lpc);
        }
        */
        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());
        // POI INGLESE 
        if (params.get("inglese").equals("true")) {
            addeng(params, poi2.getId(), coverimg, img_gallery);
        } else {
            EnCompletePOI enpoi = new EnCompletePOI();
            enpoi.setAddress(poi.getAddress());
            enpoi.setCategories(poi.getCategories());
            enpoi.setId(poi.getId());
            enpoi.setName(poi.getName());
            enpoi.setShortDescription(poi.getShortDescription());
            enpoi.setStart_date(poi.getStart_date());
            enpoi.setEnd_date(poi.getEnd_date());
            double enlat = Double.parseDouble(params.get("latitude"));
            double enlongi = Double.parseDouble(params.get("longitude"));
            poi.setLocation(new double[] { enlat, enlongi });
            enpoi.setComponents(listComponent);

            pm.saveEnPoi(enpoi);
        }

        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:eionet.webq.web.controller.WebQProxyDelegation.java

/**
 * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used.
 *
 * @param uri              the address to forward the request
 * @param fileId           UserFile id stored in session
 * @param multipartRequest file part in multipart request
 * @return response from remote host/*  www  . j av  a2s .c  o m*/
 * @throws URISyntaxException provide URI is incorrect
 * @throws IOException        could not read file from request
 */
@RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId,
        MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException {

    UserFile file = userFileHelper.getUserFile(fileId, multipartRequest);

    if (!multipartRequest.getFileNames().hasNext()) {
        throw new IllegalArgumentException("File not found in multipart request.");
    }
    Map<String, String[]> parameters = multipartRequest.getParameterMap();
    // limit request to one file
    String fileName = multipartRequest.getFileNames().next();
    MultipartFile multipartFile = multipartRequest.getFile(fileName);

    HttpHeaders authorization = new HttpHeaders();
    if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) {
        authorization = envelopeService.getAuthorizationHeader(file);
    }

    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename());
    fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType()));

    MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
    byte[] content = multipartFile.getBytes();
    request.add("file", new HttpEntity<byte[]>(content, fileHeaders));
    for (Map.Entry<String, String[]> parameter : parameters.entrySet()) {
        if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId")
                && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) {
            request.add(parameter.getKey(),
                    new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0])));
        }
    }

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(
            request, authorization);

    LOGGER.info("/restProxyFileUpload [POST] uri=" + uri);
    return restTemplate.postForObject(uri, requestEntity, String.class);
}