List of usage examples for org.springframework.core.io ResourceLoader getResource
Resource getResource(String location);
From source file:org.dataconservancy.cos.osf.client.model.AbstractMockServerTest.java
/** * Starts mock HTTP servers on the port specified by the OSF client configuration and the Waterbutler client * configuration// ww w. ja va 2 s .c o m */ @Before public void startMockServer() throws Exception { final ObjectMapper mapper = new ObjectMapper(); final JacksonConfigurer<OsfClientConfiguration> osfConfigurer = new DefaultOsfJacksonConfigurer<>(); final JacksonConfigurer<WbClientConfiguration> wbConfigurer = new DefaultWbJacksonConfigurer<>(); final ResourceLoader loader = new DefaultResourceLoader(); final Resource configuration = loader.getResource(getOsfServiceConfigurationResource()); assertTrue("Unable to resolve configuration resource: '" + getOsfServiceConfigurationResource() + "'", configuration.exists()); mockServer = ClientAndServer.startClientAndServer( osfConfigurer.configure(mapper.readTree(IOUtils.toString(configuration.getURL(), "UTF-8")), mapper, OsfClientConfiguration.class).getPort()); wbMockServer = ClientAndServer.startClientAndServer( wbConfigurer.configure(mapper.readTree(IOUtils.toString(configuration.getURL(), "UTF-8")), mapper, WbClientConfiguration.class).getPort()); /* Sets up the expectations of the mock http server. * * Invokes the NodeResponseCallback when the HTTP header "X-Response-Resource" is present. * The header value is a classpath resource to the JSON document to be serialized for the * response. */ mockServer.when(request().withHeader(X_RESPONSE_RESOURCE)) .callback(callback().withCallbackClass(NodeResponseCallback.class.getName())); wbMockServer.when(request().withHeader(X_RESPONSE_RESOURCE)) .callback(callback().withCallbackClass(NodeResponseCallback.class.getName())); }
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()); }//from ww w . j av 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.impalaframework.config.SimplePropertiesLoader.java
protected Properties getProperties() { String bootstrapLocationsResource = getResourceName(); ResourceLoader resourceLoader = getResourceLoader(); Resource bootStrapResource = null; if (bootstrapLocationsResource == null) { bootStrapResource = resourceLoader.getResource(defaultBootstrapResource); } else {/* w w w . j a v a 2s .c o m*/ // figure out which resource loader to use bootStrapResource = resourceLoader.getResource(bootstrapLocationsResource); } Properties properties = null; if (bootStrapResource == null || !bootStrapResource.exists()) { logger.info("Unable to load locations resource from " + bootstrapLocationsResource + "."); properties = new Properties(); } else { properties = PropertyUtils.loadProperties(bootStrapResource); } return properties; }
From source file:org.kuali.rice.core.api.impex.xml.LocationXmlDoc.java
static Resource getResource(String location) { if (isExistingFile(location)) { return new FileSystemResource(location); } else {/*from w ww. j ava 2 s. c o m*/ ResourceLoader loader = new DefaultResourceLoader(); return loader.getResource(location); } }
From source file:org.kuali.rice.krad.datadictionary.validator.ValidationTrace.java
/** * Loads the xmlFiles of the data objects being validated into a list of Documents that can be parsed to find the * xmls related to the error./* w w w . j a va 2s .co m*/ * * @param beanFiles - The list of file paths used in the creation of the beans * @param loader - The source that was used to load the beans */ private void loadFiles(String[] beanFiles, ResourceLoader loader) { LOG.debug("Started Loading Parser Files"); for (int i = 0; i < beanFiles.length; i++) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document; String file = beanFiles[i];//.substring(0,10)+"/"+beanFiles[i].substring(10); LOG.debug("Loading file: " + file); document = builder.parse(loader.getResource(file).getInputStream()); beanMap.put(file, document); } catch (Exception e) { LOG.error("Not Found: " + beanFiles[i]); } } LOG.debug("Finished Loading Parser Files"); }
From source file:org.kuali.rice.test.RiceTestCase.java
/** * configures logging using custom properties file if specified, or the default one. * Log4j also uses any file called log4.properties in the classpath * * <p>To configure a custom logging file, set a JVM system property on using -D. For example * -Dalt.log4j.config.location=file:/home/me/kuali/test/dev/log4j.properties * </p>/*from w ww .ja va2 s . co m*/ * * <p>The above option can also be set in the run configuration for the unit test in the IDE. * To avoid log4j using files called log4j.properties that are defined in the classpath, add the following system property: * -Dlog4j.defaultInitOverride=true * </p> * @throws IOException */ protected void configureLogging() throws IOException { ResourceLoader resourceLoader = new FileSystemResourceLoader(); String altLog4jConfigLocation = System.getProperty(ALT_LOG4J_CONFIG_LOCATION_PROP); Resource log4jConfigResource = null; if (!StringUtils.isEmpty(altLog4jConfigLocation)) { log4jConfigResource = resourceLoader.getResource(altLog4jConfigLocation); } if (log4jConfigResource == null || !log4jConfigResource.exists()) { System.out.println("Alternate Log4j config resource does not exist! " + altLog4jConfigLocation); System.out.println("Using default log4j configuration: " + DEFAULT_LOG4J_CONFIG); log4jConfigResource = resourceLoader.getResource(DEFAULT_LOG4J_CONFIG); } else { System.out.println("Using alternate log4j configuration at: " + altLog4jConfigLocation); } Properties p = new Properties(); p.load(log4jConfigResource.getInputStream()); PropertyConfigurator.configure(p); }
From source file:org.springframework.beans.factory.support.AbstractBeanDefinitionReader.java
/** * Load bean definitions from the specified resource location. * <p>The location can also be a location pattern, provided that the * ResourceLoader of this bean definition reader is a ResourcePatternResolver. * @param location the resource location, to be loaded with the ResourceLoader * (or ResourcePatternResolver) of this bean definition reader * @param actualResources a Set to be filled with the actual Resource objects * that have been resolved during the loading process. May be {@code null} * to indicate that the caller is not interested in those Resource objects. * @return the number of bean definitions found * @throws BeanDefinitionStoreException in case of loading or parsing errors * @see #getResourceLoader()//from ww w . ja va 2s.c om * @see #loadBeanDefinitions(org.springframework.core.io.Resource) * @see #loadBeanDefinitions(org.springframework.core.io.Resource[]) */ public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException { ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader == null) { throw new BeanDefinitionStoreException( "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available"); } if (resourceLoader instanceof ResourcePatternResolver) { // Resource pattern matching available. try { Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); int loadCount = loadBeanDefinitions(resources); if (actualResources != null) { for (Resource resource : resources) { actualResources.add(resource); } } if (logger.isDebugEnabled()) { logger.debug( "Loaded " + loadCount + " bean definitions from location pattern [" + location + "]"); } return loadCount; } catch (IOException ex) { throw new BeanDefinitionStoreException( "Could not resolve bean definition resource pattern [" + location + "]", ex); } } else { // Can only load single resources by absolute URL. Resource resource = resourceLoader.getResource(location); int loadCount = loadBeanDefinitions(resource); if (actualResources != null) { actualResources.add(resource); } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]"); } return loadCount; } }
From source file:org.springframework.boot.autoconfigure.condition.OnResourceCondition.java
@Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String checking = ConditionLogUtils.getPrefix(logger, metadata); MultiValueMap<String, Object> attributes = metadata .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); ResourceLoader loader = context.getResourceLoader() == null ? this.defaultResourceLoader : context.getResourceLoader(); if (attributes != null) { List<String> locations = new ArrayList<String>(); collectValues(locations, attributes.get("resources")); Assert.isTrue(locations.size() > 0, "@ConditionalOnResource annotations must specify at least one resource location"); for (String location : locations) { if (logger.isDebugEnabled()) { logger.debug(checking + "Checking for resource: " + location); }// ww w. j ava 2s . c o m if (!loader.getResource(location).exists()) { if (logger.isDebugEnabled()) { logger.debug(checking + "Resource not found: " + location + " (search terminated with matches=false)"); } return false; } } } if (logger.isDebugEnabled()) { logger.debug(checking + "Match result is: true"); } return true; }
From source file:org.springframework.boot.SpringApplication.java
private Banner selectBanner(Environment environment) { String location = environment.getProperty("banner.location", "banner.txt"); ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader(getClassLoader()); Resource resource = resourceLoader.getResource(location); if (resource.exists()) { return new ResourceBanner(resource); }/*from w w w. j a v a 2s . c o m*/ if (this.banner != null) { return this.banner; } return DEFAULT_BANNER; }
From source file:org.springframework.data.jdbc.config.oracle.PoolingDataSourceBeanDefinitionParser.java
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { ResourceLoader rl = parserContext.getReaderContext().getResourceLoader(); //attributes/*from w w w. ja v a2s . c o m*/ String propertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE); String connectionPropertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE); String connectionPropertyPrefix = element.getAttribute(CONNECTION_PROPERTIES_PREFIX_ATTRIBUTE); String cachingPropertyPrefix = element.getAttribute(CONNECTON_CACHE_PROPERTIS_PREFIX_ATTRIBUTE); String url = element.getAttribute(URL_ATTRIBUTE); String username = element.getAttribute(USERNAME_ATTRIBUTE); String password = element.getAttribute(PASSWORD_ATTRIBUTE); String onsConfiguration = element.getAttribute(ONS_CONFIGURATION_ATTRIBUTE); String fastConnectionFailoverEnabled = element.getAttribute(FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE); String connectionCachingEnabled = element.getAttribute(CONNECTION_CACHING_ENABLED_ATTRIBUTE); boolean propertyFileProvided = false; Map<String, Object> providedProperties = new HashMap<String, Object>(); // defaults if (!StringUtils.hasText(propertyFileLocation) && !StringUtils.hasText(connectionPropertyFileLocation)) { propertyFileLocation = DEFAULT_PROPERTY_FILE_LOCATION; } if (!StringUtils.hasText(connectionPropertyPrefix)) { connectionPropertyPrefix = DEFAULT_PROPERTY_PREFIX; } // look for property files if (StringUtils.hasText(propertyFileLocation)) { logger.debug("Using properties location: " + propertyFileLocation); String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(propertyFileLocation); Resource r = rl.getResource(resolvedLocation); logger.debug("Loading properties from resource: " + r); PropertiesFactoryBean factoryBean = new PropertiesFactoryBean(); factoryBean.setLocation(r); try { factoryBean.afterPropertiesSet(); Properties resource = factoryBean.getObject(); for (Map.Entry<Object, Object> entry : resource.entrySet()) { providedProperties.put((String) entry.getKey(), entry.getValue()); } propertyFileProvided = true; } catch (FileNotFoundException e) { propertyFileProvided = false; if (propertyFileLocation.equals(DEFAULT_PROPERTY_FILE_LOCATION)) { logger.debug("Unable to find " + propertyFileLocation); } else { parserContext.getReaderContext() .error("pooling-datasource defined with attribute '" + PROPERTIES_LOCATION_ATTRIBUTE + "' but the property file was not found at location \"" + propertyFileLocation + "\"", element); } } catch (IOException e) { logger.warn("Error loading " + propertyFileLocation + ": " + e.getMessage()); } } else { propertyFileProvided = false; } if (logger.isDebugEnabled()) { logger.debug("Using provided properties: " + providedProperties); } if (connectionPropertyPrefix == null) { connectionPropertyPrefix = ""; } if (connectionPropertyPrefix.length() > 0 && !connectionPropertyPrefix.endsWith(".")) { connectionPropertyPrefix = connectionPropertyPrefix + "."; } logger.debug("Using connection properties prefix: " + connectionPropertyPrefix); if (cachingPropertyPrefix == null) { cachingPropertyPrefix = ""; } if (cachingPropertyPrefix.length() > 0 && !cachingPropertyPrefix.endsWith(".")) { cachingPropertyPrefix = cachingPropertyPrefix + "."; } logger.debug("Using caching properties prefix: " + cachingPropertyPrefix); if (!(StringUtils.hasText(connectionCachingEnabled) || providedProperties .containsKey(attributeToPropertyMap.get(CONNECTION_CACHING_ENABLED_ATTRIBUTE)))) { connectionCachingEnabled = DEFAULT_CONNECTION_CACHING_ENABLED; } setRequiredAttribute(builder, parserContext, element, providedProperties, connectionPropertyPrefix, propertyFileProvided, url, URL_ATTRIBUTE, "URL"); setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, username, USERNAME_ATTRIBUTE); setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, password, PASSWORD_ATTRIBUTE); setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, connectionCachingEnabled, CONNECTION_CACHING_ENABLED_ATTRIBUTE); setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, fastConnectionFailoverEnabled, FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE); setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, onsConfiguration, ONS_CONFIGURATION_ATTRIBUTE); Properties providedConnectionProperties = new Properties(); Properties providedCachingProperties = new Properties(); for (String key : providedProperties.keySet()) { if (StringUtils.hasText(connectionPropertyPrefix) && key.startsWith(connectionPropertyPrefix)) { String newKey = key.substring(connectionPropertyPrefix.length()); providedConnectionProperties.put(newKey, providedProperties.get(key)); } else { if (StringUtils.hasText(cachingPropertyPrefix) && key.startsWith(cachingPropertyPrefix)) { String newKey = key.substring(cachingPropertyPrefix.length()); providedCachingProperties.put(newKey, providedProperties.get(key)); } else { providedConnectionProperties.put(key, providedProperties.get(key)); } } } // look for connectionProperties Object connProperties = DomUtils.getChildElementValueByTagName(element, CONNECTION_PROPERTIES_CHILD_ELEMENT); if (connProperties != null) { if (logger.isDebugEnabled()) { logger.debug("Using connection-properties"); } builder.addPropertyValue("connectionProperties", connProperties); } else { if (providedConnectionProperties.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Using provided connection properties: " + providedConnectionProperties); } builder.addPropertyValue("connectionProperties", providedConnectionProperties); } } // look for connectionCacheProperties Object cacheProperties = DomUtils.getChildElementValueByTagName(element, CONNECTION_CACHE_PROPERTIES_CHILD_ELEMENT); if (cacheProperties != null) { if (logger.isDebugEnabled()) { logger.debug("Using connection-cache-properties: [" + cacheProperties + "]"); } builder.addPropertyValue("connectionCacheProperties", cacheProperties); } else { if (providedCachingProperties.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Using provided caching properties: " + providedCachingProperties); } builder.addPropertyValue("connectionCacheProperties", providedCachingProperties); } } builder.setRole(BeanDefinition.ROLE_SUPPORT); }