Example usage for java.nio.file.attribute BasicFileAttributes lastAccessTime

List of usage examples for java.nio.file.attribute BasicFileAttributes lastAccessTime

Introduction

In this page you can find the example usage for java.nio.file.attribute BasicFileAttributes lastAccessTime.

Prototype

FileTime lastAccessTime();

Source Link

Document

Returns the time of last access.

Usage

From source file:org.apache.maven.plugin.cxx.GenerateMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    //Properties systemProperties = session.getSystemProperties();
    //Properties userProperties = session.getUserProperties();
    //Properties properties = session.getExecutionProperties();

    org.apache.maven.artifact.versioning.DefaultArtifactVersion defautCMakeVersion = new org.apache.maven.artifact.versioning.DefaultArtifactVersion(
            "3.0.0");
    org.apache.maven.artifact.versioning.DefaultArtifactVersion askedCMakeVersion = new org.apache.maven.artifact.versioning.DefaultArtifactVersion(
            cmakeMinVersion);/*from ww  w  . jav a2  s.c  o m*/
    boolean bCMake3OrAbove = (askedCMakeVersion.compareTo(defautCMakeVersion) >= 0);

    getLog().debug("CMake 3 or above asked (" + cmakeMinVersion + ") ? " + (bCMake3OrAbove ? "yes" : "no"));

    HashMap<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("parentGroupId", parentGroupId);
    valuesMap.put("parentArtifactId", parentArtifactId);
    valuesMap.put("parentVersion", parentVersion);
    valuesMap.put("groupId", groupId);
    valuesMap.put("artifactId", artifactId);
    valuesMap.put("artifactName", artifactName);
    valuesMap.put("version", version);
    valuesMap.put("cmakeMinVersion", cmakeMinVersion);
    valuesMap.put("parentScope", bCMake3OrAbove ? "PARENT_SCOPE" : "");
    valuesMap.put("projectVersion", bCMake3OrAbove ? "VERSION ${TARGET_VERSION}" : "");
    valuesMap.put("scmConnection", "");

    //1/ search for properties
    // -DgroupId=fr.neticoa -DartifactName=QtUtils -DartifactId=qtutils -Dversion=1.0-SNAPSHOT

    if (StringUtils.isEmpty(archetypeArtifactId)) {
        throw new MojoExecutionException("archetypeArtifactId is empty ");
    }

    Map<String, String> resources = listResourceFolderContent(archetypeArtifactId, valuesMap);

    if (null == resources || resources.size() == 0) {
        throw new MojoExecutionException("Unable to find archetype : " + archetypeArtifactId);
    }
    //1.1/ search potential scm location of current dir
    // svn case
    SvnInfo basedirSvnInfo = SvnService.getSvnInfo(basedir, null, basedir.getAbsolutePath(), getLog(), true);
    if (basedirSvnInfo.isValide()) {
        valuesMap.put("scmConnection", "scm:svn:" + basedirSvnInfo.getSvnUrl());
    }
    // todo : handle other scm : git (git remote -v; git log --max-count=1), etc.

    //2/ unpack resource to destdir 
    getLog().info("archetype " + archetypeArtifactId + " has " + resources.entrySet().size() + " item(s)");
    getLog().info("basedir = " + basedir);

    StrSubstitutor substitutor = new StrSubstitutor(valuesMap, "$(", ")");
    String sExecutionDate = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss.SSS").format(new Date());
    for (Map.Entry<String, String> entry : resources.entrySet()) {
        String curRes = entry.getKey();
        String curDest = entry.getValue();
        InputStream resourceStream = null;
        resourceStream = getClass().getResourceAsStream(curRes);
        if (null == resourceStream) {
            try {
                resourceStream = new FileInputStream(new File(curRes));
            } catch (Exception e) {
                // handled later
                resourceStream = null;
            }
        }

        getLog().debug("resource stream to open : " + curRes);
        getLog().debug("destfile pattern : " + curDest);
        if (null != resourceStream) {
            String sRelativePath = curDest.replaceFirst(Pattern.quote(archetypeArtifactId + File.separator),
                    "");
            File newFile = new File(basedir + File.separator + sRelativePath);

            //3/ create empty dir struct; if needed using a descriptor 
            //create all non exists folders
            File newDirs = new File(newFile.getParent());
            if (Files.notExists(Paths.get(newDirs.getPath()))) {
                getLog().info("dirs to generate : " + newDirs.getAbsoluteFile());
                newDirs.mkdirs();
            }

            if (!newFile.getName().equals("empty.dir")) {
                getLog().info("file to generate : " + newFile.getAbsoluteFile());
                try {
                    if (!newFile.createNewFile()) {
                        // duplicate existing file
                        FileInputStream inStream = new FileInputStream(newFile);
                        File backFile = File.createTempFile(newFile.getName() + ".",
                                "." + sExecutionDate + ".back", newFile.getParentFile());
                        FileOutputStream outStream = new FileOutputStream(backFile);

                        IOUtils.copy(inStream, outStream);
                        // manage file times
                        //backFile.setLastModified(newFile.lastModified());
                        BasicFileAttributes attributesFrom = Files.getFileAttributeView(
                                Paths.get(newFile.getPath()), BasicFileAttributeView.class).readAttributes();
                        BasicFileAttributeView attributesToView = Files.getFileAttributeView(
                                Paths.get(backFile.getPath()), BasicFileAttributeView.class);
                        attributesToView.setTimes(attributesFrom.lastModifiedTime(),
                                attributesFrom.lastAccessTime(), attributesFrom.creationTime());

                        inStream.close();
                        outStream.close();
                    }
                    FileOutputStream outStream = new FileOutputStream(newFile);

                    //4/ variable substitution :
                    // change prefix and suffix to '$(' and ')'
                    // see https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/text/StrSubstitutor.html
                    String content = IOUtils.toString(resourceStream, "UTF8");
                    content = substitutor.replace(content);

                    //IOUtils.copy( resourceStream, outStream );
                    IOUtils.write(content, outStream, "UTF8");

                    outStream.close();
                    resourceStream.close();
                } catch (IOException e) {
                    getLog().error("File " + newFile.getAbsoluteFile() + " can't be created : " + e);
                }
            }
        } else {
            getLog().error("Unable to open resource " + curRes);
        }
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

private void copyAttributes(Path src, Path dst) throws IOException {
    Set<Class<? extends FileAttributeView>> supportedAttributeViewTypes = fileStore
            .supportedFileAttributeViewTypes();
    if (supportedAttributeViewTypes.contains(BasicFileAttributeView.class)) {
        BasicFileAttributes srcAttrs = Files.readAttributes(src, BasicFileAttributes.class);
        BasicFileAttributeView dstAttrView = Files.getFileAttributeView(dst, BasicFileAttributeView.class);
        dstAttrView.setTimes(srcAttrs.lastModifiedTime(), srcAttrs.lastAccessTime(), srcAttrs.creationTime());
    }//from ww w . j  av a2 s  . c om
    if (supportedAttributeViewTypes.contains(FileOwnerAttributeView.class)) {
        FileOwnerAttributeView srcAttrView = Files.getFileAttributeView(src, FileOwnerAttributeView.class);
        FileOwnerAttributeView dstAttrView = Files.getFileAttributeView(dst, FileOwnerAttributeView.class);
        dstAttrView.setOwner(srcAttrView.getOwner());
    }
    if (supportedAttributeViewTypes.contains(PosixFileAttributeView.class)) {
        PosixFileAttributes srcAttrs = Files.readAttributes(src, PosixFileAttributes.class);
        PosixFileAttributeView dstAttrView = Files.getFileAttributeView(dst, PosixFileAttributeView.class);
        dstAttrView.setGroup(srcAttrs.group());
        dstAttrView.setPermissions(srcAttrs.permissions());
    }
    if (supportedAttributeViewTypes.contains(DosFileAttributeView.class)) {
        DosFileAttributes srcAttrs = Files.readAttributes(src, DosFileAttributes.class);
        DosFileAttributeView dstAttrView = Files.getFileAttributeView(dst, DosFileAttributeView.class);
        dstAttrView.setArchive(srcAttrs.isArchive());
        dstAttrView.setHidden(srcAttrs.isHidden());
        dstAttrView.setReadOnly(srcAttrs.isReadOnly());
        dstAttrView.setSystem(srcAttrs.isSystem());
    }
}

From source file:org.cryptomator.frontend.webdav.servlet.DavFolder.java

private void copyInternal(DavNode destination, boolean shallow) throws DavException {
    assert exists();
    assert attr.isPresent();
    if (!Files.isDirectory(destination.path.getParent())) {
        throw new DavException(DavServletResponse.SC_CONFLICT, "Destination's parent doesn't exist.");
    }//  w ww  . j a v a  2  s .c o  m

    try {
        if (shallow && destination instanceof DavFolder) {
            // http://www.webdav.org/specs/rfc2518.html#copy.for.collections
            Files.createDirectory(destination.path);
            BasicFileAttributeView attrView = Files.getFileAttributeView(destination.path,
                    BasicFileAttributeView.class);
            if (attrView != null) {
                BasicFileAttributes a = attr.get();
                attrView.setTimes(a.lastModifiedTime(), a.lastAccessTime(), a.creationTime());
            }
        } else {
            Files.walkFileTree(path,
                    new CopyingFileVisitor(path, destination.path, StandardCopyOption.REPLACE_EXISTING));
        }
    } catch (IOException e) {
        throw new DavException(DavServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    }
}

From source file:org.duracloud.retrieval.mgmt.RetrievalWorkerTest.java

@Test
public void testRetrieveToFile() throws Exception {
    RetrievalWorker worker = createRetrievalWorker(true);
    File localFile = new File(tempDir, "retrieve-to-file-test");
    assertFalse(localFile.exists());//w  ww  . j ava 2  s. c om

    worker.retrieveToFile(localFile, null);
    assertTrue(localFile.exists());

    // Test timestamps
    BasicFileAttributes fileAttributes = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
    assertEquals(testTime, fileAttributes.creationTime().toMillis());
    assertEquals(testTime, fileAttributes.lastAccessTime().toMillis());
    assertEquals(testTime, fileAttributes.lastModifiedTime().toMillis());

    // Test file value
    String fileValue = FileUtils.readFileToString(localFile);
    assertEquals(fileValue, contentValue);

    // Test failure
    worker = createBrokenRetrievalWorker(true);
    localFile = new File(tempDir, "retrieve-to-file-failure-test");
    assertFalse(localFile.exists());

    try {
        worker.retrieveToFile(localFile, null);
        fail("Exception expected with non-matching checksum");
    } catch (IOException expected) {
        assertNotNull(expected);
    }
}

From source file:org.duracloud.retrieval.mgmt.RetrievalWorkerTest.java

@Test
public void testApplyTimestamps() throws Exception {
    String time1 = DateUtil.convertToStringLong(testTime + 100000);
    String time2 = DateUtil.convertToStringLong(testTime + 200000);
    String time3 = DateUtil.convertToStringLong(testTime + 300000);
    Map<String, String> props = new HashMap<>();
    props.put(ContentStore.CONTENT_FILE_CREATED, time1);
    props.put(ContentStore.CONTENT_FILE_ACCESSED, time2);
    props.put(ContentStore.CONTENT_FILE_MODIFIED, time3);

    ContentStream content = new ContentStream(null, props);

    File localFile = new File(tempDir, "timestamp-test");
    FileUtils.writeStringToFile(localFile, contentValue);

    // Check that initial timestamps are current
    BasicFileAttributes fileAttributes = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
    long now = System.currentTimeMillis();
    assertTrue(isTimeClose(fileAttributes.creationTime().toMillis(), now));
    assertTrue(isTimeClose(fileAttributes.lastAccessTime().toMillis(), now));
    assertTrue(isTimeClose(fileAttributes.lastModifiedTime().toMillis(), now));

    RetrievalWorker worker = createRetrievalWorker(true);
    worker.applyTimestamps(content, localFile);

    // Verify that timestamps were set
    fileAttributes = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
    long creationTime = fileAttributes.creationTime().toMillis();
    long lastAccessTime = fileAttributes.lastAccessTime().toMillis();
    long lastModifiedTime = fileAttributes.lastModifiedTime().toMillis();

    assertFalse(isTimeClose(creationTime, now));
    assertFalse(isTimeClose(lastAccessTime, now));
    assertFalse(isTimeClose(lastModifiedTime, now));
    assertTrue(testTime + 100000 == creationTime || // windows
            testTime + 300000 == creationTime); // linux
    assertEquals(testTime + 200000, lastAccessTime);
    assertEquals(testTime + 300000, lastModifiedTime);
}

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

private void simulateHardwareCorruption(String fileName) throws IOException {
    Path file = rootDir.resolve(fileName);
    // Keep original timestamps
    BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);

    // A zero byte appears in the middle of the file
    byte[] bytes = Files.readAllBytes(file);
    bytes[bytes.length / 2] = 0;/*from   w  ww .ja  v  a  2 s  .  com*/

    Files.delete(file);
    Files.write(file, bytes, CREATE);

    // Restore the original timestamps
    Files.getFileAttributeView(file, BasicFileAttributeView.class).setTimes(attributes.lastModifiedTime(),
            attributes.lastAccessTime(), attributes.creationTime());
}

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

@Override
public long getLastAccessTime() {
    try {// w  w  w . j a  va 2s .  c om
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        return attr.lastAccessTime().toMillis();
    } catch (IOException e) {
        logger.error("Error in getLastAccessTime()", e);
        return 0;
    }
}