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:org.globus.security.stores.CertKeyCredential.java

public CertKeyCredential(Resource certResource, Resource keyResource, X509Credential credential)
        throws ResourceStoreException {
    this.certFile = certResource;
    try {/*from  ww w .j  av a  2s .  c om*/
        if (!certResource.exists()) {
            FileUtils.touch(certResource.getFile());
            this.certLastModified = certResource.lastModified();
        }
        this.keyFile = keyResource;
        if (!keyResource.exists()) {
            FileUtils.touch(keyResource.getFile());
            this.keyLastModified = keyResource.lastModified();
        }
    } catch (IOException e) {
        throw new ResourceStoreException(e);
    }
    this.credential = credential;
}

From source file:org.jasig.schedassist.impl.relationship.advising.AdvisorListRelationshipDataSourceImpl.java

/**
 * // ww  w  .  j  ava  2  s .  co  m
 * @param resource
 * @return
 */
protected boolean isResourceUpdated(final Resource resource) {
    boolean result = true;
    try {
        result = (this.resourceLastModified == -1L) || (resource.lastModified() > this.resourceLastModified);
    } catch (IOException e) {
        // this exception will occur if the Resource is not representable as a File
        // in this case - always return true?
        throw new IllegalStateException(
                "caught IOException from Resource#lastModified(), is " + resource + " a folder?", e);
    }
    return result;
}

From source file:com.ethlo.geodata.util.ResourceUtil.java

private Entry<Date, File> downloadIfNewer(DataType dataType, Resource resource, CheckedFunction<Path, Path> fun)
        throws IOException {
    publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 0, 1));
    final String alias = dataType.name().toLowerCase();
    final File tmpDownloadedFile = new File(tmpDir, alias);
    final Date remoteLastModified = new Date(resource.lastModified());
    final long localLastModified = tmpDownloadedFile.exists() ? tmpDownloadedFile.lastModified() : -2;
    logger.info(//from ww w .ja  va2s  .c om
            "Local file for alias {}" + "\nPath: {}" + "\nExists: {}" + "\nLocal last-modified: {} "
                    + "\nRemote last modified: {}",
            alias, tmpDownloadedFile.getAbsolutePath(), tmpDownloadedFile.exists(),
            formatDate(localLastModified), formatDate(remoteLastModified.getTime()));

    if (!tmpDownloadedFile.exists() || remoteLastModified.getTime() > localLastModified) {
        logger.info("Downloading {}", resource.getURL());
        Files.copy(resource.getInputStream(), tmpDownloadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        logger.info("Download complete");
    }

    final Path preppedFile = fun.apply(tmpDownloadedFile.toPath());
    Files.setLastModifiedTime(tmpDownloadedFile.toPath(), FileTime.fromMillis(remoteLastModified.getTime()));
    Files.setLastModifiedTime(preppedFile, FileTime.fromMillis(remoteLastModified.getTime()));
    publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 1, 1));
    return new AbstractMap.SimpleEntry<>(new Date(remoteLastModified.getTime()), preppedFile.toFile());
}

From source file:org.brekka.stillingar.spring.snapshot.ResourceSnapshotManager.java

/**
 * Perform the load operation that will convert a resource into a snapshot.
 * @param resourceToLoad the resouce to load into a snapshot
 * @return the snapshot loaded from the specified resource
 * @throws ConfigurationException if something goes wrong such as an IO error.
 *///w ww  .j  a  va  2s.co  m
protected Snapshot performLoad(Resource resourceToLoad) {
    Snapshot snapshot = null;
    if (resourceToLoad != null && resourceToLoad.exists() && resourceToLoad.isReadable()) {
        InputStream sourceStream = null;
        try {
            sourceStream = resourceToLoad.getInputStream();
            long timestamp = resourceToLoad.lastModified();
            ConfigurationSource configurationSource = configurationSourceLoader.parse(sourceStream, null);
            snapshot = new ResourceSnapshot(configurationSource, new Date(timestamp), resourceToLoad);
        } catch (IOException e) {
            throw new ConfigurationException(format("Resouce '%s'", resourceToLoad), e);
        } catch (RuntimeException e) {
            // Wrap to include location details
            throw new ConfigurationException(format("Resouce '%s' processing problem", resourceToLoad), e);
        } finally {
            closeQuietly(sourceStream);
        }
    }
    return snapshot;
}

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

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

    Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    String key = (String) pathVariables.get("key");

    Media media = mediaService.getMedia(key);
    int width = ServletRequestUtils.getIntParameter(request, "w", 0);
    int height = ServletRequestUtils.getIntParameter(request, "h", 0);
    int mode = ServletRequestUtils.getIntParameter(request, "m", 0);

    Resource resource = readResource(media, width, height, Media.ResizeMode.values()[mode]);

    if (resource == null) {
        logger.debug("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from w w  w  .j  a v  a  2s .  co m
    }
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.debug("Resource not modified - returning 304");
        return;
    }

    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource);
    }

    response.setContentLength((int) length);
    response.setContentType(media.getMimeType());
    if (!"image".equals(MediaType.parseMediaType(media.getMimeType()).getType())) {
        response.setHeader("Content-Disposition",
                "attachment;filename*=utf-8''" + URLEncoder.encode(media.getOriginalName(), "UTF-8"));
    }

    FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
}

From source file:com.netflix.genie.agent.execution.services.impl.FetchingCacheServiceImpl.java

private void lookupOrDownload(final URI sourceFileUri, final File destinationFile)
        throws DownloadException, IOException {

    final String uriString = sourceFileUri.toASCIIString();

    log.debug("Lookup: {}", uriString);

    // Unique id to store the resource on local disk
    final String resourceCacheId = getResourceCacheId(sourceFileUri);

    // Get a handle to the resource
    final Resource resource = resourceLoader.getResource(uriString);

    if (!resource.exists()) {
        throw new DownloadException("Resource not found: " + uriString);
    }//from  ww w .  j a  v a  2s  .co  m

    final long resourceLastModified = resource.lastModified();

    //Handle to resourceCacheId/version
    final File cacheResourceVersionDir = getCacheResourceVersionDir(resourceCacheId, resourceLastModified);

    //Create the resource version dir in cache if it does not exist
    createDirectoryStructureIfNotExists(cacheResourceVersionDir);

    try (CloseableLock lock = fileLockFactory
            .getLock(touchCacheResourceVersionLockFile(resourceCacheId, resourceLastModified));) {
        //Critical section begin
        lock.lock();

        //Handle to the resource cached locally
        final File cachedResourceVersionDataFile = getCacheResourceVersionDataFile(resourceCacheId,
                resourceLastModified);

        if (!cachedResourceVersionDataFile.exists()) {
            log.debug("Cache miss: {} (id: {})", uriString, resourceCacheId);

            // Download the resource into the download file in cache
            // resourceCacheId/version/data.tmp
            final File cachedResourceVersionDownloadFile = getCacheResourceVersionDownloadFile(resourceCacheId,
                    resourceLastModified);
            try (InputStream in = resource.getInputStream();
                    OutputStream out = new FileOutputStream(cachedResourceVersionDownloadFile)) {
                FileCopyUtils.copy(in, out);
                Files.move(cachedResourceVersionDownloadFile, cachedResourceVersionDataFile);
            }
        } else {
            log.debug("Cache hit: {} (id: {})", uriString, resourceCacheId);
        }

        //Copy from cache data file resourceCacheId/version/DATA_FILE_NAME to targetFile
        Files.copy(cachedResourceVersionDataFile, destinationFile);
        //Critical section end
    } catch (LockException e) {
        throw new DownloadException("Error downloading dependency", e);
    }

    //Clean up any older versions
    cleanUpTaskExecutor.execute(new CleanupOlderVersionsTask(resourceCacheId, resourceLastModified));
}

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

private Resource readResource(final Media media, final int width, final int height, final Media.ResizeMode mode)
        throws IOException {
    //      Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    //      final Resource prefix = resourceLoader.getResource(blog.getMediaPath());
    final Resource prefix = resourceLoader.getResource(wallRideProperties.getMediaLocation());
    final Resource resource = prefix.createRelative(media.getId());

    if (!resource.exists()) {
        return null;
    }//from  w  ww  .j a  va2s  .c  o  m

    Resource resized = resource;
    boolean doResize = (width > 0 || height > 0);
    if (doResize && "image".equals(MediaType.parseMediaType(media.getMimeType()).getType())) {
        resized = prefix.createRelative(
                String.format("%s.resized/%dx%d-%d", media.getId(), width, height, mode.ordinal()));
        if (!resized.exists() || resource.lastModified() > resized.lastModified()) {
            File temp = File.createTempFile(getClass().getCanonicalName() + ".resized-",
                    "." + MediaType.parseMediaType(media.getMimeType()).getSubtype());
            temp.deleteOnExit();
            resizeImage(resource, temp, width, height, mode);

            //            AmazonS3ResourceUtils.writeFile(temp, resized);
            ExtendedResourceUtils.write(resized, temp);
            FileUtils.deleteQuietly(temp);
        }
    }
    return resized;
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyConfigImpl.java

/**
 * Save last modification of the file to track it and override this bean
 * properties if the file has been changed
 * // www. ja va2  s.  c om
 * @param location
 *            Resource location of the file
 * 
 * @throws IOException
 */
private void trackLocation(Resource location) throws IOException {
    String fileName = location.getFilename();
    Long lastModified = location.lastModified();
    if (!(timeModificationByLocation.containsKey(fileName))) {
        // Save last modification timestamp
        timeModificationByLocation.put(fileName, lastModified);
    } else if (isModified(fileName, lastModified)) {
        // Override proxy configuration
        LOGGER.log(Level.INFO, "Proxy configuration has changed at runtime in file '" + fileName + "'");
        overrideProperties(location);
    }
}

From source file:inti.ws.spring.resource.config.ResourceConfigProviderImpl.java

protected void update(String key) throws Exception {
    Resource configFile;
    JsonNode configNode;/*  ww  w  .  jav a2 s  .com*/
    InputStream inputStream;

    LOGGER.debug("update - paths for key {}: {}", key, hostToConfigfileMapping.get(key));

    for (String path : hostToConfigfileMapping.get(key)) {

        if (path.startsWith("/")) {
            configFile = new ServletContextResource(ctx, path);
        } else {
            configFile = new UrlResource(path);
        }

        LOGGER.debug("update - updating {} for key {}", path, key);
        if (lastModifies.containsKey(path) && configFile.lastModified() <= lastModifies.get(path)) {
            LOGGER.debug("update - no newer version available for {} for key {}", path, key);
            continue;
        } else {
            lastModifies.put(path, configFile.lastModified());
        }

        inputStream = configFile.getInputStream();
        try {
            configNode = mapper.readTree(inputStream);
        } finally {
            inputStream.close();
        }

        if (configNode != null) {

            configure(key, configNode);

        }

    }

}

From source file:com.civilizer.web.handler.ResourceHttpRequestHandler.java

/**
 * Processes a resource request.//from  w  w  w.  j  ava 2s  .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.
 */
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    checkRequest(request);
    prepareResponse(response);

    // 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;
    }

    // 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
    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);
}