List of usage examples for org.springframework.core.io Resource getURL
URL getURL() throws IOException;
From source file:net.javacrumbs.springws.test.template.FreeMarkerTemplateProcessor.java
public Resource processTemplate(Resource resource, WebServiceMessage message) throws IOException { try {/*from w w w . j a v a 2 s . c o m*/ Configuration configuration = configurationFactory.createConfiguration(); Map<String, Object> properties = new HashMap<String, Object>(); properties.putAll(WsTestContextHolder.getTestContext().getAttributeMap()); if (message != null) { properties.put("request", getXmlUtil().loadDocument(message)); } properties.put("IGNORE", "${IGNORE}"); StringWriter out = new StringWriter(); configuration.getTemplate(resource.getURL().toString()).process(properties, out); return new ByteArrayResource(out.toString().getBytes("UTF-8")); } catch (TemplateException e) { throw new IllegalStateException("FreeMarker exception", e); } }
From source file:com.griddynamics.banshun.ContextParentBean.java
ConfigurableApplicationContext createChildContext(Resource res, ApplicationContext parent) throws Exception { if (childContextPrototype != null && childContextPrototype.length() > 0) { try {/*from w w w. j a v a 2s . co m*/ return (ConfigurableApplicationContext) parent.getBean(childContextPrototype, res, parent); } catch (Exception e) { log.warn("Can not initialize ApplicationContext {} with configuration location {}", new Object[] { childContextPrototype, res.getURL(), e }); } } return new SingleResourceXmlChildContext(res, parent); }
From source file:com.apdplat.platform.compass.APDPlatLocalCompassBean.java
public void afterPropertiesSet() throws Exception { CompassConfiguration config = this.config; if (config == null) { config = newConfiguration();//www. ja v a 2 s . co m } if (classLoader != null) { config.setClassLoader(getClassLoader()); } if (this.configLocation != null) { config.configure(this.configLocation.getURL()); } if (this.configLocations != null) { for (Resource configLocation1 : configLocations) { config.configure(configLocation1.getURL()); } } if (this.mappingScan != null) { config.addScan(this.mappingScan); } if (this.compassSettings != null) { config.getSettings().addSettings(this.compassSettings); } if (this.settings != null) { config.getSettings().addSettings(this.settings); } if (resourceLocations != null) { for (Resource resourceLocation : resourceLocations) { config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename()); } } if (resourceJarLocations != null && !"".equals(resourceJarLocations.trim())) { log.info("apdplatcompass2"); log.info("compass resourceJarLocations:" + resourceJarLocations); String[] jars = resourceJarLocations.split(","); for (String jar : jars) { try { FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(jar)); config.addJar(resource.getFile()); log.info("compass resourceJarLocations find:" + jar); } catch (Exception e) { log.info("compass resourceJarLocations not exists:" + jar); } } } if (classMappings != null) { for (String classMapping : classMappings) { config.addClass(ClassUtils.forName(classMapping, getClassLoader())); } } if (resourceDirectoryLocations != null && !"".equals(resourceDirectoryLocations.trim())) { log.info("apdplatcompass3"); log.info("compass resourceDirectoryLocations:" + resourceDirectoryLocations); String[] dirs = resourceDirectoryLocations.split(","); for (String dir : dirs) { ClassPathResource resource = new ClassPathResource(dir); try { File file = resource.getFile(); if (!file.isDirectory()) { log.info("Resource directory location [" + dir + "] does not denote a directory"); } else { config.addDirectory(file); } log.info("compass resourceDirectoryLocations find:" + dir); } catch (Exception e) { log.info("compass resourceDirectoryLocations not exists:" + dir); } } } if (mappingResolvers != null) { for (InputStreamMappingResolver mappingResolver : mappingResolvers) { config.addMappingResover(mappingResolver); } } if (dataSource != null) { ExternalDataSourceProvider.setDataSource(dataSource); if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) { config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS, ExternalDataSourceProvider.class.getName()); } } String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY); if (compassTransactionFactory == null && transactionManager != null) { // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one. config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY, SpringSyncTransactionFactory.class.getName()); } if (compassTransactionFactory != null && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) { if (transactionManager == null) { throw new IllegalArgumentException( "When using SpringSyncTransactionFactory the transactionManager property must be set"); } } SpringSyncTransactionFactory.setTransactionManager(transactionManager); if (convertersByName != null) { for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) { config.registerConverter(entry.getKey(), entry.getValue()); } } if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) { config.getSettings().setSetting(CompassEnvironment.NAME, beanName); } if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) { config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath()); } if (applicationContext != null) { String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class); for (String name : names) { try { PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext .getBean(name); Method method = findMethod(propConfigurer.getClass(), "mergeProperties"); method.setAccessible(true); Properties props = (Properties) method.invoke(propConfigurer); method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class); method.setAccessible(true); method.invoke(propConfigurer, props); method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class, Properties.class, Set.class); method.setAccessible(true); String nullValue = null; try { Field field = propConfigurer.getClass().getDeclaredField("nullValue"); field.setAccessible(true); nullValue = (String) field.get(propConfigurer); } catch (NoSuchFieldException e) { // no field (old spring version) } for (Map.Entry entry : config.getSettings().getProperties().entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); value = (String) method.invoke(propConfigurer, value, props, new HashSet()); config.getSettings().setSetting(key, value.equals(nullValue) ? null : value); } } catch (Exception e) { log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e); } } } if (postProcessor != null) { postProcessor.process(config); } this.compass = newCompass(config); this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(), new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass)); }
From source file:org.atm.mvn.run.JavaBootstrap.java
/** * Attempt to resolve the class from the class name specified. * /*w ww. j a va 2 s . c o m*/ * @param bootstrapClassLoader * The class loader to use to load the class. * @return The {@link Class} instance * @throws RuntimeException * if the class cannot be resolved. */ protected Class<?> resolveClass(ClassLoader bootstrapClassLoader) { // try resolving just the fully qualified class name try { Class<?> loadedClass = bootstrapClassLoader.loadClass(className); log.debug("Resolved fully qualified class name: " + className); return loadedClass; } catch (ClassNotFoundException e) { } PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver( bootstrapClassLoader); // look for class files for the simple class name String locationPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "**/" + className + ".class"; Resource[] resources; try { // run the search with spring // TODO might be possible to do this without a spring dependency resources = resourceResolver.getResources(locationPattern); log.debug("Found resources matching class name pattern: " + locationPattern); for (Resource resource : resources) { log.debug(" " + resource); } } catch (IOException e) { throw new RuntimeException(e); } if (resources.length > 0) { // assume that the first resource found is the one we want. Resource resource = resources[0]; try { String url = resource.getURL().toString(); log.debug("Attempting to resolve class name from URL: " + url); int jarMarkerIndex = url.indexOf('!'); if (jarMarkerIndex != -1) { /* * This is not a jar based class file, so the proper fully * qualified class name is not clear since the URL may * contain path segments that are not part of the package */ String classUrl = url.toString(); int pathStartIndex = classUrl.indexOf(":/") + 2; String classFilePath = classUrl.substring(pathStartIndex); /* * begin with the path minus .class and converted to fully * qualified class name format. */ String currentClassName = classFilePath // remove the file extension .substring(0, classFilePath.indexOf(".class")) // convert the path separators to package separators .replace('/', '.'); // search for the class while (StringUtils.isNotEmpty(currentClassName)) { // try loading the current class name try { Class<?> loadedClass = bootstrapClassLoader.loadClass(currentClassName); log.debug(MessageFormat.format( "Resolved class {0} " + "from URL {1} " + "for specified class name {1}.", currentClassName, url, className)); return loadedClass; } catch (ClassNotFoundException e) { // class not found, so substring the path if possible int nextPackageSeparatorIndex = currentClassName.indexOf('.'); if (nextPackageSeparatorIndex == -1) { // nothing more to try throw new RuntimeException("Unable to load class from class file " + classUrl, e); } else { // the next child path currentClassName = currentClassName.substring(nextPackageSeparatorIndex + 1); } } } } else { /* * this is a resource contained in a JAR file, the pattern is: * jar://path/to/jarFile.jar!/fully/qualified/ClassName.class */ String className = url.substring(jarMarkerIndex + 2, url.indexOf(".class")).replace('/', '.'); try { Class<?> loadedClass = bootstrapClassLoader.loadClass(className); log.debug(MessageFormat.format( "Resolved class {0} " + "from URL {1} " + "for specified class name {1}.", className, url, this.className)); return loadedClass; } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to load class from resource: " + url, e); } } } catch (IOException e) { throw new RuntimeException("Unable to convert resource URL to String: " + resource, e); } } throw new RuntimeException("Unable to resolve class for class name specified: " + className); }
From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java
/** * Checks the folder entries from the Bundle-Classpath for the given * pattern./*from w w w. j av a 2 s . com*/ * * @param list list * @param bundle bundle * @param cpEntryPath cpEntryPath * @param pattern pattern * @throws java.io.IOException */ private void findBundleClassPathMatchingFolders(List<String> list, Bundle bundle, String cpEntryPath, String pattern) throws IOException { // append path to the pattern and do a normal search // folder/<pattern> starts being applied String bundlePathPattern; boolean entryWithFolderSlash = cpEntryPath.endsWith(FOLDER_SEPARATOR); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // concatenate entry + pattern w/o double slashes if (entryWithFolderSlash) { if (patternWithFolderSlash) bundlePathPattern = cpEntryPath + pattern.substring(1, pattern.length()); else bundlePathPattern = cpEntryPath + pattern; } else { if (patternWithFolderSlash) bundlePathPattern = cpEntryPath + pattern; else bundlePathPattern = cpEntryPath + FOLDER_SEPARATOR + pattern; } // search the bundle space for the detected resource OsgiBundleResourcePatternResolver localResolver = new OsgiBundleResourcePatternResolver(bundle, getClassLoader()); Resource[] resources = localResolver.getResources(bundlePathPattern); boolean trace = logger.isTraceEnabled(); List<String> foundResources = (trace ? new ArrayList<String>(resources.length) : null); try { // skip when dealing with non-existing resources if (resources.length == 1 && !resources[0].exists()) { return; } int cutStartingIndex = cpEntryPath.length(); // add the resource stripping the cp for (Resource resource : resources) { String path = resource.getURL().getPath().substring(cutStartingIndex); list.add(path); if (trace) foundResources.add(path); } } finally { if (trace) logger.trace( "Searching for [" + bundlePathPattern + "] revealed resources (relative to the cp entry [" + cpEntryPath + "]): " + foundResources); } }
From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBean.java
@Override public void afterPropertiesSet() throws IOException { HibernateSpringSessionFactoryBuilder sfb = new HibernateSpringSessionFactoryBuilder(this.dataSource, getResourceLoader(), getMetadataSources()); if (this.configLocations != null) { for (Resource resource : this.configLocations) { // Load Hibernate configuration from given location. sfb.configure(resource.getURL()); }//from w w w . j a v a2 s. c om } if (this.mappingResources != null) { // Register given Hibernate mapping definitions, contained in // resource files. for (String mapping : this.mappingResources) { Resource mr = new ClassPathResource(mapping.trim(), this.resourcePatternResolver.getClassLoader()); sfb.addInputStream(mr.getInputStream()); } } if (this.mappingLocations != null) { // Register given Hibernate mapping definitions, contained in // resource files. for (Resource resource : this.mappingLocations) { sfb.addInputStream(resource.getInputStream()); } } if (this.cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from // the file system. for (Resource resource : this.cacheableMappingLocations) { sfb.addCacheableFile(resource.getFile()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar // files. for (Resource resource : this.mappingJarLocations) { sfb.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given // directories. for (Resource resource : this.mappingDirectoryLocations) { File file = resource.getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException( "Mapping directory location [" + resource + "] does not denote a directory"); } sfb.addDirectory(file); } } if (this.entityInterceptor != null) { sfb.setInterceptor(this.entityInterceptor); } if (this.implicitNamingStrategy != null) { sfb.setImplicitNamingStrategy(this.implicitNamingStrategy); } if (this.physicalNamingStrategy != null) { sfb.setPhysicalNamingStrategy(this.physicalNamingStrategy); } if (this.jtaTransactionManager != null) { sfb.setJtaTransactionManager(this.jtaTransactionManager); } if (this.multiTenantConnectionProvider != null) { sfb.setMultiTenantConnectionProvider(this.multiTenantConnectionProvider); } if (this.currentTenantIdentifierResolver != null) { sfb.setCurrentTenantIdentifierResolver(this.currentTenantIdentifierResolver); } if (this.entityTypeFilters != null) { sfb.setEntityTypeFilters(this.entityTypeFilters); } if (this.hibernateProperties != null) { sfb.addProperties(this.hibernateProperties); } if (this.annotatedClasses != null) { sfb.addAnnotatedClasses(this.annotatedClasses); } if (this.annotatedPackages != null) { sfb.addPackages(this.annotatedPackages); } if (this.packagesToScan != null) { sfb.scanPackages(this.packagesToScan); } // Build SessionFactory instance. this.configuration = sfb; this.sessionFactory = buildSessionFactory(sfb); // TODO Caratacus sessionFactory EntityInfoUtils.initSession(sessionFactory, setting); }
From source file:org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java
protected void buildSessionFactory() throws Exception { configuration = newConfiguration();/*from w w w . java 2 s .c o m*/ if (configLocations != null) { for (Resource resource : configLocations) { // Load Hibernate configuration from given location. configuration.configure(resource.getURL()); } } if (mappingResources != null) { // Register given Hibernate mapping definitions, contained in resource files. for (String mapping : mappingResources) { Resource mr = new ClassPathResource(mapping.trim(), resourcePatternResolver.getClassLoader()); configuration.addInputStream(mr.getInputStream()); } } if (mappingLocations != null) { // Register given Hibernate mapping definitions, contained in resource files. for (Resource resource : mappingLocations) { configuration.addInputStream(resource.getInputStream()); } } if (cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from the file system. for (Resource resource : cacheableMappingLocations) { configuration.addCacheableFile(resource.getFile()); } } if (mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (Resource resource : mappingJarLocations) { configuration.addJar(resource.getFile()); } } if (mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (Resource resource : mappingDirectoryLocations) { File file = resource.getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException( "Mapping directory location [" + resource + "] does not denote a directory"); } configuration.addDirectory(file); } } if (entityInterceptor != null) { configuration.setInterceptor(entityInterceptor); } if (namingStrategy != null) { configuration.setNamingStrategy(namingStrategy); } if (hibernateProperties != null) { configuration.addProperties(hibernateProperties); } if (annotatedClasses != null) { configuration.addAnnotatedClasses(annotatedClasses); } if (annotatedPackages != null) { configuration.addPackages(annotatedPackages); } if (packagesToScan != null) { configuration.scanPackages(packagesToScan); } if (eventListeners != null) { configuration.setEventListeners(eventListeners); } sessionFactory = doBuildSessionFactory(); buildSessionFactoryProxy(); }
From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java
/** * Applies synthetic class-path analysis. That is, search the bundle space * and the bundle class-path for entries matching the given path. * * @param bundle bundle//from w ww. j a v a 2 s .c o m * @param path path * @param foundPaths foundPaths * @throws java.io.IOException */ private void findSyntheticClassPathMatchingResource(Bundle bundle, String path, Collection<String> foundPaths) throws IOException { // 1. bundle space lookup OsgiBundleResourcePatternResolver localPatternResolver = new OsgiBundleResourcePatternResolver(bundle, getClassLoader()); Resource[] foundResources = localPatternResolver.findResources(path); boolean trace = logger.isTraceEnabled(); if (trace) logger.trace("Found synthetic cp resources " + ObjectUtils.nullSafeToString(foundResources)); for (Resource foundResource : foundResources) { // assemble only the OSGi paths foundPaths.add(foundResource.getURL().getPath()); } // 2. Bundle-Classpath lookup (on the path stripped of the prefix) Collection<String> cpMatchingPaths = findBundleClassPathMatchingPaths(bundle, path); if (trace) logger.trace("Found Bundle-ClassPath matches " + cpMatchingPaths); foundPaths.addAll(cpMatchingPaths); // 3. Required-Bundle is considered already by the dependency resolver }
From source file:com.thoughtworks.go.http.mocks.MockServletContext.java
@Override public URL getResource(String path) throws MalformedURLException { Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); if (!resource.exists()) { return null; }/* www .j av a 2 s.c om*/ try { return resource.getURL(); } catch (MalformedURLException ex) { throw ex; } catch (IOException ex) { logger.warn("Couldn't get URL for " + resource, ex); return null; } }
From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java
/** * Causes the historical dataPointMap to load from a file determined by archiveFileLocation * @param archiveFile file definition to persist the data set to * @return true if dataPointMap loaded correctly, false if not */// www.j a v a 2 s. com @PostConstruct public boolean load() { repositoryLoaded = false; if (!persistHistoricData) { LOG.info("not loading persisted data as persistHistoricData=false"); return false; } if (archiveFileName == null || archiveFileDirectoryLocation == null) { LOG.error("not using historical data from file as incorrect file location:" + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName=" + archiveFileName); return false; } String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName; File archiveFile = null; try { Resource resource = resourceLoader.getResource(archiveFileLocation); if (!resource.exists()) { LOG.warn("cannot load historical data as file at archiveFileLocation='" + archiveFileLocation + "' does not exist"); return false; } archiveFile = new File(resource.getURL().getFile()); } catch (IOException e) { LOG.error("cannot load historical data from file at archiveFileLocation='" + archiveFileLocation + "' due to error:", e); return false; } catch (Exception e) { LOG.error("cannot load historical data from file at archiveFileLocation='" + archiveFileLocation + "' due to error:", e); return false; } try { //TODO CHANGE TO PACKAGE // JAXBContext jaxbContext = JAXBContext.newInstance( // PmatrixDpdCalculatorImpl.class, // PmatrixDpdCalculatorEmaImpl.class, // PmatrixDpdCalculatorRepository.class, // org.opennms.features.vaadin.pmatrix.model.NameValuePair.class); // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix // need to provide bundles class loader ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader(); JAXBContext jaxbContext = JAXBContext.newInstance( "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl); //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator"); Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller(); Object unmarshalledObject = jaxbUnMarshaller.unmarshal(archiveFile); if (unmarshalledObject instanceof PmatrixDpdCalculatorRepository) { PmatrixDpdCalculatorRepository pdcr = (PmatrixDpdCalculatorRepository) unmarshalledObject; dataPointMap = pdcr.getDataPointMap(); LOG.info("successfully unmarshalled historical pmatrix data from file location:" + archiveFile.getAbsolutePath()); repositoryLoaded = true; return true; } else { LOG.error("cant unmarshal received object:" + unmarshalledObject); } } catch (JAXBException e) { LOG.error("problem unmarshalling file: " + archiveFile.getAbsolutePath(), e); } catch (Exception e) { LOG.error("problem unmarshalling file: " + archiveFile.getAbsolutePath(), e); } return false; }