List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:helma.servlet.AbstractServletClient.java
/** * Forward the request to a static file. The file must be reachable via * the context's protectedStatic resource base. *///from w w w .j a va 2 s . c om void sendForward(HttpServletResponse res, HttpServletRequest req, ResponseTrans hopres) throws IOException { String forward = hopres.getForward(); // Jetty 5.1 bails at forward paths without leading slash, so fix it if (!forward.startsWith("/")) { forward = "/" + forward; } ServletContext cx = getServletConfig().getServletContext(); String path = cx.getRealPath(forward); if (path == null) { throw new IOException("Resource " + forward + " not found"); } File file = new File(path); // check if the client has an up-to-date copy so we can // send a not-modified response if (checkNotModified(file, req, res)) { res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } int length = (int) file.length(); res.setContentLength(length); res.setContentType(hopres.getContentType()); InputStream in = cx.getResourceAsStream(forward); if (in == null) { throw new IOException("Can't read " + path); } try { OutputStream out = res.getOutputStream(); int bufferSize = 4096; byte buffer[] = new byte[bufferSize]; int l; while (length > 0) { if (length < bufferSize) { l = in.read(buffer, 0, length); } else { l = in.read(buffer, 0, bufferSize); } if (l == -1) { break; } length -= l; out.write(buffer, 0, l); } } finally { in.close(); } }
From source file:lucee.runtime.net.rpc.server.RPCServer.java
/** * Initialization method.//from ww w. jav a 2 s.co m * @throws AxisFault */ private RPCServer(ServletContext context) throws AxisFault { this.context = context; initQueryStringHandlers(); ServiceAdmin.setEngine(this.getEngine(), context.getServerInfo()); webInfPath = context.getRealPath("/WEB-INF"); homeDir = ReqRspUtil.getRootPath(context); }
From source file:managedBeans.facturacion.ListadoFacturaMB.java
public void generarPDF() { // guardarFactura(); if (documentoSeleccionado != null) { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext();//from w w w . j av a 2 s. co m String ruta = null; switch (tipoImpresion) { case 1: ruta = servletContext.getRealPath("/facturacion/reportes/facturaTicket.jasper"); break; case 2: ruta = servletContext.getRealPath("/facturacion/reportes/facturaCarta.jasper"); break; } // setTipoImpresion(2); try { generarFactura(ruta); } catch (IOException ex) { Logger.getLogger(FacturaMB.class.getName()).log(Level.SEVERE, null, ex); } catch (JRException ex) { Logger.getLogger(FacturaMB.class.getName()).log(Level.SEVERE, null, ex); } // documentoActual = null; } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.FedoraDatastreamController.java
public void setup(OntModel model, ServletContext context) { this.configurationStatus = ""; StringBuffer status = new StringBuffer(""); if (connected && configured) return;/*from w w w. j av a 2 s. c o m*/ Properties props = new Properties(); String path = context.getRealPath(FEDORA_PROPERTIES); try { InputStream in = new FileInputStream(new File(path)); props.load(in); fedoraUrl = props.getProperty("fedoraUrl"); adminUser = props.getProperty("adminUser"); adminPassword = props.getProperty("adminPassword"); pidNamespace = props.getProperty("pidNamespace"); if (fedoraUrl == null || adminUser == null || adminPassword == null) { if (fedoraUrl == null) { log.error("'fedoraUrl' not found in properties file"); status.append("<p>'fedoraUrl' not found in properties file.</p>\n"); } if (adminUser == null) { log.error("'adminUser' was not found in properties file, the " + "user name of the fedora admin is needed to access the " + "fedora API-M services."); status.append("<p>'adminUser' was not found in properties file, the " + "user name of the fedora admin is needed to access the " + "fedora API-M services.</p>\n"); } if (adminPassword == null) { log.error("'adminPassword' was not found in properties file, the " + "admin password is needed to access the fedora API-M services."); status.append("<p>'adminPassword' was not found in properties file, the " + "admin password is needed to access the fedora API-M services.</p>\n"); } if (pidNamespace == null) { log.error("'pidNamespace' was not found in properties file, the " + "PID namespace indicates which namespace to use when creating " + "new fedor digital objects."); status.append("<p>'pidNamespace' was not found in properties file, the " + "PID namespace indicates which namespace to use when creating " + "new fedor digital objects.</p>\n"); } fedoraUrl = null; adminUser = null; adminPassword = null; configured = false; } else { configured = true; } } catch (FileNotFoundException e) { log.error("No fedora.properties file found," + "it should be located at " + path); status.append("<h1>Fedora configuration failed.</h1>\n"); status.append("<p>No fedora.properties file found," + "it should be located at " + path + "</p>\n"); configured = false; return; } catch (Exception ex) { status.append("<p>Fedora configuration failed.</p>\n"); status.append("<p>Exception while loading" + path + "</p>\n"); status.append("<p>" + ex.getMessage() + "</p>\n"); log.error("could not load fedora properties", ex); fedoraUrl = null; adminUser = null; adminPassword = null; configured = false; return; } status.append(RELOAD_MSG); this.configurationStatus += status.toString(); // else{ // status.append("<h2>Fedora configuration file ").append(path).append(" was loaded</h2>"); // status.append("<p>fedoraUrl: ").append(fedoraUrl).append("</p>\n"); // checkFedoraServer(); // } }
From source file:org.alfresco.web.forms.xforms.XFormsBean.java
/** @param xformsSession the current session */ public void setXFormsSession(final XFormsSession xformsSession) throws FormBuilderException, XFormsException { this.xformsSession = xformsSession; final FacesContext facesContext = FacesContext.getCurrentInstance(); final ExternalContext externalContext = facesContext.getExternalContext(); final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); final ServletContext servletContext = (ServletContext) externalContext.getContext(); writeLock.lock();//from w ww . j ava 2s. c om try { final ChibaBean chibaBean = new ChibaBean(); chibaBean.setConfig(servletContext.getRealPath("/WEB-INF/chiba.xml")); Pair<Document, XSModel> chibaPair = this.getXFormsDocument(); chibaBean.setXMLContainer(chibaPair.getFirst(), chibaPair.getSecond()); final EventTarget et = (EventTarget) chibaBean.getXMLContainer().getDocumentElement(); final EventListener el = new EventListener() { public void handleEvent(final Event e) { final XMLEvent xmle = (XMLEvent) e; if (XFormsBean.LOGGER.isDebugEnabled()) XFormsBean.LOGGER.debug("received event " + xmle.getType() + ": " + xmle); XFormsBean.this.xformsSession.eventLog.add(xmle); } }; // interaction events my occur during init so we have to register before et.addEventListener(ChibaEventNames.LOAD_URI, el, true); et.addEventListener(ChibaEventNames.RENDER_MESSAGE, el, true); et.addEventListener(ChibaEventNames.REPLACE_ALL, el, true); et.addEventListener(XFormsEventNames.ENABLED, el, true); et.addEventListener(XFormsEventNames.DISABLED, el, true); et.addEventListener(XFormsEventNames.REQUIRED, el, true); et.addEventListener(XFormsEventNames.OPTIONAL, el, true); et.addEventListener(XFormsEventNames.READONLY, el, true); et.addEventListener(XFormsEventNames.READWRITE, el, true); et.addEventListener(XFormsEventNames.VALID, el, true); et.addEventListener(XFormsEventNames.INVALID, el, true); et.addEventListener(XFormsEventNames.IN_RANGE, el, true); et.addEventListener(XFormsEventNames.OUT_OF_RANGE, el, true); et.addEventListener(XFormsEventNames.SELECT, el, true); et.addEventListener(XFormsEventNames.DESELECT, el, true); et.addEventListener(XFormsEventNames.INSERT, el, true); et.addEventListener(XFormsEventNames.DELETE, el, true); chibaBean.init(); // register for notification events et.addEventListener(XFormsEventNames.SUBMIT, el, true); et.addEventListener(XFormsEventNames.SUBMIT_DONE, el, true); et.addEventListener(XFormsEventNames.SUBMIT_ERROR, el, true); et.addEventListener(ChibaEventNames.STATE_CHANGED, el, true); et.addEventListener(ChibaEventNames.PROTOTYPE_CLONED, el, true); et.addEventListener(ChibaEventNames.ID_GENERATED, el, true); et.addEventListener(ChibaEventNames.ITEM_INSERTED, el, true); et.addEventListener(ChibaEventNames.ITEM_DELETED, el, true); et.addEventListener(ChibaEventNames.INDEX_CHANGED, el, true); et.addEventListener(ChibaEventNames.SWITCH_TOGGLED, el, true); this.xformsSession.chibaBean = chibaBean; } finally { writeLock.unlock(); } }
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; }/* www . j a va 2s . 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.deegree.services.controller.OGCFrontController.java
/** * 'Heuristical' method to retrieve the {@link URL} for a file referenced from an init-param of a webapp config file * which may be:/* w w w . j a v a2 s. c o m*/ * <ul> * <li>a (absolute) <code>URL</code></li> * <li>a file location</li> * <li>a (relative) URL which in turn is resolved using <code>ServletContext.getRealPath</code></li> * </ul> * * @param location * @param context * @return the full (and whitespace-escaped) URL * @throws MalformedURLException */ public static URL resolveFileLocation(String location, ServletContext context) throws MalformedURLException { URL serviceConfigurationURL = null; LOG.debug("Resolving configuration file location: '" + location + "'..."); try { // construction of URI performs whitespace escaping serviceConfigurationURL = new URI(location).toURL(); } catch (Exception e) { LOG.debug("No valid (absolute) URL. Trying context.getRealPath() now."); String realPath = context.getRealPath(location); if (realPath == null) { LOG.debug("No 'real path' available. Trying to parse as a file location now."); serviceConfigurationURL = new File(location).toURI().toURL(); } else { try { // realPath may either be a URL or a File serviceConfigurationURL = new URI(realPath).toURL(); } catch (Exception e2) { LOG.debug("'Real path' cannot be parsed as URL. Trying to parse as a file location now."); // construction of URI performs whitespace escaping serviceConfigurationURL = new File(realPath).toURI().toURL(); LOG.debug("configuration URL: " + serviceConfigurationURL); } } } return serviceConfigurationURL; }
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 {// w w w . j av a 2s. 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:org.red5.server.winstone.WinstoneLoader.java
/** * Initialization./*from ww w. ja va2 s . c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void init() { log.info("Loading Winstone context"); //get a reference to the current threads classloader final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); // root location for servlet container String serverRoot = System.getProperty("red5.root"); log.info("Server root: {}", serverRoot); String confRoot = System.getProperty("red5.config_root"); log.info("Config root: {}", confRoot); // configure the webapps folder, make sure we have one if (webappFolder == null) { // Use default webapps directory webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps"); } System.setProperty("red5.webapp.root", webappFolder); log.info("Application root: {}", webappFolder); // create one embedded (server) and use it everywhere Map args = new HashMap(); //args.put("webroot", webappFolder + "/root"); args.put("webappsDir", webappFolder); // Start server try { log.info("Starting Winstone servlet engine"); Launcher.initLogger(args); // spawns threads, so your application doesn't block embedded = new StoneLauncher(args); log.trace("Classloader for embedded: {} TCL: {}", Launcher.class.getClassLoader(), originalClassLoader); // get the default host HostConfiguration host = embedded.getHostGroup().getHostByName(null); // set the primary application loader LoaderBase.setApplicationLoader(new WinstoneApplicationLoader(host, applicationContext)); // get root first, we may want to start a spring config internally but for now skip it WebAppConfiguration root = host.getWebAppByURI("/"); log.trace("Root: {}", root); // scan the sub directories to determine our context names buildContextNameList(webappFolder); // loop the other contexts for (String contextName : contextNames) { WebAppConfiguration ctx = host.getWebAppByURI(contextName); // get access to the servlet context final ServletContext servletContext = ctx.getContext(contextName); log.debug("Context initialized: {}", servletContext.getContextPath()); //set the hosts id servletContext.setAttribute("red5.host.id", host.getHostname()); // get the path String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { final ClassLoader cldr = ctx.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); // get the (spring) config file path final String contextConfigLocation = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null ? defaultSpringConfigLocation : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM); log.debug("Spring context config location: {}", contextConfigLocation); // get the (spring) parent context key final String parentContextKey = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null ? defaultParentContextKey : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM); log.debug("Spring parent context key: {}", parentContextKey); //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(cldr); //create a thread to speed-up application loading Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) { public void run() { //set thread context classloader to web classloader Thread.currentThread().setContextClassLoader(cldr); //get the web app's parent context ApplicationContext parentContext = null; if (applicationContext.containsBean(parentContextKey)) { parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey); } else { log.warn("Parent context was not found: {}", parentContextKey); } // create a spring web application context final String contextClass = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null ? XmlWebApplicationContext.class.getName() : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM); //web app context (spring) ConfigurableWebApplicationContext appctx = null; try { Class<?> clazz = Class.forName(contextClass, true, cldr); appctx = (ConfigurableWebApplicationContext) clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("Failed to load webapplication context class.", e); } appctx.setConfigLocations(new String[] { contextConfigLocation }); appctx.setServletContext(servletContext); //set parent context or use current app context if (parentContext != null) { appctx.setParent(parentContext); } else { appctx.setParent(applicationContext); } // set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); //refresh the factory log.trace("Classloader prior to refresh: {}", appctx.getClassLoader()); appctx.refresh(); if (log.isDebugEnabled()) { log.debug("Red5 app is active: {} running: {}", appctx.isActive(), appctx.isRunning()); } } }; thread.setDaemon(true); thread.start(); } catch (Throwable t) { log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(), t.getMessage()); t.printStackTrace(); } finally { //reset the classloader Thread.currentThread().setContextClassLoader(originalClassLoader); } } } catch (Exception e) { if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) { log.error( "Error loading Winstone, unable to bind connector. You may not have permission to use the selected port", e); } else { log.error("Error loading Winstone", e); } } finally { registerJMX(); } }
From source file:org.opencms.main.CmsServletContainerSettings.java
/** * Creates a new object.<p>//w w w .j av a 2 s .c om * * @param context used to find out specifics of the servlet container */ public CmsServletContainerSettings(ServletContext context) { // CmsSystemInfo<init> has to call this with null (for setup) if (context != null) { // check for OpenCms home (base) directory path String webInfRfsPath = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_HOME); if (CmsStringUtil.isEmpty(webInfRfsPath)) { webInfRfsPath = CmsFileUtil.searchWebInfFolder(context.getRealPath("/")); if (CmsStringUtil.isEmpty(webInfRfsPath)) { throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_FOLDER_0)); } } // set the default web application name // read the the default name from the servlet context parameters String defaultWebApplication = context.getInitParameter("DefaultWebApplication"); // read the the OpenCms servlet mapping from the servlet context parameters String servletMapping = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_SERVLET); if (servletMapping == null) { throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_SERVLET_0)); } // read the servlet container name String servletContainerName = context.getServerInfo(); // web application context: // read it from the servlet context parameters // this is needed in case an application server specific deployment descriptor is used to changed the webapp context String webApplicationContext = context .getInitParameter(OpenCmsServlet.SERVLET_PARAM_WEB_APPLICATION_CONTEXT); if (CmsStringUtil.isEmptyOrWhitespaceOnly(webApplicationContext)) { try { URL contextRelativeUrl = context.getResource("/"); webApplicationContext = contextRelativeUrl.getPath(); String[] pathTokens = CmsStringUtil.splitAsArray(webApplicationContext, '/'); if (pathTokens.length == 1) { /* * There may be a "" context configured (e.g. in GlassFish). */ webApplicationContext = ""; } else { webApplicationContext = pathTokens[pathTokens.length - 1]; } } catch (MalformedURLException e) { LOG.error(Messages.get().getBundle().key(Messages.LOG_INIT_CONTEXTNAME_0), e); } } // init values: init(webInfRfsPath, defaultWebApplication, servletMapping, servletContainerName, webApplicationContext); // finally care for the speciality of different servlet containers: initContainerSpecifics(context); } }