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.kuali.maven.plugins.externals.MojoHelper.java

public boolean exists(String url) {
    ResourceLoader loader = new DefaultResourceLoader();
    Resource resource = loader.getResource(url);
    return resource.exists();
}

From source file:com.edgenius.wiki.service.impl.SystemPropertyPlaceholderConfigurer.java

/**
 * Loading global content from Global configure xml file (defined by geniuswiki.properties), then
 * push all value to <code>com.edgenius.core.Global</code> class, which value become static and ready for 
 * later use. /*  w  w  w .  j av a2s. c  o m*/
 *
 * There 3 level global setting. First, server.properties will assign a global.xml, this file usually is outside
 * the deploy file, and put together with data file, this is makes upgrade easily. <br>
 * Second, there is global.default.xml is inside classpath. This file is useful when installer initialized setup 
 * system. see publish process.<br>
 * Third, if both above file not exist, Global.java even has its default value. and it also will automatically generate
 * global.xml in this case. <br>
 * @param globalConf 
 *   
 */
private void initGlobal(Resource globalConf) {
    GlobalSetting setting = null;
    try {
        //http://forum.springframework.org/showthread.php?p=201562#post201562
        //don't use Resource.getInputStream() as it can not handle file://c:/var/data format: error is try to get unknown host "c"
        setting = GlobalSetting.loadGlobalSetting(new FileInputStream(globalConf.getFile()));
    } catch (Exception e) {
        log.info("Unable to load global xml, try load global default xml then...");
        setting = null;
    }
    if (setting == null) {
        //try to load global.default.xml from class path.
        try {
            setting = GlobalSetting.loadGlobalSetting(FileUtil.getFileInputStream(Global.DEFAULT_GLOBAL_XML));
        } catch (Exception e) {
            log.warn("Loading global default xml failed, using Global class default instead.");
        }
        if (setting == null) {
            //the third option, just use Global.java value
            //no global file found, so keep Global default static value instead.
            setting = new GlobalSetting();
            Global.syncTo(setting);
        }

        if (globalConf.exists()) {
            //global exist, maybe wrong format, then try to backup original one
            try {
                String dir = FileUtil.getFileDirectory(globalConf.getFile().getAbsolutePath());
                String name = globalConf.getFilename() + "."
                        + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".failure.backup";
                File orig = new File(FileUtil.getFullPath(dir, name));
                FileUtils.copyFile(globalConf.getFile(), orig);
                log.info("Original global conf file rename to " + name);
            } catch (Exception e) {
                log.warn("Unable backup original global conf file, old one will replaced.");
            }
        }
        //Anyway, global.xml file under data root is missed or crashed, then create or recreate required.
        //As I want to user SettingService.saveOrUpdateGlobalSetting() to save rather than create duplicated code,
        //so here a little bit tricky,  I put a flag value to tell SettingService trigger saving in afterProperties()
        log.info("System is going to create/recreate new global.xml in your data root directory.");
        System.setProperty("rebuild.global.xml", "true");

    }

    //finally, initial Global static varible according to setting
    Global.syncFrom(setting);
}

From source file:org.ow2.authzforce.pap.dao.flatfile.FlatFileBasedDomainsDAO.java

/**
 * Creates instance//from  w  w  w  .  ja  va2  s  . c om
 * 
 * @param domainsRoot
 *            root directory of the configuration data of security domains,
 *            one subdirectory per domain
 * @param domainTmpl
 *            domain template directory; directories of new domains are
 *            created from this template
 * @param domainsSyncIntervalSec
 *            how often (in seconds) the synchronization of managed domains
 *            (in memory) with the domain subdirectories in the
 *            <code>domainsRoot</code> directory (on disk) is done. If
 *            <code>domainSyncInterval</code> > 0, every
 *            <code>domainSyncInterval</code>, the managed domains (loaded
 *            in memory) are updated if any change has been detected in the
 *            <code>domainsRoot</code> directory in this interval (since
 *            last sync). To be more specific, <i>any change</i> here means
 *            any creation/deletion/modification of a domain folder
 *            (modification means: any file changed within the folder). If
 *            <code>domainSyncInterval</code> &lt;= 0, synchronization is
 *            disabled.
 * @param pdpModelHandler
 *            PDP configuration model handler
 * @param useRandomAddressBasedUUID
 *            true iff a random multicast address must be used as node field
 *            of generated UUIDs (Version 1), else the MAC address of one of
 *            the network interfaces is used. Setting this to 'true' is NOT
 *            recommended unless the host is disconnected from the network.
 *            These generated UUIDs are used for domain IDs.
 * @param domainDAOClientFactory
 *            domain DAO client factory
 * @throws IOException
 *             I/O error occurred scanning existing domain folders in
 *             {@code domainsRoot} for loading.
 */
@ConstructorProperties({ "domainsRoot", "domainTmpl", "domainsSyncIntervalSec", "pdpModelHandler",
        "useRandomAddressBasedUUID", "domainDAOClientFactory" })
public FlatFileBasedDomainsDAO(final Resource domainsRoot, final Resource domainTmpl,
        final int domainsSyncIntervalSec, final PdpModelHandler pdpModelHandler,
        final boolean useRandomAddressBasedUUID,
        final DomainDAOClient.Factory<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT, FlatFileBasedDomainDAO<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT>, DOMAIN_DAO_CLIENT> domainDAOClientFactory)
        throws IOException {
    if (domainsRoot == null || domainTmpl == null || pdpModelHandler == null
            || domainDAOClientFactory == null) {
        throw ILLEGAL_CONSTRUCTOR_ARGS_EXCEPTION;
    }

    this.domainDAOClientFactory = domainDAOClientFactory;
    this.policyDAOClientFactory = domainDAOClientFactory.getPolicyDAOClientFactory();
    this.policyVersionDAOClientFactory = policyDAOClientFactory.getVersionDAOClientFactory();

    this.uuidGen = initUUIDGenerator(useRandomAddressBasedUUID);
    this.pdpModelHandler = pdpModelHandler;

    // Validate domainsRoot arg
    if (!domainsRoot.exists()) {
        throw new IllegalArgumentException(
                "'domainsRoot' resource does not exist: " + domainsRoot.getDescription());
    }

    final String ioExMsg = "Cannot resolve 'domainsRoot' resource '" + domainsRoot.getDescription()
            + "' as a file on the file system";
    File domainsRootFile = null;
    try {
        domainsRootFile = domainsRoot.getFile();
    } catch (final IOException e) {
        throw new IllegalArgumentException(ioExMsg, e);
    }

    this.domainsRootDir = domainsRootFile.toPath();
    FlatFileDAOUtils.checkFile("File defined by SecurityDomainManager parameter 'domainsRoot'", domainsRootDir,
            true, true);

    // Validate domainTmpl directory arg
    if (!domainTmpl.exists()) {
        throw new IllegalArgumentException(
                "'domainTmpl' resource does not exist: " + domainTmpl.getDescription());
    }

    final String ioExMsg2 = "Cannot resolve 'domainTmpl' resource '" + domainTmpl.getDescription()
            + "' as a file on the file system";
    File domainTmplFile = null;
    try {
        domainTmplFile = domainTmpl.getFile();
    } catch (final IOException e) {
        throw new IllegalArgumentException(ioExMsg2, e);
    }

    this.domainTmplDirPath = domainTmplFile.toPath();
    FlatFileDAOUtils.checkFile("File defined by SecurityDomainManager parameter 'domainTmpl'",
            domainTmplDirPath, true, false);

    LOGGER.debug("Looking for domain sub-directories in directory {}", domainsRootDir);
    try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(domainsRootDir)) {
        for (final Path domainPath : dirStream) {
            LOGGER.debug("Checking domain in file {}", domainPath);
            if (!Files.isDirectory(domainPath)) {
                LOGGER.warn("Ignoring invalid domain file {} (not a directory)", domainPath);
                continue;
            }

            // domain folder name is the domain ID
            final Path lastPathSegment = domainPath.getFileName();
            if (lastPathSegment == null) {
                throw new RuntimeException("Invalid Domain folder path '" + domainPath + "': no filename");
            }

            final String domainId = lastPathSegment.toString();
            FlatFileBasedDomainDAO<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT> domainDAO = null;
            try {
                domainDAO = new FileBasedDomainDAOImpl(domainPath, null);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException("Invalid domain data for domain '" + domainId + "'", e);
            }

            final DOMAIN_DAO_CLIENT domain = domainDAOClientFactory.getInstance(domainId, domainDAO);
            domainMap.put(domainId, domain);
        }
    } catch (final IOException e) {
        throw new IOException("Failed to scan files in the domains root directory '" + domainsRootDir
                + "' looking for domain directories", e);
    }

    this.domainDirToMemSyncIntervalSec = Integer.valueOf(domainsSyncIntervalSec).longValue();
}

From source file:no.abmu.util.hibernate3.spring.ApplicationContextLoaderH3.java

public void init() {
    configFile = System.getProperty(CONFIG_FILE_KEY);
    if (applicationContext != null) {
        Map beans = applicationContext.getBeansOfType(LocalSessionFactoryBean.class);
        for (Iterator iterator = beans.values().iterator(); iterator.hasNext();) {
            LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) iterator.next();
            //                localSessionFactoryBean.dropDatabaseSchema();

            try {
                localSessionFactoryBean.destroy();
            } catch (HibernateException e) {
                throw new RuntimeException(e);
            }//from ww w. ja  v  a  2s. c  om
        }
    }
    applicationContext = null;

    Resource res = null;
    try {
        if (configFile == null) {
            throw new IllegalArgumentException("you need to set the system property " + CONFIG_FILE_KEY);
        }

        res = new FileSystemResource(configFile);
        if (!res.exists()) {
            res = new ClassPathResource(configFile);
        }
        if (!res.exists()) {
            res = new UrlResource(configFile);
        }
        if (!res.exists()) {
            throw new IllegalArgumentException("The resource " + configFile
                    + " could not be loaded as a url, classpath resource or a file");
        }
        factory = new XmlBeanFactory(res);
    } catch (Exception e) {
        logger.error("Problem when loading application context", e);

        if (!(e instanceof IllegalArgumentException)) {
            resultingException = new IllegalArgumentException("Problem creating context " + e.getMessage());
            resultingException.initCause(e);
        } else {
            resultingException = (IllegalArgumentException) e;
        }
    }

}

From source file:org.alfresco.filesys.alfresco.DesktopAction.java

/**
 * Initialize the desktop action/*from w  w w .  j a  v a 2 s .c o  m*/
 * 
 * @exception DesktopActionException
 */
public void initializeAction(ServiceRegistry serviceRegistry, AlfrescoContext filesysContext)
        throws DesktopActionException {
    this.serviceRegistry = serviceRegistry;

    // Save the filesystem device and I/O handler
    m_filesysContext = filesysContext;

    // Check for standard config values

    if (m_name == null || m_name.length() == 0)
        throw new DesktopActionException("Desktop action name not specified");

    // Get the pseudo file name
    if (m_pseudoFile == null) {
        if (m_filename == null || m_filename.length() == 0)
            throw new DesktopActionException("Desktop action pseudo name not specified");

        // Get the local path to the executable
        if (m_path == null || m_path.length() == 0) {
            m_path = m_filesysContext.getGlobalDesktopActionConfig().getPath();
        }
        if (m_path == null || m_path.length() == 0)
            throw new DesktopActionException("Desktop action executable path not specified");

        // Check that the application exists on the local filesystem

        Resource resource = new ResourceFinder().getResource(m_path);
        if (!resource.exists()) {
            throw new DesktopActionException("Failed to find drag and drop application, " + m_path);
        }

        PseudoFile pseudoFile = null;
        try {
            pseudoFile = new MemoryPseudoFile(m_filename, IOUtils.toByteArray(resource.getInputStream()));
        } catch (IOException e) {
            throw new DesktopActionException(
                    "Drag and drop application resource is invalid, " + resource.getDescription());
        }

        setPseudoFile(pseudoFile);
    }

    // Check if confirmations should be switched off for the action

    if (m_filesysContext.getGlobalDesktopActionConfig().getNoConfirm() && hasPreProcessAction(PreConfirmAction))
        setPreProcessActions(getPreProcessActions() - PreConfirmAction);

    // Check if the webapp URL has been specified

    SysAdminParams sysAdminParams = m_filesysContext.getSysAdminParams();
    if (m_webappURL == null || m_webappURL.length() == 0) {
        m_webappURL = m_filesysContext.getShareUrlPrefix();
    } else {
        // Check if the path name contains the local name token
        m_webappURL = sysAdminParams.subsituteHost(m_webappURL);

        if (!m_webappURL.endsWith("/")) {
            m_webappURL = m_webappURL + "/";
        }
    }

    // Check if debug output is enabled for the action

    if (m_filesysContext.getGlobalDesktopActionConfig().getDebug())
        setDebug(true);

    // DEBUG

    if (logger.isDebugEnabled() && hasDebug())
        logger.debug("Initialized desktop action " + getName() + ", pseudo name " + m_pseudoFile.getFileName());
}

From source file:org.alfresco.module.vti.web.actions.VtiResourceAction.java

private byte[] cacheResource(String resourceLocation, String alfrescoContext) throws IOException {
    Resource resource = applicationContext.getResource(resourceLocation);

    if (!resource.exists()) {
        if (resourceLocation.endsWith(DialogUtils.IMAGE_POSTFIX)) {
            resource = applicationContext.getResource(DialogUtils.DEFAULT_IMAGE);
        } else {/*from   w ww .ja va 2s  . co  m*/
            return null;
        }
    }

    InputStream input = resource.getInputStream();

    byte[] result = new byte[input.available()];
    input.read(result);

    try {
        resourceMapLock.writeLock().lock();
        resourcesMap.put(resourceLocation, result);
    } finally {
        resourceMapLock.writeLock().unlock();
    }

    return result;
}

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

/**
 * Replaces the dialect placeholder in the resource URL and attempts to find a file for
 * it.  If not found, the dialect hierarchy will be walked until a compatible resource is
 * found.  This makes it possible to have resources that are generic to all dialects.
 * /*from w w  w. j  a v a  2  s .  com*/
 * @return The Resource, otherwise null
 */
private Resource getDialectResource(Class<?> dialectClass, String resourceUrl) {
    // replace the dialect placeholder
    String dialectResourceUrl = resolveDialectUrl(dialectClass, resourceUrl);
    // get a handle on the resource
    Resource resource = rpr.getResource(dialectResourceUrl);
    if (!resource.exists()) {
        // it wasn't found.  Get the superclass of the dialect and try again
        Class<?> superClass = dialectClass.getSuperclass();
        if (Dialect.class.isAssignableFrom(superClass)) {
            // we still have a Dialect - try again
            return getDialectResource(superClass, resourceUrl);
        } else {
            // we have exhausted all options
            return null;
        }
    } else {
        // we have a handle to it
        return resource;
    }
}

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

/**
 * Collate differences and validation problems with the schema with respect to an appropriate
 * reference schema./* w  w  w.  ja  va2s .com*/
 * 
 * @param outputFileNameTemplate String
 * @param out PrintWriter
 * @return the number of potential problems found.
 */
public synchronized int validateSchema(String outputFileNameTemplate, PrintWriter out) {
    int totalProblems = 0;

    // Discover available reference files (e.g. for prefixes alf_, etc.)
    // and process each in turn.
    for (String schemaReferenceUrl : schemaReferenceUrls) {
        Resource referenceResource = getDialectResource(dialect.getClass(), schemaReferenceUrl);

        if (referenceResource == null || !referenceResource.exists()) {
            String resourceUrl = resolveDialectUrl(dialect.getClass(), schemaReferenceUrl);
            LogUtil.debug(logger, DEBUG_SCHEMA_COMP_NO_REF_FILE, resourceUrl);
        } else {
            // Validate schema against each reference file
            int problems = validateSchema(referenceResource, outputFileNameTemplate, out);
            totalProblems += problems;
        }
    }

    // Return number of problems found across all reference files.
    return totalProblems;
}

From source file:org.alfresco.repo.domain.schema.script.ScriptExecutorImpl.java

/**
 * Replaces the dialect placeholder in the resource URL and attempts to find a file for
 * it.  If not found, the dialect hierarchy will be walked until a compatible resource is
 * found.  This makes it possible to have resources that are generic to all dialects.
 * /*from  ww  w.j  av a 2s .  com*/
 * @return The Resource, otherwise null
 */
private Resource getDialectResource(Class dialectClass, String resourceUrl) {
    // replace the dialect placeholder
    String dialectResourceUrl = resolveDialectUrl(dialectClass, resourceUrl);
    // get a handle on the resource
    Resource resource = rpr.getResource(dialectResourceUrl);
    if (!resource.exists()) {
        // it wasn't found.  Get the superclass of the dialect and try again
        Class superClass = dialectClass.getSuperclass();
        if (Dialect.class.isAssignableFrom(superClass)) {
            // we still have a Dialect - try again
            return getDialectResource(superClass, resourceUrl);
        } else {
            // we have exhausted all options
            return null;
        }
    } else {
        // we have a handle to it
        return resource;
    }
}