List of usage examples for java.nio.file Files getFileAttributeView
public static <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options)
From source file:com.nsn.squirrel.tab.utils.PathUtils.java
/** * @param path//from w w w. j a v a 2s . c o m * @return */ public static String getDosAttributesString(Path path) { DosFileAttributeView basicView = Files.getFileAttributeView(path, DosFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); StringBuilder attrs = new StringBuilder(); try { // + all basic attributes DosFileAttributes dosAttrs = basicView.readAttributes(); attrs.append(dosAttrs.isReadOnly() ? "r" : "-"); //$NON-NLS-1$ //$NON-NLS-2$ attrs.append(dosAttrs.isHidden() ? "h" : "-");//$NON-NLS-1$ //$NON-NLS-2$ attrs.append(dosAttrs.isArchive() ? "a" : "-");//$NON-NLS-1$ //$NON-NLS-2$ attrs.append(dosAttrs.isSystem() ? "s" : "-");//$NON-NLS-1$ //$NON-NLS-2$ } catch (IOException e) { log.warn("unable to read DOS attributes.", e); //$NON-NLS-1$ } return attrs.toString(); }
From source file:cane.brothers.e4.commander.utils.PathUtils.java
/** * @param path//from ww w . j av a 2 s .c o m * @return */ public static String getDosAttributesString(Path path) { DosFileAttributeView basicView = Files.getFileAttributeView(path, DosFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); StringBuilder attrs = new StringBuilder(); try { // + all basic attributes DosFileAttributes dosAttrs = basicView.readAttributes(); attrs.append(dosAttrs.isReadOnly() ? "r" : "-"); //$NON-NLS-1$ //$NON-NLS-2$ attrs.append(dosAttrs.isHidden() ? "h" : "-");//$NON-NLS-1$ //$NON-NLS-2$ attrs.append(dosAttrs.isArchive() ? "a" : "-");//$NON-NLS-1$ //$NON-NLS-2$ attrs.append(dosAttrs.isSystem() ? "s" : "-");//$NON-NLS-1$ //$NON-NLS-2$ } catch (IOException e) { log.warn("unable to read DOS attributes.", e); //$NON-NLS-1$ } return attrs.toString(); }
From source file:RestoreService.java
public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException { // advanced attributes // owner// w w w. jav a2 s . co m if (StringUtils.isNotBlank(voBackupFile.getOwner())) { try { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(voBackupFile.getOwner()); Files.setOwner(file.toPath(), userPrincipal); } catch (UserPrincipalNotFoundException e) { logger.warn("Cannot set owner {}", voBackupFile.getOwner()); } } if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class) && BooleanUtils.isTrue(voBackupFile.getDosAttr())) { Files.setAttribute(file.toPath(), "dos:hidden", BooleanUtils.isTrue(voBackupFile.getDosHidden())); Files.setAttribute(file.toPath(), "dos:archive", BooleanUtils.isTrue(voBackupFile.getDosArchive())); Files.setAttribute(file.toPath(), "dos:readonly", BooleanUtils.isTrue(voBackupFile.getDosReadOnly())); Files.setAttribute(file.toPath(), "dos:system", BooleanUtils.isTrue(voBackupFile.getDosSystem())); } if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class) && BooleanUtils.isTrue(voBackupFile.getPosixAttr())) { try { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); GroupPrincipal groupPrincipal = lookupService .lookupPrincipalByGroupName(voBackupFile.getPosixGroup()); Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) .setGroup(groupPrincipal); } catch (UserPrincipalNotFoundException e) { logger.warn("Cannot set group {}", voBackupFile.getOwner()); } if (StringUtils.isNotBlank(voBackupFile.getPosixPermitions())) { Set<PosixFilePermission> perms = PosixFilePermissions.fromString(voBackupFile.getPosixPermitions()); Files.setPosixFilePermissions(file.toPath(), perms); } } }
From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java
@Override public void setProperty(DavProperty<?> property) throws DavException { getProperties().add(property);/*from w w w .ja v a 2s .c o m*/ LOG.info("Set property {}", property.getName()); try { final Path path = ResourcePathUtils.getPhysicalPath(this); if (DavPropertyName.CREATIONDATE.equals(property.getName()) && property.getValue() instanceof String) { final String createDateStr = (String) property.getValue(); final FileTime createTime = FileTimeUtils.fromRfc1123String(createDateStr); final BasicFileAttributeView attrView = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); attrView.setTimes(null, null, createTime); LOG.info("Updating Creation Date: {}", createTime.toString()); } else if (DavPropertyName.GETLASTMODIFIED.equals(property.getName()) && property.getValue() instanceof String) { final String lastModifiedTimeStr = (String) property.getValue(); final FileTime lastModifiedTime = FileTimeUtils.fromRfc1123String(lastModifiedTimeStr); final BasicFileAttributeView attrView = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); attrView.setTimes(lastModifiedTime, null, null); LOG.info("Updating Last Modified Date: {}", lastModifiedTime.toString()); } } catch (IOException e) { throw new DavException(DavServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.eclipse.tycho.plugins.tar.TarGzArchiver.java
private PosixFileAttributes getAttributes(File source) { PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(source.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); if (fileAttributeView == null) { return null; }/*from w ww . ja v a 2s . c om*/ PosixFileAttributes attrs; try { attrs = fileAttributeView.readAttributes(); } catch (IOException e) { return null; } return attrs; }
From source file:io.hops.hopsworks.common.security.CertificatesMgmService.java
@PostConstruct public void init() { masterPasswordFile = new File(settings.getHopsworksMasterEncPasswordFile()); if (!masterPasswordFile.exists()) { throw new IllegalStateException("Master encryption file does not exist"); }//from w w w . ja v a 2 s . c om try { PosixFileAttributeView fileView = Files.getFileAttributeView(masterPasswordFile.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); Set<PosixFilePermission> filePermissions = fileView.readAttributes().permissions(); boolean ownerRead = filePermissions.contains(PosixFilePermission.OWNER_READ); boolean ownerWrite = filePermissions.contains(PosixFilePermission.OWNER_WRITE); boolean ownerExecute = filePermissions.contains(PosixFilePermission.OWNER_EXECUTE); boolean groupRead = filePermissions.contains(PosixFilePermission.GROUP_READ); boolean groupWrite = filePermissions.contains(PosixFilePermission.GROUP_WRITE); boolean groupExecute = filePermissions.contains(PosixFilePermission.GROUP_EXECUTE); boolean othersRead = filePermissions.contains(PosixFilePermission.OTHERS_READ); boolean othersWrite = filePermissions.contains(PosixFilePermission.OTHERS_WRITE); boolean othersExecute = filePermissions.contains(PosixFilePermission.OTHERS_EXECUTE); // Permissions should be 700 if ((ownerRead && ownerWrite && ownerExecute) && (!groupRead && !groupWrite && !groupExecute) && (!othersRead && !othersWrite && !othersExecute)) { String owner = fileView.readAttributes().owner().getName(); String group = fileView.readAttributes().group().getName(); String permStr = PosixFilePermissions.toString(filePermissions); LOG.log(Level.INFO, "Passed permissions check for file " + masterPasswordFile.getAbsolutePath() + ". Owner: " + owner + " Group: " + group + " Permissions: " + permStr); } else { throw new IllegalStateException("Wrong permissions for file " + masterPasswordFile.getAbsolutePath() + ", it should be 700"); } } catch (UnsupportedOperationException ex) { LOG.log(Level.WARNING, "Associated filesystem is not POSIX compliant. " + "Continue without checking the permissions of " + masterPasswordFile.getAbsolutePath() + " This might be a security problem."); } catch (IOException ex) { throw new IllegalStateException( "Error while getting POSIX permissions of " + masterPasswordFile.getAbsolutePath()); } // Register handlers when master encryption password changes MasterPasswordChangeHandler<CertsFacade> psUserCertsHandler = new PSUserCertsMasterPasswordHandler( userFacade); psUserCertsHandler.setFacade(certsFacade); registerMasterPasswordChangeHandler(UserCerts.class, psUserCertsHandler); MasterPasswordChangeHandler<CertsFacade> pgUserCertsHandler = new PGUserCertsMasterPasswordHandler( projectFacade); pgUserCertsHandler.setFacade(certsFacade); registerMasterPasswordChangeHandler(ProjectGenericUserCerts.class, pgUserCertsHandler); MasterPasswordChangeHandler<ClusterCertificateFacade> delaClusterCertsHandler = new DelaCertsMasterPasswordHandler( settings); delaClusterCertsHandler.setFacade(clusterCertificateFacade); registerMasterPasswordChangeHandler(ClusterCertificate.class, delaClusterCertsHandler); }
From source file:com.twosigma.beaker.core.rest.FileIORest.java
@POST @Consumes("application/x-www-form-urlencoded") @Path("setPosixFileOwnerAndPermissions") @Produces(MediaType.TEXT_PLAIN)//from w w w . j a v a 2 s .com public Response setPosixFilePermissions(@FormParam("path") String pathString, @FormParam("owner") String owner, @FormParam("group") String group, @FormParam("permissions[]") List<String> permissions) throws IOException { HashSet<PosixFilePermission> filePermissions = getPosixFilePermissions(permissions); try { java.nio.file.Path path = Paths.get(pathString); Files.setPosixFilePermissions(path, filePermissions); UserPrincipalLookupService userPrincipalLookupService = FileSystems.getDefault() .getUserPrincipalLookupService(); if (StringUtils.isNoneBlank(owner)) { Files.setOwner(path, userPrincipalLookupService.lookupPrincipalByName(owner)); } if (StringUtils.isNoneBlank(group)) { Files.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) .setGroup(userPrincipalLookupService.lookupPrincipalByGroupName(group)); } return status(OK).build(); } catch (FileSystemException e) { return status(INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } }
From source file:ch.psi.zmq.receiver.FileReceiver.java
/** * Receive ZMQ messages with pilatus-1.0 header type and write the data part * to disk/*from w w w . j a va2 s. c o m*/ */ public void receive(Integer numImages) { try { done = false; counter = 0; counterDropped = 0; receive = true; context = ZMQ.context(1); socket = context.socket(ZMQ.PULL); socket.connect("tcp://" + hostname + ":" + port); ObjectMapper mapper = new ObjectMapper(); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; String path = ""; // User lookup service UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService(); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); while (receive) { try { byte[] message = socket.recv(); byte[] content = null; if (socket.hasReceiveMore()) { content = socket.recv(); } logger.info("Message received: " + new String(message)); Map<String, Object> h = mapper.readValue(message, typeRef); if (!"pilatus-1.0".equals(h.get("htype"))) { logger.warning("Message type [" + h.get("htype") + "] not supported - ignore message"); continue; } String username = (String) h.get("username"); // Save content to file (in basedir) String p = (String) h.get("path"); if (!p.startsWith("/")) { p = basedir + "/" + p; } File f = new File(p); // if(!f.exists()){ if (!path.equals(p)) { if (username == null) { logger.info("Create directory " + p + ""); f.mkdirs(); } else { logger.info("Create directory " + p + " for user " + username); try { Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>(); permissions.add(PosixFilePermission.OWNER_READ); permissions.add(PosixFilePermission.OWNER_WRITE); permissions.add(PosixFilePermission.OWNER_EXECUTE); permissions.add(PosixFilePermission.GROUP_READ); permissions.add(PosixFilePermission.GROUP_WRITE); permissions.add(PosixFilePermission.GROUP_EXECUTE); // username and groupname is the same by // convention mkdir(f, lookupservice.lookupPrincipalByName(username), lookupservice.lookupPrincipalByGroupName(username), permissions); } catch (IOException e) { throw new RuntimeException("Unable to create directory for user " + username + "", e); } } path = p; } File file = new File(f, (String) h.get("filename")); logger.finest("Write to " + file.getAbsolutePath()); try (FileOutputStream s = new FileOutputStream(file)) { s.write(content); } if (username != null) { Files.setOwner(file.toPath(), lookupservice.lookupPrincipalByName(username)); // username and groupname is the same by convention Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) .setGroup(lookupservice.lookupPrincipalByGroupName(username)); Files.setPosixFilePermissions(file.toPath(), perms); } counter++; if (numImages != null && numImages == counter) { break; } } catch (IOException e) { logger.log(Level.SEVERE, "", e); counterDropped++; } } } catch (Exception e) { if (receive) { e.printStackTrace(); } } }
From source file:uk.ac.ebi.metabolights.webservice.utils.FileUtil.java
/** * Create a private FTP folder for uploading big study files * * @param folder/*from w ww.j a va 2s . c om*/ * @return a String containing created folder * @author jrmacias * @date 20151102 */ @PostConstruct public static Path createFtpFolder(String folder) throws IOException { String privateFTPRoot = PropertiesUtil.getProperty("privateFTPRoot"); // ~/ftp_private/ // create the folder File ftpFolder = new File(privateFTPRoot + File.separator + folder); Path folderPath = ftpFolder.toPath(); if (!ftpFolder.mkdir()) throw new IOException(); // set folder owner, group and access permissions // 'chmod 770' UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // owner permissions perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); // group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); // apply changes Files.getFileAttributeView(folderPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) .setPermissions(perms); return folderPath; }
From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java
@PostConstruct public void init() { File tmpDir = new File(settings.getHopsworksTmpCertDir()); if (!tmpDir.exists()) { throw new IllegalStateException( "Transient certificates directory <" + tmpDir.getAbsolutePath() + "> does NOT exist!"); }/*from w w w.java2s. c om*/ try { PosixFileAttributeView fileView = Files.getFileAttributeView(tmpDir.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); Set<PosixFilePermission> permissions = fileView.readAttributes().permissions(); boolean ownerRead = permissions.contains(PosixFilePermission.OWNER_READ); boolean ownerWrite = permissions.contains(PosixFilePermission.OWNER_WRITE); boolean ownerExecute = permissions.contains(PosixFilePermission.OWNER_EXECUTE); boolean groupRead = permissions.contains(PosixFilePermission.GROUP_READ); boolean groupWrite = permissions.contains(PosixFilePermission.GROUP_WRITE); boolean groupExecute = permissions.contains(PosixFilePermission.GROUP_EXECUTE); boolean othersRead = permissions.contains(PosixFilePermission.OTHERS_READ); boolean othersWrite = permissions.contains(PosixFilePermission.OTHERS_WRITE); boolean othersExecute = permissions.contains(PosixFilePermission.OTHERS_EXECUTE); // Permissions should be 750 if ((ownerRead && ownerWrite && ownerExecute) && (groupRead && !groupWrite && groupExecute) && (!othersRead && !othersWrite & !othersExecute)) { String owner = fileView.readAttributes().owner().getName(); String group = fileView.readAttributes().group().getName(); String permStr = PosixFilePermissions.toString(permissions); LOG.log(Level.INFO, "Passed permissions check for " + tmpDir.getAbsolutePath() + ". Owner: " + owner + " Group: " + group + " permissions: " + permStr); } else { throw new IllegalStateException( "Wrong permissions for " + tmpDir.getAbsolutePath() + ", it should be 0750"); } } catch (UnsupportedOperationException ex) { LOG.log(Level.WARNING, "Associated filesystem is not POSIX compliant. " + "Continue without checking the permissions of " + tmpDir.getAbsolutePath() + " This might be a security problem."); } catch (IOException ex) { throw new IllegalStateException( "Error while getting filesystem " + "permissions of " + tmpDir.getAbsolutePath(), ex); } try { FileUtils.cleanDirectory(tmpDir); } catch (IOException ex) { LOG.log(Level.WARNING, "Could not clean directory " + tmpDir.getAbsolutePath() + " during startup, there might be stale " + "certificates", ex); } transientDir = tmpDir.getAbsolutePath(); String delayRaw = settings.getCertificateMaterializerDelay(); DELAY_VALUE = settings.getConfTimeValue(delayRaw); DELAY_TIMEUNIT = settings.getConfTimeTimeUnit(delayRaw); try { String hostAddress = InetAddress.getLocalHost().getHostAddress(); long threadId = Thread.currentThread().getId(); String lock_identifier = hostAddress + "_" + threadId; lock_id = lock_identifier.length() <= 30 ? lock_identifier : lock_identifier.substring(0, 30); } catch (UnknownHostException ex) { throw new IllegalStateException(ex); } }