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.jahia.settings.SettingsBean.java

@Override
public void afterPropertiesSet() throws Exception {

    // init build number
    setBuildNumber(Jahia.getBuildNumber());

    // set maintenance mode state
    Jahia.setMaintenance(isMaintenanceMode());

    if (licenseFileLocations != null) {
        for (String location : licenseFileLocations) {
            String path = location.trim();
            if ("file:/".equals(path)) {
                continue;
            }//from  w ww .j  a  va 2 s . c  o m
            try {
                for (Resource resource : applicationContext.getResources(path)) {
                    if (resource.exists()) {
                        licenseFile = resource;
                        break;
                    }
                }
                if (licenseFile != null) {
                    break;
                }
            } catch (IOException e) {
                // ignore missing locations
            }
        }
    }
}

From source file:org.jasig.portal.portlets.portletadmin.xmlsupport.XmlChannelPublishingDefinitionDao.java

private PortletPublishingDefinition loadChannelPublishingDefinition(int channelTypeId) {
    // if the CPD is not already in the cache, determine the CPD URI
    final String cpdUri;
    if (channelTypeId >= 0) {
        final IPortletType type = this.portletTypeRegistry.getPortletType(channelTypeId);
        if (type == null) {
            throw new IllegalArgumentException("No ChannelType registered with id: " + channelTypeId);
        }/*from w  w w.j a  v a 2  s . com*/
        cpdUri = type.getCpdUri();
    } else {
        cpdUri = CUSTOM_CPD_PATH;
    }

    // read and parse the CPD
    final PortletPublishingDefinition def;
    final Resource cpdResource = this.resourceLoader.getResource("classpath:" + cpdUri);
    if (!cpdResource.exists()) {
        throw new MissingResourceException(
                "Failed to find CPD '" + cpdUri + "' for channel type " + channelTypeId,
                this.getClass().getName(), cpdUri);
    }

    final InputStream cpdStream;
    try {
        cpdStream = cpdResource.getInputStream();
    } catch (IOException e) {
        throw new MissingResourceException(
                "Failed to load CPD '" + cpdUri + "' for channel type " + channelTypeId,
                this.getClass().getName(), cpdUri);
    }

    try {
        def = (PortletPublishingDefinition) this.unmarshaller.unmarshal(cpdStream);
        final List<Step> sharedParameters = this.getSharedParameters();
        def.getSteps().addAll(sharedParameters);
        // add the CPD to the cache and return it
        this.cpdCache.put(channelTypeId, def);

        return def;
    } catch (JAXBException e) {
    } finally {
        IOUtils.closeQuietly(cpdStream);
    }

    return null;

}

From source file:org.josso.tooling.gshell.core.spring.GShellApplicationContext.java

@Override
protected Resource[] getConfigResources() {

    List<Resource> resources = new ArrayList<Resource>();

    try {/*from w  ww  . java  2  s. com*/
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                Thread.currentThread().getContextClassLoader());

        Collections.addAll(resources, resolver.getResources(DEFAULT_JOSSO_GSHELL_CFG_FILE));

    } catch (IOException ex) {
        // ignore
    }

    if (null == cfgFiles) {
        cfgFiles = new String[] { "josso-gshell.xml" };
    }

    for (String cfgFile : cfgFiles) {
        boolean found = false;
        Resource cpr = new ClassPathResource(cfgFile);
        if (!cpr.exists()) {
            try {
                //see if it's a URL
                URL url = new URL(cfgFile);
                cpr = new UrlResource(url);
                if (cpr.exists()) {
                    resources.add(cpr);
                    found = true;
                }
            } catch (MalformedURLException e) {
                //ignore
            }
            if (!found) {
                //try loading it our way
                URL url = getResource(cfgFile, this.getClass());
                if (url != null) {
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        resources.add(cpr);
                        found = true;
                    }
                }
            }
        } else {
            resources.add(cpr);
            found = true;
        }
        if (!found) {
            logger.warn("No Process Descriptor found: " + cfgFile);
        }
    }

    if (null != cfgFileURLs) {
        for (URL cfgFileURL : cfgFileURLs) {
            UrlResource ur = new UrlResource(cfgFileURL);
            if (ur.exists()) {
                resources.add(ur);
            } else {
                logger.warn("No Process Descriptor found: " + cfgFileURL);
            }
        }
    }

    logger.info("Creating application context with resources: " + resources);

    if (0 == resources.size()) {
        return null;
    }

    Resource[] res = new Resource[resources.size()];
    res = resources.toArray(res);
    return res;
}

From source file:org.jzkit.search.util.RecordConversion.XSLFragmentTransformer.java

private void reloadStylesheet() throws javax.xml.transform.TransformerConfigurationException {
    log.debug("XSLFragmentTransformer::reloadStylesheet()");
    try {/*ww w  .  ja v a  2 s .  c  o m*/
        TransformerFactory tFactory = TransformerFactory.newInstance();
        if (ctx == null)
            throw new RuntimeException("Application Context Is Null. Cannot resolve resources");

        org.springframework.core.io.Resource r = ctx.getResource(the_path);
        if ((r != null) && (r.exists())) {
            URL path_url = r.getURL();
            URLConnection conn = path_url.openConnection();
            datestamp = conn.getDate();
            log.debug("get template for " + the_path + " url:" + path_url + " datestamp=" + datestamp);
            t = tFactory.newTemplates(new javax.xml.transform.stream.StreamSource(conn.getInputStream()));
        } else {
            log.error("Unable to resolve URL for " + the_path);
        }
    } catch (java.io.IOException ioe) {
        log.warn("Problem with XSL mapping", ioe);
        throw new RuntimeException("Unable to locate mapping: " + the_path);
    } catch (javax.xml.transform.TransformerConfigurationException tce) {
        log.warn("Problem with XSL mapping", tce);
        throw (tce);
    }

}

From source file:org.kuali.rice.core.api.util.RiceUtilities.java

/**
 * Attempts to retrieve the resource stream.
 * /*  www .  ja v a  2  s . c  o  m*/
 * @param resourceLoc resource location; syntax supported by {@link DefaultResourceLoader} 
 * @return the resource stream or null if the resource could not be obtained
 * @throws MalformedURLException
 * @throws IOException
 * @see DefaultResourceLoader
 */
public static InputStream getResourceAsStream(String resourceLoc) throws MalformedURLException, IOException {
    Resource resource = getResource(resourceLoc);
    if (resource.exists()) {
        return resource.getInputStream();
    }
    return null;
}

From source file:org.kuali.rice.krad.datadictionary.DataDictionary.java

/**
 * Processes a given source for XML files to populate the dictionary with
 *
 * @param namespaceCode - namespace the beans loaded from the location should be associated with
 * @param sourceName - a file system or classpath resource locator
 * @throws IOException//  www .j  a  v a  2  s. co m
 */
protected void indexSource(String namespaceCode, String sourceName) throws IOException {
    if (sourceName == null) {
        throw new DataDictionaryException("Source Name given is null");
    }

    if (!sourceName.endsWith(".xml")) {
        Resource resource = getFileResource(sourceName);
        if (resource.exists()) {
            try {
                indexSource(namespaceCode, resource.getFile());
            } catch (IOException e) {
                // ignore resources that exist and cause an error here
                // they may be directories resident in jar files
                LOG.debug("Skipped existing resource without absolute file path");
            }
        } else {
            LOG.warn("Could not find " + sourceName);
            throw new DataDictionaryException("DD Resource " + sourceName + " not found");
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("adding sourceName " + sourceName + " ");
        }

        Resource resource = getFileResource(sourceName);
        if (!resource.exists()) {
            throw new DataDictionaryException("DD Resource " + sourceName + " not found");
        }

        addModuleDictionaryFile(namespaceCode, sourceName);
    }
}

From source file:org.kuali.rice.test.RiceTestCase.java

/**
 * configures logging using custom properties file if specified, or the default one.
 * Log4j also uses any file called log4.properties in the classpath
 *
 * <p>To configure a custom logging file, set a JVM system property on using -D. For example
 * -Dalt.log4j.config.location=file:/home/me/kuali/test/dev/log4j.properties
 * </p>/*from   w w w . j  a v a  2  s. c om*/
 *
 * <p>The above option can also be set in the run configuration for the unit test in the IDE.
 * To avoid log4j using files called log4j.properties that are defined in the classpath, add the following system property:
 * -Dlog4j.defaultInitOverride=true
 * </p>
 * @throws IOException
 */
protected void configureLogging() throws IOException {
    ResourceLoader resourceLoader = new FileSystemResourceLoader();
    String altLog4jConfigLocation = System.getProperty(ALT_LOG4J_CONFIG_LOCATION_PROP);
    Resource log4jConfigResource = null;
    if (!StringUtils.isEmpty(altLog4jConfigLocation)) {
        log4jConfigResource = resourceLoader.getResource(altLog4jConfigLocation);
    }
    if (log4jConfigResource == null || !log4jConfigResource.exists()) {
        System.out.println("Alternate Log4j config resource does not exist! " + altLog4jConfigLocation);
        System.out.println("Using default log4j configuration: " + DEFAULT_LOG4J_CONFIG);
        log4jConfigResource = resourceLoader.getResource(DEFAULT_LOG4J_CONFIG);
    } else {
        System.out.println("Using alternate log4j configuration at: " + altLog4jConfigLocation);
    }
    Properties p = new Properties();
    p.load(log4jConfigResource.getInputStream());
    PropertyConfigurator.configure(p);
}

From source file:org.lightadmin.core.config.LightAdminWebApplicationInitializer.java

private ResourceServlet logoResourceServlet(ServletContext servletContext) {
    Resource resource = servletContextResourceLoader(servletContext)
            .getResource(LIGHT_ADMIN_CUSTOM_LOGO_LOCATION);
    if (resource.exists()) {
        return concreteResourceServlet(LIGHT_ADMIN_CUSTOM_LOGO_LOCATION);
    }/*  w  w  w .  j ava2 s .  c  om*/
    return concreteResourceServlet(resourceServletMapping(servletContext, LIGHT_ADMIN_DEFAULT_LOGO_LOCATION));
}

From source file:org.mifos.config.business.MifosConfigurationManager.java

private MifosConfigurationManager() {
    String defaultConfig = "org/mifos/config/resources/applicationConfiguration.default.properties";
    Properties props = new Properties();
    try {//from www . java  2  s .  c om
        InputStream applicationConfig = MifosResourceUtil.getClassPathResourceAsStream(defaultConfig);
        props.load(applicationConfig);

        ConfigurationLocator configurationLocator = new ConfigurationLocator();
        Resource customApplicationConfig = configurationLocator.getResource(CUSTOM_CONFIG_PROPS_FILENAME);
        if (customApplicationConfig.exists()) {
            InputStream is = customApplicationConfig.getInputStream();
            props.load(is);
            is.close();
        }
        LOGGER.info(
                "Dump of all configuration properties read by MifosConfigurationManager: " + props.toString());
    } catch (IOException e) {
        throw new MifosRuntimeException(e);
    }
    configuration = ConfigurationConverter.getConfiguration(props);
}

From source file:org.mifos.framework.util.ConfigurationLocator.java

/**
 * Will not throw an exception if the file is not found. This method may be
 * used to find files in cases where we don't care if the file cannot be
 * found.//from   w  ww . j  a  v a2s .  c o m
 * @throws IOException
 */
@SuppressWarnings("PMD")
// TODO It may be clearer if this returned an URI or URL instead of a String?
public String getCustomFilePath(String filename) throws IOException {
    String returnValue = filename;
    LOGGER.info("Checking existance of : " + filename);
    Resource configFile = getResource(filename);
    if (configFile != null && configFile.exists()) {
        returnValue = configFile.getURL().toExternalForm();
        LOGGER.info("Custom configuration file exists : " + returnValue);
    }
    return returnValue;
}