List of usage examples for org.springframework.core.io Resource exists
boolean exists();
From source file:com.haulmont.restapi.config.RestQueriesConfiguration.java
protected void init() { String configName = AppContext.getProperty(CUBA_REST_QUERIES_CONFIG_PROP_NAME); StrTokenizer tokenizer = new StrTokenizer(configName); for (String location : tokenizer.getTokenArray()) { Resource resource = resources.getResource(location); if (resource.exists()) { InputStream stream = null; try { stream = resource.getInputStream(); loadConfig(Dom4j.readDocument(stream).getRootElement()); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(stream); }/*from w ww .j a v a2 s . c o m*/ } else { log.warn("Resource " + location + " not found, ignore it"); } } }
From source file:com.netflix.genie.web.tasks.node.DiskCleanupTaskUnitTests.java
/** * Make sure we can run successfully when runAsUser is false for the system. * * @throws IOException on error/* www .ja va 2s .c o m*/ * @throws GenieException on error */ @Test public void canRunWithoutSudo() throws IOException, GenieException { final JobsProperties jobsProperties = new JobsProperties(); jobsProperties.getUsers().setRunAsUserEnabled(false); // Create some random junk file that should be ignored this.tmpJobDir.newFile(UUID.randomUUID().toString()); final DiskCleanupProperties properties = new DiskCleanupProperties(); final Calendar cal = TaskUtils.getMidnightUTC(); TaskUtils.subtractDaysFromDate(cal, properties.getRetention()); final Date threshold = cal.getTime(); final String job1Id = UUID.randomUUID().toString(); final String job2Id = UUID.randomUUID().toString(); final String job3Id = UUID.randomUUID().toString(); final String job4Id = UUID.randomUUID().toString(); final String job5Id = UUID.randomUUID().toString(); final Job job1 = Mockito.mock(Job.class); Mockito.when(job1.getStatus()).thenReturn(JobStatus.INIT); final Job job2 = Mockito.mock(Job.class); Mockito.when(job2.getStatus()).thenReturn(JobStatus.RUNNING); final Job job3 = Mockito.mock(Job.class); Mockito.when(job3.getStatus()).thenReturn(JobStatus.SUCCEEDED); Mockito.when(job3.getFinished()).thenReturn(Optional.of(new Date(threshold.getTime() - 1))); final Job job4 = Mockito.mock(Job.class); Mockito.when(job4.getStatus()).thenReturn(JobStatus.FAILED); Mockito.when(job4.getFinished()).thenReturn(Optional.of(threshold)); this.createJobDir(job1Id); this.createJobDir(job2Id); this.createJobDir(job3Id); this.createJobDir(job4Id); this.createJobDir(job5Id); final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class); final Resource jobDir = Mockito.mock(Resource.class); Mockito.when(jobDir.exists()).thenReturn(true); Mockito.when(jobDir.getFile()).thenReturn(this.tmpJobDir.getRoot()); final JobSearchService jobSearchService = Mockito.mock(JobSearchService.class); final Registry registry = Mockito.mock(Registry.class); final AtomicLong numberOfDeletedJobDirs = new AtomicLong(); Mockito.when(registry.gauge(Mockito.eq("genie.tasks.diskCleanup.numberDeletedJobDirs.gauge"), Mockito.any(AtomicLong.class))).thenReturn(numberOfDeletedJobDirs); final AtomicLong numberOfDirsUnableToDelete = new AtomicLong(); Mockito.when(registry.gauge(Mockito.eq("genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge"), Mockito.any(AtomicLong.class))).thenReturn(numberOfDirsUnableToDelete); final Counter unableToGetJobCounter = Mockito.mock(Counter.class); Mockito.when(registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate")) .thenReturn(unableToGetJobCounter); final Counter unabledToDeleteJobsDir = Mockito.mock(Counter.class); Mockito.when(registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate")) .thenReturn(unabledToDeleteJobsDir); Mockito.when(jobSearchService.getJob(job1Id)).thenReturn(job1); Mockito.when(jobSearchService.getJob(job2Id)).thenReturn(job2); Mockito.when(jobSearchService.getJob(job3Id)).thenReturn(job3); Mockito.when(jobSearchService.getJob(job4Id)).thenReturn(job4); Mockito.when(jobSearchService.getJob(job5Id)).thenThrow(new GenieServerException("blah")); final DiskCleanupTask task = new DiskCleanupTask(properties, scheduler, jobDir, jobSearchService, jobsProperties, Mockito.mock(Executor.class), registry); Assert.assertThat(numberOfDeletedJobDirs.get(), Matchers.is(0L)); Assert.assertThat(numberOfDirsUnableToDelete.get(), Matchers.is(0L)); task.run(); Assert.assertThat(numberOfDeletedJobDirs.get(), Matchers.is(1L)); Assert.assertThat(numberOfDirsUnableToDelete.get(), Matchers.is(1L)); Assert.assertTrue(new File(jobDir.getFile(), job1Id).exists()); Assert.assertTrue(new File(jobDir.getFile(), job2Id).exists()); Assert.assertFalse(new File(jobDir.getFile(), job3Id).exists()); Assert.assertTrue(new File(jobDir.getFile(), job4Id).exists()); Assert.assertTrue(new File(jobDir.getFile(), job5Id).exists()); }
From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java
protected void initAppProperties(ServletContext sc) { // get properties from web.xml String appProperties = sc.getInitParameter(APP_PROPS_PARAM); if (appProperties != null) { StrTokenizer tokenizer = new StrTokenizer(appProperties); for (String str : tokenizer.getTokenArray()) { int i = str.indexOf("="); if (i < 0) continue; String name = StringUtils.substring(str, 0, i); String value = StringUtils.substring(str, i + 1); if (!StringUtils.isBlank(name)) { AppContext.setProperty(name, value); }/*from w ww. j a va 2 s . c om*/ } } // get properties from a set of app.properties files defined in web.xml String propsConfigName = getAppPropertiesConfig(sc); if (propsConfigName == null) throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined"); final Properties properties = new Properties(); DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); StrTokenizer tokenizer = new StrTokenizer(propsConfigName); tokenizer.setQuoteChar('"'); for (String str : tokenizer.getTokenArray()) { log.trace("Processing properties location: {}", str); str = StrSubstitutor.replaceSystemProperties(str); InputStream stream = null; try { if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) { Resource resource = resourceLoader.getResource(str); if (resource.exists()) stream = resource.getInputStream(); } else { stream = sc.getResourceAsStream(str); } if (stream != null) { log.info("Loading app properties from {}", str); try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { properties.load(reader); } } else { log.trace("Resource {} not found, ignore it", str); } } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(stream); } } for (Object key : properties.keySet()) { AppContext.setProperty((String) key, properties.getProperty((String) key).trim()); } }
From source file:org.obiba.onyx.engine.ActionDefinitionConfiguration.java
/** * Finds and loads action-definition.xml to build the cache of {@code ActionDefinition} instances. * @throws IOException//from w w w .j av a 2 s. c o m */ protected void findDefinitions() throws IOException { ResourcePatternResolver resolver = (ResourcePatternResolver) this.resourceLoader; // Find definitions in onyx jar files (including module jar files) String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "META-INF/" + ACTION_DEFINITION_FILENAME; Resource[] resources = resolver.getResources(pattern); loadDefinitions(resources); Resource configPath = resolver.getResource(onyxConfigPath); if (configPath != null && configPath.exists()) { // Find definitions in the configuration directory resources = resolver.getResources(onyxConfigPath + "/" + ACTION_DEFINITION_FILENAME); loadDefinitions(resources); // Find definitions in the module configuration directory resources = resolver.getResources(onyxConfigPath + "/*/" + ACTION_DEFINITION_FILENAME); loadDefinitions(resources); } }
From source file:com.netflix.genie.web.configs.MvcConfigUnitTests.java
/** * Make sure we can get a valid job resource when all conditions are met. * * @throws IOException for any problem//from w w w . j av a2s . c o m */ @Test public void canGetJobsDir() throws IOException { final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class); final String jobsDirLocation = UUID.randomUUID().toString() + "/"; final JobsProperties jobsProperties = new JobsProperties(); jobsProperties.getLocations().setJobs(jobsDirLocation); final Resource jobsDirResource = Mockito.mock(Resource.class); Mockito.when(resourceLoader.getResource(jobsDirLocation)).thenReturn(jobsDirResource); Mockito.when(jobsDirResource.exists()).thenReturn(true); final File file = Mockito.mock(File.class); Mockito.when(jobsDirResource.getFile()).thenReturn(file); Mockito.when(file.isDirectory()).thenReturn(true); final Resource jobsDir = this.mvcConfig.jobsDir(resourceLoader, jobsProperties); Assert.assertNotNull(jobsDir); }
From source file:com.haulmont.cuba.web.testsupport.TestContainer.java
protected void initAppProperties() { final Properties properties = new Properties(); List<String> locations = getAppPropertiesFiles(); DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); for (String location : locations) { Resource resource = resourceLoader.getResource(location); if (resource.exists()) { InputStream stream = null; try { stream = resource.getInputStream(); properties.load(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(stream); }// ww w .ja v a 2s. c o m } else { log.warn("Resource " + location + " not found, ignore it"); } } StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() { @Override public String lookup(String key) { String subst = properties.getProperty(key); return subst != null ? subst : System.getProperty(key); } }); for (Object key : properties.keySet()) { String value = substitutor.replace(properties.getProperty((String) key)); appProperties.put((String) key, value); } File dir; dir = new File(appProperties.get("cuba.confDir")); dir.mkdirs(); dir = new File(appProperties.get("cuba.logDir")); dir.mkdirs(); dir = new File(appProperties.get("cuba.tempDir")); dir.mkdirs(); dir = new File(appProperties.get("cuba.dataDir")); dir.mkdirs(); AppContext.setProperty(AppConfig.CLIENT_TYPE_PROP, ClientType.WEB.toString()); }
From source file:com.civilizer.web.handler.ResourceHttpRequestHandler.java
protected Resource getResource(HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (path == null) { throw new IllegalStateException("Required request attribute '" + HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set"); }//w w w . j a v a 2 s. c o m // // For resources having UTF-8 encoded path; // path = FsUtil.toUtf8Path(path); if (!StringUtils.hasText(path) || isInvalidPath(path)) { if (logger.isDebugEnabled()) { logger.debug("Ignoring invalid resource path [" + path + "]"); } return null; } for (Resource location : this.locations) { try { if (logger.isDebugEnabled()) { logger.debug("Trying relative path [" + path + "] against base location: " + location); } Resource resource = location.createRelative(path); if (resource.exists() && resource.isReadable()) { if (logger.isDebugEnabled()) { logger.debug("Found matching resource: " + resource); } return resource; } else if (logger.isTraceEnabled()) { logger.trace("Relative resource doesn't exist or isn't readable: " + resource); } } catch (IOException ex) { logger.debug("Failed to create relative resource - trying next resource location", ex); } } return null; }
From source file:org.beanlet.springframework.impl.SpringHelper.java
public static synchronized ListableBeanFactory getListableBeanFactory(BeanletConfiguration<?> configuration, Element element) {/*from w w w . j a va 2 s.c om*/ SpringContext springContext = getSpringContext(configuration, element); if (springContext == null) { throw new ApplicationContextException("No spring context specified."); } final ClassLoader loader = configuration.getComponentUnit().getClassLoader(); Map<SpringContext, ListableBeanFactory> map = factories.get(loader); if (map == null) { map = new HashMap<SpringContext, ListableBeanFactory>(); factories.put(loader, map); } ListableBeanFactory factory = map.get(springContext); if (factory == null) { ClassLoader org = null; try { org = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { // PERMISSION: java.lang.RuntimePermission getClassLoader ClassLoader org = Thread.currentThread().getContextClassLoader(); // PERMISSION: java.lang.RuntimePermission setContextClassLoader Thread.currentThread().setContextClassLoader(loader); return org; } }); if (springContext.applicationContext()) { factory = new GenericApplicationContext(); } else { factory = new DefaultListableBeanFactory(); } // Do not create spring context in priviliged scope! for (SpringResource r : springContext.value()) { String path = r.value(); Resource resource = null; BeanDefinitionReader reader = null; switch (r.type()) { case CLASSPATH: resource = new ClassPathResource(path); break; case FILESYSTEM: resource = new FileSystemResource(path); break; case URL: resource = new UrlResource(path); break; default: assert false : r.type(); } switch (r.format()) { case XML: reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) factory); break; case PROPERTIES: reader = new PropertiesBeanDefinitionReader((BeanDefinitionRegistry) factory); break; default: assert false : r.format(); } if (resource != null && resource.exists()) { reader.loadBeanDefinitions(resource); } } if (factory instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) factory).refresh(); } map.put(springContext, factory); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ApplicationContextException("Failed to construct spring " + (springContext.applicationContext() ? "application context" : "bean factory") + ".", e); } finally { final ClassLoader tmp = org; AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { // PERMISSION: java.lang.RuntimePermission setContextClassLoader Thread.currentThread().setContextClassLoader(tmp); return null; } }); } } return factory; }