Example usage for org.springframework.core.io Resource exists

List of usage examples for org.springframework.core.io Resource exists

Introduction

In this page you can find the example usage for org.springframework.core.io Resource exists.

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:org.mifos.reports.MifosViewerServletContextListener.java

private void copyFromClassPathToDirectory(String directoryToScan, File rootDirectory) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources(LOCATION_PATTERN);
    LOGGER.info("Found " + resources.length + " Resources on " + LOCATION_PATTERN);
    for (Resource resource : resources) {
        if (resource.exists() & resource.isReadable() && resource.contentLength() > 0) {
            URL url = resource.getURL();
            String urlString = url.toExternalForm();
            String targetName = urlString.substring(urlString.indexOf(directoryToScan));
            File destination = new File(rootDirectory, targetName);
            FileUtils.copyURLToFile(url, destination);
            LOGGER.info("Copied " + url + " to " + destination.getAbsolutePath());
        } else {//from  ww w .  j a v  a 2s. c o m
            LOGGER.debug("Did not copy, seems to be directory: " + resource.getDescription());
        }
    }
}

From source file:org.mitre.mpf.wfm.util.MpfPropertiesConfigurationBuilder.java

private CompositeConfiguration createCompositeConfiguration() {

    if (!customPropFile.exists()) {
        try {//  w ww.  j a v a2 s  .  c om
            PropertiesUtil.createParentDir(customPropFile);
            customPropFile.getFile().createNewFile();
        } catch (IOException e) {
            throw new IllegalStateException("Cannot create " + customPropFile + ".", e);
        }
    }

    CompositeConfiguration compositeConfig = new CompositeConfiguration();

    // add resources in the order they are specified in the application context XML;
    // the first configs that are added to the composite override property values in configs that are added later
    for (Resource resource : propFiles) {
        try {
            if (resource.equals(customPropFile)) {
                mpfCustomPropertiesConfig = createFileBasedConfigurationBuilder(customPropFile)
                        .getConfiguration();
                compositeConfig.addConfiguration(mpfCustomPropertiesConfig);
            } else if (resource.exists()) {
                compositeConfig
                        .addConfiguration(createFileBasedConfigurationBuilder(resource).getConfiguration());
            }
        } catch (ConfigurationException e) {
            throw new IllegalStateException("Cannot create configuration from " + resource + ".", e);
        }
    }

    if (mpfCustomPropertiesConfig == null) {
        throw new IllegalStateException("List of configuration properties files did not contain the "
                + "custom configuration property file: " + propFiles);
    }

    return compositeConfig;
}

From source file:org.openehealth.ipf.commons.map.config.CustomMappings.java

public void setMappingScripts(Collection<Resource> mappingScripts) {
    this.mappingScripts = new ArrayList<Resource>(mappingScripts.size());
    for (Resource mappingScript : mappingScripts) {
        if (mappingScript.exists() && mappingScript.isReadable()) {
            this.mappingScripts.add(mappingScript);
        } else {/* ww w .  j  a va  2  s  .co  m*/
            LOG.warn("Could not read mapping script " + mappingScript.getFilename());
        }
    }
    this.mappingScripts = mappingScripts;
}

From source file:org.openehealth.ipf.commons.map.config.CustomMappings.java

public void setMappingScript(Resource mappingScript) {
    if (mappingScript.exists() && mappingScript.isReadable()) {
        this.mappingScript = mappingScript;
    } else {//w  w w .  j  a v a 2  s. c  o m
        LOG.warn("Could not read mapping script " + mappingScript.getFilename());
    }
}

From source file:org.openlegacy.providers.applinx.ApxServerLoader.java

private static void loadLogger() throws IOException {
    Resource resource = new ClassPathResource("/log4j.properties");
    if (resource.exists()) {
        Properties logProperties = PropertiesLoaderUtils.loadProperties(resource);
        new PropertyConfigurator().doConfigure(logProperties, LogManager.getLoggerRepository());
    }//from   ww w  .  ja va  2 s. co m
}

From source file:org.openlegacy.providers.applinx.ApxServerLoader.java

private static void initFile(File tempDir, String fileName, String targetFileName) throws IOException {
    if (targetFileName == null) {
        targetFileName = fileName;/*ww  w . j  a  va2s . co m*/
    }

    Resource fileResource = new ClassPathResource(fileName);

    if (fileResource.exists()) {
        initResource(tempDir, targetFileName, fileResource);
    }
}

From source file:org.openmrs.messagesource.impl.MutableResourceBundleMessageSource.java

/**
 * Searches the filesystem for message properties files. ABKTODO: consider caching this, rather
 * than searching every time//from   www .  jav  a  2  s .co  m
 *
 * @return collection of property file names
 */
private Collection<File> findPropertiesFiles() {
    Collection<File> propertiesFiles = new Vector<File>();

    try {
        for (String basename : basenames) {
            File basefilename = new File(basename);
            basename = basefilename.getPath();
            int nameIndex = basename.lastIndexOf(File.separatorChar) + 1;
            String basedir = (nameIndex > 0) ? basename.substring(0, nameIndex) : "";
            String namePrefix = basename.substring(nameIndex);
            Resource propertiesDir = applicationContext.getResource(basedir);
            boolean filesFound = false;
            if (propertiesDir.exists()) {
                for (File possibleFile : propertiesDir.getFile().listFiles()) {
                    if (possibleFile.getName().startsWith(namePrefix)
                            && possibleFile.getName().endsWith(".properties")) {
                        propertiesFiles.add(possibleFile);
                        filesFound = true;
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Parent directory " + propertiesDir + " does not exist");
                }
            }

            if (log.isDebugEnabled() && !filesFound) {
                log.debug("No messages for basename " + basename);
            }
        }
    } catch (IOException e) {
        log.error("Error generated", e);
    }
    if (log.isWarnEnabled() && (propertiesFiles.size() == 0)) {
        log.warn("No properties files found.");
    }
    return propertiesFiles;
}

From source file:org.opennms.netmgt.provision.persist.AbstractForeignSourceRepository.java

/**
 * <p>getDefaultForeignSource</p>
 *
 * @return a {@link org.opennms.netmgt.provision.persist.foreignsource.ForeignSource} object.
 * @throws org.opennms.netmgt.provision.persist.ForeignSourceRepositoryException if any.
 *///  ww  w.ja va  2  s.c  o  m
@Override
public ForeignSource getDefaultForeignSource() throws ForeignSourceRepositoryException {
    Resource defaultForeignSource = new ClassPathResource("/default-foreign-source.xml");
    if (!defaultForeignSource.exists()) {
        defaultForeignSource = new ClassPathResource(
                "/org/opennms/netmgt/provision/persist/default-foreign-source.xml");
    }
    final ForeignSource fs = JaxbUtils.unmarshal(ForeignSource.class, defaultForeignSource);
    fs.setDefault(true);
    return fs;
}

From source file:org.openspaces.pu.container.integrated.IntegratedProcessingUnitContainerProvider.java

/**
 * Creates a new {@link IntegratedProcessingUnitContainer} based on the configured parameters.
 *
 * <p> If {@link #addConfigLocation(org.springframework.core.io.Resource)} or {@link
 * #addConfigLocation(String)} were used, the Spring xml context will be read based on the
 * provided locations. If no config location was provided the default config location will be
 * <code>classpath*:/META-INF/spring/pu.xml</code>.
 *
 * <p> If {@link #setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)} is
 * set will use the configured bean level properties in order to configure the application
 * context and specific beans within it based on properties. This is done by adding {@link
 * org.openspaces.core.properties.BeanLevelPropertyBeanPostProcessor} and {@link
 * org.openspaces.core.properties.BeanLevelPropertyPlaceholderConfigurer} to the application
 * context.//  w  w  w. j a v a 2 s . c o  m
 *
 * <p> If {@link #setClusterInfo(org.openspaces.core.cluster.ClusterInfo)} is set will use it to
 * inject {@link org.openspaces.core.cluster.ClusterInfo} into beans that implement {@link
 * org.openspaces.core.cluster.ClusterInfoAware}.
 *
 * @return An {@link IntegratedProcessingUnitContainer} instance or an {@link
 * CompoundProcessingUnitContainer} in case of a clustered processing unit without a specific
 * instance Id.
 */
public ProcessingUnitContainer createContainer() throws CannotCreateContainerException {
    if (configResources.size() == 0) {
        try {
            addConfigLocation(DEFAULT_PU_CONTEXT_LOCATION);
            boolean foundValidResource = false;
            for (Resource resource : configResources) {
                if (resource.exists()) {
                    foundValidResource = true;
                    break;
                }
            }
            if (!foundValidResource) {
                addConfigLocation(new FileSystemResource(DEFAULT_FS_PU_CONTEXT_LOCATION));
                for (Resource resource : configResources) {
                    if (!resource.exists()) {
                        throw new CannotCreateContainerException("No explicit config location, tried ["
                                + DEFAULT_PU_CONTEXT_LOCATION + "], [" + DEFAULT_FS_PU_CONTEXT_LOCATION
                                + "] (relative to working director), [pu.config], and no configuration found");
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("No explicit config location, default location [" + DEFAULT_PU_CONTEXT_LOCATION
                            + "] has no configuration, loading from [" + DEFAULT_FS_PU_CONTEXT_LOCATION
                            + "] relative to working directory [" + new File(".").getAbsolutePath() + "]");
                } else {
                    logger.debug(
                            "No explicit config location, defaulting to [" + DEFAULT_PU_CONTEXT_LOCATION + "]");
                }
            }
        } catch (IOException e) {
            throw new CannotCreateContainerException(
                    "Failed to read config files from " + DEFAULT_PU_CONTEXT_LOCATION, e);
        }
    }

    final ProcessingUnitContainerConfig config = getConfig();
    final ClusterInfo clusterInfo = config.getClusterInfo();
    if (clusterInfo != null) {
        ClusterInfoParser.guessSchema(clusterInfo);
    }

    // in case we don't have a cluster info specific members
    if (clusterInfo != null && clusterInfo.getInstanceId() == null
            && clusterInfo.getNumberOfInstances() != null) {
        ClusterInfo origClusterInfo = clusterInfo;
        List<ProcessingUnitContainer> containers = new ArrayList<ProcessingUnitContainer>();
        for (int i = 0; i < clusterInfo.getNumberOfInstances(); i++) {
            ClusterInfo containerClusterInfo = clusterInfo.copy();
            containerClusterInfo.setInstanceId(i + 1);
            containerClusterInfo.setBackupId(null);
            setClusterInfo(containerClusterInfo);
            containers.add(createContainer());
            if (clusterInfo.getNumberOfBackups() != null) {
                for (int j = 0; j < clusterInfo.getNumberOfBackups(); j++) {
                    containerClusterInfo = containerClusterInfo.copy();
                    containerClusterInfo.setBackupId(j + 1);
                    setClusterInfo(containerClusterInfo);
                    containers.add(createContainer());
                }
            }
        }
        setClusterInfo(origClusterInfo);
        return new CompoundProcessingUnitContainer(
                containers.toArray(new ProcessingUnitContainer[containers.size()]));
    }

    // handle security
    final BeanLevelProperties beanLevelProperties = config.getBeanLevelProperties();
    if (credentialsProvider != null) {
        try {
            CredentialsProviderHelper.appendMarshalledCredentials(beanLevelProperties.getContextProperties(),
                    null, credentialsProvider);
        } catch (IOException e) {
            throw new CannotCreateContainerException("Failed to marshall user details", e);
        }
    } else if (secured != null) {
        beanLevelProperties.getContextProperties().setProperty(SpaceURL.SECURED, "true");
    }

    Resource[] resources = configResources.toArray(new Resource[configResources.size()]);
    // create the Spring application context
    ResourceApplicationContext applicationContext = new ResourceApplicationContext(resources, parentContext,
            config);
    if (classLoader != null) {
        applicationContext.setClassLoader(classLoader);
    }

    // "start" the application context
    applicationContext.refresh();

    return new IntegratedProcessingUnitContainer(applicationContext);
}

From source file:org.openspaces.pu.container.jee.context.BootstrapWebApplicationContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    Boolean bootstraped = (Boolean) servletContext.getAttribute(BOOTSTRAP_CONTEXT_KEY);
    if (bootstraped != null && bootstraped) {
        logger.debug("Already performed bootstrap, ignoring");
        return;//from  ww  w .j  a  v  a2s  .c o m
    }
    servletContext.setAttribute(BOOTSTRAP_CONTEXT_KEY, true);

    logger.info("Booting OpenSpaces Web Application Support");
    logger.info(ClassLoaderUtils.getCurrentClassPathString("Web Class Loader"));
    final ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig();

    InputStream is = servletContext.getResourceAsStream(MARSHALLED_CLUSTER_INFO);
    if (is != null) {
        try {
            config.setClusterInfo((ClusterInfo) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT,
                    config.getClusterInfo());
        } catch (Exception e) {
            logger.warn("Failed to read cluster info from " + MARSHALLED_CLUSTER_INFO, e);
        }
    } else {
        logger.debug("No cluster info found at " + MARSHALLED_CLUSTER_INFO);
    }
    is = servletContext.getResourceAsStream(MARSHALLED_BEAN_LEVEL_PROPERTIES);
    if (is != null) {
        try {
            config.setBeanLevelProperties(
                    (BeanLevelProperties) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT,
                    config.getBeanLevelProperties());
        } catch (Exception e) {
            logger.warn("Failed to read bean level properties from " + MARSHALLED_BEAN_LEVEL_PROPERTIES, e);
        }
    } else {
        logger.debug("No bean level properties found at " + MARSHALLED_BEAN_LEVEL_PROPERTIES);
    }

    Resource resource = null;
    String realPath = servletContext.getRealPath("/META-INF/spring/pu.xml");
    if (realPath != null) {
        resource = new FileSystemResource(realPath);
    }
    if (resource != null && resource.exists()) {
        logger.debug("Loading [" + resource + "]");
        // create the Spring application context
        final ResourceApplicationContext applicationContext = new ResourceApplicationContext(
                new Resource[] { resource }, null, config);
        // "start" the application context
        applicationContext.refresh();

        servletContext.setAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT,
                applicationContext);
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            if (applicationContext.getType(beanName) != null)
                servletContext.setAttribute(beanName, applicationContext.getBean(beanName));
        }

        if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
            final String key = config.getClusterInfo().getUniqueName();

            SharedServiceData.addServiceDetails(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceDetails> serviceDetails = new ArrayList<ServiceDetails>();
                    Map map = applicationContext.getBeansOfType(ServiceDetailsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceDetails[] details = ((ServiceDetailsProvider) it.next()).getServicesDetails();
                        if (details != null) {
                            for (ServiceDetails detail : details) {
                                serviceDetails.add(detail);
                            }
                        }
                    }
                    return serviceDetails.toArray(new Object[serviceDetails.size()]);
                }
            });

            SharedServiceData.addServiceMonitors(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceMonitors> serviceMonitors = new ArrayList<ServiceMonitors>();
                    Map map = applicationContext.getBeansOfType(ServiceMonitorsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceMonitors[] monitors = ((ServiceMonitorsProvider) it.next())
                                .getServicesMonitors();
                        if (monitors != null) {
                            for (ServiceMonitors monitor : monitors) {
                                serviceMonitors.add(monitor);
                            }
                        }
                    }
                    return serviceMonitors.toArray(new Object[serviceMonitors.size()]);
                }
            });

            Map map = applicationContext.getBeansOfType(MemberAliveIndicator.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final MemberAliveIndicator memberAliveIndicator = (MemberAliveIndicator) it.next();
                if (memberAliveIndicator.isMemberAliveEnabled()) {
                    SharedServiceData.addMemberAliveIndicator(key, new Callable<Boolean>() {
                        public Boolean call() throws Exception {
                            return memberAliveIndicator.isAlive();
                        }
                    });
                }
            }

            map = applicationContext.getBeansOfType(ProcessingUnitUndeployingListener.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final ProcessingUnitUndeployingListener listener = (ProcessingUnitUndeployingListener) it
                        .next();
                SharedServiceData.addUndeployingEventListener(key, new Callable() {
                    public Object call() throws Exception {
                        listener.processingUnitUndeploying();
                        return null;
                    }
                });
            }

            map = applicationContext.getBeansOfType(InternalDumpProcessor.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                SharedServiceData.addDumpProcessors(key, it.next());
            }
        }
    } else {
        logger.debug("No [" + ApplicationContextProcessingUnitContainerProvider.DEFAULT_PU_CONTEXT_LOCATION
                + "] to load");
    }

    // load jee specific context listener
    if (config.getBeanLevelProperties() != null) {
        String jeeContainer = JeeProcessingUnitContainerProvider
                .getJeeContainer(config.getBeanLevelProperties());
        String className = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + StringUtils.capitalize(jeeContainer) + "WebApplicationContextListener";
        Class clazz = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            // no class, ignore
        }
        if (clazz != null) {
            try {
                jeeContainerContextListener = (ServletContextListener) clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Failed to create JEE specific context listener [" + clazz.getName() + "]", e);
            }
            jeeContainerContextListener.contextInitialized(servletContextEvent);
        }
    }

    // set the class loader used so the service bean can use it
    if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
        SharedServiceData.putWebAppClassLoader(config.getClusterInfo().getUniqueName(),
                Thread.currentThread().getContextClassLoader());
    }
}