Search in sources :

Example 36 with FileSystemResource

use of org.springframework.core.io.FileSystemResource in project opennms by OpenNMS.

the class AssetLocatorImpl method getResource.

protected Resource getResource(final String requestPath, final List<? extends Resource> locations) {
    for (final Resource location : locations) {
        try {
            if (resourcesMatch(s_assetsPath, location)) {
                final Resource resource = location.createRelative(requestPath);
                LOG.debug("checking request {} in location {}", requestPath, location);
                final String fileName = resource.getFilename();
                if (s_filesystemPath != null) {
                    final File f = Paths.get(s_filesystemPath, fileName).toFile();
                    LOG.debug("Checking for resource in filesystem: {}", f);
                    if (f.exists() && f.canRead()) {
                        LOG.trace("File exists and is readable: {}", f);
                        return new FileSystemResource(f);
                    }
                }
                final int index = fileName.lastIndexOf(".");
                if (index > 0) {
                    final String assetName = fileName.substring(0, index);
                    final String type = fileName.substring(index + 1);
                    final Optional<AssetResource> assetResource = getResource(assetName, type);
                    LOG.debug("Checking for resource in classpath: {}.{} ({})", assetName, type, assetResource);
                    if (assetResource.isPresent()) {
                        final Resource found = new ClassPathResource(assetResource.get().getPath());
                        LOG.debug("Found ClassPathResource: {}", found);
                        if (found.exists() && found.isReadable()) {
                            LOG.trace("Resource exists and is readable: {}", found);
                            return found;
                        }
                    }
                }
                if (resource.exists()) {
                    return resource;
                }
            }
            LOG.debug("unhandled location {} for request path {}", location, requestPath);
        } catch (final IOException e) {
            LOG.debug("Failed to create relative path from {} in {}. Trying next location.", requestPath, location, e);
        }
    }
    return null;
}
Also used : UrlResource(org.springframework.core.io.UrlResource) ClassPathResource(org.springframework.core.io.ClassPathResource) AssetResource(org.opennms.web.assets.api.AssetResource) ServletContextResource(org.springframework.web.context.support.ServletContextResource) Resource(org.springframework.core.io.Resource) FileSystemResource(org.springframework.core.io.FileSystemResource) FileSystemResource(org.springframework.core.io.FileSystemResource) IOException(java.io.IOException) File(java.io.File) AssetResource(org.opennms.web.assets.api.AssetResource) ClassPathResource(org.springframework.core.io.ClassPathResource)

Example 37 with FileSystemResource

use of org.springframework.core.io.FileSystemResource in project opennms by OpenNMS.

the class AssetLocatorImpl method loadAssets.

private Map<String, List<AssetResource>> loadAssets(final boolean minified) {
    try {
        final Map<String, List<AssetResource>> newAssets = new HashMap<>();
        Resource r = new ClassPathResource(minified ? "/assets/assets.min.json" : "/assets/assets.json");
        if (s_filesystemPath != null) {
            final Path p = Paths.get(s_filesystemPath).resolve(minified ? "assets.min.json" : "assets.json");
            if (p.toFile().exists()) {
                r = new FileSystemResource(p.toFile());
            }
        }
        LOG.info("Loading asset data from {}", r);
        byte[] bdata = FileCopyUtils.copyToByteArray(r.getInputStream());
        final String json = new String(bdata, StandardCharsets.UTF_8);
        final JSONObject assetsObj = new JSONObject(json);
        final JSONArray names = assetsObj.names();
        for (int i = 0; i < names.length(); i++) {
            final String assetName = names.getString(i);
            final JSONObject assetObj = assetsObj.getJSONObject(assetName);
            final List<AssetResource> assets = new ArrayList<>(assetObj.length());
            final JSONArray keys = assetObj.names();
            for (int j = 0; j < keys.length(); j++) {
                final String type = keys.getString(j);
                final String path = assetObj.getString(type);
                assets.add(new AssetResource(assetName, type, path));
            }
            if (assetObj.length() > 0) {
                newAssets.put(assetName, assets);
            }
        }
        m_lastModified = r.lastModified();
        return newAssets;
    } catch (final Exception e) {
        LOG.warn("Failed to load asset manifest.", e);
    }
    return null;
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) UrlResource(org.springframework.core.io.UrlResource) ClassPathResource(org.springframework.core.io.ClassPathResource) AssetResource(org.opennms.web.assets.api.AssetResource) ServletContextResource(org.springframework.web.context.support.ServletContextResource) Resource(org.springframework.core.io.Resource) FileSystemResource(org.springframework.core.io.FileSystemResource) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) FileSystemResource(org.springframework.core.io.FileSystemResource) ClassPathResource(org.springframework.core.io.ClassPathResource) AssetResource(org.opennms.web.assets.api.AssetResource) IOException(java.io.IOException) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List)

Example 38 with FileSystemResource

use of org.springframework.core.io.FileSystemResource in project opennms by OpenNMS.

the class AbstractMergingJaxbConfigDao method reconfigureDaos.

private void reconfigureDaos() {
    final Set<File> xmlFilesWithUnusedDaos = new HashSet<>();
    xmlFilesWithUnusedDaos.addAll(m_configDaosByPath.keySet());
    for (File xmlFile : m_xmlFiles) {
        // Try to fetch an existing DAO
        JaxbConfigDao dao = m_configDaosByPath.get(xmlFile);
        if (dao == null) {
            // We need to create one
            FileSystemResource fs = new FileSystemResource(xmlFile);
            dao = new JaxbConfigDao();
            dao.setConfigResource(fs);
            dao.afterPropertiesSet();
            m_configDaosByPath.put(xmlFile, dao);
        } else {
            xmlFilesWithUnusedDaos.remove(xmlFile);
        }
    }
    // Remove any DAOs we don't need anymore
    for (File fileWithUnusedDao : xmlFilesWithUnusedDaos) {
        m_configDaosByPath.remove(fileWithUnusedDao);
    }
}
Also used : FileSystemResource(org.springframework.core.io.FileSystemResource) File(java.io.File) HashSet(java.util.HashSet)

Example 39 with FileSystemResource

use of org.springframework.core.io.FileSystemResource in project opennms by OpenNMS.

the class JtiIT method updateDaoWithConfig.

private void updateDaoWithConfig(TelemetrydConfiguration config) throws IOException {
    final File tempFile = tempFolder.newFile();
    JaxbUtils.marshal(config, tempFile);
    telemetrydConfigDao.setConfigResource(new FileSystemResource(tempFile));
    telemetrydConfigDao.afterPropertiesSet();
}
Also used : FileSystemResource(org.springframework.core.io.FileSystemResource) File(java.io.File)

Example 40 with FileSystemResource

use of org.springframework.core.io.FileSystemResource in project opennms by OpenNMS.

the class PropertiesGraphDao method createPrefabGraphType.

/**
 * 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
 * @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);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) InputStreamResource(org.springframework.core.io.InputStreamResource) OnmsResource(org.opennms.netmgt.model.OnmsResource) Resource(org.springframework.core.io.Resource) FileSystemResource(org.springframework.core.io.FileSystemResource) FileSystemResource(org.springframework.core.io.FileSystemResource) IOException(java.io.IOException) Properties(java.util.Properties) PrefabGraph(org.opennms.netmgt.model.PrefabGraph) File(java.io.File)

Aggregations

FileSystemResource (org.springframework.core.io.FileSystemResource)148 File (java.io.File)77 Test (org.junit.Test)44 Resource (org.springframework.core.io.Resource)42 Before (org.junit.Before)27 ClassPathResource (org.springframework.core.io.ClassPathResource)16 IOException (java.io.IOException)12 FileWriter (java.io.FileWriter)10 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)8 Properties (java.util.Properties)8 PrefabGraph (org.opennms.netmgt.model.PrefabGraph)8 FileOutputStream (java.io.FileOutputStream)7 URL (java.net.URL)7 InputStreamResource (org.springframework.core.io.InputStreamResource)7 UrlResource (org.springframework.core.io.UrlResource)7 Date (java.util.Date)5 FilesystemResourceStorageDao (org.opennms.netmgt.dao.support.FilesystemResourceStorageDao)5 FileReader (java.io.FileReader)4 OutputStreamWriter (java.io.OutputStreamWriter)4