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

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

Introduction

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

Prototype

long lastModified() throws IOException;

Source Link

Document

Determine the last-modified timestamp for this resource.

Usage

From source file:com.javaetmoi.core.spring.vfs.Vfs2ResourceHttpRequestHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    checkAndPrepare(request, response, true);

    // check whether a matching resource exists
    Resource resource = getResource(request);
    if (resource == null) {
        logger.debug("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from   w ww .  j a v a2s.  c om*/
    }

    // check the resource's media type
    MediaType mediaType = getMediaType(resource);
    if (mediaType != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Determined media type '" + mediaType + "' for " + resource);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("No media type found for " + resource + " - not sending a content-type header");
        }
    }

    // header phase
    // Use a Vfs2Resource when asset are probided by the JBoss 5 Virtaul File System
    URL url = resource.getURL();
    if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
        resource = new Vfs2Resource(Vfs2Utils.getRoot(url));
    }

    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.debug("Resource not modified - returning 304");
        return;
    }
    setHeaders(response, resource, mediaType);

    // content phase
    if (METHOD_HEAD.equals(request.getMethod())) {
        logger.trace("HEAD request - skipping content");
        return;
    }
    writeContent(response, resource);
}

From source file:org.parancoe.web.util.ReloadableResourceBundleMessageSource.java

/**
 * Refresh the PropertiesHolder for the given bundle filename. The holder can be
 * <code>null</code> if not cached before, or a timed-out cache entry (potentially getting
 * re-validated against the current last-modified timestamp).
 *
 * @param filename the bundle filename (basename + Locale)
 * @param propHolder the current PropertiesHolder for the bundle
 *///from  w w w. ja va2s  .c o m
protected ReloadableResourceBundleMessageSource.PropertiesHolder refreshProperties(String filename,
        ReloadableResourceBundleMessageSource.PropertiesHolder propHolder) {
    long refreshTimestamp = (this.cacheMillis < 0) ? -1 : System.currentTimeMillis();

    Resource[] resources = null;
    try {
        if (this.resourceLoader instanceof ResourcePatternResolver) {
            resources = ((ResourcePatternResolver) this.resourceLoader)
                    .getResources(filename + PROPERTIES_SUFFIX);
            if (resources == null || resources.length == 0) {
                resources = ((ResourcePatternResolver) this.resourceLoader).getResources(filename + XML_SUFFIX);
            }
        } else {
            Resource resource = this.resourceLoader.getResource(filename + PROPERTIES_SUFFIX);
            if (!resource.exists()) {
                resource = this.resourceLoader.getResource(filename + XML_SUFFIX);
            }
            resources = new Resource[1];
            resources[0] = resource;
        }
        if (resources != null && resources.length > 0) {
            propHolder = new ReloadableResourceBundleMessageSource.PropertiesHolder();
            for (Resource resource : resources) {
                if (resource.exists()) {
                    long fileTimestamp = -1;
                    if (this.cacheMillis >= 0) {
                        // Last-modified timestamp of file will just be read if caching with timeout.
                        try {
                            fileTimestamp = resource.lastModified();
                            if (propHolder != null && propHolder.getFileTimestamp() == fileTimestamp) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Re-caching properties for filename [" + filename
                                            + "] - file hasn't been modified");
                                }
                                propHolder.setRefreshTimestamp(refreshTimestamp);
                                return propHolder;
                            }
                        } catch (IOException ex) {
                            // Probably a class path resource: cache it forever.
                            if (logger.isDebugEnabled()) {
                                logger.debug(resource
                                        + " could not be resolved in the file system - assuming that is hasn't changed",
                                        ex);
                            }
                            fileTimestamp = -1;
                        }
                    }
                    try {
                        Properties props = loadProperties(resource, filename);
                        if (propHolder.getProperties() != null) {
                            propHolder.getProperties().putAll(props);
                        } else {
                            propHolder.properties = props;
                        }
                        propHolder.fileTimestamp = fileTimestamp;
                    } catch (IOException ex) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Could not parse properties file [" + resource.getFilename() + "]", ex);
                        }
                    }
                } else {
                    // Resource does not exist.
                    if (logger.isDebugEnabled()) {
                        logger.debug("No properties file found for [" + resource.getFilename()
                                + "] - neither plain properties nor XML");
                    }
                }
            }
        } else {
            // Resource does not exist.
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "No properties files found for [" + filename + "] - neither plain properties nor XML");
            }
            // Empty holder representing "not found".
            propHolder = new ReloadableResourceBundleMessageSource.PropertiesHolder();
        }
    } catch (IOException iOException) {
        if (logger.isWarnEnabled()) {
            logger.warn("Could not match pattern [" + filename + "]", iOException);
        }
        // Empty holder representing "not valid".
        propHolder = new ReloadableResourceBundleMessageSource.PropertiesHolder();
    }

    propHolder.setRefreshTimestamp(refreshTimestamp);
    this.cachedProperties.put(filename, propHolder);
    return propHolder;
}

From source file:org.jahia.services.content.rules.RulesListener.java

public void addRules(Resource dsrlFile, JahiaTemplatesPackage aPackage) {
    long start = System.currentTimeMillis();
    try {/*from  w  ww .j  a  v  a  2 s .  com*/
        File compiledRulesDir = new File(SettingsBean.getInstance().getJahiaVarDiskPath() + "/compiledRules");
        if (aPackage != null) {
            compiledRulesDir = new File(compiledRulesDir, aPackage.getIdWithVersion());
        } else {
            compiledRulesDir = new File(compiledRulesDir, "system");
        }
        if (!compiledRulesDir.exists()) {
            compiledRulesDir.mkdirs();
        }

        ClassLoader packageClassLoader = aPackage != null ? aPackage.getClassLoader() : null;
        if (packageClassLoader != null) {
            ruleBaseClassLoader.addClassLoaderToEnd(packageClassLoader);
        }

        // first let's test if the file exists in the same location, if it was pre-packaged as a compiled rule
        File pkgFile = new File(compiledRulesDir,
                StringUtils.substringAfterLast(dsrlFile.getURL().getPath(), "/") + ".pkg");
        if (pkgFile.exists() && pkgFile.lastModified() > dsrlFile.lastModified()) {
            ObjectInputStream ois = null;
            try {
                ois = new DroolsObjectInputStream(new FileInputStream(pkgFile),
                        packageClassLoader != null ? packageClassLoader : null);
                Package pkg = new Package();
                pkg.readExternal(ois);
                if (ruleBase.getPackage(pkg.getName()) != null) {
                    ruleBase.removePackage(pkg.getName());
                }
                applyDisabledRulesConfiguration(pkg);
                ruleBase.addPackage(pkg);
                if (aPackage != null) {
                    modulePackageNameMap.put(aPackage.getName(), pkg.getName());
                }
            } finally {
                IOUtils.closeQuietly(ois);
            }
        } else {
            InputStream drlInputStream = dsrlFile.getInputStream();
            List<String> lines = Collections.emptyList();
            try {
                lines = IOUtils.readLines(drlInputStream);
            } finally {
                IOUtils.closeQuietly(drlInputStream);
            }
            StringBuilder drl = new StringBuilder(4 * 1024);
            for (String line : lines) {
                if (drl.length() > 0) {
                    drl.append("\n");
                }
                if (line.trim().length() > 0 && line.trim().charAt(0) == '#') {
                    drl.append(StringUtils.replaceOnce(line, "#", "//"));
                } else {
                    drl.append(line);
                }
            }

            PackageBuilderConfiguration cfg = packageClassLoader != null
                    ? new PackageBuilderConfiguration(packageClassLoader)
                    : new PackageBuilderConfiguration();

            PackageBuilder builder = new PackageBuilder(cfg);

            Reader drlReader = new StringReader(drl.toString());
            try {
                builder.addPackageFromDrl(drlReader, new StringReader(getDslFiles()));
            } finally {
                IOUtils.closeQuietly(drlReader);
            }

            PackageBuilderErrors errors = builder.getErrors();

            if (errors.getErrors().length == 0) {
                Package pkg = builder.getPackage();

                ObjectOutputStream oos = null;
                try {
                    pkgFile.getParentFile().mkdirs();
                    oos = new DroolsObjectOutputStream(new FileOutputStream(pkgFile));
                    pkg.writeExternal(oos);
                } catch (IOException e) {
                    logger.error("Error writing rule package to file " + pkgFile, e);
                } finally {
                    IOUtils.closeQuietly(oos);
                }

                if (ruleBase.getPackage(pkg.getName()) != null) {
                    ruleBase.removePackage(pkg.getName());
                }
                applyDisabledRulesConfiguration(pkg);
                ruleBase.addPackage(pkg);
                if (aPackage != null) {
                    modulePackageNameMap.put(aPackage.getName(), pkg.getName());
                }
                logger.info("Rules for " + pkg.getName() + " updated in " + (System.currentTimeMillis() - start)
                        + "ms.");
            } else {
                logger.error(
                        "---------------------------------------------------------------------------------");
                logger.error("Errors when compiling rules in " + dsrlFile + " : " + errors.toString());
                logger.error(
                        "---------------------------------------------------------------------------------");
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.jahia.services.render.filter.StaticAssetsFilter.java

private void addLastModified(Map<String, Map<String, Map<String, String>>> assets) throws IOException {
    for (Map.Entry<String, Map<String, Map<String, String>>> assetsEntry : assets.entrySet()) {
        if (assetsEntry.getKey().equals("css") || assetsEntry.getKey().equals("javascript")) {
            Map<String, Map<String, String>> newMap = new LinkedHashMap<String, Map<String, String>>();
            for (Map.Entry<String, Map<String, String>> entry : assetsEntry.getValue().entrySet()) {
                Resource r = getResource(getKey(entry.getKey()));
                if (r != null) {
                    newMap.put(entry.getKey() + "?" + r.lastModified(), entry.getValue());
                } else {
                    newMap.put(entry.getKey(), entry.getValue());
                }//from   w ww.  j a v  a 2  s  . c om
            }
            assetsEntry.getValue().clear();
            assetsEntry.getValue().putAll(newMap);
        }
    }
}

From source file:org.jahia.services.render.filter.StaticAssetsFilter.java

private Map<String, Map<String, String>> aggregate(Map<String, Map<String, String>> assets, String type)
        throws IOException {

    List<Map.Entry<String, Map<String, String>>> entries = new ArrayList<Map.Entry<String, Map<String, String>>>(
            assets.entrySet());//w  ww .  j  a va  2 s  .  c  o  m
    Map<String, Map<String, String>> newEntries = new LinkedHashMap<String, Map<String, String>>();

    for (int i = 0; i < entries.size();) {

        long maxLastModified = 0;
        LinkedHashMap<String, Resource> pathsToAggregate = new LinkedHashMap<String, Resource>();
        for (; i < entries.size(); i++) {
            Map.Entry<String, Map<String, String>> entry = entries.get(i);
            String key = getKey(entry.getKey());
            Resource resource = getResource(key);
            if (entry.getValue().isEmpty() && !excludesFromAggregateAndCompress.contains(key)
                    && resource != null) {
                long lastModified = resource.lastModified();
                pathsToAggregate.put(key + "_" + lastModified, resource);
                if (lastModified > maxLastModified) {
                    maxLastModified = lastModified;
                }
            } else {
                // In case current entry should not be aggregated for whatever reason, let's stop and aggregate a group of entries preceding it.
                break;
            }
        }

        if (!pathsToAggregate.isEmpty()) {
            String minifiedAggregatedPath = aggregate(pathsToAggregate, type, maxLastModified);
            newEntries.put(Jahia.getContextPath() + minifiedAggregatedPath, new HashMap<String, String>());
        }

        if (i < entries.size()) {
            // In case current entry should not be aggregated for whatever reason, add it as a non-aggregated one.
            Map.Entry<String, Map<String, String>> entry = entries.get(i);
            Resource resource;
            if (addLastModifiedDate && (resource = getResource(getKey(entry.getKey()))) != null) {
                newEntries.put(entry.getKey() + "?lastModified=" + resource.lastModified(), entry.getValue());
            } else {
                newEntries.put(entry.getKey(), entry.getValue());
            }
            i++;
        }
    }

    return newEntries;
}

From source file:org.jahia.utils.FileUtils.java

/**
 * Returns the last modified date of the specified resource.
 * //from  w w  w.  ja  v  a2s  .c  o m
 * @param resource
 *            resource to check the last modified date on
 * @return the last modified date of the specified resource
 * @throws IOException
 *             in case of an I/O error
 */
public static long getLastModified(Resource resource) throws IOException {
    URL resourceUrl = resource.getURL();
    return ResourceUtils.isJarURL(resourceUrl)
            ? ResourceUtils.getFile(ResourceUtils.extractJarFileURL(resourceUrl)).lastModified()
            : resource.lastModified();
}

From source file:org.springframework.integration.expression.ReloadableResourceBundleExpressionSource.java

/**
 * Refresh the PropertiesHolder for the given bundle filename.
 * The holder can be <code>null</code> if not cached before, or a timed-out cache entry
 * (potentially getting re-validated against the current last-modified timestamp).
 * @param filename the bundle filename (basename + Locale)
 * @param propHolder the current PropertiesHolder for the bundle
 *///from  w  ww .  ja  v a2  s.  c  om
private PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) {
    long refreshTimestamp = (this.cacheMillis < 0) ? -1 : System.currentTimeMillis();

    Resource resource = this.resourceLoader.getResource(filename + PROPERTIES_SUFFIX);
    if (!resource.exists()) {
        resource = this.resourceLoader.getResource(filename + XML_SUFFIX);
    }

    if (resource.exists()) {
        long fileTimestamp = -1;
        if (this.cacheMillis >= 0) {
            // Last-modified timestamp of file will just be read if caching with timeout.
            try {
                fileTimestamp = resource.lastModified();
                if (propHolder != null && propHolder.getFileTimestamp() == fileTimestamp) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Re-caching properties for filename [" + filename
                                + "] - file hasn't been modified");
                    }
                    propHolder.setRefreshTimestamp(refreshTimestamp);
                    return propHolder;
                }
            } catch (IOException ex) {
                // Probably a class path resource: cache it forever.
                if (logger.isDebugEnabled()) {
                    logger.debug(resource
                            + " could not be resolved in the file system - assuming that is hasn't changed",
                            ex);
                }
                fileTimestamp = -1;
            }
        }
        try {
            Properties props = loadProperties(resource, filename);
            propHolder = new PropertiesHolder(props, fileTimestamp);
        } catch (IOException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Could not parse properties file [" + resource.getFilename() + "]", ex);
            }
            // Empty holder representing "not valid".
            propHolder = new PropertiesHolder();
        }
    }

    else {
        // Resource does not exist.
        if (logger.isDebugEnabled()) {
            logger.debug("No properties file found for [" + filename + "] - neither plain properties nor XML");
        }
        // Empty holder representing "not found".
        propHolder = new PropertiesHolder();
    }

    propHolder.setRefreshTimestamp(refreshTimestamp);
    this.cachedProperties.put(filename, propHolder);
    return propHolder;
}

From source file:org.springframework.ui.freemarker.SpringTemplateLoader.java

@Override
public long getLastModified(Object templateSource) {
    Resource resource = (Resource) templateSource;
    try {//from  w  ww . ja  v  a2  s  . co  m
        return resource.lastModified();
    } catch (IOException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not obtain last-modified timestamp for FreeMarker template in " + resource
                    + ": " + ex);
        }
        return -1;
    }
}

From source file:org.springframework.web.servlet.resource.PathExtensionResourceResolver.java

@Override
public Resource resolveResource(HttpServletRequest request, String requestPath, List<Resource> locations,
        ResourceResolverChain chain) {/*ww w .j  a v  a  2 s .  co m*/

    Resource resource = chain.resolveResource(request, requestPath, locations);
    if ((resource != null) && !this.compareTimeStamp) {
        return resource;
    }

    for (Resource location : locations) {
        String baseFilename = StringUtils.getFilename(requestPath);
        try {
            Resource basePath = location.createRelative(StringUtils.delete(requestPath, baseFilename));
            if (basePath.getFile().isDirectory()) {
                for (String fileName : basePath.getFile().list(new ExtensionFilenameFilter(baseFilename))) {
                    //Always use the first match
                    Resource matched = basePath.createRelative(fileName);
                    if ((resource == null) || (matched.lastModified() > resource.lastModified())) {
                        return matched;
                    } else {
                        return resource;
                    }
                }
            }
        } catch (IOException e) {
            logger.trace("Error occurred locating resource based on file extension mapping", e);
        }
    }

    return resource;
}

From source file:org.springframework.web.servlet.resource.ResourceHttpRequestHandler.java

/**
 * Processes a resource request.//from  w  w  w. j  ava2  s. co m
 * <p>Checks for the existence of the requested resource in the configured list of locations.
 * If the resource does not exist, a {@code 404} response will be returned to the client.
 * If the resource exists, the request will be checked for the presence of the
 * {@code Last-Modified} header, and its value will be compared against the last-modified
 * timestamp of the given resource, returning a {@code 304} status code if the
 * {@code Last-Modified} value  is greater. If the resource is newer than the
 * {@code Last-Modified} value, or the header is not present, the content resource
 * of the resource will be written to the response with caching headers
 * set to expire one year in the future.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // For very general mappings (e.g. "/") we need to check 404 first
    Resource resource = getResource(request);
    if (resource == null) {
        logger.trace("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (HttpMethod.OPTIONS.matches(request.getMethod())) {
        response.setHeader("Allow", getAllowHeader());
        return;
    }

    // Supported methods and required session
    checkRequest(request);

    // Header phase
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.trace("Resource not modified - returning 304");
        return;
    }

    // Apply cache settings, if any
    prepareResponse(response);

    // Check the media type for the resource
    MediaType mediaType = getMediaType(request, resource);
    if (mediaType != null) {
        if (logger.isTraceEnabled()) {
            logger.trace("Determined media type '" + mediaType + "' for " + resource);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("No media type found for " + resource + " - not sending a content-type header");
        }
    }

    // Content phase
    if (METHOD_HEAD.equals(request.getMethod())) {
        setHeaders(response, resource, mediaType);
        logger.trace("HEAD request - skipping content");
        return;
    }

    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
    if (request.getHeader(HttpHeaders.RANGE) == null) {
        Assert.state(this.resourceHttpMessageConverter != null, "Not initialized");
        setHeaders(response, resource, mediaType);
        this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage);
    } else {
        Assert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized");
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
        try {
            List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            this.resourceRegionHttpMessageConverter.write(HttpRange.toResourceRegions(httpRanges, resource),
                    mediaType, outputMessage);
        } catch (IllegalArgumentException ex) {
            response.setHeader("Content-Range", "bytes */" + resource.contentLength());
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        }
    }
}