@Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return templates[rowIndex].getName(); } else if (columnIndex == 1) { return templates[rowIndex].getVersion(); } else if (columnIndex == 2) { return templates[rowIndex].getShortDescription(); } else if (columnIndex == 3) { Path temPath = Paths.get(templates[rowIndex].getFile().getAbsolutePath()); try { BasicFileAttributes view = Files.getFileAttributeView(temPath, BasicFileAttributeView.class).readAttributes(); FileTime creationTime = view.creationTime(); DateFormat df = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy"); String cTime = df.format(creationTime.toMillis()); return cTime; } catch (IOException e) { return "--"; } } else { return null; } }
private void walkClientsForServerFile(File serverFile) throws IOException { if(!Files.exists(serverFile.getAbsolutePath())) { return; } FileTime modifiedTime = Files.getLastModifiedTime(serverFile.getAbsolutePath()); List<Inspector> inspectors = new ArrayList<>(getServerFileInspectors(serverFile, modifiedTime)); for (Client client : clients.values()) { File clientFile = client.files.get(serverFile.getId()); if(clientFile != null) { inspectors.addAll(getClientFileInspectors(clientFile)); } } inspect(serverFile, inspectors); }
public void flush() { if (!needsFlush) { return; } needsFlush = false; LOGGER.info("flushing bucket {}", bucketNumber); try { synchronized (this) { final FileChannel openChannel = getOpenChannel(); if (openChannel.isOpen()) { openChannel.force(wantsTimestampUpdate); if (!wantsTimestampUpdate) { Files.setLastModifiedTime(filePath, lastModifiedTime); } else { lastModifiedTime = FileTime.from(Instant.now()); } wantsTimestampUpdate = false; } } } catch (IOException e) { LOGGER.warn("unable to flush file of bucket {}", bucketNumber); } }
static void testTimeConversions(long from, long to, long step) { ZipEntry ze = new ZipEntry("TestExtraTime.java"); for (long time = from; time <= to; time += step) { ze.setTime(time); FileTime lastModifiedTime = ze.getLastModifiedTime(); if (lastModifiedTime.toMillis() != time) { throw new RuntimeException("setTime should make getLastModifiedTime " + "return the specified instant: " + time + " got: " + lastModifiedTime.toMillis()); } if (ze.getTime() != time) { throw new RuntimeException("getTime after setTime, expected: " + time + " got: " + ze.getTime()); } } }
/** * Like the unix command of the same name, creates an empty file or updates the last modified * timestamp of the existing file at the given path to the current system time. */ public static void touch(Path path) throws IOException { checkNotNull(path); try { Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis())); } catch (NoSuchFileException e) { try { Files.createFile(path); } catch (FileAlreadyExistsException ignore) { // The file didn't exist when we called setLastModifiedTime, but it did when we called // createFile, so something else created the file in between. The end result is // what we wanted: a new file that probably has its last modified time set to approximately // now. Or it could have an arbitrary last modified time set by the creator, but that's no // different than if another process set its last modified time to something else after we // created it here. } } }
/** * Sets the {@link Path}'s last modified time and last access time to * the given valid times. * * @param mtime the modification time to set (only if no less than zero). * @param atime the access time to set (only if no less than zero). * @throws IOException if setting the times fails. */ @Override public void setTimes(Path p, long mtime, long atime) throws IOException { try { BasicFileAttributeView view = Files.getFileAttributeView( pathToFile(p).toPath(), BasicFileAttributeView.class); FileTime fmtime = (mtime >= 0) ? FileTime.fromMillis(mtime) : null; FileTime fatime = (atime >= 0) ? FileTime.fromMillis(atime) : null; view.setTimes(fmtime, fatime, null); } catch (NoSuchFileException e) { throw new FileNotFoundException("File " + p + " does not exist"); } }
@Test public void testBasicFileAttributesToFileStat() { Instant instant = Instant.ofEpochSecond(424242l, 42); FileTime ftime = FileTime.from(instant); BasicFileAttributes attr = Mockito.mock(BasicFileAttributes.class); Mockito.when(attr.isDirectory()).thenReturn(true); Mockito.when(attr.lastModifiedTime()).thenReturn(ftime); Mockito.when(attr.creationTime()).thenReturn(ftime); Mockito.when(attr.lastAccessTime()).thenReturn(ftime); Mockito.when(attr.size()).thenReturn(42l); FileAttributesUtil util = new FileAttributesUtil(); FileStat stat = util.basicFileAttributesToFileStat(attr); Assertions.assertTrue((FileStat.S_IFDIR & stat.st_mode.intValue()) == FileStat.S_IFDIR); Assertions.assertEquals(424242l, stat.st_mtim.tv_sec.get()); Assertions.assertEquals(42, stat.st_mtim.tv_nsec.intValue()); Assertions.assertEquals(424242l, stat.st_ctim.tv_sec.get()); Assertions.assertEquals(42, stat.st_ctim.tv_nsec.intValue()); Assumptions.assumingThat(Platform.IS_MAC || Platform.IS_WINDOWS, () -> { Assertions.assertEquals(424242l, stat.st_birthtime.tv_sec.get()); Assertions.assertEquals(42, stat.st_birthtime.tv_nsec.intValue()); }); Assertions.assertEquals(424242l, stat.st_atim.tv_sec.get()); Assertions.assertEquals(42, stat.st_atim.tv_nsec.intValue()); Assertions.assertEquals(42l, stat.st_size.longValue()); }
@Override public Lock obtainLock(@NonNull Directory dir, String lockName) throws IOException { if (!(dir instanceof RedisDirectory)) { throw new IllegalArgumentException("Expect argument of type [" + RedisDirectory.class.getName() + "]!"); } Path lockFile = lockFileDirectory.resolve(lockName); try { Files.createFile(lockFile); log.debug("Lock file path = {}", lockFile.toFile().getAbsolutePath()); } catch (IOException ignore) { //ignore log.debug("Lock file already exists!"); } final Path realPath = lockFile.toRealPath(); final FileTime creationTime = Files.readAttributes(realPath, BasicFileAttributes.class).creationTime(); if (LOCK_HELD.add(realPath.toString())) { FileChannel fileChannel = null; FileLock lock = null; try { fileChannel = FileChannel.open(realPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE); lock = fileChannel.tryLock(); if (lock != null) { return new RedisLock(lock, fileChannel, realPath, creationTime); } else { throw new LockObtainFailedException("Lock held by another program: " + realPath); } } finally { if (lock == null) { IOUtils.closeQuietly(fileChannel); clearLockHeld(realPath); } } } else { throw new LockObtainFailedException("Lock held by this virtual machine: " + realPath); } }
static void check(FileTime mtime, FileTime atime, FileTime ctime, ZipEntry ze, byte[] extra) { /* System.out.printf(" mtime [%tc]: [%tc]/[%tc]%n", mtime.to(TimeUnit.MILLISECONDS), ze.getTime(), ze.getLastModifiedTime().to(TimeUnit.MILLISECONDS)); */ if (mtime.to(TimeUnit.SECONDS) != ze.getLastModifiedTime().to(TimeUnit.SECONDS)) throw new RuntimeException("Timestamp: storing mtime failed!"); if (atime != null && atime.to(TimeUnit.SECONDS) != ze.getLastAccessTime().to(TimeUnit.SECONDS)) throw new RuntimeException("Timestamp: storing atime failed!"); if (ctime != null && ctime.to(TimeUnit.SECONDS) != ze.getCreationTime().to(TimeUnit.SECONDS)) throw new RuntimeException("Timestamp: storing ctime failed!"); if (extra != null) { // if extra data exists, the current implementation put it at // the end of the extra data array (implementation detail) byte[] extra1 = ze.getExtra(); if (extra1 == null || extra1.length < extra.length || !Arrays.equals(Arrays.copyOfRange(extra1, extra1.length - extra.length, extra1.length), extra)) { throw new RuntimeException("Timestamp: storing extra field failed!"); } } }
/** * Finds the file that stores the content BLOB for an application layer. * * @param layerType the type of layer * @param sourceFiles the source files the layer must be built from * @return the newest cached layer file that matches the {@code layerType} and {@code sourceFiles} */ public Path getLayerFile(CachedLayerType layerType, Set<Path> sourceFiles) throws CacheMetadataCorruptedException { switch (layerType) { case DEPENDENCIES: case RESOURCES: case CLASSES: CacheMetadata cacheMetadata = cache.getMetadata(); ImageLayers<CachedLayerWithMetadata> cachedLayers = cacheMetadata.filterLayers().byType(layerType).bySourceFiles(sourceFiles).filter(); // Finds the newest cached layer for the layer type. FileTime newestLastModifiedTime = FileTime.from(Instant.MIN); Path newestLayerFile = null; for (CachedLayerWithMetadata cachedLayer : cachedLayers) { FileTime cachedLayerLastModifiedTime = cachedLayer.getMetadata().getLastModifiedTime(); if (cachedLayerLastModifiedTime.compareTo(newestLastModifiedTime) > 0) { newestLastModifiedTime = cachedLayerLastModifiedTime; newestLayerFile = cachedLayer.getContentFile(); } } return newestLayerFile; default: throw new UnsupportedOperationException("Can only find layer files for application layers"); } }
static void eq(Instant ins, long v2, TimeUnit u2) { FileTime t1 = FileTime.from(ins); FileTime t2 = FileTime.from(v2, u2); if (!t1.equals(t2)) throw new RuntimeException("not equal"); if (t1.hashCode() != t2.hashCode()) throw new RuntimeException("hashCodes should be equal"); }
LayerMetadata(List<String> sourceFiles, FileTime lastModifiedTime) { if (sourceFiles.isEmpty()) { throw new IllegalArgumentException("Source files for application layer cannot be empty"); } this.sourceFiles = sourceFiles; this.lastModifiedTime = lastModifiedTime; }
static void checkFileTime(long now, long original) { if (Math.abs(now - original) > PRECISION) { System.out.format("Extracted to %s, expected to be close to %s%n", FileTime.fromMillis(now), FileTime.fromMillis(original)); fail(); } }
/** * Given a filename, of the versioned form "path-version.type" look at all the files matching * "path.*\.type" and find the one with the newest modified date. * * @param path Path of file * @return the newest version * @throws IOException If the path is not valid. */ public static String findNewest(Path path) throws IOException { final String pattern = toPattern(path); return ls(path.getParent(), pattern).sorted((o1, o2) -> { try { final FileTime t1 = Files.getLastModifiedTime(o1); final FileTime t2 = Files.getLastModifiedTime(o2); return t2.compareTo(t1); } catch (IOException e) { e.printStackTrace(); } return 0; }).findFirst().get().toString(); }
private void pakArchiefBestandOpnieuwIn(final Path tmpFolder, final Set<String> keys) throws MojoExecutionException { final FileTime bestandstijd = maakFileTime(time); try (final JarOutputStream nieuwArchiefStream = new JarOutputStream(new FileOutputStream(artifact))) { verwerkManifest(tmpFolder, bestandstijd, nieuwArchiefStream); keys.forEach(key -> { if (!META_INF_PATH.equals(key) && !JarFile.MANIFEST_NAME.equals(key)) { verwerkNieuweJarEntry(tmpFolder, bestandstijd, nieuwArchiefStream, key); } }); } catch (IOException | WrappedException e) { getLog().debug("Artifact cannot be fixed", e); } }
static void to(long v, TimeUnit unit) { FileTime t = FileTime.from(v, unit); for (TimeUnit u: TimeUnit.values()) { long result = t.to(u); long expected = u.convert(v, unit); if (result != expected) { throw new RuntimeException("unexpected result"); } } }
@Override public boolean setTime( final BitField<FsAccessOption> options, final FsNodeName name, final BitField<Access> types, final long value) throws IOException { final Path file = target.resolve(name.getPath()); final FileTime time = FileTime.fromMillis(value); getBasicFileAttributeView(file).setTimes( types.get(WRITE) ? time : null, types.get(READ) ? time : null, types.get(CREATE) ? time : null); return types.clear(WRITE).clear(READ).clear(CREATE).isEmpty(); }
static void ts(long v, TimeUnit unit, String expected) { String result = FileTime.from(v, unit).toString(); if (!result.equals(expected)) { System.err.format("FileTime.from(%d, %s).toString() failed\n", v, unit); System.err.format("Expected: %s\n", expected); System.err.format(" Got: %s\n", result); throw new RuntimeException(); } }
static void test(FileTime mtime, FileTime atime, FileTime ctime, TimeZone tz, byte[] extra) throws Throwable { test0(mtime, null, null, null, extra); test0(mtime, null, null, tz, extra); // non-default tz test0(mtime, atime, null, null, extra); test0(mtime, null, ctime, null, extra); test0(mtime, atime, ctime, null, extra); test0(mtime, atime, null, tz, extra); test0(mtime, null, ctime, tz, extra); test0(mtime, atime, ctime, tz, extra); }
/** * Exercise Files.setLastModifiedTime on the given file */ void test(Path path) throws Exception { FileTime now = Files.getLastModifiedTime(path); FileTime zero = FileTime.fromMillis(0L); Path result = Files.setLastModifiedTime(path, zero); assertTrue(result == path); assertEquals(Files.getLastModifiedTime(path), zero); result = Files.setLastModifiedTime(path, now); assertTrue(result == path); assertEquals(Files.getLastModifiedTime(path), now); }
@Override public void inspectRegion(Region region) { FileTime regionFastModifiedTime = region.getSlowModifiedTime(); if (regionFastModifiedTime != null && currentAccessTime.compareTo(regionFastModifiedTime) >= 0) { upToDate++; } count++; }
@Override public void inspectRegion(Region region) { FileTime regionFastModifiedTime = region.getFastModifiedTime(); if (regionFastModifiedTime != null && currentAccessTime.compareTo(regionFastModifiedTime) >= 0) { upToDate++; } count++; }
private List<Inspector> getServerFileInspectors(File serverFile, FileTime modifiedTime) { List<Inspector> inspectors = new ArrayList<>(); inspectors.add( new FastCompletionServerFileInspector(serverFile, modifiedTime)); inspectors.add( new SlowCompletionServerFileInspector(serverFile, modifiedTime)); return inspectors; }
static void ts(Instant instant, String expected) { String result = FileTime.from(instant).toString(); if (!result.equals(expected)) { System.err.format("FileTime.from(%s).toString() failed\n", instant); System.err.format("Expected: %s\n", expected); System.err.format(" Got: %s\n", result); throw new RuntimeException(); } }
public void testTouchTime() throws IOException { Path temp = createTempFile(); assertTrue(Files.exists(temp)); Files.setLastModifiedTime(temp, FileTime.fromMillis(0)); assertEquals(0, Files.getLastModifiedTime(temp).toMillis()); MoreFiles.touch(temp); assertThat(Files.getLastModifiedTime(temp).toMillis()).isNotEqualTo(0); }
@Override public void setTimestamp(final Path file, final Long modified) throws BackgroundException { try { Files.setLastModifiedTime(session.toPath(file), FileTime.from(modified, TimeUnit.MILLISECONDS)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Failure to write attributes of {0}", e, file); } }
@Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { // fix up modification time of directory when done if (exc == null) { Path newdir = target.resolve(source.relativize(dir)); try { FileTime time = Files.getLastModifiedTime(dir); Files.setLastModifiedTime(newdir, time); } catch (IOException x) { LOGGER.log(Level.WARNING, "Unable to copy all attributes to: " + newdir, x); } } return CONTINUE; }
public FileInfo(long inode, FileTime mtime, FileTime ctime, long size) { super(); this.inode = inode; this.mtime = mtime; this.ctime = ctime; this.size = size; }
public FileInfo(long inode, Instant mtime, Instant ctime, long size) { super(); this.inode = inode; this.mtime = FileTime.from(mtime); this.ctime = FileTime.from(ctime); this.size = size; }
@Override @FromAnyThread public synchronized void assetRequested(@NotNull final AssetKey key) { if (key.getCacheType() == null) { return; } final String extension = key.getExtension(); if (StringUtils.isEmpty(extension)) return; final ObjectDictionary<String, Reference> table = getAssetCacheTable(); final Reference reference = table.get(key.getName()); if (reference == null) return; final Path assetFile = getRealFile(Paths.get(key.getName())); if (assetFile == null || !Files.exists(assetFile)) return; try { final long timestamp = reference.getLong(); final FileTime lastModifiedTime = Files.getLastModifiedTime(assetFile); if (lastModifiedTime.to(TimeUnit.MILLISECONDS) <= timestamp) return; final Editor editor = Editor.getInstance(); final AssetManager assetManager = editor.getAssetManager(); assetManager.deleteFromCache(key); } catch (final IOException e) { LOGGER.warning(e); } }
@Test public void testStat() throws Exception { // Given int nonce = 123; FileSystem fileSystem = mockFileSystem(); Path path = mockPath("/", fileSystem); Instant base = Instant.now(); Map<String, Object> attributes = mockAttributes(nonce, base); when(fileSystem.provider().readAttributes(eq(path), eq("unix:*"), any())).thenReturn(attributes); UnixFileStatImpl stat = new UnixFileStatImpl(); // When UnixFileStat result = stat.stat(path); // Then assertThat(result).isSameAs(stat); assertThat(stat.getDev()).isEqualTo(nonce * 3L); assertThat(stat.getIno()).isEqualTo(nonce * 5L); assertThat(stat.getLinks()).isEqualTo(nonce * 7); assertThat(stat.getMode()).isEqualTo(nonce * 11); assertThat(stat.getUid()).isEqualTo(nonce * 13); assertThat(stat.getGid()).isEqualTo(nonce * 17); assertThat(stat.getRdev()).isEqualTo(nonce * 19L); assertThat(stat.getSize()).isEqualTo(nonce * 23L); assertThat(stat.getBlocks()).isEqualTo(stat.getSize() / 512 + 1); assertThat(stat.getAccessTime()).isEqualTo(FileTime.from(base.minus(29, ChronoUnit.DAYS)).toInstant()); assertThat(stat.getModificationTime()).isEqualTo(FileTime.from(base.minus(31, ChronoUnit.DAYS)).toInstant()); assertThat(stat.getInodeTime()).isEqualTo(FileTime.from(base.minus(37, ChronoUnit.DAYS)).toInstant()); }
/** * altera o longtime da última modificação no arquivo * * @param time data no formato longtime */ public static void setLastModifiedTime(File file, long time) { try { Path path = file.toPath(); FileTime fileTime = FileTime.fromMillis(time); Files.setLastModifiedTime(path, fileTime); } catch (IOException ex) { } }
public ConsistentJarEntry( String name, long lastModified, boolean consistentDates ) { this( name, consistentDates ); if ( !consistentDates ) { FileTime fileTime = FileTime.from( Instant.ofEpochMilli( lastModified ) ); this.setLastModifiedTime( fileTime ); } }
private static void setLastModified(String fileName, long newTime) throws IOException { Path path = Paths.get(fileName); FileTime fileTime = FileTime.fromMillis(newTime); Files.setLastModifiedTime(path, fileTime); }
static void neq(long v1, TimeUnit u1, long v2, TimeUnit u2) { FileTime t1 = FileTime.from(v1, u1); FileTime t2 = FileTime.from(v2, u2); if (t1.equals(t2)) throw new RuntimeException("should not be equal"); }
public static void setFileCreationDate(String filePath, Date creationDate) throws IOException { BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class); FileTime time = FileTime.fromMillis(creationDate.getTime()); attributes.setTimes(time, time, time); }
public final FileTime lastModifiedTime() { return fileAttrs.lastModifiedTime(); }
@Override public FileTime lastModifiedTime() { return FileTime.fromMillis(e.mtime); }
static void cmp(long v1, TimeUnit u1, long v2, TimeUnit u2, int expected) { int result = FileTime.from(v1, u1).compareTo(FileTime.from(v2, u2)); if (result != expected) throw new RuntimeException("unexpected order"); }