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.finra.dm.dao.Log4jOverridableConfigurer.java

/**
 * Initializes Log4J from a resource location.
 *
 * @param resourceLocation the resource location.
 *
 * @return true if Log4J was initialized or false if not.
 *///  ww w  . j ava  2s  . co  m
@SuppressWarnings("PMD.SystemPrintln")
private boolean initializeLog4jFromResourceLocation(String resourceLocation) {
    // Default the return boolean to false (i.e. we didn't initialize Log4J).
    boolean isInitSuccessful = false;

    // See if an override resource location is configured.
    if (StringUtils.isNotBlank(resourceLocation)) {
        // Trim the resource location and get a handle to the resource.
        String resourceLocationTrimmed = resourceLocation.trim();
        Resource resource = applicationContext.getResource(resourceLocationTrimmed);

        // If the resource exists, then initialize Log4J with the resource.
        if (resource.exists()) {
            // Initialize Log4J from the resource location.
            // Write the "good" parameters to System.out since logging hasn't been initialized yet.
            System.out.println("Using Log4J configuration location \"" + resourceLocationTrimmed
                    + "\" and refresh interval \"" + refreshIntervalMillis + "\".");

            try {
                if (refreshIntervalMillis != 0) {
                    // Initialize with refresh interval (i.e. with Log4J's watchdog thread checking the file in the background).
                    Log4jConfigurer.initLogging(resourceLocationTrimmed, refreshIntervalMillis);
                } else {
                    // Initialize without refresh check (i.e. without Log4J's watchdog thread).
                    Log4jConfigurer.initLogging(resourceLocationTrimmed);
                }

                // Now that Logging has been initialized, log something so we know it's working.
                LOGGER.info("Logging successfully initialized.");
            } catch (FileNotFoundException ex) {
                // We shouldn't get here since we already checked if the location existed previously.
                throw new IllegalArgumentException(
                        "Invalid location configuration: \"" + resourceLocationTrimmed + "\".", ex);
            }

            // Mark that we successfully initialized Log4J.
            isInitSuccessful = true;
        }
    }

    // Return if we successfully initialized Log4J or not.
    return isInitSuccessful;
}

From source file:org.finra.herd.dao.Log4jOverridableConfigurer.java

/**
 * Initializes Log4J from a resource location.
 *
 * @param resourceLocation the resource location.
 *
 * @return true if Log4J was initialized or false if not.
 *///from  w ww  .j  a v  a2s.  co  m
// Using System.out and System.err is okay here because we need a place to output information before logging is initialized.
@SuppressWarnings("PMD.SystemPrintln")
private boolean initializeLog4jFromResourceLocation(String resourceLocation) {
    // Default the return boolean to false (i.e. we didn't initialize Log4J).
    boolean isInitSuccessful = false;

    // See if an override resource location is configured.
    if (StringUtils.isNotBlank(resourceLocation)) {
        // Trim the resource location and get a handle to the resource.
        String resourceLocationTrimmed = resourceLocation.trim();
        Resource resource = applicationContext.getResource(resourceLocationTrimmed);

        // If the resource exists, then initialize Log4J with the resource.
        if (resource.exists()) {
            // Initialize Log4J from the resource location.
            // Write the "good" parameters to System.out since logging hasn't been initialized yet.
            System.out.println("Using Log4J configuration location \"" + resourceLocationTrimmed + "\".");

            // Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file.
            loggerContext = Configurator.initialize(null, resourceLocationTrimmed);

            // For some initialization errors, a null context will be returned.
            if (loggerContext == null) {
                // We shouldn't get here since we already checked if the location existed previously.
                throw new IllegalArgumentException("Invalid configuration found at resource location: \""
                        + resourceLocationTrimmed + "\".");
            }

            // Now that Logging has been initialized, log something so we know it's working.
            // Note that it is possible that Log4J didn't initialize properly and didn't let us know. In this case, an error will be displayed on the
            // console by Log4J and the default logging level will be "error". As such, the below logging message won't be displayed.
            LOGGER.info("Logging successfully initialized.");

            // Mark that we successfully initialized Log4J - as much as we're able to.
            isInitSuccessful = true;
        }
    }

    // Return if we successfully initialized Log4J or not.
    return isInitSuccessful;
}

From source file:org.grails.gsp.GroovyPageMetaInfo.java

public Resource checkIfReloadableResourceHasChanged(final PrivilegedAction<Resource> resourceCallable) {
    Callable<Resource> checkerCallable = new Callable<Resource>() {
        public Resource call() {
            Resource resource = resourceCallable.run();
            if (resource != null && resource.exists()) {
                long currentLastmodified = establishLastModified(resource);
                // granularity is required since lastmodified information is rounded some where in copying & war (zip) file information
                // usually the lastmodified time is 1000L apart in files and in files extracted from the zip (war) file
                if (currentLastmodified > 0
                        && Math.abs(currentLastmodified - lastModified) > LASTMODIFIED_CHECK_GRANULARITY) {
                    return resource;
                }/*from   w ww .  j av a  2s  .  c o m*/
            }
            return null;
        }
    };
    return shouldReloadCacheEntry.getValue(LASTMODIFIED_CHECK_INTERVAL, checkerCallable, true, null);
}

From source file:org.grails.gsp.GroovyPageResourceLoader.java

@Override
public Resource getResource(String location) {
    Assert.hasLength(location, "Argument [location] cannot be null or blank");

    Resource resource = super.getResource(location);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolved GSP location [" + location + "] to resource [" + resource + "] (exists? ["
                + resource.exists() + "]) using base resource [" + localBaseResource + "]");
    }/*from w  ww  .  ja v  a 2  s  .co  m*/
    return resource;
}

From source file:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *///from   ww w. j  a v a  2 s  . c  o m
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    this.cause = t;
    Throwable cause = t;

    FastStringPrintWriter pw = FastStringPrintWriter.newInstance();
    cause.printStackTrace(pw);
    stackTrace = pw.toString();

    while (cause.getCause() != cause) {
        if (cause.getCause() == null) {
            break;
        }
        cause = cause.getCause();
    }

    stackTraceLines = stackTrace.split("\\n");

    if (cause instanceof MultipleCompilationErrorsException) {
        MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause;
        Object message = mcee.getErrorCollector().getErrors().iterator().next();
        if (message instanceof SyntaxErrorMessage) {
            SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
            lineNumber = sem.getCause().getLine();
            className = sem.getCause().getSourceLocator();
            sem.write(pw);
        }
    } else {
        Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace);
        Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace);
        Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace);
        try {
            if (gsp.find()) {
                className = gsp.group(2);
                lineNumber = Integer.parseInt(gsp.group(3));
                gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className;
            } else {
                if (m1.find()) {
                    do {
                        className = m1.group(1);
                        lineNumber = Integer.parseInt(m1.group(2));
                    } while (m1.find());
                } else {
                    while (m2.find()) {
                        className = m2.group(1);
                        lineNumber = Integer.parseInt(m2.group(2));
                    }
                }
            }
        } catch (NumberFormatException nfex) {
            // ignore
        }
    }

    LineNumberReader reader = null;
    try {
        checkIfSourceCodeAware(t);
        checkIfSourceCodeAware(cause);

        if (getLineNumber() > -1) {
            String fileLocation;
            String url = null;

            if (fileName != null) {
                fileLocation = fileName;
            } else {
                String urlPrefix = "";
                if (gspFile == null) {
                    fileName = className.replace('.', '/') + ".groovy";

                    GrailsApplication application = WebApplicationContextUtils
                            .getRequiredWebApplicationContext(servletContext)
                            .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
                    // @todo Refactor this to get the urlPrefix from the ArtefactHandler
                    if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) {
                        urlPrefix += "/controllers/";
                    } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) {
                        urlPrefix += "/taglib/";
                    } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) {
                        urlPrefix += "/services/";
                    }
                    url = URL_PREFIX + urlPrefix + fileName;
                } else {
                    url = gspFile;
                    GrailsApplicationAttributes attrs = null;
                    try {
                        attrs = grailsApplicationAttributesConstructor.newInstance(servletContext);
                    } catch (Exception e) {
                        ReflectionUtils.rethrowRuntimeException(e);
                    }
                    ResourceAwareTemplateEngine engine = attrs.getPagesTemplateEngine();
                    lineNumber = engine.mapStackLineNumber(url, lineNumber);
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!GrailsStringUtils.isBlank(url)) {
                in = servletContext.getResourceAsStream(url);
                LOG.debug("Attempting to display code snippet found in url " + url);
            }
            if (in == null) {
                Resource r = null;
                try {
                    r = resolver.getResource(fileLocation);
                    in = r.getInputStream();
                } catch (Throwable e) {
                    r = resolver.getResource("file:" + fileLocation);
                    if (r.exists()) {
                        try {
                            in = r.getInputStream();
                        } catch (IOException e1) {
                            // ignore
                        }
                    }
                }
            }

            if (in != null) {
                reader = new LineNumberReader(new InputStreamReader(in, "UTF-8"));
                String currentLine = reader.readLine();
                StringBuilder buf = new StringBuilder();
                while (currentLine != null) {
                    int currentLineNumber = reader.getLineNumber();
                    if ((lineNumber > 0 && currentLineNumber == lineNumber - 1)
                            || (currentLineNumber == lineNumber)) {
                        buf.append(currentLineNumber).append(": ").append(currentLine).append("\n");
                    } else if (currentLineNumber == lineNumber + 1) {
                        buf.append(currentLineNumber).append(": ").append(currentLine);
                        break;
                    }
                    currentLine = reader.readLine();
                }
                codeSnippet = buf.toString().split("\n");
            }
        }
    } catch (IOException e) {
        LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.grails.web.servlet.context.support.GrailsRuntimeConfigurator.java

protected void doPostResourceConfiguration(GrailsApplication app, RuntimeSpringConfiguration springConfig) {
    ClassLoader classLoader = app.getClassLoader();
    String resourceName = null;/* w w  w  . j  a  v  a  2s  .  c o m*/
    try {
        Resource springResources;
        if (app.isWarDeployed()) {
            resourceName = GrailsRuntimeConfigurator.SPRING_RESOURCES_XML;
            springResources = parent.getResource(resourceName);
        } else {
            resourceName = DEVELOPMENT_SPRING_RESOURCES_XML;
            ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
            springResources = patternResolver.getResource(resourceName);
        }

        if (springResources != null && springResources.exists()) {
            if (LOG.isDebugEnabled())
                LOG.debug(
                        "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL());
            DefaultListableBeanFactory xmlBf = new OptimizedAutowireCapableBeanFactory();
            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, ex);
    }

    GrailsRuntimeConfigurator.loadSpringGroovyResources(springConfig, app);
}

From source file:org.granite.grails.web.GrailsGAEWebSWFServlet.java

/**
 * Attempts to retrieve a reference to a GSP as a Spring Resource instance for the given URI.
 *
 * @param uri The URI to check/*from  w ww . ja  va2  s  . co m*/
 * @return A Resource instance
 */
@Override
public Resource getResourceForUri(String uri) {
    Resource r = getResourceWithinContext(uri);
    if (r != null && r.exists()) {
        return r;
    }

    // try plugin
    String pluginUri = GrailsResourceUtils.WEB_INF + uri;
    r = getResourceWithinContext(pluginUri);
    if (r != null && r.exists()) {
        return r;
    }

    uri = getUriWithinGrailsViews(uri);
    return getResourceWithinContext(uri);
}

From source file:org.granite.grails.web.GrailsGAEWebSWFServlet.java

private Resource getResourceWithinContext(String uri) {
    Resource r = servletContextLoader.getResource(uri);
    if (r.exists()) {
        return r;
    }/*from ww  w .  j  a v  a 2  s  .  com*/
    return resourceLoader != null ? resourceLoader.getResource(uri) : null;
}

From source file:org.granite.grails.web.GrailsWebSWFServlet.java

/**
 * Attempts to retrieve a reference to a GSP as a Spring Resource instance for the given URI.
 *
 * @param uri The URI to check//from   w ww  . jav a2s  .co m
 * @return A Resource instance
 */
public Resource getResourceForUri(String uri) {
    Resource r = getResourceWithinContext(uri);
    if (r != null && r.exists()) {
        return r;
    }

    // try plugin
    String pluginUri = GrailsResourceUtils.WEB_INF + uri;
    r = getResourceWithinContext(pluginUri);
    if (r != null && r.exists()) {
        return r;
    }

    uri = getUriWithinGrailsViews(uri);
    return getResourceWithinContext(uri);
}

From source file:org.impalaframework.config.SimplePropertiesLoader.java

protected Properties getProperties() {

    String bootstrapLocationsResource = getResourceName();

    ResourceLoader resourceLoader = getResourceLoader();
    Resource bootStrapResource = null;

    if (bootstrapLocationsResource == null) {
        bootStrapResource = resourceLoader.getResource(defaultBootstrapResource);
    } else {/*from  ww  w  .  j  a  v a  2  s .  c o  m*/
        // figure out which resource loader to use
        bootStrapResource = resourceLoader.getResource(bootstrapLocationsResource);
    }
    Properties properties = null;
    if (bootStrapResource == null || !bootStrapResource.exists()) {
        logger.info("Unable to load locations resource from " + bootstrapLocationsResource + ".");
        properties = new Properties();
    } else {
        properties = PropertyUtils.loadProperties(bootStrapResource);
    }

    return properties;
}