List of usage examples for java.nio.file.attribute BasicFileAttributes lastModifiedTime
FileTime lastModifiedTime();
From source file:com.arpnetworking.metrics.common.tailer.StatefulTailer.java
private Attributes getAttributes(final Path file, final Optional<Long> lastChecked) throws IOException { final BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class); LOGGER.trace().setMessage("File attributes").addData("file", file) .addData("lastModifiedTime", attributes.lastModifiedTime().toMillis()) .addData("size", attributes.size()).log(); return new Attributes(attributes.size(), attributes.lastModifiedTime().toMillis(), lastChecked.isPresent() && attributes.lastModifiedTime().toMillis() > lastChecked.get()); }
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 {// w w w . j a v a 2 s . 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:com.spectralogic.ds3client.metadata.MACMetadataRestore_Test.java
@Test public void restoreFileTimes_Test() throws Exception { if (Platform.isMac()) { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yy:HH:mm"); final BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); final BasicHeader basicHeader[] = new BasicHeader[3]; basicHeader[0] = new BasicHeader( MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_CREATION_TIME, String.valueOf(attr.creationTime().toMillis())); basicHeader[1] = new BasicHeader( MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_ACCESS_TIME, String.valueOf(attr.lastAccessTime().toMillis())); basicHeader[2] = new BasicHeader( MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_LAST_MODIFIED_TIME, String.valueOf(attr.lastModifiedTime().toMillis())); final Metadata metadata = genMetadata(basicHeader); final MACMetadataRestore macMetadataRestore = new MACMetadataRestore(metadata, file.getPath(), MetaDataUtil.getOS());//ww w . ja v a 2 s. com macMetadataRestore.restoreFileTimes(); final BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class); Assert.assertEquals(simpleDateFormat.format(fileAttributes.creationTime().toMillis()), simpleDateFormat.format(Long.valueOf(basicHeader[0].getValue()))); Assert.assertEquals(simpleDateFormat.format(fileAttributes.lastModifiedTime().toMillis()), simpleDateFormat.format(Long.valueOf(basicHeader[2].getValue()))); } }
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 w w . j a v a 2 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:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param attr File attributes//from w w w. j ava 2 s. c om */ @SuppressWarnings("NestedAssignment") private void checkIfModifiedSince(HttpServletRequest request, BasicFileAttributes attr) { try { long headerValue; // If an If-None-Match header has been specified, if modified since // is ignored. if (request.getHeader(HttpHeaders.IF_NONE_MATCH) == null && (headerValue = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)) != -1 && attr.lastModifiedTime().toMillis() < headerValue + 1000) { // The entity has not been modified since the date // specified by the client. This is not an error case. throw new UncheckException(HttpServletResponse.SC_NOT_MODIFIED); } } catch (IllegalArgumentException ex) { } }
From source file:org.tinymediamanager.core.entities.MediaEntity.java
public void setDateAddedFromMediaFile(MediaFile mf) { try {//from w w w. ja va 2 s . c om 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:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java
/** * get the version history for an item// w ww . j a va2s.c om * @param path - the path of the item */ public VersionTO[] getContentVersionHistory(String path) { final List<VersionTO> versionList = new ArrayList<VersionTO>(); try { final String pathToContent = path.substring(0, path.lastIndexOf(File.separator)); final String filename = path.substring(path.lastIndexOf(File.separator) + 1); Path versionPath = constructVersionRepoPath(pathToContent); EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(versionPath, opts, 1, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path visitPath, BasicFileAttributes attrs) throws IOException { String versionFilename = visitPath.toString(); if (versionFilename.contains(filename)) { VersionTO version = new VersionTO(); String label = versionFilename.substring(versionFilename.lastIndexOf("--") + 2); BasicFileAttributes attr = Files.readAttributes(visitPath, BasicFileAttributes.class); version.setVersionNumber(label); version.setLastModifier("ADMIN"); version.setLastModifiedDate(new Date(attr.lastModifiedTime().toMillis())); version.setComment(""); versionList.add(version); } return FileVisitResult.CONTINUE; } }); } catch (Exception err) { logger.error("error while getting history for content item " + path); logger.debug("error while getting history for content item " + path, err); } final List<VersionTO> finalVersionList = new ArrayList<VersionTO>(); if (versionList.size() > 0) { Collections.sort(versionList); VersionTO latest = versionList.get(versionList.size() - 1); String latestVersionLabel = latest.getVersionNumber(); int temp = latestVersionLabel.indexOf("."); String currentMajorVersion = latestVersionLabel.substring(0, temp); for (int i = versionList.size(); i > 0; i--) { VersionTO v = versionList.get(i - 1); String versionId = v.getVersionNumber(); boolean condition = !versionId.startsWith(currentMajorVersion) && !versionId.endsWith(".0"); if (condition) continue; finalVersionList.add(v); } } //Collections.reverse(versionList); VersionTO[] versions = new VersionTO[finalVersionList.size()]; versions = finalVersionList.toArray(versions); return versions; }
From source file:org.wso2.carbon.uuf.internal.io.StaticResolver.java
private ZonedDateTime getLastModifiedDate(Path resourcePath) { if (!Files.isReadable(resourcePath)) { throw new ResourceNotFoundException("Static resource file '" + resourcePath + "' is not readable."); }/*from www. java2 s . c o m*/ BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(resourcePath, BasicFileAttributes.class); } catch (NoSuchFileException | FileNotFoundException e) { // This shouldn't be happening because we checked the file's readability before. But just in case. throw new ResourceNotFoundException("Static resource file '" + resourcePath + "' does not exists.", e); } catch (Exception e) { // UnsupportedOperationException, IOException or any other Exception that might occur. throw new FileOperationException( "Cannot read file attributes from static resource file '" + resourcePath + "'.", e); } if (fileAttributes.isRegularFile()) { return ZonedDateTime.ofInstant(fileAttributes.lastModifiedTime().toInstant(), GMT_TIME_ZONE); } else { /* * From book "OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide" page 478: * Java defines a regular file as one that contains content, as opposed to a symbolic link, * directory, resource (e.g. port, pipe), or other non-regular files that may be present in some * operating systems. [...] It is possible for isRegularFile() to return true for a symbolic link, * as long as the link resolves to a regular file. * Hence, checking 'isRegularFile' of a file is enough to determine its existence and not being a directory. */ throw new ResourceNotFoundException( "Static resource file '" + resourcePath + "' is not a regular file."); } }
From source file:de.tiqsolutions.hdfs.BasicFileAttributeViewImpl.java
Map<String, Object> readAttributes(String attributes) throws IOException { BasicFileAttributes attr = readAttributes(); List<String> attrlist = Arrays.asList(attributes.split(",")); boolean readall = attrlist.contains("*"); Map<String, Object> ret = new HashMap<>(); if (readall || attrlist.contains("fileKey")) ret.put("fileKey", attr.fileKey()); if (readall || attrlist.contains("creationTime")) ret.put("creationTime", attr.creationTime()); if (readall || attrlist.contains("isDirectory")) ret.put("isDirectory", attr.isDirectory()); if (readall || attrlist.contains("isOther")) ret.put("isOther", attr.isOther()); if (readall || attrlist.contains("isRegularFile")) ret.put("isRegularFile", attr.isRegularFile()); if (readall || attrlist.contains("isSymbolicLink")) ret.put("isSymbolicLink", attr.isSymbolicLink()); if (readall || attrlist.contains("lastAccessTime")) ret.put("lastAccessTime", attr.lastAccessTime()); if (readall || attrlist.contains("lastModifiedTime")) ret.put("lastModifiedTime", attr.lastModifiedTime()); if (readall || attrlist.contains("size")) ret.put("size", attr.size()); return ret;/*from w w w . j av a 2s . c o m*/ }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Parse the range header.//www .j a v a 2s . c o m * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param attr File attributes * @param etag ETag of the entity * @return array of ranges */ @Nullable @SuppressWarnings("ReturnOfCollectionOrArrayField") private Range[] parseRange(HttpServletRequest request, HttpServletResponse response, BasicFileAttributes attr, String etag) throws IOException { // Checking If-Range String headerValue = request.getHeader(HttpHeaders.IF_RANGE); if (headerValue != null) { long headerValueTime = -1; try { headerValueTime = request.getDateHeader(HttpHeaders.IF_RANGE); } catch (IllegalArgumentException e) { // Ignore } // If the ETag the client gave does not match the entity // eTag, then the entire entity is returned. if (headerValueTime == -1 && !headerValue.trim().equals(etag) || attr.lastModifiedTime().toMillis() > headerValueTime + 1000) { // If the timestamp of the entity the client got is older than // the last modification date of the entity, the entire entity // is returned. return FULL; } } long fileLength = attr.size(); if (fileLength == 0) { return FULL; } // Retrieving the range header (if any is specified String rangeHeader = request.getHeader(HttpHeaders.RANGE); if (rangeHeader == null) { return FULL; } // bytes is the only range unit supported (and I don't see the point // of adding new ones). if (!rangeHeader.startsWith("bytes=")) { return FULL; } // List which will contain all the ranges which are successfully // parsed. List<Range> result = new ArrayList<>(4); // Parsing the range list // "bytes=".length() = 6 for (int index, last = 6;; last = index + 1) { index = rangeHeader.indexOf(',', last); boolean isLast = index == -1; final String rangeDefinition = (isLast ? rangeHeader.substring(last) : rangeHeader.substring(last, index)).trim(); final int dashPos = rangeDefinition.indexOf('-'); if (dashPos == -1) { break; } final Range currentRange = new Range(fileLength); try { if (dashPos == 0) { final long offset = Long.parseLong(rangeDefinition); if (offset == 0) { // -0, --0 break; } currentRange.start = Math.max(fileLength + offset, 0); } else { currentRange.start = Long.parseLong(rangeDefinition.substring(0, dashPos)); if (dashPos < rangeDefinition.length() - 1) { currentRange.end = Long .parseLong(rangeDefinition.substring(dashPos + 1, rangeDefinition.length())); } } } catch (NumberFormatException e) { break; } if (!currentRange.validate()) { break; } result.add(currentRange); if (isLast) { int size = result.size(); if (size == 0) { break; } return result.toArray(new Range[size]); } } response.addHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }