List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:cn.edu.henu.rjxy.lms.controller.Tea_Controller.java
@RequestMapping("kcnr_submit") public @ResponseBody String kcnr_submit(HttpServletRequest request, @RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException { String sn = getCurrentUsername(); Teacher tec = TeacherDao.getTeacherBySn(sn); String tec_sn = tec.getTeacherSn(); String tec_name = tec.getTeacherName(); String collage = tec.getTeacherCollege(); String term = request.getParameter("term"); String courseName = request.getParameter("courseName"); String node1 = request.getParameter("node1"); String node2 = request.getParameter("node2"); String node3 = request.getParameter("node3"); String type = request.getParameter("type"); System.out.println(type);/*from w w w . ja va 2 s. com*/ System.out.println(node1 + " " + node2 + " " + node3 + " " + term + " " + courseName); String ff = getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/" + courseName + "/" + "" + "/"; if (node2.equals("undefined") && node3.equals("undefined")) {//1 ff = ff + node1; } else if (node3.equals("undefined") && (!node2.equals("undefined"))) {//2 ff = ff + "/" + node1 + "/" + node2 + "/"; } else if ((!node1.equals("undefined")) && (!node2.equals("undefined")) && (!node3.equals("undefined"))) {//3 ff = ff + "/" + node1 + "/" + node2 + "/" + node3 + "/"; } File f = new File(ff); //?? if (!f.exists() && !f.isDirectory()) { System.out.println("?"); f.mkdirs(); } //? if (type.endsWith("")) { ff = ff + "/" + "" + "/"; File fwork = new File(ff); if (!fwork.exists() && !fwork.isDirectory()) { System.out.println("?"); fwork.mkdirs(); } } // if (!file.isEmpty()) { try { InputStream in; try (FileOutputStream os = new FileOutputStream(f + "/" + file.getOriginalFilename())) { in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { os.write(b); } os.flush(); } in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // System.out.println(" "+file.getOriginalFilename()); // DocConverter dc=new DocConverter(f+"/"+file.getOriginalFilename()); // boolean res=dc.conver(); // String swftmp=(f+"/"+file.getOriginalFilename()).replace(getFileFolder(request), ""); // swftmp=swftmp.substring(0,swftmp.lastIndexOf("."))+".swf"; // if (res){ // System.out.println("?flash??:http://localhost:8080/Web/getswf?uri="+swftmp); // } return "1"; }
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 w w w. j ava 2s .c om*/ } 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:controller.ClientController.java
@RequestMapping(value = "/ajoutercontrat", method = RequestMethod.POST) String ajoutercontratAction(HttpServletRequest request, Model model, HttpSession session, @RequestParam("file") MultipartFile file) throws ParseException, InterruptedException { //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}/*from ww w.j a va2s . co m*/ //session.setAttribute("Modify", this.modif.modifcontrat(id)); Set<Region> regions = new HashSet<>(); Set<Typerayon> typerayons = new HashSet<>(); java.util.Date date = new java.util.Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); ClientConnecte cl = new ClientConnecte((Client) session.getAttribute("UserConnected")); List<Compte> listCompte = CompteDAO.RegionCompte(); String[] choixrayon = request.getParameterValues("rayon"); String[] choixregion = request.getParameterValues("region"); for (int i = 0; i < choixrayon.length; i++) { typerayons.add(TypeRayonDAO.RayonPrec(choixrayon[i]).get(0)); System.out.println(choixrayon[i]); } for (int i = 0; i < choixregion.length; i++) { regions.add(RegionDAO.RegionPrec(choixregion[i]).get(0)); System.out.println(choixregion[i]); } String titrecontrat = request.getParameter("titre"); String freqcontrat = request.getParameter("frequence"); String durecontrat = request.getParameter("duree"); String datedebutcontrat = request.getParameter("dateDebut"); String datefincontrat = request.getParameter("dateFin"); String daterecepcontrat = request.getParameter("dateReception"); String datevalidcontrat = request.getParameter("dateValidation"); String tarifcontrat = request.getParameter("tarif"); String choixstatut = request.getParameter("statut"); Video vid = new Video(cl.getCli(), listCompte.get(0), titrecontrat, Integer.parseInt(freqcontrat), Integer.parseInt(durecontrat), sdf.parse(datedebutcontrat), sdf.parse(datefincontrat), sdf.parse(sdf.format(date)), sdf.parse(sdf.format(date)), 0, 2); vid.setRegions(regions); vid.setTyperayons(typerayons); int i = vidBDD.addcliVideo(vid); if (i != 0) { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file String rootPath = System.getProperty("catalina.home"); // Create the file on server //Chemin officiel du serveur File serverFile = new File(rootPath + File.separator + "webapps" + File.separator + "manager" + File.separator + "videos" + File.separator + i + ".mp4"); System.out.println("" + serverFile); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("You failed to upload "); } return "redirect:/client"; } else { return "cliEditContrat"; } }
From source file:com.orchestra.portale.controller.EditEventController.java
@RequestMapping(value = "/updateevent", method = RequestMethod.POST) public ModelAndView updateEvent(HttpServletRequest request, @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) 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 ww w .j a v a2 s . 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("1"); 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.setStart_date(params.get("datai")); poi.setEnd_date(params.get("dataf")); 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]; 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); } 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; } } 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:cn.edu.henu.rjxy.lms.controller.TeaController.java
@RequestMapping("teacher/homework_submit") public @ResponseBody String homework_submit(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws FileNotFoundException, IOException { int length = 0; String textWork = request.getParameter("arr1");//? String time = request.getParameter("time");//?? String miaoshu = request.getParameter("miaoshu"); String coursename = request.getParameter("courseName"); String term = request.getParameter("term"); String tec_name = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName(); String sn = getCurrentUsername(); String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege(); // ? ?? ?? String ff = getFileFolder(request) + "homework/" + term + "/" + collage + "/" + sn + "/" + tec_name + "/" + coursename + "/"; file(ff);//?? length = haveFile(ff);//ww w . j av a2 s . c om ff = ff + (length + 1) + "/"; file(ff); //?html OutputStreamWriter pw = null;//? pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "textWork.html")), "GBK"); pw.write(textWork); pw.close(); //?? PrintStream ps = null; ps = new PrintStream(new FileOutputStream(new File(ff + File.separator + "Workall.txt"))); ps.printf(miaoshu);//??: ps.println(); ; ps.println(time);//??: ps.close(); // if (!file.isEmpty()) { try { InputStream in; try (FileOutputStream os = new FileOutputStream(ff + "/" + file.getOriginalFilename())) { in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { os.write(b); } os.flush(); } in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "1"; }
From source file:com.jd.survey.web.settings.InvitationController.java
/** * Sends email invitations to the list of invitees from csv file. * @param file/*from w w w . j a v a2 s .c o m*/ * @param surveyDefinitionId * @param proceed * @param principal * @param uiModel * @param httpServletRequest * @return */ @SuppressWarnings("unchecked") @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html") public String sendInvitations(@RequestParam("file") MultipartFile file, @RequestParam("id") Long surveyDefinitionId, @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { try { short firstNameFieldIndex = 0; short middleNameFieldIndex = 1; short lastNameFieldIndex = 2; short emailNameFieldIndex = 3; if (proceed != null) { //prepare the base url links String emailSubject = messageSource.getMessage(INVITATION_EMAIL_TITLE, null, LocaleContextHolder.getLocale()); //String surveyLink =messageSource.getMessage(EXTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale()); String surveyLink = externalBaseUrl; //String trackingImageLink =messageSource.getMessage(INTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale()); String trackingImageLink = internalBaseUrl; SurveyDefinition surveyDefinition = surveySettingsService .surveyDefinition_findById(surveyDefinitionId); User user = userService.user_findByLogin(principal.getName()); Set<SurveyDefinition> surveyDefinitions = surveySettingsService .surveyDefinition_findAllCompletedInternal(user); //Check if the user is authorized if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (trackingImageLink.endsWith("/")) { trackingImageLink = trackingImageLink + "public/w/"; } else { trackingImageLink = trackingImageLink + "/public/w/"; } if (surveyDefinition.getIsPublic()) { if (surveyLink.endsWith("/")) { surveyLink = surveyLink + "open/"; } else { surveyLink = surveyLink + "/open/"; } } else { if (surveyLink.endsWith("/")) { surveyLink = surveyLink + "private/"; } else { surveyLink = surveyLink + "/private/"; } } String emailContent; if (!file.isEmpty() && ((file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) || (file.getContentType().equalsIgnoreCase("text/csv")) || (file.getContentType().equalsIgnoreCase("text/plain")))) { CSVReader csvReader = new CSVReader(new InputStreamReader(file.getInputStream())); String[] nextLine; nextLine = csvReader.readNext(); //skip the first row the continue on with loop while ((nextLine = csvReader.readNext()) != null) { emailContent = ""; StringWriter sw = new StringWriter(); // Prevents IndexOutOfBoundException by skipping line if there are not enough elements in the array nextLine. if (nextLine.length < 4) { //Continues if a blank line is present without setting an error message (if a new line character is present CSVReader will return and array with one empty string at index 0). if (nextLine.length == 1 && nextLine[0].isEmpty()) { continue; } uiModel.addAttribute("fileContentError", true); continue; } //Prevents exception from attempting to send an email with an empty string for an email address. if (nextLine[3].isEmpty()) { uiModel.addAttribute("fileContentError", true); continue; } //creating the Invitation Invitation invitation = new Invitation(nextLine[firstNameFieldIndex].trim(), nextLine[middleNameFieldIndex].trim(), nextLine[lastNameFieldIndex].trim(), nextLine[emailNameFieldIndex].trim(), surveyDefinition); Map model = new HashMap(); //survey name model.put(messageSource.getMessage(SURVEY_NAME, null, LocaleContextHolder.getLocale()) .replace("${", "").replace("}", ""), surveyDefinition.getName()); //full name model.put( messageSource.getMessage(INVITEE_FULLNAME_PARAMETER_NAME, null, LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""), invitation.getFullName()); //survey link model.put( messageSource.getMessage(INVITE_FILL_SURVEY_LINK_PARAMETER_NAME, null, LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""), "<a href='" + surveyLink + surveyDefinition.getId() + "?list'>" + messageSource.getMessage(INVITE_FILL_SURVEY_LINK_LABEL, null, LocaleContextHolder.getLocale()) + "</a>"); VelocityContext velocityContext = new VelocityContext(model); Velocity.evaluate(velocityContext, sw, "velocity-log", surveyDefinition.getEmailInvitationTemplate()); emailContent = sw.toString().trim(); if (emailContent.length() > 14 && emailContent.substring(emailContent.length() - 14) .toUpperCase().equalsIgnoreCase("</BODY></HTML>")) { emailContent = emailContent.substring(0, emailContent.length() - 14) + "<img src='" + trackingImageLink + invitation.getUuid() + "'/></BODY></HTML>"; emailContent = "<BODY><HTML>" + emailContent; } else { // template is incorrect or not html do not include tracking white gif emailContent = emailContent + "<img src='" + trackingImageLink + invitation.getUuid() + "'/></BODY></HTML>"; } surveySettingsService.invitation_send(invitation, emailSubject, emailContent); } return "redirect:/settings/invitations/list?id=" + encodeUrlPathSegment(surveyDefinitionId.toString(), httpServletRequest); } else { uiModel.addAttribute("surveyDefinitions", surveyDefinitions); uiModel.addAttribute("surveyDefinition", surveyDefinition); uiModel.addAttribute("emptyFileError", true); return "settings/invitations/upload"; } } else { return "redirect:/settings/invitations/list?id=" + encodeUrlPathSegment(surveyDefinitionId.toString(), httpServletRequest); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:de.steilerdev.myVerein.server.controller.admin.SettingsController.java
/** * This function is saving the settings for the system durable. In case the database connection changed, the system is restarted. The function is invoked by POSTing the parameters to the URI /api/admin/settings. * NOTE: At the moment the restarting of the application is not working correctly. To apply changed database settings the application needs to be redeployed manually from the management interface. * @param currentAdmin If the logged in user is a super admin, this field specifies the new super admin. If the logged in user is a normal admin, this field needs to contain his email. * @param adminPasswordNew The new password for the currently logged in admin. * @param adminPasswordNewRe The retyped new password for the currently logged in admin. * @param clubName The club name.// www. j av a 2s .c om * @param clubLogo The club logo. If this parameter is present the former club logo is going to be replaced. * @param databaseHost The hostname of the used MongoDB server. * @param databasePort The port of the used MongoDB server. * @param databaseUser The username, used to authenticate against the MongoDB server. * @param databasePassword The password, used to authenticate against the MongoDB server. * @param databaseCollection The name of the database collection, where the data of this system is stored in. * @param rememberMeTokenKey The phrase used to secure the remember me cookies. * @param parameters The complete map of all parameters, containing the custom user fields. * @param currentAdminPassword The password of the currently logged in user, used to authenticate the changes. * @param currentUser The currently logged in user. * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available. */ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<String> saveSettings(@RequestParam(required = false) String currentAdmin, @RequestParam(required = false) String adminPasswordNew, @RequestParam(required = false) String adminPasswordNewRe, @RequestParam(required = false) String clubName, @RequestParam(required = false) MultipartFile clubLogo, @RequestParam(required = false) String databaseHost, @RequestParam(required = false) String databasePort, @RequestParam(required = false) String databaseUser, @RequestParam(required = false) String databasePassword, @RequestParam(required = false) String databaseCollection, @RequestParam Map<String, String> parameters, @RequestParam String currentAdminPassword, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Starting to save settings"); Settings settings = Settings.loadSettings(settingsRepository); if (!passwordEncoder.isPasswordValid(currentUser.getPassword(), currentAdminPassword, currentUser.getSalt())) { logger.warn("[" + currentUser + "] The stated password is invalid"); return new ResponseEntity<>("The stated password is incorrect, please try again", HttpStatus.FORBIDDEN); } else if (currentUser.isAdmin()) { if (currentUser.isSuperAdmin()) { logger.debug("[" + currentUser + "] The user is a super admin"); if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) { logger.warn("[" + currentUser + "] The super admin user is changing to " + currentAdmin); Division rootDivision = divisionRepository.findByName(settings.getClubName()); if (rootDivision == null) { logger.warn("[" + currentUser + "] Unable to find root division " + settings.getClubName()); return new ResponseEntity<>("Unable to find root division", HttpStatus.INTERNAL_SERVER_ERROR); } User newSuperAdmin = userRepository.findByEmail(currentAdmin); if (newSuperAdmin == null) { logger.warn("[" + currentUser + "] Unable to find new super admin " + currentAdmin); return new ResponseEntity<>("Unable to find new super admin", HttpStatus.INTERNAL_SERVER_ERROR); } logger.debug("[" + currentUser + "] Saving new super admin"); rootDivision.setAdminUser(newSuperAdmin); divisionRepository.save(rootDivision); logger.info("[" + currentUser + "] Successfully saved " + currentAdmin + " as new super admin"); } try { if (clubName != null && !clubName.isEmpty()) { logger.debug("[" + currentUser + "] Setting club name to " + clubName); Division rootDivision = divisionRepository.findByName(settings.getClubName()); if (rootDivision == null) { logger.warn("[" + currentUser + "] Unable to find former root division."); return new ResponseEntity<>("Unable to find former root division", HttpStatus.INTERNAL_SERVER_ERROR); } //Changing and saving the root division rootDivision.setName(clubName); divisionRepository.save(rootDivision); settings.setClubName(clubName); } if (clubLogo != null && !clubLogo.isEmpty()) { logger.debug("[" + currentUser + "] Saving club logo"); try { gridFSRepository.storeClubLogo(clubLogo); } catch (MongoException e) { logger.warn("[" + currentUser + "] Problem while saving club logo: " + e.getMessage()); return new ResponseEntity<>("Problem while saving club logo: " + e.getMessage(), HttpStatus.BAD_REQUEST); } } if (databaseHost != null && !databaseHost.isEmpty()) { logger.debug("[" + currentUser + "] Setting database host to " + databaseHost); settings.setDatabaseHost(databaseHost); } if (databasePort != null && !databasePort.isEmpty()) { logger.debug("[" + currentUser + "] Setting database port to " + databasePort); settings.setDatabasePort(databasePort); } if (databaseUser != null) { logger.debug("[" + currentUser + "] Setting database user to " + databaseUser); settings.setDatabaseUser(databaseUser); } if (databasePassword != null) { logger.debug("[" + currentUser + "] Setting database password"); settings.setDatabasePassword(databasePassword); } if (databaseCollection != null && !databaseCollection.isEmpty()) { logger.debug( "[" + currentUser + "] Setting database collection name " + databaseCollection); settings.setDatabaseName(databaseCollection); } logger.debug("[" + currentUser + "] Gathering all custom user fields"); //Reducing parameters to custom user field parameters only and the value of the input List<String> reducedValues = parameters.keySet().parallelStream() .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty()) .distinct() //Only allowing distinct keys .map(key -> key.substring(4)) //Reducing the key to the initial 'name' value, used to create the fields by jQuery .collect(Collectors.toList()); //Analysing the values and checking, if if (!reducedValues.isEmpty()) { logger.debug("[" + currentUser + "] There are custom user fields available"); ArrayList<String> customUserFieldValues = new ArrayList<>(); reducedValues.parallelStream().forEach(key -> { if (parameters.get("delete" + key) != null) { logger.warn("[" + currentUser + "] Deleting custom user field " + key); if (parameters.get("deleteContent" + key) != null) { logger.warn("[" + currentUser + "] Deleting content of custom user field " + key + " on every user object"); List<User> user = mongoTemplate.find( new Query(Criteria.where("customUserField." + key).exists(true)), User.class); if (user != null && !user.isEmpty()) { user.parallelStream().forEach(thisUser -> { thisUser.removeCustomUserField(key); try { logger.trace( "[" + currentUser + "] Deleting custom user field content " + key + " for user " + thisUser.getEmail()); userRepository.save(thisUser); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while trying to delete the custom user field " + key + " for user " + thisUser.getEmail() + ": " + e.getMessage()); } }); } } } else { String value = parameters.get("cuf_" + key).trim(); if (!key.equals(value) && settings.getCustomUserFields().contains(key)) //The key was renamed { logger.debug("[" + currentUser + "] The custom user field " + key + " changed to " + value); List<User> user = mongoTemplate.find( new Query(Criteria.where("customUserField." + key).exists(true)), User.class); if (user != null && !user.isEmpty()) { user.parallelStream().forEach(thisUser -> { thisUser.renameCustomUserField(key, value); try { logger.trace("[" + currentUser + "] Renaming custom user field " + key + " to " + value + " for user " + thisUser.getEmail()); userRepository.save(thisUser); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while trying to rename the custom user field " + key + " for user " + thisUser.getEmail() + ": " + e.getMessage()); } }); } } logger.debug("[" + currentUser + "] Adding " + value + " as custom user field"); customUserFieldValues.add(value); } }); settings.setCustomUserFields(customUserFieldValues); } logger.debug("[" + currentUser + "] Saving updated settings file"); settings.saveSettings(currentUser, settingsRepository); logger.info("[" + currentUser + "] Successfully saved updated settings file"); } catch (IOException e) { logger.warn("[" + currentUser + "] Unable to update settings file: " + e.getMessage()); return new ResponseEntity<>("Unable to update settings file", HttpStatus.INTERNAL_SERVER_ERROR); } } else { logger.debug("[" + currentUser + "] The user is an admin"); if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) { logger.warn("[" + currentUser + "] The current user differs from the stated user"); return new ResponseEntity<>("The current user differs from the stated user", HttpStatus.BAD_REQUEST); } } if (adminPasswordNew != null && adminPasswordNewRe != null && !adminPasswordNew.isEmpty() && !adminPasswordNewRe.isEmpty()) { logger.info("[" + currentUser + "] The user wants to change his password."); if (!adminPasswordNew.equals(adminPasswordNewRe)) { logger.warn("[" + currentUser + "] The stated passwords did not match"); return new ResponseEntity<>("The stated passwords did not match", HttpStatus.BAD_REQUEST); } else { currentUser.setPassword(adminPasswordNew); try { logger.debug("[" + currentUser + "] Saving new user password."); userRepository.save(currentUser); logger.info("[" + currentUser + "] Successfully saved new user password"); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while saving the user: " + e.getMessage()); return new ResponseEntity<>("A database constraint was violated while saving the user.", HttpStatus.BAD_REQUEST); } } } } else { logger.warn("[" + currentUser + "] A user who is not an admin tries to change the settings "); return new ResponseEntity<>("You are not allowed to change these settings", HttpStatus.FORBIDDEN); } logger.info("[" + currentUser + "] Successfully updated all settings"); return new ResponseEntity<>("Successfully updated settings", HttpStatus.OK); }
From source file:np.com.drose.studentmanagementsystem.controller.ProjectController.java
public String fileUpload(@RequestParam("files") MultipartFile projectfile, RedirectAttributes redirectAttr) throws FileNotFoundException, IOException { if (!projectfile.isEmpty()) { File fileUploadPath = new File("/opt/files"); File filePathToStore = File.createTempFile("project", ".pdf", fileUploadPath); if (!fileUploadPath.exists()) { fileUploadPath.mkdir();//www . j av a 2 s . com } BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filePathToStore)); FileCopyUtils.copy(projectfile.getInputStream(), stream); redirectAttr.addFlashAttribute("message", "FIle with name" + filePathToStore.toString() + " is upload"); return filePathToStore.toString(); } else { redirectAttr.addFlashAttribute("message", "failed to upload file"); } return null; }
From source file:org.benetech.secureapp.generator.ObtainXFormController.java
@RequestMapping(value = WebPage.OBTAIN_XFORM_NEXT, method = RequestMethod.POST) public String retrieveXForm(HttpSession session, @RequestParam("xmlCustomFile") MultipartFile xmlFile, @RequestParam("selectedForm") String formLocation, Model model, AppConfiguration appConfig) { String xFormName = null;/* ww w .j a va 2s . c o m*/ File xFormFile = null; if (xmlFile.isEmpty()) { xFormFile = copyXFormsFileSelectedToTempFile(session, formLocation); if (xFormFile == null) { SagLogger.logError(session, "Default Form not found? :" + formLocation); return WebPage.ERROR; } xFormName = getFormNameOnly(formLocation); } else { try { if (!xmlFile.getContentType().contains(XML_TYPE)) { SagLogger.logInfo(session, "Non-XML xForm: " + xmlFile.getContentType()); return returnLocalizedErrorMessage(model, appConfig, "xform_file_type_invalid"); } xFormName = getFormNameOnly(xmlFile.getOriginalFilename()); xFormFile = File.createTempFile(xFormName, XFORM_FILE_EXTENSION); SecureAppGeneratorApplication.saveMultiPartFileToLocation(xmlFile, xFormFile); SagLogger.logInfo(session, "Uploaded Custom XFORM Location = " + xFormFile.getAbsolutePath()); } catch (Exception e) { SagLogger.logException(session, e); xFormFile.delete(); return returnLocalizedErrorMessage(model, appConfig, "xform_upload_failed"); } } try { isValidXForm(xFormFile); } catch (Exception e) { String localizedErrorMessage = SecureAppGeneratorApplication.getLocalizedErrorMessage("xform_invalid", e); SagLogger.logWarning(session, "Custom xForm Invalid: " + localizedErrorMessage); return returnRawErrorMessage(model, appConfig, localizedErrorMessage); } AppConfiguration config = (AppConfiguration) session.getAttribute(SessionAttributes.APP_CONFIG); config.setAppXFormFile(xFormFile); config.setAppXFormName(xFormName); session.setAttribute(SessionAttributes.APP_CONFIG, config); model.addAttribute(SessionAttributes.APP_CONFIG, config); return WebPage.OBTAIN_CLIENT_TOKEN; }