Example usage for org.springframework.core.io Resource getDescription

List of usage examples for org.springframework.core.io Resource getDescription

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getDescription.

Prototype

String getDescription();

Source Link

Document

Return a description for this resource, to be used for error output when working with the resource.

Usage

From source file:org.broadleafcommerce.common.resource.service.ResourceBundlingServiceImpl.java

protected void saveBundle(Resource resource) {
    FileWorkArea tempWorkArea = fileService.initializeWorkArea();
    String fileToSave = FilenameUtils.separatorsToSystem(getResourcePath(resource.getDescription()));
    String tempFilename = FilenameUtils.concat(tempWorkArea.getFilePathLocation(), fileToSave);
    File tempFile = new File(tempFilename);
    if (!tempFile.getParentFile().exists()) {
        if (!tempFile.getParentFile().mkdirs()) {
            if (!tempFile.getParentFile().exists()) {
                throw new RuntimeException("Unable to create parent directories for file: " + tempFilename);
            }//ww  w.  j a  v  a2 s.  c  o m
        }
    }

    BufferedOutputStream out = null;
    InputStream ris = null;
    try {
        ris = resource.getInputStream();
        out = new BufferedOutputStream(new FileOutputStream(tempFile));
        StreamUtils.copy(ris, out);

        ris.close();
        out.close();

        fileService.addOrUpdateResourceForPath(tempWorkArea, tempFile, true);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(ris);
        IOUtils.closeQuietly(out);
        fileService.closeWorkArea(tempWorkArea);
    }
}

From source file:org.codehaus.groovy.grails.support.MockApplicationContext.java

public Resource[] getResources(String locationPattern) throws IOException {
    if (locationPattern.startsWith("classpath:") || locationPattern.startsWith("file:")) {
        throw new UnsupportedOperationException(
                "Location patterns 'classpath:' and 'file:' not supported by implementation");
    }//w  w  w .  j  av a2s.  c  o m

    locationPattern = StringUtils.removeStart(locationPattern, "/"); // starting with "**/" is OK
    List<Resource> result = new ArrayList<Resource>();
    for (Resource res : resources) {
        String path = res instanceof ClassPathResource ? ((ClassPathResource) res).getPath()
                : res.getDescription();
        if (pathMatcher.match(locationPattern, path)) {
            result.add(res);
        }
    }
    return result.toArray(new Resource[0]);
}

From source file:org.codehaus.groovy.grails.support.MockApplicationContext.java

public Resource getResource(String location) {
    for (Resource mockResource : resources) {
        if (pathMatcher.match(mockResource.getDescription(), StringUtils.removeStart(location, "/"))) {
            return mockResource;
        }//from w  w  w  .j  a va  2  s. c o m
    }
    // Check for ignored resources and return null instead of a classpath resource in that case.
    for (String resourceLocation : ignoredClassLocations) {
        if (pathMatcher.match(StringUtils.removeStart(location, "/"),
                StringUtils.removeStart(resourceLocation, "/"))) {
            return null;
        }
    }

    return new ClassPathResource(location);
}

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

/**
 * Constructs a GroovyPageMetaInfo instance which holds the script class, modified date and so on
 *
 * @param inputStream The InputStream to construct the GroovyPageMetaInfo instance from
 * @param res The Spring Resource to construct the MetaInfo from
 * @param pageName The name of the page (can be null, in which case method responsible for calculating appropriate alternative)
 * @return The GroovyPageMetaInfo instance
 *///w  ww  .ja  v  a2 s.c o m
protected GroovyPageMetaInfo buildPageMetaInfo(InputStream inputStream, Resource res, String pageName) {
    String name = establishPageName(res, pageName);

    GroovyPageParser parser;
    String path = getPathForResource(res);
    try {
        parser = new GroovyPageParser(name, path, path, inputStream, null, null);

        if (grailsApplication != null) {
            Map<String, Object> config = grailsApplication.getFlatConfig();

            Object keepDirObj = config.get(GroovyPageParser.CONFIG_PROPERTY_GSP_KEEPGENERATED_DIR);
            if (keepDirObj instanceof File) {
                parser.setKeepGeneratedDirectory((File) keepDirObj);
            } else if (keepDirObj != null) {
                parser.setKeepGeneratedDirectory(new File(String.valueOf(keepDirObj)));
            }
        }
    } catch (IOException e) {
        throw new GroovyPagesException("I/O parsing Groovy page [" + (res != null ? res.getDescription() : name)
                + "]: " + e.getMessage(), e);
    }

    InputStream in = parser.parse();

    // Make a new metaInfo
    GroovyPageMetaInfo metaInfo = createPageMetaInfo(parser, in);
    metaInfo.applyLastModifiedFromResource(res);
    try {
        metaInfo.setPageClass(compileGroovyPage(in, name, path, metaInfo));
        metaInfo.setHtmlParts(parser.getHtmlPartsArray());
    } catch (GroovyPagesException e) {
        metaInfo.setCompilationException(e);
    }

    if (!name.startsWith(GENERATED_GSP_NAME_PREFIX)) {
        pageCache.put(name, metaInfo);
    }

    return metaInfo;
}

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

private String getPathForResource(Resource res) {
    if (res == null)
        return "";

    String path = null;//  w ww. j  av  a 2s .c om
    try {
        File file = res.getFile();
        if (file != null) {
            path = file.getAbsolutePath();
        }
    } catch (IOException e) {
        // ignore
    }
    if (path != null) {
        return path;
    }
    if (res.getDescription() != null) {
        return res.getDescription();
    }
    return "";
}

From source file:org.craftercms.commons.mongo.MongoScriptRunner.java

private void runScript(DB db, Resource scriptPath) throws MongoDataException {
    String script;/* w  w w. j  a va  2  s  .c o m*/
    try {
        if (scriptPath.getFile().isDirectory()) {
            final File[] files = scriptPath.getFile().listFiles(new FilenameFilter() {
                @Override
                public boolean accept(final File dir, final String name) {
                    return name.toLowerCase().endsWith(".js");
                }
            });
            List<File> orderFiles = Arrays.asList(files);
            Collections.sort(orderFiles, new Comparator<File>() {
                @Override
                public int compare(final File o1, final File o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            logger.debug("Directory {} files to exec {}", scriptPath.getFile(), orderFiles);
            for (File file : orderFiles) {
                runScript(db, new FileSystemResource(file.getPath()));
            }
        } else {
            logger.debug("Running Script {}", scriptPath.getURI());
            try {
                script = IOUtils.toString(scriptPath.getInputStream(), "UTF-8");
            } catch (IOException e) {
                throw new MongoDataException("Unable to read script at " + scriptPath.getURI().toString());
            }

            CommandResult result = db.doEval(script);
            if (!result.ok()) {
                Exception ex = result.getException();

                throw new MongoDataException(
                        "An error occurred while running script at " + scriptPath.getURI().toString(), ex);

            }
            logger.info("Mongo script at {} executed successfully", scriptPath.getDescription());
        }
    } catch (IOException ex) {
        logger.error("Unable to read files from {}", ex);
    }
}

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

/**
 * Constructs a GroovyPageMetaInfo instance which holds the script class, modified date and so on
 *
 * @param inputStream The InputStream to construct the GroovyPageMetaInfo instance from
 * @param res The Spring Resource to construct the MetaInfo from
 * @param pageName The name of the page (can be null, in which case method responsible for calculating appropriate alternative)
 * @return The GroovyPageMetaInfo instance
 */// ww w . ja v a  2 s .c om
protected GroovyPageMetaInfo buildPageMetaInfo(InputStream inputStream, Resource res, String pageName) {
    String name = establishPageName(res, pageName);

    GroovyPageParser parser;
    String path = getPathForResource(res);
    try {
        String gspSource = IOUtils.toString(inputStream, GroovyPageParser.getGspEncoding());
        parser = new GroovyPageParser(name, path, path,
                decorateGroovyPageSource(new StringBuilder(gspSource)).toString());

        if (grailsApplication != null) {
            Config config = grailsApplication.getConfig();

            Object keepDirObj = config.getProperty(GroovyPageParser.CONFIG_PROPERTY_GSP_KEEPGENERATED_DIR,
                    Object.class);
            if (keepDirObj instanceof File) {
                parser.setKeepGeneratedDirectory((File) keepDirObj);
            } else if (keepDirObj != null) {
                parser.setKeepGeneratedDirectory(new File(String.valueOf(keepDirObj)));
            }
        }
    } catch (IOException e) {
        throw new GroovyPagesException("I/O parsing Groovy page [" + (res != null ? res.getDescription() : name)
                + "]: " + e.getMessage(), e);
    }

    InputStream in = parser.parse();

    // Make a new metaInfo
    GroovyPageMetaInfo metaInfo = createPageMetaInfo(parser, in);
    metaInfo.applyLastModifiedFromResource(res);
    try {
        metaInfo.setPageClass(compileGroovyPage(in, name, path, metaInfo));
        metaInfo.setHtmlParts(parser.getHtmlPartsArray());
    } catch (GroovyPagesException e) {
        metaInfo.setCompilationException(e);
    }

    return metaInfo;
}

From source file:org.grails.web.pages.GroovyPagesTemplateEngine.java

/**
 * Constructs a GroovyPageMetaInfo instance which holds the script class, modified date and so on
 *
 * @param inputStream The InputStream to construct the GroovyPageMetaInfo instance from
 * @param res The Spring Resource to construct the MetaInfo from
 * @param pageName The name of the page (can be null, in which case method responsible for calculating appropriate alternative)
 * @return The GroovyPageMetaInfo instance
 *///  ww w .j  a  v a  2 s  .  c  o m
protected GroovyPageMetaInfo buildPageMetaInfo(InputStream inputStream, Resource res, String pageName) {
    String name = establishPageName(res, pageName);

    GroovyPageParser parser;
    String path = getPathForResource(res);
    try {
        parser = new GroovyPageParser(name, path, path, inputStream, null, null);

        if (grailsApplication != null) {
            Map<String, Object> config = grailsApplication.getFlatConfig();

            Object keepDirObj = config.get(GroovyPageParser.CONFIG_PROPERTY_GSP_KEEPGENERATED_DIR);
            if (keepDirObj instanceof File) {
                parser.setKeepGeneratedDirectory((File) keepDirObj);
            } else if (keepDirObj != null) {
                parser.setKeepGeneratedDirectory(new File(String.valueOf(keepDirObj)));
            }
        }
    } catch (IOException e) {
        throw new GroovyPagesException("I/O parsing Groovy page [" + (res != null ? res.getDescription() : name)
                + "]: " + e.getMessage(), e);
    }

    InputStream in = parser.parse();

    // Make a new metaInfo
    GroovyPageMetaInfo metaInfo = createPageMetaInfo(parser, in);
    metaInfo.applyLastModifiedFromResource(res);
    try {
        metaInfo.setPageClass(compileGroovyPage(in, name, path, metaInfo));
        metaInfo.setHtmlParts(parser.getHtmlPartsArray());
    } catch (GroovyPagesException e) {
        metaInfo.setCompilationException(e);
    }

    return metaInfo;
}

From source file:org.impalaframework.module.source.BaseInternalModuleDefinitionSource.java

URL getResourceForModule(String moduleName, String resourceName) {
    URL resource = ModuleResourceUtils.loadModuleResource(moduleLocationResolver, moduleName, resourceName);

    if (resource == null) {
        final List<Resource> classLocations = moduleLocationResolver
                .getApplicationModuleClassLocations(moduleName);

        logger.error("Problem locating resources for module: " + moduleName + ". Locations being searched are "
                + (classLocations.isEmpty() ? "empty" : "listed next:"));
        for (Resource classLocation : classLocations) {
            logger.error(classLocation.getDescription()
                    + (classLocation.exists() ? ": is present on file system" : " cannot be found"));
        }/*www.j a v a2 s. com*/

        throw new ConfigurationException("Application is using internally defined module structure, but no "
                + MODULE_PROPERTIES + " file is present on the classpath for module '" + moduleName
                + "'. It must exist in one of the following locations: " + classLocations);
    }
    return resource;
}

From source file:org.impalaframework.spring.bean.OptionalPropertiesFactoryBean.java

@Override
public void setLocations(Resource[] locations) {
    List<Resource> resources = new ArrayList<Resource>();
    for (int i = 0; i < locations.length; i++) {
        final Resource resource = locations[i];
        if (resource.exists()) {
            resources.add(resource);/*from ww w  .  ja  va  2  s.c  o  m*/
            if (logger.isDebugEnabled())
                logger.debug("Extracting properties from resource " + resource.getDescription());
        } else {
            logger.info("Not extracting properties from resource " + resource.getDescription()
                    + " as this resource does not exist");
        }
    }
    Resource[] existingArray = new Resource[resources.size()];
    resources.toArray(existingArray);
    super.setLocations(existingArray);
}