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.solmix.runtime.support.spring.SpringContainerFactory.java

/**
 * @param strings/*  www . j  a  v a2 s  . com*/
 * @param includeDefaults
 * @return
 */
public Container createContainer(String[] cfgFiles, boolean includeDefaults) {
    try {
        final Resource r = ContainerApplicationContext
                .findResource(ContainerApplicationContext.DEFAULT_USER_CFG_FILE);
        boolean exists = true;
        if (r != null) {
            exists = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                @Override
                public Boolean run() {
                    return r.exists();
                }
            });
        }
        if (parent == null && includeDefaults && (r == null || !exists)) {
            return new ContainerFactoryImpl().createContainer();
        }
        ConfigurableApplicationContext cac = createApplicationContext(cfgFiles, includeDefaults, parent);
        return completeCreating(cac);
    } catch (BeansException ex) {
        throw new java.lang.RuntimeException(ex);
    }
}

From source file:org.alfresco.reporting.util.resource.HierarchicalResourceLoader.java

/**
 * Get a resource using the defined class hierarchy as a search path.
 * //from   ww w  . j av a  2 s. c  o  m
 * @param location          the location including a {@link #DEFAULT_DIALECT_PLACEHOLDER placeholder}
 * @return                  a resource found by successive searches using class name replacement, or
 *                          <tt>null</tt> if not found.
 */
@SuppressWarnings("unchecked")
@Override
public Resource getResource(String location) {
    if (dialectClass == null || dialectBaseClass == null) {
        return super.getResource(location);
    }

    // If a property value has not been substituted, extract the property name and load from system
    String dialectBaseClassStr = dialectBaseClass;
    if (!PropertyCheck.isValidPropertyString(dialectBaseClass)) {
        String prop = PropertyCheck.getPropertyName(dialectBaseClass);
        dialectBaseClassStr = System.getProperty(prop, dialectBaseClass);
    }
    String dialectClassStr = dialectClass;
    if (!PropertyCheck.isValidPropertyString(dialectClass)) {
        String prop = PropertyCheck.getPropertyName(dialectClass);
        dialectClassStr = System.getProperty(prop, dialectClass);
    }

    Class dialectBaseClazz;
    try {
        dialectBaseClazz = Class.forName(dialectBaseClassStr);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Dialect base class not found: " + dialectBaseClassStr);
    }
    Class dialectClazz;
    try {
        dialectClazz = Class.forName(dialectClassStr);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Dialect class not found: " + dialectClassStr);
    }
    // Ensure that we are dealing with classes and not interfaces
    if (!Object.class.isAssignableFrom(dialectBaseClazz)) {
        throw new RuntimeException(
                "Dialect base class must be derived from java.lang.Object: " + dialectBaseClazz.getName());
    }
    if (!Object.class.isAssignableFrom(dialectClazz)) {
        throw new RuntimeException(
                "Dialect class must be derived from java.lang.Object: " + dialectClazz.getName());
    }
    // We expect these to be in the same hierarchy
    if (!dialectBaseClazz.isAssignableFrom(dialectClazz)) {
        throw new RuntimeException("Non-existent HierarchicalResourceLoader hierarchy: "
                + dialectBaseClazz.getName() + " is not a superclass of " + dialectClazz);
    }

    Class<? extends Object> clazz = dialectClazz;
    Resource resource = null;
    while (resource == null) {
        // Do replacement
        String newLocation = location.replaceAll(DEFAULT_DIALECT_REGEX, clazz.getName());
        resource = super.getResource(newLocation);
        if (resource != null && resource.exists()) {
            // Found
            break;
        }
        // Not found
        resource = null;
        // Are we at the base class?
        if (clazz.equals(dialectBaseClazz)) {
            // We don't go any further
            break;
        }
        // Move up the hierarchy
        clazz = clazz.getSuperclass();
        if (clazz == null) {
            throw new RuntimeException("Non-existent HierarchicalResourceLoaderBean hierarchy: "
                    + dialectBaseClazz.getName() + " is not a superclass of " + dialectClazz);
        }
    }
    //System.out.println("HierarchyResourceLoader returning: " + resource.toString());
    setResourcePath(resource.toString());

    return resource;
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

/**
 * Constructor that accepts a handler factory mock for easier testing.
 *///w  ww . j a  v  a2s . c o  m
@VisibleForTesting
JobDirectoryServerServiceImpl(final ResourceLoader resourceLoader,
        final JobPersistenceService jobPersistenceService, final JobFileService jobFileService,
        final AgentFileStreamService agentFileStreamService, final MeterRegistry meterRegistry,
        final GenieResourceHandler.Factory genieResourceHandlerFactory) {

    this.resourceLoader = resourceLoader;
    this.jobPersistenceService = jobPersistenceService;
    this.jobFileService = jobFileService;
    this.agentFileStreamService = agentFileStreamService;
    this.meterRegistry = meterRegistry;
    this.genieResourceHandlerFactory = genieResourceHandlerFactory;

    // TODO: This is a local cache. It might be valuable to have a shared cluster cache?
    // TODO: May want to tweak parameters or make them configurable
    // TODO: Should we expire more proactively than just waiting for size to fill up?
    this.manifestCache = CacheBuilder.newBuilder().maximumSize(50L).recordStats()
            .build(new CacheLoader<String, ManifestCacheValue>() {
                @Override
                public ManifestCacheValue load(final String key) throws Exception {
                    // TODO: Probably need more specific exceptions so we can map them to response codes
                    final String archiveLocation = jobPersistenceService.getJobArchiveLocation(key)
                            .orElseThrow(() -> new JobNotArchivedException("Job " + key + " wasn't archived"));

                    final URI jobDirectoryRoot = new URI(archiveLocation + SLASH).normalize();

                    final URI manifestLocation;
                    if (StringUtils.isBlank(JobArchiveService.MANIFEST_DIRECTORY)) {
                        manifestLocation = jobDirectoryRoot.resolve(JobArchiveService.MANIFEST_NAME)
                                .normalize();
                    } else {
                        manifestLocation = jobDirectoryRoot
                                .resolve(JobArchiveService.MANIFEST_DIRECTORY + SLASH)
                                .resolve(JobArchiveService.MANIFEST_NAME).normalize();
                    }

                    final Resource manifestResource = resourceLoader.getResource(manifestLocation.toString());
                    if (!manifestResource.exists()) {
                        throw new GenieNotFoundException("No job manifest exists at " + manifestLocation);
                    }
                    final JobDirectoryManifest manifest = GenieObjectMapper.getMapper()
                            .readValue(manifestResource.getInputStream(), JobDirectoryManifest.class);

                    return new ManifestCacheValue(manifest, jobDirectoryRoot);
                }
            });

    // TODO: Record metrics for cache using stats() method return
}

From source file:org.openspaces.pu.container.jee.jetty.JettyJeeProcessingUnitContainerProvider.java

private Resource getJettyPuResource() {
    Resource jettyPuResource = new ClassPathResource(DEFAULT_JETTY_PU);
    if (!jettyPuResource.exists()) {
        String instanceProp = getBeanLevelProperties().getContextProperties().getProperty(JETTY_INSTANCE_PROP,
                INSTANCE_PLAIN);/*from  ww w.  ja  va  2  s  .co m*/
        String defaultLocation = System.getProperty(JETTY_LOCATION_PREFIX_SYSPROP, INTERNAL_JETTY_PU_PREFIX)
                + instanceProp + ".pu.xml";
        jettyPuResource = new ClassPathResource(defaultLocation);
        if (!jettyPuResource.exists()) {
            throw new CannotCreateContainerException("Failed to read internal pu file [" + defaultLocation
                    + "] as well as user defined [" + DEFAULT_JETTY_PU + "]");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using internal built in jetty pu.xml from [" + defaultLocation + "]");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Using user specific jetty pu.xml from [" + DEFAULT_JETTY_PU + "]");
        }
    }

    return jettyPuResource;
}

From source file:eu.dnetlib.maven.plugin.properties.WritePredefinedProjectProperties.java

/**
 * Checks whether file exists./*w w  w .  j  a va  2  s. c om*/
 * @param location
 * @return true when exists, false otherwise.
 */
protected boolean exists(String location) {
    if (StringUtils.isBlank(location)) {
        return false;
    }
    File file = new File(location);
    if (file.exists()) {
        return true;
    }
    ResourceLoader loader = new DefaultResourceLoader();
    Resource resource = loader.getResource(location);
    return resource.exists();
}

From source file:com.haulmont.cuba.desktop.theme.impl.DesktopThemeLoaderImpl.java

private void includeThemeFile(DesktopThemeImpl theme, Element element, Resource resource) throws IOException {
    String fileName = element.attributeValue("file");
    if (StringUtils.isEmpty(fileName)) {
        log.error("Missing 'file' attribute to include");
        return;//from   w w w. j av  a  2s  .  c om
    }

    Resource relativeResource = resource.createRelative(fileName);
    if (relativeResource.exists()) {
        log.info("Including theme file " + relativeResource.getURL());
        loadThemeFromXml(theme, relativeResource);
    } else {
        log.error("Resource " + fileName + " not found, ignore it");
    }
}

From source file:net.javacrumbs.springws.test.lookup.PayloadRootBasedResourceLookup.java

public Resource lookupResource(URI uri, WebServiceMessage message) throws IOException {
    QName payloadQName;/*from w  w w  . j  a  v a  2 s  .co m*/
    try {
        payloadQName = PayloadRootUtils.getPayloadRootQName(message.getPayloadSource(), TRANSFORMER_FACTORY);
    } catch (TransformerException e) {
        logger.warn("Can not resolve payload.", e);
        return null;
    } catch (XMLStreamException e) {
        logger.warn("Can not resolve payload.", e);
        return null;
    }
    String payloadName = payloadQName.getLocalPart();
    String[] expressions = getDiscriminators(payloadName);
    Document document = getXmlUtil().loadDocument(message);
    Resource resource;
    int discriminatorsCount = expressions.length;
    do {
        String resourceName = getResourceName(uri, payloadName, expressions, discriminatorsCount, document);
        logger.debug("Looking for resource " + resourceName);
        resource = getResourceLoader().getResource(resourceName);
        discriminatorsCount--;
    } while ((resource == null || !resource.exists()) && discriminatorsCount >= 0);
    if (resource != null && resource.exists()) {
        logger.debug("Found resource " + resource);
        return processResource(uri, message, resource);
    } else {
        return null;
    }
}

From source file:org.jruby.rack.mock.MockServletContext.java

public InputStream getResourceAsStream(String path) {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }//ww w . j  av a  2s  .com
    try {
        return resource.getInputStream();
    } catch (IOException ex) {
        logger.log("WARN: Couldn't open InputStream for " + resource, ex);
        return null;
    }
}

From source file:org.jruby.rack.mock.MockServletContext.java

public URL getResource(String path) throws MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }// ww w  .j ava  2  s  .c  om
    try {
        return resource.getURL();
    } catch (MalformedURLException ex) {
        throw ex;
    } catch (IOException ex) {
        logger.log("WARN: Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:org.ireland.jnetty.webapp.ServletContextImpl.java

/**
 * Returns the resource for a uripath as an input stream.
 * @see org.springframework.mock.web.MockServletContext
 *//* w  ww.  ja  va2  s .  com*/
@Override
public InputStream getResourceAsStream(String path) {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }
    try {
        return resource.getInputStream();
    } catch (IOException ex) {
        log.debug("Couldn't open InputStream for " + resource, ex);
        return null;
    }
}