List of usage examples for java.nio.file LinkOption NOFOLLOW_LINKS
LinkOption NOFOLLOW_LINKS
To view the source code for java.nio.file LinkOption NOFOLLOW_LINKS.
Click Source Link
From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java
/** * Runs a command specified by a compiler invocation. * * @param compilerInvocation//from www .j av a 2 s. co m * specifies what program with which flags is being executed * @param pathToSourceFolder * the path to the source folder of the submission * @return CompilerOutput with fields initialized according to the outcome * of the process * @throws BadFlagException * if a flag is not known to javac */ private CompilerOutput runJavacProcess(List<String> compilerInvocation, Path pathToSourceFolder, boolean junit) throws BadFlagException { Process compilerProcess = null; try { ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation); // make sure the compiler stays in its directory. if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) { compilerProcessBuilder.directory(pathToSourceFolder.toFile()); } else { compilerProcessBuilder.directory(pathToSourceFolder.getParent().toFile()); } compilerProcess = compilerProcessBuilder.start(); } catch (IOException e) { // If we cannot call the compiler we return a CompilerOutput // which is // initialized with false, false, indicating // that the compiler wasn't invoked properly and that there was no // clean Compile. CompilerOutput compilerInvokeError = new CompilerOutput(); compilerInvokeError.setClean(false); compilerInvokeError.setCompilerInvoked(false); return compilerInvokeError; } // Now we read compiler output. If everything is ok javac reports // nothing at all. InputStream compilerOutputStream = compilerProcess.getErrorStream(); InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream); BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader); String line; CompilerOutput compilerOutput = new CompilerOutput(); compilerOutput.setCompilerInvoked(true); List<String> compilerOutputLines = new LinkedList<>(); try { while ((line = compilerOutputBuffer.readLine()) != null) { compilerOutputLines.add(line); } compilerOutputStream.close(); compilerStreamReader.close(); compilerOutputBuffer.close(); compilerProcess.destroy(); } catch (IOException e) { // Reading might go wrong here if javac should unexpectedly // terminate LOGGER.severe("Could not read compiler ourput from its output stream." + " Aborting compile of: " + pathToSourceFolder.toString() + " Got message: " + e.getMessage()); compilerOutput.setClean(false); compilerOutput.setCompileStreamBroken(true); return compilerOutput; } splitCompilerOutput(compilerOutputLines, compilerOutput); if (compilerOutputLines.size() == 0) { compilerOutput.setClean(true); } return compilerOutput; }
From source file:net.sourceforge.jencrypt.FileEncrypter.java
/** * Encrypt file [inputFile] relative to [pathToEncrypt] into the archive * specified by [outputFile].//from w w w . j a va2s. c om * * @param pathToEncrypt * @param inputFile * @param outputFile * @throws Exception */ private void encryptAndArchivePath(String folderToEncryptString, String inputFileRelativePath, OutputStream os) throws Exception { // Full path to file to encrypt String fullSourcePath = folderToEncryptString + File.separator + inputFileRelativePath; // Path to encrypt is a folder if it ends with a file separator boolean pathIsFolder = (inputFileRelativePath .charAt(inputFileRelativePath.length() - 1) == File.separatorChar); // Use a Unix separator for storing file paths inputFileRelativePath = FilenameUtils.normalize(inputFileRelativePath, true); // To indicate a folder add a Unix file separator at the end if (pathIsFolder) inputFileRelativePath += Utils.UNIX_SEPARATOR; File inputFile = new File(fullSourcePath); Set<PosixFilePermission> perms = null; // Get the "Encrypting [file] ... " message String message = getCipherMessage(inputFile.getName(), commandline.getCipherMode()); // Instantiate ProgressInfo ProgressInfo progress = new FileProgressInfo(message, inputFile.length(), config.getReadBufferSize()); assert (inputFileRelativePath.length() > 0); byte[] pathLength = ByteBuffer.allocate(4).putInt(inputFileRelativePath.length()).array(); byte[] pathLengthEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(pathLength, Cipher.ENCRYPT_MODE); // write 4 bytes path size os.write(pathLengthEnc); byte[] fullPath = inputFileRelativePath.getBytes(); byte[] fullPathEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(fullPath, Cipher.ENCRYPT_MODE); // write full path of encrypted file os.write(fullPathEnc); // Retain file permissions on Unix flavours if (fileSystemIsPosixCompliant()) { perms = Files.getPosixFilePermissions(Paths.get(fullSourcePath), LinkOption.NOFOLLOW_LINKS); } else { /* * On non-POSIX file systems use default Unix (umask 022) file and * directory permissions */ if (pathIsFolder) perms = PosixFilePermissions.fromString("rwxr-xr-x"); else perms = PosixFilePermissions.fromString("rw-r--r--"); } byte[] permBytes = Utils.permsToByte(perms); byte[] permBytesEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(permBytes, Cipher.ENCRYPT_MODE); // write 2 bytes with the file's permissions os.write(permBytesEnc); // Start file encryption if the supplied relative path is not a folder if (!pathIsFolder) { long l = inputFile.length(); byte[] fileSize = ByteBuffer.allocate(8).putLong(l).array(); byte[] fileSizeEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(fileSize, Cipher.ENCRYPT_MODE); // write 8 bytes filesize os.write(fileSizeEnc); cryptoWrapperFileContent.doCipherOperation(getInputFileStream(fullSourcePath), os, new File(fullSourcePath).length(), Cipher.ENCRYPT_MODE, progress); } }
From source file:it.reexon.lib.files.FileUtils.java
/** * Deletes a file. // w w w . ja va 2 s .c om * * @param file the path to the file * @return boolean * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if file is null */ public static boolean deleteFile(Path file) throws IOException { if ((file == null)) throw new IllegalArgumentException("file cannot be null"); try { if (file.toFile().canWrite()) { Files.delete(file); } return !Files.exists(file, LinkOption.NOFOLLOW_LINKS); } catch (IOException e) { e.printStackTrace(); throw new IOException("An IO exception occured while deleting file '" + file + "' with error:" + e.getLocalizedMessage()); } }
From source file:nl.minvenj.pef.stream.LiveCapture.java
private static boolean checkConfiguration(final XMLConfiguration config) { final long MAX_FILE_SIZE = 1000; //Test if all fields are available. For now it exits per field. try {/*from ww w. j a v a2 s . c o m*/ //First all normal fields. The library field is optional, default to metal. final boolean live = config.getBoolean("live"); final String inputFile = config.getString("input"); if (!live) { if (inputFile == null) { throw new NoSuchElementException( "For offline use, the parameter 'input' file needs to be specified"); } File testInput = new File(inputFile); if (!testInput.exists()) { logger.severe("The specified input file " + testInput.toPath().toAbsolutePath().toString() + " does not exist."); return false; } if (!testInput.canRead()) { logger.severe("The user is not allowed to read the file"); } } // Will throw an error if conversion fails. config.getBoolean("remove_failing_packets"); config.getBoolean("remove_unknown_protocols"); config.getBoolean("checksum_reset"); config.getBoolean("timer", false); final String outputDir = config.getString("output_directory"); // The file size does not need to be specified. Therefore a default is provided. final long fileSize = config.getLong("file_size", 120); if (fileSize > MAX_FILE_SIZE) { logger.severe(" A file size over 1000 MB is not supported."); return false; } if (outputDir == null) { throw new NoSuchElementException("The output_directory parameter is not set"); } final Path path = Paths.get(outputDir); if (!Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { logger.severe("The output directory configured is not a path."); return false; } if (!Files.isWritable(path)) { logger.severe("The selected output directory is not writable."); return false; } final String parseLibrary = config.getString("parse_library"); if (!parseLibrary.equals("metal")) { logger.severe("Only the metal library is currently implemented as parse library."); return false; } String[] packetInputLibraryOptions = { "metal", "jnetpcap" }; final String packetInputLibrary = config.getString("packets_input_library"); if (!Arrays.asList(packetInputLibraryOptions).contains(packetInputLibrary)) { logger.severe("Packet Input Library: " + packetInputLibrary + " is not implemented."); } // Test all algorithms and their parameters. testPseudonymizationSettings(config); } catch (NoSuchElementException e) { logger.severe("Input element is missing: " + e.getMessage()); return false; } catch (InvalidPathException e) { logger.severe("The path specified in the config file is invalid: " + e.getMessage()); return false; } catch (ConversionException e) { logger.severe("Conversion failed: " + e.getMessage()); return false; } catch (ClassNotFoundException e) { logger.severe("Error in creating a parameter: the class could not be found: " + e.getMessage()); return false; } catch (ConfigurationException e) { logger.severe(e.getMessage()); return false; } return true; }
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 2s.c o m*/ 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:ws.michalski.velogen.VeloGenManager.java
public void writeOutputFile(String fileName, String content, boolean replace) throws VeloGenException { Path target = Paths.get(getOutputPath(), fileName); if (!replace && Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { throw new VeloGenException(target.normalize().toString() + " exist. Use option -ov for overwrite."); }/* w w w . j a va2 s . c o m*/ try (FileOutputStream fos = new FileOutputStream(target.toFile(), false)) { try (BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(fos))) { bwr.write(content); bwr.flush(); } fos.flush(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java
@Override public long getLastAccessTime() { try {//from ww w . j a v a 2s . co m BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); return attr.lastAccessTime().toMillis(); } catch (IOException e) { logger.error("Error in getLastAccessTime()", e); return 0; } }
From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java
/** * checkProgram invokes the Haskell compiler on a given file and reports * the output./*from w w w . ja v a 2s .co m*/ * * @param pathToProgramFile * Specifies the file or folder containing that should be * compiled. (accepts .lhs and .hs files) * @param compilerName * The compiler to be used (usually ghc). * @param compilerFlags * Additional flags to be passed to the compiler. * @throws FileNotFoundException * Is thrown when the file in pathToProgramFile cannot be * opened * @throws BadCompilerSpecifiedException * Is thrown when the given compiler cannot be called * @return A {@link CompilerOutput} that contains all compiler messages and * flags on how the compile run went. * @throws BadFlagException * When ghc doesn't recognize a flag, this exception is thrown. */ @Override public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags) throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException { Process compilerProcess = null; try { // create compiler invocation. List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags); ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation); // make sure the compiler stays in its directory. compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile()); compilerProcess = compilerProcessBuilder.start(); // this will never happen because createCompilerInvocation never // throws this Exception. Throw declaration needs to be in method // declaration because of the implemented Interface although we // never use it in the HaskellCompileChecker } catch (CompilerOutputFolderExistsException e) { LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage()); } catch (BadCompilerSpecifiedException e) { throw new BadCompilerSpecifiedException(e.getMessage()); } catch (IOException e) { // If we cannot call the compiler we return a CompilerOutput // initialized with false, false, indicating // that the compiler wasn't invoked properly and that there was no // clean Compile. CompilerOutput compilerInvokeError = new CompilerOutput(); compilerInvokeError.setClean(false); compilerInvokeError.setCompilerInvoked(false); return compilerInvokeError; } // Now we read compiler output. If everything is ok ghc reports // nothing in the errorStream. InputStream compilerOutputStream = compilerProcess.getErrorStream(); InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream); BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader); String line; CompilerOutput compilerOutput = new CompilerOutput(); compilerOutput.setCompilerInvoked(true); List<String> compilerOutputLines = new LinkedList<>(); try { while ((line = compilerOutputBuffer.readLine()) != null) { compilerOutputLines.add(line); } // Errors are separated via an empty line (""). But after the // the last error the OutputBuffer has nothing more to write. // In order to recognize the last error we insert an empty String // at the end of the list. // Only needs to be done when there are errors. if (compilerOutputLines.size() != 0) { line = ""; compilerOutputLines.add(line); } compilerOutputStream.close(); compilerStreamReader.close(); compilerOutputBuffer.close(); compilerProcess.destroy(); } catch (IOException e) { // Reading might go wrong here if ghc should unexpectedly die LOGGER.severe("Error while reading from compiler stream."); compilerOutput.setClean(false); compilerOutput.setCompileStreamBroken(true); return compilerOutput; } // ghc -c generates a .o(object) and a .hi(haskell interface) file. // But we don't need those files so they can be deleted. // The generated files have the same name like our input file so we // can just exchange the file endings in order to get the // correct file paths for deletion if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) { // we use a file walker in order to find all files in the folder // and its subfolders RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]"); try { Files.walkFileTree(pathToProgramFile, dirWalker); } catch (IOException e) { LOGGER.severe("Could not walk submission " + pathToProgramFile.toString() + " while building copiler invocation: " + e.getMessage()); } for (Path candidatePath : dirWalker.getFoundFiles()) { File candidateFile = candidatePath.toFile(); if (!candidateFile.isDirectory()) { String extension = FilenameUtils.getExtension(candidateFile.toString()); if (extension.matches("[Ll]?[Hh][Ss]")) { File ghcGeneratedObject = new File( FilenameUtils.removeExtension(candidateFile.toString()) + ".o"); File ghcGeneratedInterface = new File( FilenameUtils.removeExtension(candidateFile.toString()) + ".hi"); ghcGeneratedObject.delete(); ghcGeneratedInterface.delete(); } } } } else { String extension = FilenameUtils.getExtension(pathToProgramFile.toString()); if (extension.matches("[Ll]?[Hh][Ss]")) { File ghcGeneratedObject = new File( FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o"); File ghcGeneratedInterface = new File( FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi"); ghcGeneratedObject.delete(); ghcGeneratedInterface.delete(); } } // if there are no errors there is no Output to handle if (compilerOutputLines.size() != 0) { compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput); } else { compilerOutput.setClean(true); } return compilerOutput; }
From source file:org.fim.internal.StateGenerator.java
private void scanFileTree(BlockingDeque<Path> filesToHashQueue, Path directory, FimIgnore parentFimIgnore) throws NoSuchAlgorithmException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) { FimIgnore fimIgnore = fimIgnoreManager.loadLocalIgnore(directory, parentFimIgnore); for (Path file : stream) { if (!fileHashersStarted && filesToHashQueue.size() > FILES_QUEUE_CAPACITY / 2) { startFileHashers();/* w ww . ja v a 2 s .c om*/ } BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); String fileName = file.getFileName().toString(); if (fimIgnoreManager.isIgnored(fileName, attributes, fimIgnore)) { fimIgnoreManager.ignoreThisFiles(file, attributes); } else { if (attributes.isRegularFile()) { enqueueFile(filesToHashQueue, file); } else if (attributes.isDirectory()) { scanFileTree(filesToHashQueue, file, fimIgnore); } } } } catch (IOException ex) { Console.newLine(); Logger.error("Skipping - Error scanning directory '" + directory + "'", ex, context.isDisplayStackTrace()); } }
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 ww. j av a2 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(); } } }