List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:org.nuxeo.runtime.deployment.NuxeoStarter.java
protected void findEnv(ServletContext servletContext) { for (String param : Arrays.asList( // NUXEO_RUNTIME_HOME, // NUXEO_CONFIG_DIR, // NUXEO_DATA_DIR, // NUXEO_LOG_DIR, // NUXEO_TMP_DIR, // NUXEO_WEB_DIR)) {/*from w w w . java2 s.co m*/ String value = servletContext.getInitParameter(param); if (value != null && !"".equals(value.trim())) { env.put(param, value); } } // default env values if (!env.containsKey(NUXEO_CONFIG_DIR)) { String webinf = servletContext.getRealPath("/WEB-INF"); env.put(NUXEO_CONFIG_DIR, webinf); } if (!env.containsKey(NUXEO_RUNTIME_HOME)) { File home = new File(DEFAULT_HOME); env.put(NUXEO_RUNTIME_HOME, home.getAbsolutePath()); } // host if (getClass().getClassLoader().getClass().getName().startsWith("org.jboss.classloader")) { env.put(FrameworkLoader.HOST_NAME, JBOSS_HOST); } else if (servletContext.getClass().getName().startsWith("org.apache.catalina")) { env.put(FrameworkLoader.HOST_NAME, TOMCAT_HOST); } }
From source file:org.sakaiproject.portal.render.portlet.PortletToolRenderService.java
private boolean isPortletApplication(ServletContext context, ToolConfiguration configuration) throws ToolRenderException, MalformedURLException { SakaiPortletWindow window = registry.getOrCreatePortletWindow(configuration); if (window == null) { return false; }//w ww. j a v a 2s . c om if (LOG.isDebugEnabled()) { LOG.debug("Checking context for potential portlet "); } ServletContext crossContext = context.getContext(window.getContextPath()); if (LOG.isDebugEnabled()) { LOG.debug("Got servlet context as " + crossContext); LOG.debug("Getting Context for path " + window.getContextPath()); LOG.debug("Base Path " + crossContext.getRealPath("/")); LOG.debug("Context Name " + crossContext.getServletContextName()); LOG.debug("Server Info " + crossContext.getServerInfo()); LOG.debug(" and it is a portlet ? :" + (crossContext.getResource("/WEB-INF/portlet.xml") != null)); } return crossContext.getResource("/WEB-INF/portlet.xml") != null; }
From source file:org.red5.server.tomcat.TomcatVHostLoader.java
/** * Starts a web application and its red5 (spring) component. This is basically a stripped down * version of init()./*from ww w .j a v a 2 s.c om*/ * * @return true on success */ @SuppressWarnings("cast") public boolean startWebApplication(String applicationName) { boolean result = false; log.info("Starting Tomcat virtual host - Web application"); log.info("Virtual host root: {}", webappRoot); log.info("Virtual host context id: {}", defaultApplicationContextId); // application directory String contextName = '/' + applicationName; Container cont = null; //check if the context already exists for the host if ((cont = host.findChild(contextName)) == null) { log.debug("Context did not exist in host"); String webappContextDir = FileUtil.formatPath(webappRoot, applicationName); //prepend slash Context ctx = addContext(contextName, webappContextDir); //set the newly created context as the current container cont = ctx; } else { log.debug("Context already exists in host"); } try { ServletContext servletContext = ((Context) cont).getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); Loader cldr = cont.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); //create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" }); //check for red5 context bean if (applicationContext.containsBean(defaultApplicationContextId)) { appctx.setParent((ApplicationContext) applicationContext.getBean(defaultApplicationContextId)); } else { log.warn("{} bean was not found in context: {}", defaultApplicationContextId, applicationContext.getDisplayName()); //lookup context loader and attempt to get what we need from it if (applicationContext.containsBean("context.loader")) { ContextLoader contextLoader = (ContextLoader) applicationContext.getBean("context.loader"); appctx.setParent(contextLoader.getContext(defaultApplicationContextId)); } else { log.debug("Context loader was not found, trying JMX"); MBeanServer mbs = JMXFactory.getMBeanServer(); //get the ContextLoader from jmx ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader"); ContextLoaderMBean proxy = null; if (mbs.isRegistered(oName)) { proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName, ContextLoaderMBean.class, true); log.debug("Context loader was found"); appctx.setParent(proxy.getContext(defaultApplicationContextId)); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } // appctx.setServletContext(servletContext); //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); appctx.refresh(); result = true; } catch (Throwable t) { log.error("Error setting up context: {}", applicationName, t); if (log.isDebugEnabled()) { t.printStackTrace(); } } return result; }
From source file:org.apache.struts2.views.jasperreports.JasperReportsResult.java
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { // Will throw a runtime exception if no "datasource" property. TODO Best place for that is...? initializeProperties(invocation);//from w ww .ja v a 2s . c o m if (LOG.isDebugEnabled()) { LOG.debug("Creating JasperReport for dataSource = " + dataSource + ", format = " + format); } HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext() .get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext() .get(ServletActionContext.HTTP_RESPONSE); // Handle IE special case: it sends a "contype" request first. // TODO Set content type to config settings? if ("contype".equals(request.getHeader("User-Agent"))) { try { response.setContentType("application/pdf"); response.setContentLength(0); ServletOutputStream outputStream = response.getOutputStream(); outputStream.close(); } catch (IOException e) { LOG.error("Error writing report output", e); throw new ServletException(e.getMessage(), e); } return; } // Construct the data source for the report. ValueStack stack = invocation.getStack(); ValueStackDataSource stackDataSource = null; Connection conn = (Connection) stack.findValue(connection); if (conn == null) stackDataSource = new ValueStackDataSource(stack, dataSource); // Determine the directory that the report file is in and set the reportDirectory parameter // For WW 2.1.7: // ServletContext servletContext = ((ServletConfig) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext(); ServletContext servletContext = (ServletContext) invocation.getInvocationContext() .get(ServletActionContext.SERVLET_CONTEXT); String systemId = servletContext.getRealPath(finalLocation); Map parameters = new ValueStackShadowMap(stack); File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator))); parameters.put("reportDirectory", directory); parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale()); // put timezone in jasper report parameter if (timeZone != null) { timeZone = conditionalParse(timeZone, invocation); final TimeZone tz = TimeZone.getTimeZone(timeZone); if (tz != null) { // put the report time zone parameters.put(JRParameter.REPORT_TIME_ZONE, tz); } } // Add any report parameters from action to param map. Map reportParams = (Map) stack.findValue(reportParameters); if (reportParams != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found report parameters; adding to parameters..."); } parameters.putAll(reportParams); } byte[] output; JasperPrint jasperPrint; // Fill the report and produce a print object try { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(systemId); if (conn == null) jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource); else jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn); } catch (JRException e) { LOG.error("Error building report for uri " + systemId, e); throw new ServletException(e.getMessage(), e); } // Export the print object to the desired output format try { if (contentDisposition != null || documentName != null) { final StringBuffer tmp = new StringBuffer(); tmp.append((contentDisposition == null) ? "inline" : contentDisposition); if (documentName != null) { tmp.append("; filename="); tmp.append(documentName); tmp.append("."); tmp.append(format.toLowerCase()); } response.setHeader("Content-disposition", tmp.toString()); } JRExporter exporter; if (format.equals(FORMAT_PDF)) { response.setContentType("application/pdf"); exporter = new JRPdfExporter(); } else if (format.equals(FORMAT_CSV)) { response.setContentType("text/csv"); exporter = new JRCsvExporter(); } else if (format.equals(FORMAT_HTML)) { response.setContentType("text/html"); // IMAGES_MAPS seems to be only supported as "backward compatible" from JasperReports 1.1.0 Map imagesMap = new HashMap(); request.getSession(true).setAttribute("IMAGES_MAP", imagesMap); exporter = new JRHtmlExporter(); exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + imageServletUrl); // Needed to support chart images: exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint); } else if (format.equals(FORMAT_XLS)) { response.setContentType("application/vnd.ms-excel"); exporter = new JRXlsExporter(); } else if (format.equals(FORMAT_XML)) { response.setContentType("text/xml"); exporter = new JRXmlExporter(); } else if (format.equals(FORMAT_RTF)) { response.setContentType("application/rtf"); exporter = new JRRtfExporter(); } else { throw new ServletException("Unknown report format: " + format); } Map exportParams = (Map) stack.findValue(exportParameters); if (exportParams != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found export parameters; adding to exporter parameters..."); } exporter.getParameters().putAll(exportParams); } output = exportReportToBytes(jasperPrint, exporter); } catch (JRException e) { String message = "Error producing " + format + " report for uri " + systemId; LOG.error(message, e); throw new ServletException(e.getMessage(), e); } response.setContentLength(output.length); // Will throw ServletException on IOException. writeReport(response, output); }
From source file:eu.earthobservatory.org.StrabonEndpoint.Authenticate.java
/** * Authenticate user// ww w . j ava 2 s .c om * @throws IOException * */ public boolean authenticateUser(String authorization, ServletContext context) throws IOException { Properties properties = new Properties(); if (authorization == null) return false; // no authorization if (!authorization.toUpperCase().startsWith("BASIC ")) return false; // only BASIC authentication // get encoded user and password, comes after "BASIC " String userpassEncoded = authorization.substring(6); // decode String userpassDecoded = new String(Base64.decodeBase64(userpassEncoded)); Pattern pattern = Pattern.compile(":"); String[] credentials = pattern.split(userpassDecoded); // get credentials.properties as input stream InputStream input = new FileInputStream(context.getRealPath(CREDENTIALS_PROPERTIES_FILE)); // load the properties properties.load(input); // close the stream input.close(); // check if the given credentials are allowed if (!userpassDecoded.equals(":") && credentials[0].equals(properties.get("username")) && credentials[1].equals(properties.get("password"))) return true; else return false; }
From source file:controller.CommercialController.java
@RequestMapping(value = "regub/commercial/contrats/facturecom", method = RequestMethod.POST) //public @ResponseBody String factureAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException { int idvideo = Integer.parseInt(request.getParameter("idvideo")); Facture facture = new Facture(); facture.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0), request.getServletContext()); //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}//ww w. ja va2 s . com //session.setAttribute("Modify", this.modif.modifcontrat(id)); int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println(appPath); try { File downloadFile = new File(appPath + "\\resources\\reports\\facture.pdf"); FileInputStream fis = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(appPath + "\\resources\\reports\\facture.pdf"); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = fis.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } fis.close(); outStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return "redirect:/regub/commercial/contrats/" + VidBDD.VideoPrec(idvideo).get(0).getClient().getIdClient(); }
From source file:controller.CommercialController.java
@RequestMapping(value = "regub/commercial/facturecom", method = RequestMethod.POST) //public @ResponseBody String facture2Action(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException { int idvideo = Integer.parseInt(request.getParameter("idvideo")); Facture facture = new Facture(); facture.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0), request.getServletContext()); //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}// w w w .j a v a 2s .com //session.setAttribute("Modify", this.modif.modifcontrat(id)); int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println(appPath); try { File downloadFile = new File(appPath + "\\resources\\reports\\facture.pdf"); FileInputStream fis = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(appPath + "\\resources\\reports\\facture.pdf"); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = fis.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } fis.close(); outStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return "redirect:/regub/commercial/contrats/derniercontrats"; }
From source file:controller.CommercialController.java
@RequestMapping(value = "regub/commercial/contrats/deviscom", method = RequestMethod.POST) //public @ResponseBody String devisAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException { Client cli = (Client) request.getAttribute("clicom"); int idvideo = Integer.parseInt(request.getParameter("idvideo")); Devis devis = new Devis(); devis.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0), request.getServletContext()); //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}/* w w w .ja v a 2 s .c o m*/ //session.setAttribute("Modify", this.modif.modifcontrat(id)); int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println(appPath); try { File downloadFile = new File(appPath + "\\resources\\reports\\devis.pdf"); FileInputStream fis = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(appPath + "\\resources\\reports\\devis.pdf"); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = fis.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } fis.close(); outStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return "redirect:/regub/commercial/contrats/" + cli.getIdClient(); }
From source file:controller.CommercialController.java
@RequestMapping(value = "regub/commercial/deviscom", method = RequestMethod.POST) //public @ResponseBody String devis2Action(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException { Client cli = (Client) request.getAttribute("clicom"); int idvideo = Integer.parseInt(request.getParameter("idvideo")); Devis devis = new Devis(); devis.Consulter(VidBDD.VideoPrec(idvideo).get(0).getClient(), VidBDD.VideoPrec(idvideo).get(0), request.getServletContext()); //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}/* w w w . j a v a 2s.c o m*/ //session.setAttribute("Modify", this.modif.modifcontrat(id)); int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println(appPath); try { File downloadFile = new File(appPath + "\\resources\\reports\\devis.pdf"); FileInputStream fis = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(appPath + "\\resources\\reports\\devis.pdf"); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = fis.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } fis.close(); outStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return "redirect:/regub/commercial/derniercontras"; }
From source file:org.openmrs.web.Listener.java
/** * Convenience method to empty out the dwr-modules.xml file to fix any errors that might have * occurred in it when loading or unloading modules. * * @param servletContext//from w w w .j a v a2 s.c om */ private void clearDWRFile(ServletContext servletContext) { Log log = LogFactory.getLog(Listener.class); String realPath = servletContext.getRealPath(""); String absPath = realPath + "/WEB-INF/dwr-modules.xml"; File dwrFile = new File(absPath.replace("/", File.separator)); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a DTD) we return an InputSource // with no data at the end, causing the parser to ignore the DTD. return new InputSource(new StringReader("")); } }); Document doc = db.parse(dwrFile); Element elem = doc.getDocumentElement(); elem.setTextContent(""); OpenmrsUtil.saveDocument(doc, dwrFile); } catch (Exception e) { // got here because the dwr-modules.xml file is empty for some reason. This might // happen because the servlet container (i.e. tomcat) crashes when first loading this file log.debug("Error clearing dwr-modules.xml", e); dwrFile.delete(); FileWriter writer = null; try { writer = new FileWriter(dwrFile); writer.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE dwr PUBLIC \"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN\" \"http://directwebremoting.org/schema/dwr20.dtd\">\n<dwr></dwr>"); } catch (IOException io) { log.error("Unable to clear out the " + dwrFile.getAbsolutePath() + " file. Please redeploy the openmrs war file", io); } finally { if (writer != null) { try { writer.close(); } catch (IOException io) { log.warn("Couldn't close Writer: " + io); } } } } }