Search in sources :

Example 1 with AssetResource

use of org.opennms.web.assets.api.AssetResource 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 2 with AssetResource

use of org.opennms.web.assets.api.AssetResource in project opennms by OpenNMS.

the class AssetLocatorImpl method open.

@Override
public Optional<InputStream> open(final String assetName, final String type, final boolean minified) throws IOException {
    final Optional<AssetResource> r = getResource(assetName, type, minified);
    if (!r.isPresent()) {
        LOG.info("Unable to locate asset resource {}:{}", assetName, type);
        return Optional.empty();
    }
    final AssetResource resource = r.get();
    if (s_filesystemPath != null) {
        final Path p = Paths.get(s_filesystemPath).resolve(resource.getPath());
        LOG.debug("assets path is set, attempting to load {}:{} from {}", assetName, type, p);
        if (p.toFile().exists()) {
            return Optional.of(new FileInputStream(p.toFile()));
        }
    }
    final String resourcePath = resource.getPath();
    LOG.debug("Opening resource {} for asset {}", resourcePath, r);
    final URL url = getClass().getResource(resourcePath);
    if (url != null) {
        return Optional.of(url.openStream());
    }
    return Optional.of(new ClassPathResource(resourcePath).getInputStream());
}
Also used : Path(java.nio.file.Path) AssetResource(org.opennms.web.assets.api.AssetResource) FileInputStream(java.io.FileInputStream) URL(java.net.URL) ClassPathResource(org.springframework.core.io.ClassPathResource)

Example 3 with AssetResource

use of org.opennms.web.assets.api.AssetResource 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 4 with AssetResource

use of org.opennms.web.assets.api.AssetResource in project opennms by OpenNMS.

the class WebAssetsRestService method getResource.

@GET
@Path("{assetName}.{type}")
public Response getResource(@PathParam("assetName") final String assetName, @PathParam("type") final String type) {
    InputStream is = null;
    try {
        Optional<InputStream> resourceInputStream = m_assetLocator.open(assetName, type);
        if (!resourceInputStream.isPresent()) {
            final List<String> split = Arrays.asList(assetName.split("-"));
            if (split.size() > 1) {
                split.remove(split.size() - 1);
                final String newAssetName = String.join("-", split);
                final Optional<AssetResource> newResource = m_assetLocator.getResource(newAssetName, type);
                LOG.debug("{}.{} not found, found {} instead", assetName, type, newResource);
                if (newResource.isPresent() && newResource.get().getPath().equals(assetName + "." + type)) {
                    resourceInputStream = m_assetLocator.open(newAssetName, type);
                }
            }
        }
        if (!resourceInputStream.isPresent()) {
            return Response.status(Status.NOT_FOUND).build();
        }
        is = resourceInputStream.get();
        final byte[] bytes = FileCopyUtils.copyToByteArray(is);
        switch(type) {
            case "js":
                return Response.ok(new String(bytes, StandardCharsets.UTF_8)).type("application/javascript").build();
            case "css":
                return Response.ok(new String(bytes, StandardCharsets.UTF_8)).type("text/css").build();
            default:
                throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN).entity("Unhandled resource type: " + type).build());
        }
    } catch (final IOException e) {
        LOG.debug("I/O error while reading {}.{}", assetName, type, e);
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN).entity("Resource " + assetName + "/" + type + " exists, but could not be read.\n" + e.getMessage() + "\n" + e.getStackTrace()).build());
    } finally {
        IOUtils.closeQuietly(is);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) InputStream(java.io.InputStream) IOException(java.io.IOException) AssetResource(org.opennms.web.assets.api.AssetResource) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 5 with AssetResource

use of org.opennms.web.assets.api.AssetResource in project opennms by OpenNMS.

the class AssetLocatorImplTest method testGetResources.

@Test
public void testGetResources() throws Exception {
    final Optional<Collection<AssetResource>> resources = m_locator.getResources("test-asset");
    assertTrue(resources.isPresent());
    assertNotNull(resources.get());
    assertEquals(1, resources.get().size());
    final AssetResource resource = resources.get().iterator().next();
    assertEquals("test-asset", resource.getAsset());
    assertEquals("js", resource.getType());
    assertEquals("assets/test.min.js", resource.getPath());
}
Also used : Collection(java.util.Collection) AssetResource(org.opennms.web.assets.api.AssetResource) Test(org.junit.Test)

Aggregations

AssetResource (org.opennms.web.assets.api.AssetResource)6 IOException (java.io.IOException)3 ClassPathResource (org.springframework.core.io.ClassPathResource)3 Path (java.nio.file.Path)2 Collection (java.util.Collection)2 Test (org.junit.Test)2 FileSystemResource (org.springframework.core.io.FileSystemResource)2 Resource (org.springframework.core.io.Resource)2 UrlResource (org.springframework.core.io.UrlResource)2 ServletContextResource (org.springframework.web.context.support.ServletContextResource)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 WebApplicationException (javax.ws.rs.WebApplicationException)1