Java Code Examples for javax.servlet.ServletContext#getResource()

The following examples show how to use javax.servlet.ServletContext#getResource() . These examples are extracted from open source projects. 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 Project: oxygen   File: FatJarScanner.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: javamelody   File: MavenArtifact.java    License: Apache License 2.0 6 votes vote down vote up
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 3
@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 4
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 5
Source Project: Tomcat8-Source-Read   File: SSIServlet.java    License: MIT License 5 votes vote down vote up
/**
 * 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 6
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 7
Source Project: birt   File: ChartWebHelper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 8
@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 9
Source Project: oxygen   File: FatJarScanner.java    License: Apache License 2.0 5 votes vote down vote up
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 10
Source Project: Tomcat7.0.67   File: SSIServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
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 12
@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 13
Source Project: scipio-erp   File: ConfigXMLReader.java    License: Apache License 2.0 5 votes vote down vote up
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 14
Source Project: scipio-erp   File: ScreenFactory.java    License: Apache License 2.0 5 votes vote down vote up
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 15
@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 16
Source Project: scipio-erp   File: GridFactory.java    License: Apache License 2.0 5 votes vote down vote up
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 17
Source Project: scipio-erp   File: MenuFactory.java    License: Apache License 2.0 5 votes vote down vote up
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 18
Source Project: javamelody   File: Parameters.java    License: Apache License 2.0 5 votes vote down vote up
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 19
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 20
@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();
    }
}