List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:io.milton.cloud.server.web.templating.TextTemplater.java
public TextTemplater(SpliffySecurityManager securityManager, ServletContext servletContext) { this.securityManager = securityManager; this.servletContext = servletContext; templateLoader = new SimpleTemplateLoader(); java.util.Properties p = new java.util.Properties(); p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); engine = new VelocityEngine(p); engine.setProperty("resource.loader", "mine"); engine.setProperty("mine.resource.loader.instance", templateLoader); roots = new ArrayList<>(); File fWebappRoot = new File(servletContext.getRealPath("/")); roots.add(fWebappRoot);/* www .j a v a 2 s .c o m*/ log.info("Using webapp root dir: " + fWebappRoot.getAbsolutePath()); String extraRoots = System.getProperty(HtmlTemplater.ROOTS_SYS_PROP_NAME); if (extraRoots != null && !extraRoots.isEmpty()) { String[] arr = extraRoots.split(","); for (String s : arr) { File root = new File(s); if (!root.exists()) { throw new RuntimeException("Root template dir specified in system property does not exist: " + root.getAbsolutePath() + " from property value: " + extraRoots); } roots.add(root); } } }
From source file:com.jsmartframework.web.manager.FilterControl.java
private void versionResources(FilterConfig config) { try {/* www.j av a2 s .c om*/ if (CONFIG.getContent().getFileVersions() == null) { LOGGER.log(Level.INFO, "Not using files version control."); return; } String automaticVersion = getAutomaticResourceVersion(config); if (automaticVersion != null) { LOGGER.log(Level.INFO, "Automatic versioning detected as " + automaticVersion); } ServletContext context = config.getServletContext(); File rootFile = new File(context.getRealPath(ROOT_PATH)); Dir content = Vfs.fromURL(rootFile.toURI().toURL()); Map<String, StringBuilder> patternBuilders = new HashMap<>(); Iterator<Vfs.File> files = content.getFiles().iterator(); while (files.hasNext()) { Vfs.File file = files.next(); String relativePath = file.getRelativePath(); FileVersion fileVersion = CONFIG.getContent().getFileVersion(relativePath); if (fileVersion != null && !fileVersion.isOnExcludeFolders(relativePath)) { if (!fileVersion.isIncludeMinified() && fileVersion.isMinifiedFile(relativePath)) { continue; } String patternVersion = automaticVersion; if (!fileVersion.isAuto()) { patternVersion = fileVersion.getVersion(); } if (patternVersion == null) { continue; } StringBuilder patternBuilder = patternBuilders.get(patternVersion); if (patternBuilder == null) { patternBuilder = new StringBuilder("("); patternBuilders.put(patternVersion, patternBuilder); } if (patternBuilder.length() > 1) { patternBuilder.append("|"); } patternBuilder.append(relativePath.replace(".", "\\.")); } } for (String version : patternBuilders.keySet()) { StringBuilder patternBuilder = patternBuilders.get(version).append(")"); versionFilePatterns.put(version, Pattern.compile(patternBuilder.toString(), Pattern.DOTALL)); } } catch (Exception ex) { LOGGER.log(Level.SEVERE, ex.getMessage()); } }
From source file:org.mobicents.servlet.restcomm.RvdProjectsMigrationHelper.java
private void defineWorkspacePath(ServletContext servletContext) throws Exception { // Obtain RVD context root path String contextRootPath = servletContext.getRealPath("/"); String contextPathRvd = contextRootPath + "../" + CONTEXT_NAME_RVD + "/"; // Check RVD context to try embedded mode if necessary File rvd = new File(contextPathRvd); if (rvd.exists()) { // Load RVD configuration and check workspace path FileInputStream input = new FileInputStream(contextPathRvd + "WEB-INF/rvd.xml"); XStream xstream = new XStream(); xstream.alias("rvd", RvdConfig.class); RvdConfig rvdConfig = (RvdConfig) xstream.fromXML(input); // Define workspace location String workspaceBasePath = contextPathRvd + WORKSPACE_DIRECTORY_NAME; if (rvdConfig.getWorkspaceLocation() != null && !"".equals(rvdConfig.getWorkspaceLocation())) { if (rvdConfig.getWorkspaceLocation().startsWith("/")) workspaceBasePath = rvdConfig.getWorkspaceLocation(); // this is an absolute path else//from w w w. java 2s . c o m workspaceBasePath = contextPathRvd + rvdConfig.getWorkspaceLocation(); // this is a relative path hooked // under RVD context } this.workspacePath = workspaceBasePath; // Define workspace backup location String workspaceBackupBasePath = contextPathRvd; if (rvdConfig.getWorkspaceBackupLocation() != null && !"".equals(rvdConfig.getWorkspaceBackupLocation())) { if (rvdConfig.getWorkspaceBackupLocation().startsWith("/")) workspaceBackupBasePath = rvdConfig.getWorkspaceBackupLocation(); // this is an absolute path else workspaceBackupBasePath = contextPathRvd + rvdConfig.getWorkspaceBackupLocation(); // this is a relative // path hooked under RVD // context } this.workspaceBackupPath = workspaceBackupBasePath; } else { // Try to set embedded migration. For testing only String dir = contextRootPath + EMBEDDED_DIRECTORY_NAME + File.separator + WORKSPACE_DIRECTORY_NAME + File.separator; File embedded = new File(dir); if (embedded.exists()) { this.workspacePath = dir; this.workspaceBackupPath = contextRootPath; this.embeddedMigration = true; } else { throw new Exception("Error while searching for the workspace location. Aborting migration."); } } }
From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java
/** * Gets an absolute path to CKFinder file or folder for which path was provided as parameter. * * @param path relative or absolute path to a CKFinder resource (file or folder). * @param isAbsolute flag indicating if path to resource is absolute e.g. /usr/john/userfiles or "C:\\userfiles". If this parameter is * set to true path will be returned as is. * @param shouldExist flag indicating if resource, represented by path parameter, should exist (e.g. configuration file) in file system * or not (e.g. userfiles folder).<br> * If this parameter is set to true, path to file will only be returned if such file exists. If file can't be found, method will return * null.//ww w . j av a 2s .c om * @return an absolute path to a resource in CKFinder * @throws ConnectorException when {@code ServletContext} is {@code null} or full path to resource cannot be obtained. */ public static String getFullPath(String path, boolean isAbsolute, boolean shouldExist) throws ConnectorException { if (path != null && !path.equals("")) { if (isAbsolute) { if (path.startsWith("/")) { //Check if this isn't Windows Path. String temporary = PathUtils.removeSlashFromBeginning(path); if (isStartsWithPattern(drivePatt, temporary)) { path = temporary; } } return checkAndReturnPath(shouldExist, path); } else { ServletContext sc = ServletContextFactory.getServletContext(); String tempPath = PathUtils.addSlashToEnd(PathUtils.addSlashToBeginning(path)); try { java.net.URL url = sc.getResource(tempPath); //For srevers like Tomcat 6-7 the getResource method returns JNDI URL. if (url != null && url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("jndi")) { //Assume file is inside application context and try to get path. //This method will fail if war is not exploaded. String result = sc.getRealPath(tempPath.replace(sc.getContextPath(), "")); if (result != null) { return result; } else { //If application is packed, we have to try constructing the path manually. result = getClassPath(); if (tempPath.indexOf(sc.getContextPath() + "/") >= 0 && result.indexOf(sc.getContextPath() + "/") >= 0) { result = result.substring(0, result.indexOf(sc.getContextPath())); result = result + tempPath; } else if (result.indexOf(sc.getContextPath() + "/") >= 0) { result = result.substring(0, result.indexOf(sc.getContextPath()) + sc.getContextPath().length()); result = result + tempPath; } result = checkAndReturnPath(shouldExist, result); if (result != null) { return result; } } //At this stage path is not in application context and is not absolute. //We need to reset url as we cannot determine path from it. if (result == null) { url = null; } } //For servers like Tomact 8 getResource method should return file:// url. if (path.startsWith("/") || isStartsWithPattern(drivePatt, path)) { //This is most likely absolute path. String absolutePath = checkAndReturnPath(shouldExist, path); if (absolutePath != null && !absolutePath.equals("")) { return absolutePath; } else { //If absolute path has failed, give it one last try with relative path. //Either path or null will be returned. return sc.getRealPath(path.replace(sc.getContextPath(), "")); } } } catch (IOException ioex) { throw new ConnectorException(ioex); } } } return null; }
From source file:org.openmrs.web.Listener.java
/** * Copy the customization scripts over into the webapp * * @param servletContext//w ww . j av a2 s .co m */ private void copyCustomizationIntoWebapp(ServletContext servletContext, Properties props) { Log log = LogFactory.getLog(Listener.class); String realPath = servletContext.getRealPath(""); // TODO centralize map to WebConstants? Map<String, String> custom = new HashMap<String, String>(); custom.put("custom.template.dir", "/WEB-INF/template"); custom.put("custom.index.jsp.file", "/WEB-INF/view/index.jsp"); custom.put("custom.login.jsp.file", "/WEB-INF/view/login.jsp"); custom.put("custom.patientDashboardForm.jsp.file", "/WEB-INF/view/patientDashboardForm.jsp"); custom.put("custom.images.dir", "/images"); custom.put("custom.style.css.file", "/style.css"); custom.put("custom.messages", "/WEB-INF/custom_messages.properties"); custom.put("custom.messages_fr", "/WEB-INF/custom_messages_fr.properties"); custom.put("custom.messages_es", "/WEB-INF/custom_messages_es.properties"); custom.put("custom.messages_de", "/WEB-INF/custom_messages_de.properties"); for (Map.Entry<String, String> entry : custom.entrySet()) { String prop = entry.getKey(); String webappPath = entry.getValue(); String userOverridePath = props.getProperty(prop); // if they defined the variable if (userOverridePath != null) { String absolutePath = realPath + webappPath; File file = new File(userOverridePath); // if they got the path correct // also, if file does not start with a "." (hidden files, like SVN files) if (file.exists() && !userOverridePath.startsWith(".")) { log.debug("Overriding file: " + absolutePath); log.debug("Overriding file with: " + userOverridePath); if (file.isDirectory()) { for (File f : file.listFiles()) { userOverridePath = f.getAbsolutePath(); if (!f.getName().startsWith(".")) { String tmpAbsolutePath = absolutePath + "/" + f.getName(); if (!copyFile(userOverridePath, tmpAbsolutePath)) { log.warn("Unable to copy file in folder defined by runtime property: " + prop); log.warn("Your source directory (or a file in it) '" + userOverridePath + " cannot be loaded or destination '" + tmpAbsolutePath + "' cannot be found"); } } } } else { // file is not a directory if (!copyFile(userOverridePath, absolutePath)) { log.warn("Unable to copy file defined by runtime property: " + prop); log.warn("Your source file '" + userOverridePath + " cannot be loaded or destination '" + absolutePath + "' cannot be found"); } } } } } }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
synchronized private void readSiteCertificates(ServletContext servletContext) { if (trustedCerts != null) return;//from w w w . j a v a2 s . com trustedCerts = new ArrayList<>(); // Now to add the other certificates added to the site File certsDirectory = new File(servletContext.getRealPath("/WEB-INF/classes/certificates")); try { if (certsDirectory.exists()) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); String[] certs = certsDirectory.list(new FilenameFilter() { @Override public boolean accept(File dir, String fileName) { return fileName.endsWith(".crt") || fileName.endsWith(".cer") || fileName.endsWith(".pem"); } }); if (certs != null) { X509Certificate x509Cert; for (String cert : certs) { try (FileInputStream fis = new FileInputStream(new File(certsDirectory, cert))) { x509Cert = (X509Certificate) cf.generateCertificate(fis); } if (x509Cert != null && !trustedCerts.contains(x509Cert)) { trustedCerts.add(x509Cert); } } } } } catch (Throwable e1) { LOG.log(Level.INFO, "Failed to load certificates from diretory " + certsDirectory.getAbsolutePath(), e1); } }
From source file:jp.or.openid.eiwg.listener.InitListener.java
/** * Web???// ww w. j av a2 s . c o m * * @param contextEvent */ @Override public void contextInitialized(ServletContextEvent contextEvent) { // ? ServletContext context = contextEvent.getServletContext(); // ??DBLDAP???? // ???????? ObjectMapper mapper = new ObjectMapper(); Map<String, Object> serviceProviderConfigs = null; ArrayList<LinkedHashMap<String, Object>> resourceTypes = null; ArrayList<LinkedHashMap<String, Object>> schemas = null; ArrayList<LinkedHashMap<String, Object>> users = null; // ?(ServiceProviderConfigs.json)?? try { serviceProviderConfigs = mapper.readValue( new File(context.getRealPath("/WEB-INF/ServiceProviderConfigs.json")), new TypeReference<LinkedHashMap<String, Object>>() { }); } catch (IOException e) { e.printStackTrace(); } // (ResourceTypes.json)?? try { resourceTypes = mapper.readValue(new File(context.getRealPath("/WEB-INF/ResourceTypes.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { e.printStackTrace(); } // (Schemas.json)?? try { schemas = mapper.readValue(new File(context.getRealPath("/WEB-INF/Schemas.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { e.printStackTrace(); } // ?? try { users = mapper.readValue(new File(context.getRealPath("/WEB-INF/Users.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { e.printStackTrace(); } // ? context.setAttribute("ServiceProviderConfigs", serviceProviderConfigs); context.setAttribute("ResourceTypes", resourceTypes); context.setAttribute("Schemas", schemas); context.setAttribute("Users", users); }
From source file:com.jsmartframework.web.manager.FilterControl.java
private void copyFileResource(InputStream is, String relativePath, ServletContext context) throws Exception { int count = 0; BufferedInputStream bis = new BufferedInputStream(is); String realFilePath = new File(context.getRealPath(PATH_SEPARATOR)).getPath() + PATH_SEPARATOR + relativePath;// w w w .ja va 2s . com FileOutputStream fos = new FileOutputStream(realFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos, STREAM_BUFFER); byte data[] = new byte[STREAM_BUFFER]; while ((count = bis.read(data, 0, STREAM_BUFFER)) != -1) { bos.write(data, 0, count); } bos.close(); bis.close(); }
From source file:org.xz.qstruts.config.QStrutsXmlConfigurationProvider.java
/** * Constructs the configuration provider * * @param filename The filename to look for * @param errorIfMissing If we should throw an exception if the file can't be found * @param ctx Our ServletContext/*from ww w. ja va 2 s .com*/ */ public QStrutsXmlConfigurationProvider(String filename, boolean errorIfMissing, ServletContext ctx) { super(filename, errorIfMissing); this.servletContext = ctx; this.filename = filename; reloadKey = "configurationReload-" + filename; Map<String, String> dtdMappings = new HashMap<String, String>(getDtdMappings()); dtdMappings.put("-//Apache Software Foundation//DTD Struts Configuration 2.0//EN", "struts-2.0.dtd"); dtdMappings.put("-//Apache Software Foundation//DTD Struts Configuration 2.1//EN", "struts-2.1.dtd"); dtdMappings.put("-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN", "struts-2.1.7.dtd"); setDtdMappings(dtdMappings); this.baseDir = new File((ctx.getRealPath("/WEB-INF/modules/"))); if (!baseDir.exists()) { baseDir = null; } }
From source file:com.orchestra.portale.controller.NewPoiController.java
@RequestMapping(value = "/insertpoi", method = RequestMethod.POST) public ModelAndView insertPoi(@RequestParam Map<String, String> params, @RequestParam("file") MultipartFile[] files, @RequestParam("cover") MultipartFile cover, HttpServletRequest request) throws InterruptedException { CompletePOI poi = new CompletePOI(); CompletePOI poitest = new CompletePOI(); ModelAndView model = new ModelAndView("insertpoi"); ModelAndView model2 = new ModelAndView("errorViewPoi"); poitest = pm.findOneCompletePoiByName(params.get("name")); if (poitest != null && poitest.getName().toLowerCase().equals(params.get("name").toLowerCase())) { model2.addObject("err", "Esiste gi un poi chiamato " + params.get("name")); return model2; } else {/*www . java2 s . c o m*/ poi.setName(params.get("name")); poi.setVisibility(params.get("visibility")); poi.setAddress(params.get("address")); double lat = Double.parseDouble(params.get("latitude")); double longi = Double.parseDouble(params.get("longitude")); poi.setLocation(new double[] { lat, longi }); poi.setShortDescription(params.get("shortd")); int i = 1; ArrayList<String> categories = new ArrayList<String>(); while (params.containsKey("category" + i)) { categories.add(params.get("category" + i)); i = i + 1; } poi.setCategories(categories); ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>(); //componente cover if (!cover.isEmpty()) { CoverImgComponent coverimg = new CoverImgComponent(); coverimg.setLink("cover.jpg"); listComponent.add(coverimg); } //componente galleria immagini ArrayList<ImgGallery> links = new ArrayList<ImgGallery>(); if (files.length > 0) { ImgGalleryComponent img_gallery = new ImgGalleryComponent(); i = 0; while (i < files.length) { ImgGallery img = new ImgGallery(); Thread.sleep(100); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa"); String currentTimestamp = sdf.format(date); img.setLink("img_" + currentTimestamp + ".jpg"); if (params.containsKey("credit" + (i + 1))) img.setCredit(params.get("credit" + (i + 1))); i = i + 1; links.add(img); } img_gallery.setLinks(links); listComponent.add(img_gallery); } //componente contatti ContactsComponent contacts_component = new ContactsComponent(); //Recapiti telefonici i = 1; boolean contacts = false; if (params.containsKey("tel" + i)) { ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>(); while (params.containsKey("tel" + i)) { PhoneContact phone = new PhoneContact(); if (params.containsKey("tel" + i)) { phone.setLabel(params.get("desctel" + i)); } phone.setNumber(params.get("tel" + i)); phoneList.add(phone); i = i + 1; } contacts = true; contacts_component.setPhoneList(phoneList); } //Recapiti mail i = 1; if (params.containsKey("email" + i)) { ArrayList<EmailContact> emailList = new ArrayList<EmailContact>(); while (params.containsKey("email" + i)) { EmailContact email = new EmailContact(); if (params.containsKey("email" + i)) { email.setLabel(params.get("descemail" + i)); } email.setEmail(params.get("email" + i)); emailList.add(email); i = i + 1; } contacts = true; contacts_component.setEmailsList(emailList); } //Recapiti fax i = 1; if (params.containsKey("fax" + i)) { ArrayList<FaxContact> faxList = new ArrayList<FaxContact>(); while (params.containsKey("fax" + i)) { FaxContact fax = new FaxContact(); if (params.containsKey("fax" + i)) { fax.setLabel(params.get("descfax" + i)); } fax.setFax(params.get("fax" + i)); faxList.add(fax); i = i + 1; } contacts = true; contacts_component.setFaxList(faxList); } //Social predefiniti i = 1; if (params.containsKey("SN" + i)) { while (params.containsKey("SN" + i)) { if (params.get("SN" + i).equals("facebook")) { contacts = true; contacts_component.setFacebook(params.get("LSN" + i)); } if (params.get("SN" + i).equals("twitter")) { contacts = true; contacts_component.setTwitter(params.get("LSN" + i)); } if (params.get("SN" + i).equals("google")) { contacts = true; contacts_component.setGoogle(params.get("LSN" + i)); } if (params.get("SN" + i).equals("skype")) { contacts = true; contacts_component.setSkype(params.get("LSN" + i)); } i = i + 1; } } //Social personalizzati i = 1; if (params.containsKey("CSN" + i)) { ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>(); while (params.containsKey("CSN" + i)) { GenericSocial social = new GenericSocial(); contacts = true; social.setLabel(params.get("CSN" + i)); social.setSocial(params.get("LCSN" + i)); customsocial.add(social); i = i + 1; } contacts_component.setSocialList(customsocial); } if (contacts == true) { listComponent.add(contacts_component); } //DESCRIPTION COMPONENT i = 1; if (params.containsKey("par" + i)) { ArrayList<Section> list = new ArrayList<Section>(); while (params.containsKey("par" + i)) { Section section = new Section(); if (params.containsKey("titolo" + i)) { section.setTitle(params.get("titolo" + i)); } section.setDescription(params.get("par" + i)); list.add(section); i = i + 1; } DescriptionComponent description_component = new DescriptionComponent(); description_component.setSectionsList(list); listComponent.add(description_component); } //Orari i = 1; int k = 1; boolean ok = false; String gg = ""; boolean[] aperto = new boolean[8]; for (int z = 1; z <= 7; z++) { aperto[z] = false; } WorkingTimeComponent workingtime = new WorkingTimeComponent(); if (params.containsKey("WD" + i + "start" + k + "H")) { ok = true; ArrayList<CompactWorkingDays> workingdays = new ArrayList<CompactWorkingDays>(); while (params.containsKey("WD" + i)) { ArrayList<WorkingHours> Listwh = new ArrayList<WorkingHours>(); k = 1; while (params.containsKey("WD" + i + "start" + k + "H")) { WorkingHours wh = new WorkingHours(); wh.setStart(params.get("WD" + i + "start" + k + "H") + ":" + params.get("WD" + i + "start" + k + "M")); wh.setEnd(params.get("WD" + i + "end" + k + "H") + ":" + params.get("WD" + i + "end" + k + "M")); Listwh.add(wh); k = k + 1; } CompactWorkingDays cwd = new CompactWorkingDays(); cwd.setDays(params.get("WD" + i)); cwd.setWorkinghours(Listwh); workingdays.add(cwd); i = i + 1; } int grn = 1; ArrayList<CompactWorkingDays> wdef = new ArrayList<CompactWorkingDays>(); for (int z = 1; z <= 7; z++) { aperto[z] = false; } while (grn <= 7) { for (CompactWorkingDays g : workingdays) { if (grn == 1 && g.getDays().equals("Luned")) { aperto[1] = true; wdef.add(g); } if (grn == 2 && g.getDays().equals("Marted")) { aperto[2] = true; wdef.add(g); } if (grn == 3 && g.getDays().equals("Mercoled")) { aperto[3] = true; wdef.add(g); } if (grn == 4 && g.getDays().equals("Gioved")) { aperto[4] = true; wdef.add(g); } if (grn == 5 && g.getDays().equals("Venerd")) { aperto[5] = true; wdef.add(g); } if (grn == 6 && g.getDays().equals("Sabato")) { aperto[6] = true; wdef.add(g); } if (grn == 7 && g.getDays().equals("Domenica")) { aperto[7] = true; wdef.add(g); } } grn++; } workingtime.setWorkingdays(wdef); for (int z = 1; z <= 7; z++) { if (aperto[z] == false && z == 1) gg = gg + " " + "Luned"; if (aperto[z] == false && z == 2) gg = gg + " " + "Marted"; if (aperto[z] == false && z == 3) gg = gg + " " + "Mercoled"; if (aperto[z] == false && z == 4) gg = gg + " " + "Gioved"; if (aperto[z] == false && z == 5) gg = gg + " " + "Venerd"; if (aperto[z] == false && z == 6) gg = gg + " " + "Sabato"; if (aperto[z] == false && z == 7) gg = gg + " " + "Domenica"; } if (!gg.equals("")) { ok = true; workingtime.setWeekly_day_of_rest(gg); } } i = 1; String ggs = ""; while (params.containsKey("RDA" + i)) { ggs = ggs + " " + params.get("RDA" + i); i = i + 1; } if (!ggs.equals("")) { ok = true; workingtime.setDays_of_rest(ggs); } if (ok) { listComponent.add(workingtime); } i = 1; if (params.containsKey("type" + i)) { PricesComponent pc = new PricesComponent(); ArrayList<TicketPrice> tpList = new ArrayList<TicketPrice>(); while (params.containsKey("type" + i)) { TicketPrice tp = new TicketPrice(); tp.setType(params.get("type" + i)); double dp = Double.parseDouble(params.get("price" + i)); tp.setPrice(dp); tp.setType_description(params.get("typedesc" + i)); tpList.add(tp); i = i + 1; } pc.setPrices(tpList); listComponent.add(pc); } i = 1; if (params.containsKey("SERV" + i)) { ArrayList<String> servList = new ArrayList<String>(); while (params.containsKey("SERV" + i)) { servList.add(params.get("SERV" + i)); i = i + 1; } ServicesComponent servicescomponent = new ServicesComponent(); servicescomponent.setServicesList(servList); listComponent.add(servicescomponent); } poi.setComponents(listComponent); pm.savePoi(poi); CompletePOI poi2 = (CompletePOI) pm.findOneCompletePoiByName(poi.getName()); for (int z = 0; z < files.length; z++) { MultipartFile file = files[z]; try { byte[] bytes = file.getBytes(); // Creating the directory to store file HttpSession session = request.getSession(); ServletContext sc = session.getServletContext(); File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img" + File.separator + poi2.getId()); if (!dir.exists()) dir.mkdirs(); // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink()); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); } catch (Exception e) { return model; } } MultipartFile file = cover; try { byte[] bytes = file.getBytes(); // Creating the directory to store file HttpSession session = request.getSession(); ServletContext sc = session.getServletContext(); File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img" + File.separator + poi2.getId()); if (!dir.exists()) dir.mkdirs(); // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg"); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); } catch (Exception e) { return model; } return model; } }