List of usage examples for org.springframework.core.io ResourceLoader ResourceLoader
ResourceLoader
From source file:org.jasig.cas.WiringTests.java
@Before public void setUp() { applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocations("file:src/main/webapp/WEB-INF/cas-servlet.xml", "file:src/main/webapp/WEB-INF/deployerConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"); applicationContext.setServletContext(new MockServletContext(new ResourceLoader() { @Override/*from w w w . j a va 2 s . co m*/ public Resource getResource(final String location) { return new FileSystemResource("src/main/webapp" + location); } @Override public ClassLoader getClassLoader() { return getClassLoader(); } })); applicationContext.refresh(); }
From source file:org.owasp.webgoat.i18n.LabelProvider.java
/** * <p>updatePluginResources.</p> * * @param propertyFile a {@link java.nio.file.Path} object. *///from w w w .j a v a 2 s.c o m public static void updatePluginResources(final Path propertyFile) { pluginLabels.setBasename("WebGoatLabels"); pluginLabels.setFallbackToSystemLocale(false); pluginLabels.setUseCodeAsDefaultMessage(true); pluginLabels.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { try { return new UrlResource(propertyFile.toUri()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } }); pluginLabels.clearCache(); }
From source file:org.hdiv.web.servlet.view.freemarker.FreeMarkerConfigurerTests.java
public void testFreemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws IOException, TemplateException { FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean(); fcfb.setTemplateLoaderPath("file:/mydir"); Properties settings = new Properties(); settings.setProperty("localized_lookup", "false"); fcfb.setFreemarkerSettings(settings); fcfb.setResourceLoader(new ResourceLoader() { public Resource getResource(String location) { if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) { throw new IllegalArgumentException(location); }// www. j ava 2 s. c om return new ByteArrayResource("test".getBytes(), "test"); } public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); fcfb.afterPropertiesSet(); assertTrue(fcfb.getObject() instanceof Configuration); Configuration fc = (Configuration) fcfb.getObject(); Template ft = fc.getTemplate("test"); assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap())); }
From source file:org.codehaus.groovy.grails.context.annotation.ClosureClassIgnoringComponentScanBeanDefinitionParser.java
@Override protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) { final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element); final ResourceLoader originalResourceLoader = parserContext.getReaderContext().getResourceLoader(); if (LOG.isDebugEnabled()) { LOG.debug("Scanning only this classloader:" + originalResourceLoader.getClassLoader()); }//from w ww .j a v a 2 s. c o m ResourceLoader parentOnlyResourceLoader; try { parentOnlyResourceLoader = new ResourceLoader() { ClassLoader parentOnlyGetResourcesClassLoader = new ParentOnlyGetResourcesClassLoader( originalResourceLoader.getClassLoader()); public Resource getResource(String location) { return originalResourceLoader.getResource(location); } public ClassLoader getClassLoader() { return parentOnlyGetResourcesClassLoader; } }; } catch (Throwable t) { // restrictive classloading environment, use the original parentOnlyResourceLoader = originalResourceLoader; } final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver( parentOnlyResourceLoader) { @Override protected Resource[] findAllClassPathResources(String location) throws IOException { Set<Resource> result = new LinkedHashSet<Resource>(16); @SuppressWarnings("unused") URL classesDir = null; final boolean warDeployed = Metadata.getCurrent().isWarDeployed(); if (!warDeployed) { BuildSettings buildSettings = BuildSettingsHolder.getSettings(); if (buildSettings != null && buildSettings.getClassesDir() != null) { classesDir = buildSettings.getClassesDir().toURI().toURL(); } } // only scan classes from project classes directory String path = location; if (path.startsWith("/")) { path = path.substring(1); } Enumeration<URL> resourceUrls = getClassLoader().getResources(path); while (resourceUrls.hasMoreElements()) { URL url = resourceUrls.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug( "Scanning URL " + url.toExternalForm() + " while searching for '" + location + "'"); } /* if (!warDeployed && classesDir!= null && url.equals(classesDir)) { result.add(convertClassLoaderURL(url)); } else if (warDeployed) { result.add(convertClassLoaderURL(url)); } */ result.add(convertClassLoaderURL(url)); } return result.toArray(new Resource[result.size()]); } }; resourceResolver.setPathMatcher(new AntPathMatcher() { @Override public boolean match(String pattern, String path) { if (path.endsWith(".class")) { String filename = FilenameUtils.getBaseName(path); if (filename.indexOf("$") > -1) return false; } return super.match(pattern, path); } }); scanner.setResourceLoader(resourceResolver); return scanner; }
From source file:org.grails.spring.context.annotation.ClosureClassIgnoringComponentScanBeanDefinitionParser.java
@Override protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) { final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element); final ResourceLoader originalResourceLoader = parserContext.getReaderContext().getResourceLoader(); if (LOG.isDebugEnabled()) { LOG.debug("Scanning only this classloader:" + originalResourceLoader.getClassLoader()); }/* ww w .j a v a 2 s. c o m*/ ResourceLoader parentOnlyResourceLoader; try { parentOnlyResourceLoader = new ResourceLoader() { ClassLoader parentOnlyGetResourcesClassLoader = new ParentOnlyGetResourcesClassLoader( originalResourceLoader.getClassLoader()); public Resource getResource(String location) { return originalResourceLoader.getResource(location); } public ClassLoader getClassLoader() { return parentOnlyGetResourcesClassLoader; } }; } catch (Throwable t) { // restrictive classloading environment, use the original parentOnlyResourceLoader = originalResourceLoader; } final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver( parentOnlyResourceLoader) { @Override protected Resource[] findAllClassPathResources(String location) throws IOException { Set<Resource> result = new LinkedHashSet<Resource>(16); if (BuildSettings.CLASSES_DIR != null) { @SuppressWarnings("unused") URL classesDir = BuildSettings.CLASSES_DIR.toURI().toURL(); // only scan classes from project classes directory String path = location; if (path.startsWith("/")) { path = path.substring(1); } Enumeration<URL> resourceUrls = getClassLoader().getResources(path); while (resourceUrls.hasMoreElements()) { URL url = resourceUrls.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug("Scanning URL " + url.toExternalForm() + " while searching for '" + location + "'"); } /* if (!warDeployed && classesDir!= null && url.equals(classesDir)) { result.add(convertClassLoaderURL(url)); } else if (warDeployed) { result.add(convertClassLoaderURL(url)); } */ result.add(convertClassLoaderURL(url)); } } return result.toArray(new Resource[result.size()]); } }; resourceResolver.setPathMatcher(new AntPathMatcher() { @Override public boolean match(String pattern, String path) { if (path.endsWith(".class")) { String filename = GrailsStringUtils.getFileBasename(path); if (filename.contains("$")) return false; } return super.match(pattern, path); } }); scanner.setResourceLoader(resourceResolver); return scanner; }
From source file:org.jahia.services.render.webflow.WebflowDispatcherScript.java
/** * Execute the script and return the result as a string * * @param resource resource to display/*from w w w . j av a2s .c om*/ * @param context * @return the rendered resource * @throws org.jahia.services.render.RenderException * */ public String execute(Resource resource, RenderContext context) throws RenderException { final View view = getView(); if (view == null) { throw new RenderException("View not found for : " + resource); } else { if (logger.isDebugEnabled()) { logger.debug("View '" + view + "' resolved for resource: " + resource); } } String identifier; try { identifier = resource.getNode().getIdentifier(); } catch (RepositoryException e) { throw new RenderException(e); } String identifierNoDashes = StringUtils.replace(identifier, "-", "_"); if (!view.getKey().equals("default")) { identifierNoDashes += "__" + view.getKey(); } HttpServletRequest request; HttpServletResponse response = context.getResponse(); @SuppressWarnings("unchecked") final Map<String, List<String>> parameters = (Map<String, List<String>>) context.getRequest() .getAttribute("actionParameters"); if (xssFilteringEnabled && parameters != null) { final Map<String, String[]> m = Maps.transformEntries(parameters, new Maps.EntryTransformer<String, List<String>, String[]>() { @Override public String[] transformEntry(@Nullable String key, @Nullable List<String> value) { return value != null ? value.toArray(new String[value.size()]) : null; } }); request = new WebflowHttpServletRequestWrapper(context.getRequest(), m, identifierNoDashes); } else { request = new WebflowHttpServletRequestWrapper(context.getRequest(), new HashMap<>(context.getRequest().getParameterMap()), identifierNoDashes); } String s = (String) request.getSession().getAttribute("webflowResponse" + identifierNoDashes); if (s != null) { request.getSession().removeAttribute("webflowResponse" + identifierNoDashes); return s; } // skip aggregation for potentials fragments under the webflow boolean aggregationSkippedForWebflow = false; if (!AggregateFilter.skipAggregation(context.getRequest())) { aggregationSkippedForWebflow = true; context.getRequest().setAttribute(AggregateFilter.SKIP_AGGREGATION, true); } flowPath = MODULE_PREFIX_PATTERN.matcher(view.getPath()).replaceFirst(""); RequestDispatcher rd = request.getRequestDispatcher("/flow/" + flowPath); Object oldModule = request.getAttribute("currentModule"); request.setAttribute("currentModule", view.getModule()); if (logger.isDebugEnabled()) { dumpRequestAttributes(request); } StringResponseWrapper responseWrapper = new StringResponseWrapper(response); try { FlowDefinitionRegistry reg = ((FlowDefinitionRegistry) view.getModule().getContext() .getBean("jahiaFlowRegistry")); final GenericApplicationContext applicationContext = (GenericApplicationContext) reg .getFlowDefinition(flowPath).getApplicationContext(); applicationContext.setClassLoader(view.getModule().getClassLoader()); applicationContext.setResourceLoader(new ResourceLoader() { @Override public org.springframework.core.io.Resource getResource(String location) { return applicationContext.getParent().getResource("/" + flowPath + "/" + location); } @Override public ClassLoader getClassLoader() { return view.getModule().getClassLoader(); } }); rd.include(request, responseWrapper); String redirect = responseWrapper.getRedirect(); if (redirect != null && context.getRedirect() == null) { // if we have an absolute redirect, set it and move on if (redirect.startsWith("http:/") || redirect.startsWith("https://")) { context.setRedirect(responseWrapper.getRedirect()); } else { while (redirect != null) { final String qs = StringUtils.substringAfter(responseWrapper.getRedirect(), "?"); final Map<String, String[]> params = new HashMap<String, String[]>(); if (!StringUtils.isEmpty(qs)) { params.put("webflowexecution" + identifierNoDashes, new String[] { StringUtils .substringAfterLast(qs, "webflowexecution" + identifierNoDashes + "=") }); } HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) { @Override public String getMethod() { return "GET"; } @SuppressWarnings("rawtypes") @Override public Map getParameterMap() { return params; } @Override public String getParameter(String name) { return params.containsKey(name) ? params.get(name)[0] : null; } @Override public Enumeration getParameterNames() { return new Vector(params.keySet()).elements(); } @Override public String[] getParameterValues(String name) { return params.get(name); } @Override public Object getAttribute(String name) { if (WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE.equals(name)) { return qs; } return super.getAttribute(name); } @Override public String getQueryString() { return qs; } }; rd = requestWrapper.getRequestDispatcher("/flow/" + flowPath + "?" + qs); responseWrapper = new StringResponseWrapper(response); rd.include(requestWrapper, responseWrapper); String oldRedirect = redirect; redirect = responseWrapper.getRedirect(); if (redirect != null) { // if we have an absolute redirect, exit the loop if (redirect.startsWith("http://") || redirect.startsWith("https://")) { context.setRedirect(redirect); break; } } else if (request.getMethod().equals("POST")) { // set the redirect to the last non-null one request.getSession().setAttribute("webflowResponse" + identifierNoDashes, responseWrapper.getString()); context.setRedirect(oldRedirect); } } } } } catch (ServletException e) { throw new RenderException(e.getRootCause() != null ? e.getRootCause() : e); } catch (IOException e) { throw new RenderException(e); } finally { request.setAttribute("currentModule", oldModule); } try { if (aggregationSkippedForWebflow) { request.removeAttribute(AggregateFilter.SKIP_AGGREGATION); } return responseWrapper.getString(); } catch (IOException e) { throw new RenderException(e); } }