List of usage examples for org.springframework.core.io Resource exists
boolean exists();
From source file:com.netflix.genie.web.configs.MvcConfigUnitTests.java
/** * Test to make sure we can't create a jobs dir resource if the directory can't be created when the input jobs * dir is invalid in any way.//from w w w. j av a 2 s. co m * * @throws IOException On error */ @Test public void cantGetJobsDirWhenJobsDirInvalid() 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 tmpResource = Mockito.mock(Resource.class); Mockito.when(resourceLoader.getResource(jobsDirLocation)).thenReturn(tmpResource); Mockito.when(tmpResource.exists()).thenReturn(true); final File file = Mockito.mock(File.class); Mockito.when(tmpResource.getFile()).thenReturn(file); Mockito.when(file.isDirectory()).thenReturn(false); try { this.mvcConfig.jobsDir(resourceLoader, jobsProperties); Assert.fail(); } catch (final IllegalStateException ise) { Assert.assertThat(ise.getMessage(), Matchers.is(jobsDirLocation + " exists but isn't a directory. Unable to continue")); } final String localJobsDir = jobsDirLocation + "/"; Mockito.when(file.isDirectory()).thenReturn(true); final Resource jobsDirResource = Mockito.mock(Resource.class); Mockito.when(resourceLoader.getResource(localJobsDir)).thenReturn(jobsDirResource); Mockito.when(tmpResource.exists()).thenReturn(false); Mockito.when(jobsDirResource.exists()).thenReturn(false); Mockito.when(jobsDirResource.getFile()).thenReturn(file); Mockito.when(file.mkdirs()).thenReturn(false); try { this.mvcConfig.jobsDir(resourceLoader, jobsProperties); Assert.fail(); } catch (final IllegalStateException ise) { Assert.assertThat(ise.getMessage(), Matchers.is("Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist.")); } }
From source file:ir.caebabe.ninja.providers.ProcessEngineProvider.java
@Override public ProcessEngine get() { logger.info("Initializing Activit Process engine ..."); ProcessEngineConfiguration configuration; String cfgPath = ninjaProperties.get(ActivitiConstants.ACTIVITI_BPMS_CONFIGURATION_PATH); Resource defaultCfgResource = new ClassPathResource(ActivitiConstants.ACTIVITI_DEFAULT_CONFIGURATION_PATH); if (cfgPath != null) { Resource cfgResource = new ClassPathResource(cfgPath); if (!cfgResource.exists()) cfgPath = null;/* w w w .j av a2 s. c om*/ } if (cfgPath != null && !cfgPath.equals("")) { logger.info("Loading Activit configs file from '{}' ...", cfgPath); configuration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(cfgPath); } else if (defaultCfgResource.exists() && ninjaProperties.get(ActivitiConstants.ACTIVITI_BPMS_CONFIGURATION_PATH) == null) { logger.info("Loading default Activit configs file from '{}' ...", ActivitiConstants.ACTIVITI_DEFAULT_CONFIGURATION_PATH); configuration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource( ActivitiConstants.ACTIVITI_DEFAULT_CONFIGURATION_PATH); } else { logger.info("Loading with no Activit configs file "); // configuration = ProcessEngineConfiguration // .createStandaloneProcessEngineConfiguration(); configuration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); } logger.debug("setting activiti properties"); Field[] fields = ProcessEngineConfiguration.class.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); String propertyValue = ninjaProperties.get(ACTIVITI_CONFIG_PREFIX + fieldName); if (propertyValue != null) { logger.debug("setting value '{}' to field '{}'", propertyValue, field.getName()); setFildValue(propertyValue, field, configuration); } } return configuration.buildProcessEngine(); }
From source file:org.codehaus.griffon.runtime.spring.GriffonRuntimeConfigurator.java
private void doPostResourceConfiguration(GriffonApplication application, RuntimeSpringConfiguration springConfig) { ClassLoader classLoader = ApplicationClassLoader.get(); String resourceName = SPRING_RESOURCES_XML; try {//from www .ja v a 2s. c o m Resource springResources = new ClassPathResource(resourceName); if (springResources != null && springResources.exists()) { if (LOG.isDebugEnabled()) LOG.debug( "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL()); DefaultListableBeanFactory xmlBf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xmlBf).loadBeanDefinitions(springResources); xmlBf.setBeanClassLoader(classLoader); String[] beanNames = xmlBf.getBeanDefinitionNames(); if (LOG.isDebugEnabled()) LOG.debug("[RuntimeConfiguration] Found [" + beanNames.length + "] beans to configure"); for (String beanName : beanNames) { BeanDefinition bd = xmlBf.getBeanDefinition(beanName); final String beanClassName = bd.getBeanClassName(); Class<?> beanClass = beanClassName == null ? null : ClassUtils.forName(beanClassName, classLoader); springConfig.addBeanDefinition(beanName, bd); String[] aliases = xmlBf.getAliases(beanName); for (String alias : aliases) { springConfig.addAlias(alias, beanName); } if (beanClass != null) { if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass)) { ((ConfigurableApplicationContext) springConfig.getUnrefreshedApplicationContext()) .addBeanFactoryPostProcessor( (BeanFactoryPostProcessor) xmlBf.getBean(beanName)); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] " + resourceName + " not found. Skipping configuration."); } } catch (Exception ex) { LOG.error("[RuntimeConfiguration] Unable to perform post initialization config: " + resourceName, sanitize(ex)); } loadSpringGroovyResources(springConfig, application); }
From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.FileReadingSettingsFactory.java
private Properties loadCatalinaProperties(final ConfigResponse config) throws IOException { Resource propResource = new FileSystemResource( Metric.decode(config.getValue("installpath")) + "/conf/catalina.properties"); Properties catalinaProperties; if (propResource.exists()) { catalinaProperties = PropertiesLoaderUtils.loadProperties(propResource); } else {//from w w w .ja v a 2s .c om catalinaProperties = new Properties(); } // add catalina.home and catalina.base which are not in the props file catalinaProperties.put("catalina.home", Metric.decode(config.getValue("catalina.home"))); catalinaProperties.put("catalina.base", Metric.decode(config.getValue("installpath"))); return catalinaProperties; }
From source file:com.diaimm.april.db.jpa.hibernate.multidbsupport.PersistenceUnitReader.java
/** * Parse the <code>jar-file</code> XML elements. *//* w w w .j ava 2s. co m*/ @SuppressWarnings("unchecked") protected void parseJarFiles(Element persistenceUnit, SpringPersistenceUnitInfo unitInfo) throws IOException { List<Element> jars = DomUtils.getChildElementsByTagName(persistenceUnit, JAR_FILE_URL); for (Element element : jars) { String value = DomUtils.getTextValue(element).trim(); if (StringUtils.hasText(value)) { Resource[] resources = this.resourcePatternResolver.getResources(value); boolean found = false; for (Resource resource : resources) { if (resource.exists()) { found = true; unitInfo.addJarFileUrl(resource.getURL()); } } if (!found) { // relative to the persistence unit root, according to the JPA spec URL rootUrl = unitInfo.getPersistenceUnitRootUrl(); if (rootUrl != null) { unitInfo.addJarFileUrl(new URL(rootUrl, value)); } else { logger.warn("Cannot resolve jar-file entry [" + value + "] in persistence unit '" + unitInfo.getPersistenceUnitName() + "' without root URL"); } } } } }
From source file:org.opennms.features.vaadin.pmatrix.engine.PmatrixConfigurationFactory.java
/** * This method loads the configuration from the external file. * It is called post construct so that the pmatrixSpecificationList is populated when needed * NOTE - @PostConstruct problems in OSGi so using init-method="loadConfiguration" in application context */// w ww. j av a2 s . c om @PostConstruct private void loadConfiguration() { if (atomicInitialized.compareAndSet(false, true)) { // load configuration if not loaded else just return LOG.info("pmatrix loading configuration from configFileLocation: " + configFileLocation); File configFile = null; Resource resource = resourceLoader.getResource(configFileLocation); if (!resource.exists()) { throw new IllegalStateException("problem loading configuration file, configFileLocation='" + configFileLocation + "' does not exist"); } else { try { //configFile = new File(resource.getURL().getFile()); // 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", cl); //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model"); Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller(); Object unmarshalledObject = jaxbUnMarshaller.unmarshal(resource.getInputStream()); //Object unmarshalledObject = jaxbUnMarshaller.unmarshal(configFile); if (!(unmarshalledObject instanceof PmatrixSpecificationList)) { throw new IllegalStateException( "problem loading configuration file, configFileLocation='" + configFileLocation + "' " + "unmarshalledObject:'" + unmarshalledObject.getClass().getName() + "' is not an instance of PmatrixSpecificationList"); } else { this.pmatrixSpecificationList = (PmatrixSpecificationList) unmarshalledObject; LOG.info("pmatrix configuration successfully loaded from: " + configFileLocation); LOG.info("Loaded pmatrixSpecificationList:" + "\n********************\n" + pmatrixSpecificationList.toString() + "\n********************\n"); // get the DpdCalculatorClassName pmatrixDpdCalculatorConfig = pmatrixSpecificationList.getPmatrixDpdCalculatorConfig(); if (pmatrixDpdCalculatorConfig == null) throw new IllegalStateException( "pmatrixDpdCalculatorConfig is undefined in config File='" + configFileLocation + "'"); pmatrixDpdCalculatorClassName = pmatrixDpdCalculatorConfig .getPmatrixDpdCalculatorClassName(); if (pmatrixDpdCalculatorClassName == null) throw new IllegalStateException( "pmatrixDpdCalculatorClassName is undefined in config File ='" + configFileLocation + "'"); // check if defined pmatrixDpdCalculatorClass can be loaded by class loader Class<?> checkClass = null; try { checkClass = Class.forName(pmatrixDpdCalculatorClassName); } catch (ClassNotFoundException e) { throw new IllegalStateException( "Cannot instantiate class pmatrixDpdCalculatorClassName='" + pmatrixDpdCalculatorClassName + "' in config File ='" + configFileLocation + "'"); } // check if defined pmatrixDpdCalculatorClass extends PmatrixDpdCalculator if (!(PmatrixDpdCalculator.class.isAssignableFrom(checkClass))) { throw new IllegalStateException("class pmatrixDpdCalculatorClassName='" + pmatrixDpdCalculatorClassName + "' in config File ='" + configFileLocation + "' is not an instance of " + PmatrixDpdCalculator.class.getName()); } //check configuration list exists List<NameValuePair> configuration = pmatrixDpdCalculatorConfig.getConfiguration(); if (configuration == null) { LOG.warn("no configuration set for pmatrixDpdCalculatorClassName='" + pmatrixDpdCalculatorClassName); } } } catch (IOException e) { throw new IllegalStateException( "problem loading configuration file, configFileLocation='" + configFileLocation + "' :", e); } catch (JAXBException e) { throw new IllegalStateException("problem unmarshalling configuration file, configFileLocation='" + configFileLocation + "' :", e); } } } }
From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java
@Override protected Resource[] getConfigResources() { List<Resource> resources = new ArrayList<Resource>(); if (includeDefault) { try {//from w w w .j a v a 2 s.c om PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( Thread.currentThread().getContextClassLoader()); Collections.addAll(resources, resolver.getResources(DEFAULT_CFG_FILE)); Resource[] exts = resolver.getResources(DEFAULT_EXT_CFG_FILE); for (Resource r : exts) { InputStream is = r.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = rd.readLine(); while (line != null) { if (!"".equals(line)) { resources.add(resolver.getResource(line)); } line = rd.readLine(); } is.close(); } } catch (IOException ex) { // ignore } } boolean usingDefault = false; if (cfgFiles == null) { String userConfig = System.getProperty(BeanConfigurer.USER_CFG_FILE_PROPERTY_NAME); if (userConfig != null) { cfgFiles = new String[] { userConfig }; } } if (cfgFiles == null) { usingDefault = true; cfgFiles = new String[] { BeanConfigurer.USER_CFG_FILE }; } for (String cfgFile : cfgFiles) { final Resource f = findResource(cfgFile); if (f != null && f.exists()) { resources.add(f); LOG.info("Used configed file {}", cfgFile); } else { if (!usingDefault) { LOG.warn("Can't find configure file {}", cfgFile); throw new ApplicationContextException("Can't find configure file"); } } } if (cfgURLs != null) { for (URL u : cfgURLs) { UrlResource ur = new UrlResource(u); if (ur.exists()) { resources.add(ur); } else { LOG.warn("Can't find configure file {}", u.getPath()); } } } if (LOG.isDebugEnabled()) { LOG.debug("Creating application context with resources " + resources.size()); } if (0 == resources.size()) { return null; } Resource[] res = new Resource[resources.size()]; res = resources.toArray(res); return res; }
From source file:com.haulmont.cuba.gui.config.WindowConfig.java
protected void init() { screens.clear();/* ww w .j a v a 2 s . c om*/ Map<String, ScreenAgent> agentMap = AppBeans.getAll(ScreenAgent.class); Map<String, ScreenAgent> screenAgents = new LinkedHashMap<>(); List<ScreenAgent> availableAgents = new ArrayList<>(agentMap.values()); AnnotationAwareOrderComparator.sort(availableAgents); for (ScreenAgent screenAgent : availableAgents) { screenAgents.put(screenAgent.getAlias(), screenAgent); } this.activeScreenAgents = screenAgents; String configName = AppContext.getProperty(WINDOW_CONFIG_XML_PROP); 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("Unable to read window config from " + location, e); } finally { IOUtils.closeQuietly(stream); } } else { log.warn("Resource {} not found, ignore it", location); } } }
From source file:com.haulmont.restapi.config.RestServicesConfiguration.java
protected void init() { String configName = AppContext.getProperty(CUBA_REST_SERVICES_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("Error on parsing rest services config", e); } finally { IOUtils.closeQuietly(stream); }// w w w .jav a 2 s. com } else { log.warn("Resource " + location + " not found, ignore it"); } } }