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:eu.edisonproject.classification.prepare.controller.DataPrepare.java

private LocalDate getCreationDate(File file) {
    Path p = Paths.get(file.getAbsolutePath());
    BasicFileAttributes attr = null;
    try {/*from  w  w w  .j  a  v a  2s  . co  m*/
        attr = Files.readAttributes(p, BasicFileAttributes.class);
    } catch (IOException ex) {
        Logger.getLogger(Text2Avro.class.getName()).log(Level.SEVERE, null, ex);
    }
    FileTime ct = attr.creationTime();
    DateTimeFormatter formatter;

    //        
    //        LocalDate.parse("2016-09-18T11:40:03.750522Z", formatter);
    formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
    LocalDate date = null;
    try {
        date = LocalDate.parse(ct.toString(), formatter);
    } catch (java.lang.IllegalArgumentException ex) {
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
        date = LocalDate.parse(ct.toString(), formatter);
    }
    Logger.getLogger(Text2Avro.class.getName()).log(Level.INFO, "CreationDate: {0}", date);
    return date;
}

From source file:eu.edisonproject.classification.prepare.controller.Text2Avro.java

@Override
public void execute() {
    File file = new File(inputFolder);
    Document davro;//  ww  w . ja v  a 2s  .  c  o m
    DocumentAvroSerializer dAvroSerializer = null;
    if (file.isDirectory()) {
        File[] filesInDir = file.listFiles();
        Arrays.sort(filesInDir);
        for (File f : filesInDir) {
            if (FilenameUtils.getExtension(f.getName()).endsWith("txt")) {
                Path p = Paths.get(f.getAbsolutePath());
                BasicFileAttributes attr = null;
                try {
                    attr = Files.readAttributes(p, BasicFileAttributes.class);
                } catch (IOException ex) {
                    Logger.getLogger(Text2Avro.class.getName()).log(Level.SEVERE, null, ex);
                }
                FileTime date = attr.creationTime();

                //                    DateTimeFormatter formatter
                //                            = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
                //                    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");

                //                    System.err.println(LocalDate.parse(date.toString(), formatter));
                documentObject = new DocumentObject();
                extract(this.getDocumentObject(), f.getPath());
                documentObject.setDescription(documentObject.getDescription().toLowerCase());
                clean(this.getDocumentObject().getDescription());
                if (documentObject.getDescription().equals("")) {
                    continue;
                }
                //                    documentObject.setDate(LocalDate.parse(date.toString(), formatter));
                documentObjectList.add(this.getDocumentObject());

                davro = new Document();
                davro.setDocumentId(documentObject.getDocumentId());
                davro.setTitle(documentObject.getTitle());
                davro.setDate(documentObject.getDate().toString());
                davro.setDescription(documentObject.getDescription());

                if (dAvroSerializer == null) {
                    dAvroSerializer = new DocumentAvroSerializer(
                            outputFolder + File.separator + documentObject.getTitle() + date + ".avro",
                            davro.getSchema());
                }
                dAvroSerializer.serialize(davro);
            }
        }
        if (dAvroSerializer != null) {
            dAvroSerializer.close();
            dAvroSerializer = null;
        }

    } else {
        System.out.println("NOT A DIRECTORY");
    }
}

From source file:com.fujitsu.dc.core.eventlog.ArchiveLogCollection.java

/**
 * ????.//from w w w.j  av  a  2s. c om
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:io.personium.core.eventlog.ArchiveLogCollection.java

/**
 * ????.//from   w  w  w. ja v a  2s .c  o  m
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:functionaltests.job.log.TestJobServerLogs.java

private void printDiagnosticMessage() {
    int LIMIT = 5;
    System.out.println("This test is going to fail, but before we print diagnostic message."
            + simpleDateFormat.format(new Date()));
    // iterate over all files in the 'logsLocation'
    for (File file : FileUtils.listFiles(new File(logsLocation), TrueFileFilter.INSTANCE,
            TrueFileFilter.INSTANCE)) {//from w w  w  .ja va 2  s  . c  om
        try {
            BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            System.out.println(String.format("Name: %s, Size: %d, Created: %s, Modified: %s",
                    file.getAbsolutePath(), attr.size(), attr.creationTime(), attr.lastModifiedTime()));
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            int i;
            // print up to LIMIT first lines
            for (i = 0; i < LIMIT && (line = br.readLine()) != null; ++i) {
                System.out.println(line);
            }

            Queue<String> queue = new CircularFifoQueue<>(LIMIT);
            // reading last LIMIT lines
            for (; (line = br.readLine()) != null; ++i) {
                queue.add(line);
            }

            if (i >= LIMIT * 2) { // if there is more line than 2*LIMIT
                System.out.println(".......");
                System.out.println("....... (skipped content)");
                System.out.println(".......");
            }
            for (String l : queue) { // print rest of the file
                System.out.println(l);
            }

            System.out.println("------------------------------------");
            System.out.println();
        } catch (IOException e) {
            System.out.println("Exception ocurred during accessing file attributes " + e);
        }
    }
}

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:com.willkara.zeteo.filetypes.impl.BaseFileType.java

/**
 * Creates the BaseFileType object from the Java {@link java.io.File} class
 * as an argument.//www. j ava 2  s. c  o m
 *
 * @param f The file object
 */
public BaseFileType(File f) {

    if (f.isFile()) {
        BasicFileAttributes attr;
        try {
            attr = Files.readAttributes(f.toPath(), BasicFileAttributes.class);

            fileName = f.getName();
            filePath = f.getCanonicalPath();
            fileSize = f.length();

            lastModifiedDate = new Date(attr.lastModifiedTime().toMillis());
            createdDate = new Date(attr.creationTime().toMillis());
            lastAccessDate = new Date(attr.lastAccessTime().toMillis());
        } catch (IOException ex) {
            Logger.getLogger(BaseFileType.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.roda.core.common.monitor.TransferredResourcesScanner.java

public Map<String, String> moveTransferredResource(List<TransferredResource> resources, String newRelativePath,
        boolean replaceExisting, boolean reindexResources, boolean addOldRelativePathToNewRelativePath)
        throws AlreadyExistsException, GenericException, IsStillUpdatingException, NotFoundException {

    Map<String, String> oldToNewTransferredResourceIds = new HashMap<>();
    List<TransferredResource> resourcesToIndex = new ArrayList<>();
    boolean notFoundResources = false;

    String baseFolder = RodaCoreFactory.getRodaConfiguration().getString("core.ingest.processed.base_folder",
            "PROCESSED");
    String successFolder = RodaCoreFactory.getRodaConfiguration()
            .getString("core.ingest.processed.successfully_ingested", "SUCCESSFULLY_INGESTED");
    String unsuccessFolder = RodaCoreFactory.getRodaConfiguration()
            .getString("core.ingest.processed.unsuccessfully_ingested", "UNSUCCESSFULLY_INGESTED");

    for (TransferredResource resource : resources) {
        if (FSUtils.exists(Paths.get(resource.getFullPath()))) {
            Path newResourcePath = basePath.resolve(newRelativePath);
            if (addOldRelativePathToNewRelativePath) {
                newResourcePath = newResourcePath
                        .resolve(resource.getRelativePath().replace(baseFolder + "/" + successFolder + "/", "")
                                .replace(baseFolder + "/" + unsuccessFolder + "/", ""));
            } else {
                newResourcePath = newResourcePath.resolve(resource.getName());
            }/*from ww  w . j  a v  a2s .c  o m*/

            FSUtils.move(Paths.get(resource.getFullPath()), newResourcePath, replaceExisting);

            // create & index transferred resource in the new location
            TransferredResource newResource = instantiateTransferredResource(newResourcePath, basePath);
            Date creationDate = resource.getCreationDate();
            try {
                BasicFileAttributes attr = Files.readAttributes(newResourcePath, BasicFileAttributes.class);
                creationDate = new Date(attr.creationTime().toMillis());
            } catch (IOException e) {
                creationDate = new Date();
            }

            newResource.setCreationDate(creationDate);
            newResource.setSize(resource.getSize());
            newResource.setLastScanDate(new Date());
            try {
                index.create(TransferredResource.class, newResource);
            } catch (RequestNotValidException e) {
                // do nothing
            }

            oldToNewTransferredResourceIds.put(resource.getUUID(), newResource.getUUID());
            resourcesToIndex.add(resource);
        } else {
            notFoundResources = true;
        }
    }

    if (reindexResources) {
        updateTransferredResources(Optional.of(newRelativePath), true);
    }
    reindexOldResourcesParentsAfterMove(resourcesToIndex);

    // doing the throw after the moving process to reindex the moved ones
    if (notFoundResources) {
        throw new NotFoundException("Some transferred resources were moved or do not exist");
    }

    return oldToNewTransferredResourceIds;
}

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;/*www.  j  a va2s  .  c  o m*/

    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.mangelp.fakeSmtpWeb.httpServer.mailBrowser.MailFile.java

protected void getAttributes() throws IOException {
    BasicFileAttributes attr = Files.readAttributes(this.getFile().toPath(), BasicFileAttributes.class);

    this.setCreationDate(new Date(attr.creationTime().toMillis()));
    this.setSize(attr.size());
}