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.broadleafcommerce.common.web.resource.resolver.BundleResourceResolver.java

@Override
protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath,
        List<? extends Resource> locations, ResourceResolverChain chain) {

    if (requestPath != null) {
        if (isBundleFile(requestPath)) {
            Resource bundle = bundlingService.resolveBundleResource(requestPath);

            logTraceInformation(bundle);
            if (bundle != null && bundle.exists()) {
                return bundle;
            }//from  ww w. j a v  a  2s .  co m
        }
    }

    return chain.resolveResource(request, requestPath, locations);
}

From source file:org.broadleafcommerce.common.web.resource.resolver.BundleResourceResolver.java

protected void logTraceInformation(Resource bundle) {
    if (LOG.isTraceEnabled()) {
        if (bundle == null) {
            LOG.trace("Resolving bundle, bundle is null");
        } else {/*from   w  ww .ja v a2 s  . co m*/
            LOG.trace("Resolving bundle, bundle is not null, bundle.exists() == " + bundle.exists()
                    + " ,filename = " + bundle.getFilename());
            try {
                LOG.trace("Resolving bundle - File Path" + bundle.getFile().getAbsolutePath());
            } catch (IOException e) {
                LOG.error("IOException debugging bundle code", e);
            }
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.test.TestProfileEnvironment.java

private TestProfileEnvironment() {

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

    for (String location : DEFAULT_PROFILE_CONFIG_FILE_LOCATIONS) {
        location = environment.resolvePlaceholders(location);
        Resource resource = recourceLoader.getResource(location);
        if (resource != null && resource.exists()) {
            resources.add(resource);/*from   w w  w  .  j  av a2 s .  co m*/
        }
    }

    YamlMapFactoryBean factory = new YamlMapFactoryBean();
    factory.setResources(resources.toArray(new Resource[resources.size()]));
    factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);
    Map<String, Object> properties = factory.getObject();

    logger.debug("Decoding environment properties: " + properties.size());
    if (!properties.isEmpty()) {
        for (String name : properties.keySet()) {
            Object value = properties.get(name);
            if (value instanceof String) {
                properties.put(name, environment.resolvePlaceholders((String) value));
            }
        }
        if (properties.containsKey("spring_profiles")) {
            properties.put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
                    properties.get("spring_profiles"));
        }
        // System properties should override the ones in the config file, so
        // add it last
        environment.getPropertySources().addLast(new NestedMapPropertySource("uaa.yml", properties));
    }

    EnvironmentMapFactoryBean environmentProperties = new EnvironmentMapFactoryBean();
    environmentProperties.setEnvironment(environment);
    environmentProperties.setDefaultProperties(properties);
    Map<String, ?> debugProperties = environmentProperties.getObject();
    logger.debug("Environment properties: " + debugProperties);
}

From source file:org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.java

private void doPostResourceConfiguration(GrailsApplication app, RuntimeSpringConfiguration springConfig) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String resourceName = null;// ww w. ja v  a  2  s  .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 DefaultListableBeanFactory();
            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.codehaus.groovy.grails.scaffolding.TemplateGeneratingResponseHandler.java

/**
 * Either delegates to a pre-existing view or renders an in-memory scaffolded view to the response
 *
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @param actionName The name of the action to handle
 * @param model The View model//from ww w .j a v  a2s  .  c o  m
 * @return A Spring ModelAndView instance
 */
public ModelAndView handleResponse(HttpServletRequest request, HttpServletResponse response, String actionName,
        Map model) {

    if (templateGenerator == null)
        throw new IllegalStateException("Property [templateGenerator] must be set!");
    if (resolver == null)
        throw new IllegalStateException("Property [resolver] must be set!");
    if (scaffoldedClass == null)
        throw new IllegalStateException("Property [scaffoldedClass] must be set!");
    if (grailsApplication == null)
        throw new IllegalStateException("Property [grailsApplication] must be set!");

    GrailsDomainClass domainClass = (GrailsDomainClass) grailsApplication
            .getArtefact(DomainClassArtefactHandler.TYPE, scaffoldedClass.getName());
    GrailsControllerClass controllerClass = grailsApplication.getScaffoldingController(domainClass);
    String uri = controllerClass.getViewByName(actionName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Scaffolding response for view URI: " + uri);
    }

    try {
        // if the view exists physically then fall back to delegating to the physical view
        View v = resolver.resolveViewName(uri, RequestContextUtils.getLocale(request));
        if (v instanceof AbstractUrlBasedView) {

            uri = ((AbstractUrlBasedView) v).getUrl();
            Resource r = null;
            if (uri.endsWith(GroovyPage.EXTENSION)) {
                GroovyPagesTemplateEngine templateEngine = getTemplateEngine();
                r = templateEngine.getResourceForUri(uri);
            }

            if (r != null && r.exists()) {
                return new ModelAndView(v, model);
            } else {
                return createScaffoldedResponse(uri, model, actionName);
            }
        } else {
            return createScaffoldedResponse(uri, model, actionName);
        }

    } catch (Exception e) {
        throw new ScaffoldingException(
                "Unable to render scaffolded view for uri [" + uri + "]:" + e.getMessage(), e);
    }
}

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

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *//*w  w  w.  j a  v a2s .c  om*/
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    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 = new DefaultGrailsApplicationAttributes(servletContext);
                    GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
                    int[] lineNumbers = engine.calculateLineNumbersForPage(servletContext, url);
                    if (lineNumber < lineNumbers.length) {
                        lineNumber = lineNumbers[lineNumber - 1];
                    }
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!StringUtils.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));
                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.codehaus.groovy.grails.web.pages.discovery.DefaultGroovyPageLocator.java

protected Resource findResource(List<String> searchPaths) {
    Resource foundResource = null;
    Resource resource;
    for (ResourceLoader loader : resourceLoaders) {
        for (String path : searchPaths) {
            resource = loader.getResource(path);
            if (resource != null && resource.exists()) {
                foundResource = resource;
                break;
            }/*from   www  .  j  a v  a2 s.  co m*/
        }
        if (foundResource != null)
            break;
    }
    return foundResource;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageMetaInfo.java

public Resource checkIfReloadableResourceHasChanged(final PrivilegedAction<Resource> resourceCallable) {
    PrivilegedAction<Resource> checkerCallable = new PrivilegedAction<Resource>() {
        public Resource run() {
            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   ww  w. j  a va 2 s .  c  o m
            }
            return null;
        }
    };
    return shouldReloadCacheEntry.getValue(LASTMODIFIED_CHECK_INTERVAL, checkerCallable);
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader.java

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

    // deal with plug-in resolving
    if (location.startsWith(PLUGINS_PATH)) {
        Assert.state(pluginSettings != null, "'pluginsettings' has not been initialised.");
        List<String> pluginBaseDirectories = pluginSettings.getPluginBaseDirectories();
        DefaultGroovyPageLocator.PluginViewPathInfo pluginViewPathInfo = DefaultGroovyPageLocator
                .getPluginViewPathInfo(location);
        String path = pluginViewPathInfo.basePath;
        String pluginName = pluginViewPathInfo.pluginName;
        String pathRelativeToPlugin = pluginViewPathInfo.path;

        for (String pluginBaseDirectory : pluginBaseDirectories) {
            String pathToResource = pluginBaseDirectory + File.separatorChar + path;
            Resource r = super.getResource("file:" + pathToResource);
            if (r.exists()) {
                return r;
            }//  w ww. j  a  v a 2s  . c  o  m

            pathToResource = buildPluginViewPath(pluginBaseDirectory, pluginName, pathRelativeToPlugin);
            r = super.getResource(pathToResource);
            if (r.exists())
                return r;
        }

        Resource r = findInInlinePlugin(pluginName, pathRelativeToPlugin);
        if (r != null && r.exists()) {
            return r;
        }
    }

    Resource resource = super.getResource(location);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolved GSP location [" + location + "] to resource [" + resource + "] (exists? ["
                + resource.exists() + "]) using base resource [" + localBaseResource + "]");
    }
    return resource;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader.java

protected Resource findInInlinePlugin(String pluginFullName, String pathRelativeToPlugin) {
    // find plugins between all available
    for (GrailsPluginInfo pluginInfo : pluginSettings.getSupportedPluginInfos()) {
        if (pluginInfo.getFullName().equals(pluginFullName)) {
            try {
                // find out whether plugin is inline one
                if (!isInlinePlugin(pluginInfo)) {
                    // plugin is not inline one, return null
                    return null;
                }/*from   w  w w.  j  ava  2 s  .  c om*/
                File pluginDir = pluginInfo.getPluginDir().getFile();
                File pageFile = new File(pluginDir, pathRelativeToPlugin);
                if (pageFile.exists()) {
                    return new FileSystemResource(pageFile);
                }

                String pathToInlinePluginView = buildPluginViewPathFromBase(pluginDir.getAbsolutePath(),
                        pathRelativeToPlugin, new StringBuilder("file:"));
                Resource resource = super.getResource(pathToInlinePluginView);
                if (resource.exists()) {
                    return resource;
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return null;
}