Example usage for java.nio.file.attribute FileTime fromMillis

List of usage examples for java.nio.file.attribute FileTime fromMillis

Introduction

In this page you can find the example usage for java.nio.file.attribute FileTime fromMillis.

Prototype

public static FileTime fromMillis(long value) 

Source Link

Document

Returns a FileTime representing the given value in milliseconds.

Usage

From source file:org.fim.command.ResetFileAttributesCommand.java

private boolean resetCreationTime(Path file, FileState fileState, BasicFileAttributes attributes)
        throws IOException {
    long creationTime = attributes.creationTime().toMillis();
    long previousCreationTime = fileState.getFileTime().getCreationTime();
    if (creationTime != previousCreationTime) {
        setCreationTime(file, FileTime.fromMillis(previousCreationTime));
        System.out.printf("Set creation Time: %s \t%s -> %s%n", fileState.getFileName(),
                formatDate(creationTime), formatDate(previousCreationTime));
        return true;
    }/*from   w  w w .  j ava 2  s .co  m*/
    return false;
}

From source file:com.emc.vipr.sync.target.CuaFilesystemTarget.java

@Override
public void filter(SyncObject obj) {
    timeOperationStart(CasUtil.OPERATION_TOTAL);

    if (!(obj instanceof CasSource.ClipSyncObject))
        throw new UnsupportedOperationException("sync object was not a CAS clip");
    final CasSource.ClipSyncObject clipSync = (CasSource.ClipSyncObject) obj;

    try {//from   w  ww . j a  va2 s .  co  m
        // looking for clips with a specific name
        if (!clipSync.getClipName().equals(CLIP_NAME)) {
            LogMF.debug(l4j, "skipped clip {0} (clip name did not match)", clipSync.getRawSourceIdentifier());
        } else {

            ClipTag blobTag = null;
            String filePath = null;
            Date itime = null, mtime = null, atime = null;
            long hi = 0, lo = 0;
            for (ClipTag clipTag : clipSync.getTags()) {
                FPTag sourceTag = clipTag.getTag();
                if (sourceTag.getTagName().equals(ATTRIBUTE_TAG_NAME)) {
                    // pull all pertinent attributes
                    filePath = sourceTag.getStringAttribute(PATH_ATTRIBUTE);
                    itime = new Date(sourceTag.getLongAttribute(ITIME_ATTRIBUTE) * 1000); // tag value is in seconds
                    mtime = new Date(sourceTag.getLongAttribute(MTIME_ATTRIBUTE) * 1000); // .. convert to ms
                    atime = new Date(sourceTag.getLongAttribute(ATIME_ATTRIBUTE) * 1000);
                    hi = sourceTag.getLongAttribute(SIZE_HI_ATTRIBUTE);
                    lo = sourceTag.getLongAttribute(SIZE_LO_ATTRIBUTE);
                } else if (sourceTag.getTagName().equals(BLOB_TAG_NAME)) {
                    blobTag = clipTag;
                }
            }

            // sanity check
            if (blobTag == null)
                throw new RuntimeException("could not find blob tag");
            if (filePath == null)
                throw new RuntimeException("could not find file path attribute");
            // assume the rest have been pulled

            // make file path relative
            if (filePath.startsWith("/"))
                filePath = filePath.substring(1);

            File destFile = new File(targetDir, filePath);
            obj.setTargetIdentifier(destFile.getPath());

            // transfer the clip if:
            // - force is enabled
            // - target does not exist
            // - source mtime is after target mtime, or
            // - source size is different from target size
            long size = (lo > 0 ? hi << 32 : hi) + lo;
            if (force || !destFile.exists() || mtime.after(new Date(destFile.lastModified()))
                    || size != destFile.length()) {
                LogMF.info(l4j, "writing {0} to {1}", obj.getSourceIdentifier(), destFile);

                // make parent directories
                mkdirs(destFile.getParentFile());

                // write the file
                OutputStream out = new FileOutputStream(destFile);
                try {
                    blobTag.writeToStream(out);
                } finally {
                    try {
                        out.close();
                    } catch (Throwable t) {
                        l4j.warn("could not close target file", t);
                    }
                }

                Path destPath = destFile.toPath();

                // set times
                LogMF.debug(l4j, "updating timestamps for {0}", destPath);
                Files.setAttribute(destPath, "creationTime", FileTime.fromMillis(itime.getTime()));
                Files.setAttribute(destPath, "lastModifiedTime", FileTime.fromMillis(mtime.getTime()));
                Files.setAttribute(destPath, "lastAccessTime", FileTime.fromMillis(atime.getTime()));

                // verify size
                if (size != destFile.length())
                    throw new RuntimeException(String
                            .format("target file %s is not the right size (expected %d)", destFile, size));

            } else {
                LogMF.info(l4j, "{0} is up to date, skipping", destFile);
            }
        }

        timeOperationComplete(CasUtil.OPERATION_TOTAL);
    } catch (Throwable t) {
        timeOperationFailed(CasUtil.OPERATION_TOTAL);
        if (t instanceof RuntimeException)
            throw (RuntimeException) t;
        throw new RuntimeException("failed to sync object: " + t.getMessage(), t);
    }
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }//from   w w w. j a  va  2 s.  c  o  m
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleJarPath = getModuleJarPath(moduleId);
    Files.deleteIfExists(moduleJarPath);
    JarFile sourceJarFile;/*from   w  ww.j  a va2  s  .  c  o m*/
    try {
        sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile()));
    try {
        String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName();
        Enumeration<JarEntry> sourceEntries = sourceJarFile.entries();
        while (sourceEntries.hasMoreElements()) {
            JarEntry sourceEntry = sourceEntries.nextElement();
            if (sourceEntry.getName().equals(moduleSpecFileName)) {
                // avoid double entry for module spec
                continue;
            }
            destJarFile.putNextEntry(sourceEntry);
            if (!sourceEntry.isDirectory()) {
                InputStream inputStream = sourceJarFile.getInputStream(sourceEntry);
                IOUtils.copy(inputStream, destJarFile);
                IOUtils.closeQuietly(inputStream);
            }
            destJarFile.closeEntry();
        }
        // write the module spec
        String serialized = moduleSpecSerializer.serialize(moduleSpec);
        JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName());
        destJarFile.putNextEntry(moduleSpecEntry);
        IOUtils.write(serialized, destJarFile);
        destJarFile.closeEntry();
    } finally {
        IOUtils.closeQuietly(sourceJarFile);
        IOUtils.closeQuietly(destJarFile);
    }
    // update the timestamp on the jar file to indicate that the module has been updated
    Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:org.fim.command.ResetFileAttributesCommand.java

private boolean resetLastModified(Path file, FileState fileState, BasicFileAttributes attributes)
        throws IOException {
    long lastModified = attributes.lastModifiedTime().toMillis();
    long previousLastModified = fileState.getFileTime().getLastModified();
    if (lastModified != previousLastModified) {
        Files.setLastModifiedTime(file, FileTime.fromMillis(previousLastModified));
        System.out.printf("Set last modified: %s \t%s -> %s%n", fileState.getFileName(),
                formatDate(lastModified), formatDate(previousLastModified));
        return true;
    }//  ww  w  . j  av  a 2s .co  m
    return false;
}

From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public void setLastAccessTime(long atime) throws IOException {
    if (atime > 0) {
        FileTime fileTime = FileTime.fromMillis(atime);
        Files.setAttribute(file.toPath(), "lastAccessTime", fileTime);
    }/*from ww w.j  av  a  2 s .  co  m*/
}

From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public void setModifiedTime(long mtime) throws IOException {
    if (mtime > 0) {
        FileTime fileTime = FileTime.fromMillis(mtime);
        Files.setLastModifiedTime(file.toPath(), fileTime);
    }//from  ww  w.java  2  s .  co m
}

From source file:org.fao.geonet.api.groups.GroupsApi.java

/**
 * Writes the group logo image to the response. If no image is found it
 * writes a 1x1 transparent PNG. If the request contain cache related
 * headers it checks if the resource has changed and return a 304 Not
 * Modified response if not changed./* ww  w .  j  ava 2s  .  c om*/
 *
 * @param groupId    the group identifier.
 * @param webRequest the web request.
 * @param request    the native HTTP Request.
 * @param response   the servlet response.
 * @throws ResourceNotFoundException if no group exists with groupId.
 */
@ApiOperation(value = "Get the group logo image.", nickname = "get", notes = API_GET_LOGO_NOTE)
@RequestMapping(value = "/{groupId}/logo", method = RequestMethod.GET)
public void getGroupLogo(
        @ApiParam(value = "Group identifier", required = true) @PathVariable(value = "groupId") final Integer groupId,
        @ApiIgnore final WebRequest webRequest, HttpServletRequest request, HttpServletResponse response)
        throws ResourceNotFoundException {

    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());

    ApplicationContext context = ApplicationContextHolder.get();
    ServiceContext serviceContext = ApiUtils.createServiceContext(request, locale.getISO3Country());
    if (context == null) {
        throw new RuntimeException("ServiceContext not available");
    }

    GroupRepository groupRepository = context.getBean(GroupRepository.class);

    Group group = groupRepository.findOne(groupId);
    if (group == null) {
        throw new ResourceNotFoundException(
                messages.getMessage("api.groups.group_not_found", new Object[] { groupId }, locale));
    }
    try {
        final Path logosDir = Resources.locateLogosDir(serviceContext);
        final Path harvesterLogosDir = Resources.locateHarvesterLogosDir(serviceContext);
        final String logoUUID = group.getLogo();
        Path imagePath = null;
        FileTime lastModifiedTime = null;
        if (StringUtils.isNotBlank(logoUUID) && !logoUUID.startsWith("http://")
                && !logoUUID.startsWith("https//")) {
            imagePath = Resources.findImagePath(logoUUID, logosDir);
            if (imagePath == null) {
                imagePath = Resources.findImagePath(logoUUID, harvesterLogosDir);
            }
            if (imagePath != null) {
                lastModifiedTime = Files.getLastModifiedTime(imagePath);
                if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                    // webRequest.checkNotModified sets the right HTTP headers
                    response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);

                    return;
                }
                response.setContentType(AttachmentsApi.getFileContentType(imagePath));
                response.setContentLength((int) Files.size(imagePath));
                response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
                response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);
                FileUtils.copyFile(imagePath.toFile(), response.getOutputStream());
            }
        }

        if (imagePath == null) {
            // no logo image found. Return a transparent 1x1 png
            lastModifiedTime = FileTime.fromMillis(0);
            if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                return;
            }
            response.setContentType("image/png");
            response.setContentLength(TRANSPARENT_1_X_1_PNG.length);
            response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
            response.getOutputStream().write(TRANSPARENT_1_X_1_PNG);
        }

    } catch (IOException e) {
        Log.error(LOGGER,
                String.format("There was an error accessing the logo of the group with id '%d'", groupId));
        throw new RuntimeException(e);
    }
}

From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java

public void updateTimeFromTags(File localFile, PhotoEntry photo, boolean createdFolder)
        throws com.google.gdata.util.ParseException, IOException {
    ExifTags tags = photo.getExifTags();
    DateTime photoDate = null;/*from   w w  w  . jav  a 2s  .c  o m*/

    if (tags != null) {
        Date timestamp = tags.getTime();
        if (timestamp != null)
            photoDate = new DateTime(timestamp);
    }

    if (photoDate == null) {
        photoDate = photo.getUpdated();
    }

    log.debug("Setting datetime for " + localFile.getName() + " to " + photoDate.toString());

    Path fp = Paths.get(localFile.getPath());
    FileTime time = FileTime.fromMillis(photoDate.getValue());
    Files.setAttribute(fp, "basic:creationTime", time);

    long lastUpdated = photo.getUpdated().getValue();

    // Set the last update time of the local file...
    log.debug("Setting last update datetime for " + localFile.getName() + " to " + photo.getUpdated());
    if (!localFile.setLastModified(lastUpdated))
        log.warn("Unable to set date/time stamp for file: " + localFile);
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) {
        try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) {
            ArchiveEntry entry;/*www  .  j  a v  a2s  .  c  o m*/
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    final Path newDir = destDir.resolve(entry.getName());
                    if (!Files.exists(newDir))
                        Files.createDirectory(newDir);
                    continue;
                }
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                final Path destFile = destDir.resolve(entry.getName());
                final Path parentDir = destFile.getParent();
                if (!Files.exists(parentDir))
                    Files.createDirectories(parentDir);
                final long entryLastModified = entry.getLastModifiedDate().getTime();
                if (Files.exists(destFile) && Files.isRegularFile(destFile)
                        && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified
                        && entry.getSize() == Files.size(destFile))
                    continue;
                IOUtils.copy(in, destFile);
                Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified));
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
    }
}