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

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

Introduction

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

Prototype

FileTime creationTime();

Source Link

Document

Returns the creation time.

Usage

From source file:view.ChooseFile.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    int returnVal = chooser.showOpenDialog((Component) evt.getSource());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {//from w w w .  jav a2s .  co m
            path = file.toString();
            System.out.println(path);
            String name = chooser.getSelectedFile().getName();
            jLabel2.setText(name);

            Path filePath = Paths.get(file.getPath());
            BasicFileAttributes bfa = Files.readAttributes(filePath, BasicFileAttributes.class);

            attr_1_file_name = FilenameUtils.getBaseName(file.getName());
            attr_2_file_size = (file.length()) + "";
            attr_3_file_extension = FilenameUtils.getExtension(file.getPath());
            attr_4_file_created_time = bfa.creationTime().toMillis() + "";

            selectedFilePath = System.currentTimeMillis() + "." + FilenameUtils.getExtension(path);
            FileUtils.copyFile(file, new File(Configuration.dataCloud + selectedFilePath));

        } catch (Exception ex) {
            System.out.println("problem accessing file" + file.getAbsolutePath());
        }
    } else {
        System.out.println("File access cancelled by user.");
    }
}

From source file:org.sigmah.server.file.impl.BackupArchiveManagerImpl.java

/**
 * Builds the given {@code file} corresponding {@link BackupDTO}.
 * //from  w w  w .j  a v  a  2s . c o  m
 * @param file
 *          The backup file path.
 * @return The given {@code file} corresponding {@link BackupDTO}.
 * @throws IOException
 *           If an I/O error occurs.
 * @throws IllegalArgumentException
 *           If the given {@code file} does not reference a valid backup file.
 */
private BackupDTO fromFile(final Path file) throws IOException {

    final String filename = file.getFileName().toString();
    final Matcher matcher = BACKUP_ARCHIVE_NAME_PATTERN.matcher(filename);

    if (!matcher.matches()) {
        throw new IllegalArgumentException("Invalid backup archive file name '" + filename + "'.");
    }

    final Integer organizationId = Integer.parseInt(matcher.group(1));
    final Integer orgUnitId = Integer.parseInt(matcher.group(2));
    final LoadingScope loadingScope = LoadingScope.valueOf(matcher.group(3));
    final String extension = matcher.group(4);

    final BasicFileAttributeView view = Files.getFileAttributeView(file, BasicFileAttributeView.class);
    final BasicFileAttributes attributes = view.readAttributes();

    final BackupDTO result = new BackupDTO();

    result.setOrganizationId(organizationId);
    result.setOrgUnitId(orgUnitId);
    result.setOrgUnitName(orgUnitDAO.findById(orgUnitId).getFullName());
    result.setLoadingScope(loadingScope);
    result.setCreationDate(new Date(attributes.creationTime().toMillis()));
    result.setArchiveFileName(filename);
    result.setRunning(extension.equals(BACKUP_ARCHIVE_TEMP_EXT));

    return result;
}

From source file:org.alfresco.extension.bulkimport.source.fs.FilesystemBulkImportItemVersion.java

private final synchronized void loadMetadataIfNecessary() {
    if (cachedMetadata == null) {
        cachedMetadata = metadataLoader.loadMetadata(metadataReference);
        contentIsInPlace = false;/*from  w w w . j a v  a2s .c o  m*/

        if (contentReference != null) {
            try {
                final Path path = contentReference.toPath();
                final BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);

                // If not set in the metadata file, set the creation timestamp to what's on disk
                if (!cachedMetadata.getProperties().containsKey(ContentModel.PROP_CREATED.toString())
                        && !cachedMetadata.getProperties()
                                .containsKey(ContentModel.PROP_CREATED.toPrefixString())
                        && attributes.creationTime() != null) {
                    final Date created = new Date(attributes.creationTime().toMillis());
                    cachedMetadata.addProperty(ContentModel.PROP_CREATED.toString(), created);
                }

                // If not set in the metadata file, set the modification timestamp to what's on disk
                if (!cachedMetadata.getProperties().containsKey(ContentModel.PROP_MODIFIED.toString())
                        && !cachedMetadata.getProperties()
                                .containsKey(ContentModel.PROP_MODIFIED.toPrefixString())
                        && attributes.lastModifiedTime() != null) {
                    final Date modified = new Date(attributes.lastModifiedTime().toMillis());
                    cachedMetadata.addProperty(ContentModel.PROP_MODIFIED.toString(), modified);
                }

                // If an in-place import is possible, attempt to construct a content URL
                if (!contentReference.isDirectory()
                        && isInContentStore(configuredContentStore, contentReference)) {
                    final ContentData contentData = buildContentProperty(mimeTypeService,
                            configuredContentStore, contentReference);

                    if (contentData != null) {
                        // We have valid in-place content
                        contentIsInPlace = true;
                        cachedMetadata.addProperty(ContentModel.PROP_CONTENT.toString(), contentData);
                    } else {
                        if (warn(FilesystemBulkImportItem.log))
                            warn(FilesystemBulkImportItem.log, "Unable to in-place import '"
                                    + getFileName(contentReference) + "'. Will stream it instead.");
                    }
                }
            } catch (final IOException ioe) {
                // Not much we can do in this case - log it and keep on truckin'
                if (warn(FilesystemBulkImportItem.log))
                    warn(FilesystemBulkImportItem.log,
                            "Unable to read file attributes for " + contentReference.getAbsolutePath()
                                    + ". Creation and modification timestamps will be system generated.",
                            ioe);
            }
        }
    }
}

From source file:de.cismet.cids.custom.utils.berechtigungspruefung.BerechtigungspruefungHandler.java

/**
 * DOCUMENT ME!//from w  w  w.j  ava 2 s. c o m
 *
 * @param  user  DOCUMENT ME!
 */
public void deleteOldDateianhangFiles(final User user) {
    final File directory = new File(BerechtigungspruefungProperties.getInstance().getAnhangAbsPath());
    final Date thresholdDate = getThresholdAnhangDate();

    // look for all anhang files
    for (final File file : directory.listFiles()) {
        if (file.isFile()) {
            try {
                final String fileName = file.getName();
                final BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
                final Date creationDate = new Date(attr.creationTime().toMillis());

                // file older then threshold date (1 month) ?
                if (creationDate.before(thresholdDate)) {
                    final CidsBean anfrageBean = loadAnfrageBean(user, fileName);
                    // assuring, that the file corresponds to an existing bean This prevents accidental deletion of
                    // non-anhang files (i.e. if AnhangAbsPath was set to a path that contains also other files)
                    if (anfrageBean != null) {
                        final Timestamp anfrageTs = (Timestamp) anfrageBean.getProperty("anfrage_timestamp");
                        // timestamp filed in the bean agrees with the file creation date ?
                        if (anfrageTs.before(thresholdDate)) {
                            LOG.info("deleting old Anhang file: " + file.getName() + " (date: "
                                    + creationDate.toString() + ")");
                            // now we can delete (hopefully)
                            file.delete();
                        }
                    }
                }
            } catch (final IOException ex) {
                LOG.warn("could not delete Anhang file: " + file.getName(), ex);
            }
        }
    }
}

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 .  java 2s  .  c  o m
    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.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public long getCreationTime() {
    try {/*  w  w  w .ja  v a  2  s.c  o m*/
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        return attr.creationTime().toMillis();
    } catch (IOException e) {
        logger.error("Error in getCreationTime()", e);
        return 0;
    }
}

From source file:org.tinymediamanager.core.entities.MediaEntity.java

public void setDateAddedFromMediaFile(MediaFile mf) {
    try {/*  w  w  w  .j a v  a  2 s . c  o m*/
        BasicFileAttributes view = Files.readAttributes(mf.getFileAsPath(), BasicFileAttributes.class);
        Date creDat = new Date(view.creationTime().toMillis());
        Date modDat = new Date(view.lastModifiedTime().toMillis());
        if (creDat.compareTo(dateAdded) < 0) {
            setDateAdded(creDat);
        }
        if (modDat.compareTo(dateAdded) < 0) {
            setDateAdded(modDat);
        }
    } catch (Exception e) {
    }
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
    List<CopyOption> optionList = Arrays.asList(options);
    if (!optionList.contains(StandardCopyOption.REPLACE_EXISTING)) {
        if (Files.exists(target))
            throw new java.nio.file.FileAlreadyExistsException(source.toString(), target.toString(),
                    "could not copy file to destination");
    } else {/*from  w w w .  j av  a2s . c  o m*/
        Files.deleteIfExists(target);
    }

    FileSystem sourceFS = source.getFileSystem();
    FileSystem targetFS = target.getFileSystem();

    if (optionList.contains(HadoopCopyOption.REMOTE_COPY) && sourceFS.equals(targetFS)) {

        remoteCopy(source, target, options);
        return;

    }
    try (SeekableByteChannel sourceChannel = sourceFS.provider().newByteChannel(source,
            EnumSet.of(StandardOpenOption.READ))) {

        Set<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.WRITE);

        if (optionList.contains(StandardCopyOption.REPLACE_EXISTING))
            openOptions.add(StandardOpenOption.CREATE);
        else
            openOptions.add(StandardOpenOption.CREATE_NEW);
        List<FileAttribute<?>> fileAttributes = new ArrayList<>();
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {

            Set<String> sourceAttrViews = sourceFS.supportedFileAttributeViews();
            Set<String> targetAttrViews = targetFS.supportedFileAttributeViews();
            if (sourceAttrViews.contains(PosixFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(PosixFileAttributeViewImpl.NAME)) {
                PosixFileAttributes posixAttributes = sourceFS.provider().readAttributes(source,
                        PosixFileAttributes.class);
                fileAttributes.add(PosixFilePermissions.asFileAttribute(posixAttributes.permissions()));
            }

            if (sourceAttrViews.contains(HadoopFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(HadoopFileAttributeViewImpl.NAME)) {
                final HadoopFileAttributes hdfsAttributes = sourceFS.provider().readAttributes(source,
                        HadoopFileAttributes.class);
                fileAttributes.add(new FileAttribute<Long>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":blockSize";
                    }

                    @Override
                    public Long value() {
                        return hdfsAttributes.getBlockSize();
                    }
                });
                fileAttributes.add(new FileAttribute<Short>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":replication";
                    }

                    @Override
                    public Short value() {
                        return hdfsAttributes.getReplication();
                    }
                });

            }
        }

        FileAttribute<?>[] attributes = fileAttributes.toArray(new FileAttribute<?>[fileAttributes.size()]);

        try (SeekableByteChannel targetChannel = targetFS.provider().newByteChannel(target, openOptions,
                attributes)) {
            int buffSize = getConfiguration().getInt(DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_KEY,
                    DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_DEFAULT);
            ByteBuffer buffer = ByteBuffer.allocate(buffSize);
            buffer.clear();
            while (sourceChannel.read(buffer) > 0) {
                buffer.flip();
                targetChannel.write(buffer);
                buffer.clear();
            }

        }
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {
            BasicFileAttributes attrs = sourceFS.provider().readAttributes(source, BasicFileAttributes.class);
            BasicFileAttributeView view = targetFS.provider().getFileAttributeView(target,
                    BasicFileAttributeView.class);
            view.setTimes(attrs.lastModifiedTime(), attrs.lastAccessTime(), attrs.creationTime());

        }

    }

}

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   w ww. ja v  a2  s  .  c  om
    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.jclouds.kinetic.strategy.internal.KineticStorageStrategyImpl.java

@Override
public StorageMetadata getContainerMetadata(String container) {
    MutableStorageMetadata metadata = new MutableStorageMetadataImpl();
    metadata.setName(container);//from ww  w.  jav  a 2s  . c om
    metadata.setType(StorageType.CONTAINER);
    metadata.setLocation(getLocation(container));
    Path path = new File(buildPathStartingFromBaseDir(container)).toPath();
    BasicFileAttributes attr;
    try {
        attr = readAttributes(path, BasicFileAttributes.class);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    metadata.setCreationDate(new Date(attr.creationTime().toMillis()));
    return metadata;
}