Java Code Examples for javax.servlet.ServletContext#getResource()
The following examples show how to use
javax.servlet.ServletContext#getResource() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PortletToolRenderService.java From sakai with Educational Community License v2.0 | 6 votes |
private boolean isPortletApplication(ServletContext context, ToolConfiguration configuration) throws ToolRenderException, MalformedURLException { SakaiPortletWindow window = registry.getOrCreatePortletWindow(configuration); if (window == null) { return false; } 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; }
Example 2
Source File: FatJarScanner.java From oxygen with Apache License 2.0 | 6 votes |
private void doScanWebInf(ServletContext context, JarScannerCallback callback, Set<URL> processedURLs) { try { URL webInfURL = context.getResource(TomcatConf.WEB_INF_CLASSES); if (webInfURL != null) { // WEB-INF/classes will also be included in the URLs returned // by the web application class loader so ensure the class path // scanning below does not re-scan this location. processedURLs.add(webInfURL); URL url = context.getResource(TomcatConf.WEB_INF_CLASSES + TomcatConf.META_INF_PATH); if (url != null) { callback.scanWebInfClasses(); } } } catch (IOException e) { log.warn(SM.getString("jarScan.webinfclassesFail"), e); } }
Example 3
Source File: MavenArtifact.java From javamelody with Apache License 2.0 | 6 votes |
private static Map<String, MavenArtifact> getWebappDependenciesFromWebInfLib() throws IOException { final ServletContext servletContext = Parameters.getServletContext(); final String directory = "/WEB-INF/lib/"; final Set<String> dependencies = servletContext.getResourcePaths(directory); // If needed, catch Exception again because Tomcat 8 can throw // "IllegalStateException: The resources may not be accessed if they are not currently started" // for some ServletContext states (issue 415) if (dependencies == null || dependencies.isEmpty()) { return Collections.emptyMap(); } final Map<String, MavenArtifact> result = new TreeMap<String, MavenArtifact>(); for (final String dependency : dependencies) { if (dependency.endsWith(".jar") || dependency.endsWith(".JAR")) { final String fileName = dependency.substring(directory.length()); final URL jarFileLocation = servletContext.getResource(dependency); if (jarFileLocation != null) { result.put(fileName, parseDependency(jarFileLocation)); } else { result.put(fileName, null); } } } return result; }
Example 4
Source File: WebappPropertyToField.java From scipio-erp with Apache License 2.0 | 6 votes |
@Override public boolean exec(MethodContext methodContext) throws MiniLangException { if (methodContext.getMethodType() == MethodContext.EVENT) { String resource = resourceFse.expandString(methodContext.getEnvMap()); ServletContext servletContext = (ServletContext) methodContext.getRequest().getServletContext(); // SCIPIO: get context using servlet API 3.0 URL propsUrl = null; try { propsUrl = servletContext.getResource(resource); } catch (java.net.MalformedURLException e) { throw new MiniLangRuntimeException("Exception thrown while finding properties file " + resource + ": " + e.getMessage(), this); } if (propsUrl == null) { throw new MiniLangRuntimeException("Properties file " + resource + " not found.", this); } String property = propertyFse.expandString(methodContext.getEnvMap()); String fieldVal = UtilProperties.getPropertyValue(propsUrl, property); if (fieldVal == null) { fieldVal = defaultFse.expandString(methodContext.getEnvMap()); } fieldFma.put(methodContext.getEnvMap(), fieldVal); } return true; }
Example 5
Source File: ConfigXMLReader.java From scipio-erp with Apache License 2.0 | 5 votes |
public static URL getControllerConfigURL(ServletContext context) { try { return context.getResource(controllerXmlFileName); } catch (MalformedURLException e) { Debug.logError(e, "Error Finding XML Config File: " + controllerXmlFileName, module); return null; } }
Example 6
Source File: TestStandardContextResources.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); ServletContext context = getServletContext(); // Check resources individually URL url = context.getResource(req.getParameter("path")); if (url == null) { resp.getWriter().println("Not found"); return; } InputStream input = url.openStream(); OutputStream output = resp.getOutputStream(); try { byte[] buffer = new byte[4000]; for (int len; (len = input.read(buffer)) > 0;) { output.write(buffer, 0, len); } } finally { input.close(); output.close(); } }
Example 7
Source File: DefaultApplicationIdResolver.java From portals-pluto with Apache License 2.0 | 5 votes |
public String resolveApplicationId(ServletContext context) { try { URL webXmlUrl = context.getResource(WEB_XML); String path = webXmlUrl.toExternalForm(); path = path.substring(0, path.indexOf(WEB_XML)); int slash = path.lastIndexOf('/'); if ((slash < JNDI_PREFIX.length()) && path.startsWith(JNDI_PREFIX)) { // Tomcat resources look like "jndi:/hostname/contextPath/WEB-INF/web.xml" // where "/contextPath" is "" for the ROOT context. // So if the last slash is the one in "jndi:/", the correct // result is "" and not "/hostname" path = ""; } else { path = path.substring(slash); } int id = path.indexOf(".war"); if(id > 0) { path = path.substring(0, id); } return path; } catch (MalformedURLException e) { LOG.warn("Error retrieving web.xml from ServletContext. Unable to derive contextPath."); return null; } }
Example 8
Source File: Parameters.java From javamelody with Apache License 2.0 | 5 votes |
public static String getContextPath(ServletContext context) { // cette méthode retourne le contextPath de la webapp // en utilisant ServletContext.getContextPath si servlet api 2.5 // ou en se débrouillant sinon // (on n'a pas encore pour l'instant de request pour appeler HttpServletRequest.getContextPath) if (context.getMajorVersion() == 2 && context.getMinorVersion() >= 5 || context.getMajorVersion() > 2) { // api servlet 2.5 (Java EE 5) minimum pour appeler ServletContext.getContextPath return context.getContextPath(); } final URL webXmlUrl; try { webXmlUrl = context.getResource("/WEB-INF/web.xml"); } catch (final MalformedURLException e) { throw new IllegalStateException(e); } String contextPath = webXmlUrl.toExternalForm(); contextPath = contextPath.substring(0, contextPath.indexOf("/WEB-INF/web.xml")); final int indexOfWar = contextPath.indexOf(".war"); if (indexOfWar > 0) { contextPath = contextPath.substring(0, indexOfWar); } // tomcat peut renvoyer une url commençant pas "jndi:/localhost" // (v5.5.28, webapp dans un répertoire) if (contextPath.startsWith("jndi:/localhost")) { contextPath = contextPath.substring("jndi:/localhost".length()); } final int lastIndexOfSlash = contextPath.lastIndexOf('/'); if (lastIndexOfSlash != -1) { contextPath = contextPath.substring(lastIndexOfSlash); } return contextPath; }
Example 9
Source File: MenuFactory.java From scipio-erp with Apache License 2.0 | 5 votes |
public static ModelMenu getMenuFromWebappContext(String resourceName, String menuName, HttpServletRequest request) throws IOException, SAXException, ParserConfigurationException { String webappName = UtilHttp.getApplicationName(request); String cacheKey = webappName + "::" + resourceName; Map<String, ModelMenu> modelMenuMap = menuWebappCache.get(cacheKey); if (modelMenuMap == null) { // SCIPIO: refactored synchronized (MenuFactory.class) { modelMenuMap = menuWebappCache.get(cacheKey); if (modelMenuMap == null) { ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0 URL menuFileUrl = servletContext.getResource(resourceName); if (menuFileUrl == null) { throw new IllegalArgumentException("Could not resolve menu file location [" + resourceName + "] in the webapp [" + webappName + "]"); } Document menuFileDoc = UtilXml.readXmlDocument(menuFileUrl, true, true); if (menuFileDoc == null) { throw new IllegalArgumentException("Could not read menu file at location [" + resourceName + "] in the webapp [" + webappName + "]"); } // SCIPIO: New: Save original location as user data in Document WidgetDocumentInfo.retrieveAlways(menuFileDoc).setResourceLocation(resourceName); modelMenuMap = readMenuDocument(menuFileDoc, cacheKey); menuWebappCache.put(cacheKey, modelMenuMap); } } } ModelMenu modelMenu = modelMenuMap.get(menuName); if (modelMenu == null) { throw new IllegalArgumentException("Could not find menu with name [" + menuName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); } return modelMenu; }
Example 10
Source File: GridFactory.java From scipio-erp with Apache License 2.0 | 5 votes |
public static ModelGrid getGridFromWebappContext(String resourceName, String gridName, HttpServletRequest request) throws IOException, SAXException, ParserConfigurationException { String webappName = UtilHttp.getApplicationName(request); String cacheKey = webappName + "::" + resourceName; // + "::" + gridName; Map<String, ModelGrid> modelGridMap = gridWebappCache.get(cacheKey); if (modelGridMap == null) { // SCIPIO: refactored synchronized (GridFactory.class) { modelGridMap = gridWebappCache.get(cacheKey); if (modelGridMap == null) { ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0 Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); URL gridFileUrl = servletContext.getResource(resourceName); if (gridFileUrl == null) { throw new IllegalArgumentException("Could not resolve grid file location [" + resourceName + "] in the webapp [" + webappName + "]"); } Document gridFileDoc = UtilXml.readXmlDocument(gridFileUrl, true, true); if (gridFileDoc == null) { throw new IllegalArgumentException("Could not read grid file at resource [" + resourceName + "] in the webapp [" + webappName + "]"); } // SCIPIO: New: Save original location as user data in Document WidgetDocumentInfo.retrieveAlways(gridFileDoc).setResourceLocation(resourceName); modelGridMap = readGridDocument(gridFileDoc, delegator.getModelReader(), dispatcher.getDispatchContext(), resourceName); gridWebappCache.put(cacheKey, modelGridMap); } } } ModelGrid modelGrid = modelGridMap.get(gridName); if (modelGrid == null) { throw new IllegalArgumentException("Could not find grid with name [" + gridName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); } return modelGrid; }
Example 11
Source File: VoiceXmlSnippet.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void init() throws ServletException { super.init(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // Configure the factory to ignore comments factory.setIgnoringComments(true); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ServletException(e.getMessage(), e); } TransformerFactory transFact = TransformerFactory.newInstance( ); try { final ServletContext context = getServletContext(); final URL xsltURL = context.getResource("/VoiceXmlPromptTemplate.xsl"); final String xsltSystemID = xsltURL.toExternalForm(); promptTemplate = transFact.newTemplates( new StreamSource(xsltSystemID)); } catch (TransformerConfigurationException tce) { throw new UnavailableException("Unable to compile stylesheet"); } catch (MalformedURLException mue) { throw new UnavailableException("Unable to locate XSLT file"); } }
Example 12
Source File: ScreenFactory.java From scipio-erp with Apache License 2.0 | 5 votes |
public static ModelScreen getScreenFromWebappContext(String resourceName, String screenName, HttpServletRequest request) throws IOException, SAXException, ParserConfigurationException { String webappName = UtilHttp.getApplicationName(request); String cacheKey = webappName + "::" + resourceName; ModelScreens modelScreenMap = screenWebappCache.get(cacheKey); // SCIPIO: new: ModelScreens if (modelScreenMap == null) { // SCIPIO: refactored synchronized (ScreenFactory.class) { modelScreenMap = screenWebappCache.get(cacheKey); if (modelScreenMap == null) { ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0 URL screenFileUrl = servletContext.getResource(resourceName); if (screenFileUrl == null) { throw new IllegalArgumentException("Could not resolve screen file location [" + resourceName + "]"); } Document screenFileDoc = UtilXml.readXmlDocument(screenFileUrl, true, true); if (screenFileDoc == null) { throw new IllegalArgumentException("Could not read screen file at location [" + resourceName + "] in the webapp [" + webappName + "]"); } // SCIPIO: New: Save original location as user data in Document WidgetDocumentInfo.retrieveAlways(screenFileDoc).setResourceLocation(resourceName); modelScreenMap = readScreenDocument(screenFileDoc, resourceName); screenWebappCache.put(cacheKey, modelScreenMap); } } } ModelScreen modelScreen = modelScreenMap.get(screenName); if (modelScreen == null) { throw new IllegalArgumentException("Could not find screen with name [" + screenName + "] in webapp resource [" + resourceName + "] in the webapp [" + webappName + "]"); } return modelScreen; }
Example 13
Source File: SSIServlet.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * Process our request and locate right SSI command. * * @param req * a value of type 'HttpServletRequest' * @param res * a value of type 'HttpServletResponse' * @throws IOException an IO error occurred */ protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } processSSI(req, res, resource); }
Example 14
Source File: TestStandardContextResources.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); ServletContext context = getServletContext(); // Check resources individually URL url = context.getResource(req.getParameter("path")); if (url == null) { resp.getWriter().println("Not found"); return; } InputStream input = url.openStream(); OutputStream output = resp.getOutputStream(); try { byte[] buffer = new byte[4000]; for (int len; (len = input.read(buffer)) > 0;) { output.write(buffer, 0, len); } } finally { input.close(); output.close(); } }
Example 15
Source File: SSIServletExternalResolver.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
protected URLConnection getURLConnection(String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); URL url = context.getResource(path); if (url == null) { throw new IOException("Context did not contain resource: " + path); } URLConnection urlConnection = url.openConnection(); return urlConnection; }
Example 16
Source File: SSIServlet.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
/** * Process our request and locate right SSI command. * * @param req * a value of type 'HttpServletRequest' * @param res * a value of type 'HttpServletResponse' */ protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); processSSI(req, res, resource); }
Example 17
Source File: FatJarScanner.java From oxygen with Apache License 2.0 | 5 votes |
private void doScanWebInfLib(JarScanType scanType, ServletContext context, JarScannerCallback callback, Set<URL> processedURLs) { Set<String> dirList = context.getResourcePaths(TomcatConf.WEB_INF_LIB); if (dirList == null) { return; } for (String path : dirList) { if (path.endsWith(TomcatConf.JAR_EXT) && getJarScanFilter() .check(scanType, path.substring(path.lastIndexOf(Strings.SLASH) + 1))) { // Need to scan this JAR if (log.isDebugEnabled()) { log.debug(SM.getString("jarScan.webinflibJarScan", path)); } URL url = null; try { url = context.getResource(path); processedURLs.add(url); process(scanType, callback, url, path, true, null); } catch (IOException e) { log.warn(SM.getString("jarScan.webinflibFail", url), e); } } else { if (log.isTraceEnabled()) { log.trace(SM.getString("jarScan.webinflibJarNoScan", path)); } } } }
Example 18
Source File: TestStandardContextAliases.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); ServletContext context = getServletContext(); // Check resources individually URL url = context.getResource("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar"); if (url != null) { resp.getWriter().write("00-PASS\n"); } url = context.getResource("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar"); if (url != null) { resp.getWriter().write("01-PASS\n"); } // Check a directory listing Set<String> libs = context.getResourcePaths("/WEB-INF/lib"); if (libs == null) { return; } if (!libs.contains("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar")) { return; } if (!libs.contains("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar")) { return; } resp.getWriter().write("02-PASS\n"); }
Example 19
Source File: ChartWebHelper.java From birt with Eclipse Public License 1.0 | 5 votes |
/** * Returns the real path of the file in the web folder * * @param context * servlet context * @param fileName * the relative path of the file */ public static String getRealPath( ServletContext context, String fileName ) { String path = context.getRealPath( "/" ); //$NON-NLS-1$ if ( path == null ) { // resources are in a .war (JBoss, WebLogic) java.net.URL url; try { url = context.getResource( "/" ); //$NON-NLS-1$ path = url.getPath( ); } catch ( MalformedURLException e ) { e.printStackTrace( ); } } // In WebSphere, path may not end with separator if ( path != null && path.length( ) > 0 ) { if ( path.charAt( path.length( ) - 1 ) != '\\' || path.charAt( path.length( ) - 1 ) != '/' ) { path += File.separator; } } return path + fileName; }
Example 20
Source File: SSIServletExternalResolver.java From Tomcat8-Source-Read with MIT License | 5 votes |
protected URLConnection getURLConnection(String originalPath, boolean virtual) throws IOException { ServletContextAndPath csAndP = getServletContextAndPath(originalPath, virtual); ServletContext context = csAndP.getServletContext(); String path = csAndP.getPath(); URL url = context.getResource(path); if (url == null) { throw new IOException("Context did not contain resource: " + path); } URLConnection urlConnection = url.openConnection(); return urlConnection; }