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

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

Introduction

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

Prototype

Resource createRelative(String relativePath) throws IOException;

Source Link

Document

Create a resource relative to this resource.

Usage

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private Document parseXML(Resource resource, List<Rule> rules)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    debug("Now loading " + resource);

    try (InputStream in = resource.getInputStream()) {
        final Document doc = XMLRewrite.parseXML(in);
        rewriteXML(doc, rules, false, false);

        final List<Node> importNodes = evaluateXPath("/beans//import", doc);
        debug("Found " + importNodes.size() + " import statements");
        for (Node importNode : importNodes) {
            debug("(1) Node has parent: " + importNode.getParentNode());
            String path = importNode.getAttributes().getNamedItem("resource").getNodeValue();
            if (path.startsWith("classpath:")) {
                path = path.substring("classpath:".length());
            }//from  w  ww  .j  a  v  a  2  s  .  co m
            debug("Including '" + path + "' , now at " + resource);
            final Resource imported;
            if (path.startsWith("/")) { // absolute
                imported = new ClassPathResource(path);
            } else {
                imported = resource.createRelative(path);
            }
            final Document importedXML = parseXML(imported, rules);
            mergeAttributes(importedXML.getFirstChild(), doc.getFirstChild(), doc);

            final List<Node> beans = wrapNodeList(importedXML.getFirstChild().getChildNodes());

            for (Node beanNode : beans) {
                final Node adoptedNode = doc.adoptNode(beanNode.cloneNode(true));
                importNode.getParentNode().insertBefore(adoptedNode, importNode);
            }
            importNode.getParentNode().removeChild(importNode);
        }
        debug("*** return ***");
        return doc;
    } catch (Exception e) {
        throw new RuntimeException("Failed to load XML from '" + resource + "'", e);
    }
}

From source file:com.wavemaker.tools.project.upgrade.six_dot_four.RemoveMySQLHBMCatalogUpgradeTask.java

@Override
public void doUpgrade(Project project, UpgradeInfo upgradeInfo) {
    Folder servicesFolder = project.getRootFolder().getFolder("services");
    // Don't bother if we do not have services
    try {//from   www  .ja  va 2s .c  om
        if (servicesFolder.exists()) {
            Resource servicesDir = project.getProjectRoot().createRelative("services/");
            ArrayList<String> mySQLServices = new ArrayList<String>();
            try {
                // Find MySQL Services
                IOFileFilter propFilter = FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(),
                        FileFilterUtils.suffixFileFilter("properties"));
                List<File> propFiles = new UpgradeFileFinder(propFilter).findFiles(servicesDir.getFile());
                Iterator<File> propIt = propFiles.iterator();
                while (propIt.hasNext()) {
                    File propFile = propIt.next();
                    String propContent = FileUtils.readFileToString(propFile);
                    if (propContent.contains(mySQLStr)) {
                        String propFileName = propFile.getName();
                        int index = propFileName.lastIndexOf(".");
                        if (index > 0 && index <= propFileName.length()) {
                            mySQLServices.add(propFileName.substring(0, index));
                        }
                    }
                }
                // Find HBM files in MySQLServices
                Iterator<String> servIt = mySQLServices.iterator();
                while (servIt.hasNext()) {
                    IOFileFilter hbmFilter = FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(),
                            FileFilterUtils.suffixFileFilter("hbm.xml"));
                    String path = servIt.next();
                    Resource mySQLServiceDir = servicesDir
                            .createRelative(path.endsWith("/") ? path : path + "/");
                    List<File> hbmFiles = new UpgradeFileFinder(hbmFilter).findFiles(mySQLServiceDir.getFile());
                    Iterator<File> hbmIt = hbmFiles.iterator();
                    while (hbmIt.hasNext()) {
                        File hbmFile = hbmIt.next();
                        String hbmContent = FileUtils.readFileToString(hbmFile);
                        hbmContent.replaceFirst(catalogStr, replaceStr);
                        FileUtils.writeStringToFile(hbmFile, hbmContent);
                        System.out
                                .println("Project upgrade: Catalog removed from " + hbmFile.getAbsolutePath());
                    }
                }
                if (!mySQLServices.isEmpty()) {
                    upgradeInfo.addMessage("\nMySQL Catalog upgrade task completed. See wm.log for details");
                } else {
                    System.out.println("Project Upgrade: No MySQL Services found");
                }
            } catch (IOException ioe) {
                upgradeInfo
                        .addMessage("\nError removing Catalog from MySQL Services. Check wm.log for details.");
                ioe.printStackTrace();
            }
        } else {
            System.out.println("Project Upgrade: No Services found");
        }
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }
}

From source file:org.opennms.ng.dao.support.PropertiesGraphDao.java

/**
 * Create a PrefabGraphTypeDao from the properties file in sourceResource
 * If reloadable is true, add the type's reload call back to each graph,
 * otherwise don't If sourceResource is not a file-based resource, then
 * reloadable should be false NB: I didn't want to get into checking for
 * what the implementation class of Resource is, because that could break
 * in future with new classes and types that do have a File underneath
 * them. This way, it's up to the caller, who *should* be able to make a
 * sensible choice as to whether the resource is reloadable or not.
 *
 * @param type/*ww w .  j  a v  a  2s . c  o  m*/
 * @param sourceResource
 * @param reloadable
 * @return
 */
private PrefabGraphTypeDao createPrefabGraphType(String type, Resource sourceResource, boolean reloadable) {
    InputStream in = null;
    try {
        in = sourceResource.getInputStream();
        Properties properties = new Properties();
        properties.load(in);
        PrefabGraphTypeDao t = new PrefabGraphTypeDao();
        t.setName(type);

        t.setCommandPrefix(getProperty(properties, "command.prefix"));
        t.setOutputMimeType(getProperty(properties, "output.mime"));

        t.setDefaultReport(properties.getProperty("default.report", "none"));

        String includeDirectoryString = properties.getProperty("include.directory");
        t.setIncludeDirectory(includeDirectoryString);

        if (includeDirectoryString != null) {
            Resource includeDirectoryResource;

            File includeDirectoryFile = new File(includeDirectoryString);
            if (includeDirectoryFile.isAbsolute()) {
                includeDirectoryResource = new FileSystemResource(includeDirectoryString);
            } else {
                includeDirectoryResource = sourceResource.createRelative(includeDirectoryString);
            }

            File includeDirectory = includeDirectoryResource.getFile();

            if (includeDirectory.isDirectory()) {
                t.setIncludeDirectoryResource(includeDirectoryResource);
            } else {
                // Just warn; no need to throw a hissy fit or otherwise fail to load
                LOG.warn("includeDirectory '{}' specified in '{}' is not a directory",
                        includeDirectoryFile.getAbsolutePath(), sourceResource.getFilename());
            }
        }

        // Default to 5 minutes; it's up to users to specify a shorter
        // time if they don't mind OpenNMS spamming on that directory
        int interval;
        try {
            interval = Integer.parseInt(properties.getProperty("include.directory.rescan", "300000"));
        } catch (NumberFormatException e) {
            // Default value if one was specified but it wasn't an integer
            interval = 300000;
            LOG.warn(
                    "The property 'include.directory.rescan' in {} was not able to be parsed as an integer.  Defaulting to {}ms",
                    sourceResource, interval, e);
        }

        t.setIncludeDirectoryRescanInterval(interval);

        List<PrefabGraph> graphs = loadPrefabGraphDefinitions(t, properties);

        for (PrefabGraph graph : graphs) {
            //The graphs list may contain nulls; see loadPrefabGraphDefinitions for reasons
            if (graph != null) {
                FileReloadContainer<PrefabGraph> container;
                if (reloadable) {
                    container = new FileReloadContainer<PrefabGraph>(graph, sourceResource, t.getCallback());
                } else {
                    container = new FileReloadContainer<PrefabGraph>(graph);
                }

                t.addPrefabGraph(container);
            }
        }

        //This *must* come after loading the main graph file, to ensure overrides are correct
        this.scanIncludeDirectory(t);
        return t;

    } catch (IOException e) {
        LOG.error("Failed to load prefab graph configuration of type {} from {}", type, sourceResource, e);
        return null;
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:org.broadleafcommerce.common.web.resource.AbstractGeneratedResourceHandler.java

/**
 * This method can be used to read in a resource given a path and at least one resource location
 * //  w w  w . j  a  v a  2  s.c  o m
 * @param path
 * @param locations
 * @return the resource from the file system, classpath, etc, if it exists
 */
protected Resource getRawResource(String path, List<Resource> locations) {
    ExtensionResultHolder erh = new ExtensionResultHolder();
    extensionManager.getProxy().getOverrideResource(path, erh);
    if (erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR) != null) {
        return (Resource) erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR);
    }

    for (Resource location : locations) {
        try {
            Resource resource = location.createRelative(path);
            if (resource.exists() && resource.isReadable()) {
                return resource;
            }
        } catch (IOException ex) {
            LOG.debug("Failed to create relative resource - trying next resource location", ex);
        }
    }
    return null;
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java

private String searchPluginViewsInDevelopmentMode(String name) {

    String pluginViewLocation = null;
    for (Resource resource : GrailsPluginUtils.getPluginDirectories()) {
        try {/* w ww  . j a  v  a 2s  .  c o  m*/
            final String pathToLayoutInPlugin = "grails-app/views/layouts/" + name;
            final String absolutePathToResource = resource.getFile().getAbsolutePath();
            if (!absolutePathToResource.endsWith("/")) {
                resource = new FileSystemResource(absolutePathToResource + '/');
            }
            final Resource layoutPath = resource.createRelative(pathToLayoutInPlugin);
            if (layoutPath.exists()) {
                GrailsPluginInfo info = GrailsPluginUtils.getPluginBuildSettings()
                        .getPluginInfo(absolutePathToResource);
                pluginViewLocation = GrailsResourceUtils.WEB_INF + "/plugins/" + info.getFullName() + '/'
                        + pathToLayoutInPlugin;
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return pluginViewLocation;
}

From source file:org.impalaframework.web.module.monitor.StagingDirectoryFileModuleRuntimeMonitor.java

protected Resource getTempFileResource(Resource resource) {
    final File file = getFileFromResource(resource);
    if (file != null) {
        try {/*from   w w w  .ja  v  a2 s.c o  m*/
            return resource.createRelative(PathUtils.getPath(stagingDirectory, file.getName()));
        } catch (Exception e) {
            logger.error("Problem creating relative file '" + stagingDirectory + "' for resource '"
                    + resource.getDescription() + "'", e);
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.impalaframework.web.module.monitor.TempFileModuleRuntimeMonitor.java

protected Resource getTempFileResource(Resource resource) {
    final File file = getFileFromResource(resource);
    if (file != null) {
        String name = file.getName();
        String tempFileName = name.replace(".jar", ".tmp");
        try {/*from   w  w  w .  jav  a  2 s  . co  m*/
            return resource.createRelative(tempFileName);
        } catch (Exception e) {
            logger.error("Problem creating relative file '" + tempFileName + "' for resource '"
                    + resource.getDescription() + "'", e);
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.mongeez.reader.FilesetXMLReader.java

public List<Resource> getFiles(Resource file) {
    List<Resource> files = new ArrayList<Resource>();

    try {//  w  w w .j av a  2 s. c  om
        Digester digester = new Digester();

        digester.setValidating(false);

        digester.addObjectCreate("changeFiles", ChangeFileSet.class);
        digester.addObjectCreate("changeFiles/file", ChangeFile.class);
        digester.addSetProperties("changeFiles/file");
        digester.addSetNext("changeFiles/file", "add");

        logger.info("Parsing XML Fileset file {}", file.getFilename());
        ChangeFileSet changeFileSet = (ChangeFileSet) digester.parse(file.getInputStream());
        if (changeFileSet != null) {
            logger.info("Num of changefiles found " + changeFileSet.getChangeFiles().size());
            for (ChangeFile changeFile : changeFileSet.getChangeFiles()) {
                files.add(file.createRelative(changeFile.getPath()));
            }
        } else {
            logger.error("The file {} doesn't seem to contain a changeFiles declaration. Are you "
                    + "using the correct file to initialize Mongeez?", file.getFilename());
        }
    } catch (IOException e) {
        logger.error("IOException", e);
    } catch (org.xml.sax.SAXException e) {
        logger.error("SAXException", e);
    }
    return files;
}

From source file:org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler.java

private Resource resolveResource(String viewName) {
    for (String location : this.resourceProperties.getStaticLocations()) {
        try {//from   w  w  w. ja  va 2  s  .  c o m
            Resource resource = this.applicationContext.getResource(location);
            resource = resource.createRelative(viewName + ".html");
            if (resource.exists()) {
                return resource;
            }
        } catch (Exception ex) {
            // Ignore
        }
    }
    return null;
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//  ww  w  .  ja v a2s  .  c  o m
 * @param rootDirResource the root directory as Resource
 * @param rootDirURL the pre-resolved root directory URL
 * @param subPattern the sub pattern to match (below the root directory)
 * @return a mutable Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @since 4.3
 * @see java.net.JarURLConnection
 * @see org.springframework.util.PathMatcher
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, URL rootDirURL,
        String subPattern) throws IOException {

    URLConnection con = rootDirURL.openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean closeJarFile;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        ResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
        closeJarFile = !jarCon.getUseCaches();
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirURL.getFile();
        try {
            int separatorIndex = urlFile.indexOf(ResourceUtils.WAR_URL_SEPARATOR);
            if (separatorIndex == -1) {
                separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
            }
            if (separatorIndex != -1) {
                jarFileUrl = urlFile.substring(0, separatorIndex);
                rootEntryPath = urlFile.substring(separatorIndex + 2); // both separators are 2 chars
                jarFile = getJarFile(jarFileUrl);
            } else {
                jarFile = new JarFile(urlFile);
                jarFileUrl = urlFile;
                rootEntryPath = "";
            }
            closeJarFile = true;
        } catch (ZipException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Skipping invalid jar classpath entry [" + urlFile + "]");
            }
            return Collections.emptySet();
        }
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        if (closeJarFile) {
            jarFile.close();
        }
    }
}