Example usage for java.nio.file LinkOption NOFOLLOW_LINKS

List of usage examples for java.nio.file LinkOption NOFOLLOW_LINKS

Introduction

In this page you can find the example usage for java.nio.file LinkOption NOFOLLOW_LINKS.

Prototype

LinkOption NOFOLLOW_LINKS

To view the source code for java.nio.file LinkOption NOFOLLOW_LINKS.

Click Source Link

Document

Do not follow symbolic links.

Usage

From source file:com.phoenixnap.oss.ramlapisync.plugin.SpringMvcRamlVerifierMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    long startTime = System.currentTimeMillis();
    if (project.getPackaging().equals("pom")) {
        this.getLog().info("Skipping [pom] project: " + project.getName());

    } else if (project.getPackaging().equals("maven-plugin")) {
        this.getLog().info("Skipping [maven-plugin] project: " + project.getName());

    } else if (!Files.isDirectory(Paths.get(project.getBuild().getSourceDirectory()),
            LinkOption.NOFOLLOW_LINKS)) {
        this.getLog().info("Skipping project with missing src folder: " + project.getName());

    } else {/*from   w ww. j  ava 2  s . com*/
        try {
            verifyRaml();
        } catch (IOException e) {
            ClassLoaderUtils.restoreOriginalClassLoader();
            throw new MojoExecutionException(e, "Unexpected exception while executing Raml Sync Plugin.",
                    e.toString());
        }
    }
    this.getLog().info("Raml Generation Complete in:" + (System.currentTimeMillis() - startTime) + "ms");
}

From source file:org.duracloud.retrieval.mgmt.RetrievalWorker.java

protected void applyTimestamps(ContentStream content, File localFile) {
    FileTime createTime = convertDateToFileTime(content.getDateCreated());
    FileTime lastAccessTime = convertDateToFileTime(content.getDateLastAccessed());
    FileTime lastModTime = convertDateToFileTime(content.getDateLastModified());

    BasicFileAttributeView fileAttributeView = Files.getFileAttributeView(localFile.toPath(),
            BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    // If any time value is null, that value is left unchanged
    try {//from   w ww  .  j  a  v  a 2s  .  co  m
        fileAttributeView.setTimes(lastModTime, lastAccessTime, createTime);
    } catch (IOException e) {
        logger.error("Error setting timestamps for local file " + localFile.getAbsolutePath() + ": "
                + e.getMessage(), e);
    }
}

From source file:org.codice.ddf.configuration.migration.AbstractMigrationTest.java

/**
 * Creates a test file with the given name in the specified directory resolved under ${ddf.home}.
 *
 * <p><i>Note:</i> The file will be created with the filename (no directory) as its content.
 *
 * @param dir the directory where to create the test file
 * @param name the name of the test file to create in the specified directory
 * @param resource the resource to copy to the test file
 * @return a path corresponding to the test file created (relativized from ${ddf.home})
 * @throws IOException if an I/O error occurs while creating the test file
 *//*from w  w  w  .ja  v  a  2s  .com*/
public Path createFileFromResource(Path dir, String name, String resource) throws IOException {
    final File file = new File(ddfHome.resolve(dir).toFile(), name);
    final InputStream is = AbstractMigrationTest.class.getResourceAsStream(resource);

    if (is == null) {
        throw new FileNotFoundException("resource '" + resource + "' not found");
    }
    dir.toFile().mkdirs();
    FileUtils.copyInputStreamToFile(is, file);
    final Path path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);

    return path.startsWith(ddfHome) ? ddfHome.relativize(path) : path;
}

From source file:org.csstudio.diirt.util.preferences.DataSourcesPreferencePage.java

/**
 * Ask the user for a folder where to save the DIIRT configuration files.
 *///from  w  ww  .  ja v a2s . com
private void exportConfiguration() {

    DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SHEET);

    dialog.setText(Messages.DSPP_exportDialog_text);
    dialog.setMessage(Messages.DSPP_exportDialog_message);

    if (lastPath != null) {
        dialog.setFilterPath(lastPath);
    }

    String choice = dialog.open();

    if (choice != null) {

        try {
            choice = DIIRTPreferences.resolvePlatformPath(choice.trim());
        } catch (Exception ex) {
            notifyWarning(NLS.bind(Messages.DSPP_resolveMessage, choice));
            return;
        }

        lastPath = choice;

        Path parentPath = Paths.get(choice);
        Path dsPath = Paths.get(parentPath.toString(), DATASOURCES_DIR);
        Path dsFile = Paths.get(dsPath.toString(), DATASOURCES_FILE);
        Path caPath = Paths.get(dsPath.toString(), CA_DIR);
        Path caFile = Paths.get(caPath.toString(), CA_FILE);
        Path[] content = new Path[] { dsPath, dsFile, caPath, caFile };

        if (Arrays.asList(content).stream().anyMatch(p -> Files.exists(p, LinkOption.NOFOLLOW_LINKS))) {

            boolean overwrite = MessageDialog.openConfirm(getShell(), Messages.DSPP_exportFilesExist_title,
                    NLS.bind(Messages.DSPP_exportFilesExist_message, choice));

            if (!overwrite) {
                return;
            }

        }

        try {
            DIIRTPreferences.get().toFiles(parentPath.toFile());
            notifyInformation(NLS.bind(Messages.DSPP_exportSuccessful_message, choice));
        } catch (IOException ex) {
            notifyWarning(NLS.bind(Messages.DSPP_exportFailed_message, choice, ex.getMessage()));
        }

    }

}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * Checks whether the specified directory already contains a svn
 * repository./* w w  w .  ja v a 2s . co m*/
 *
 * @param targetDirectory
 *            the directory which will contain a repository
 * @return true if there is a repository, false otherwise
 */
private static boolean isDataSourceInitialized(Path targetDirectory) {
    return (targetDirectory != null)
            && Files.exists(targetDirectory.resolve(".svn/"), LinkOption.NOFOLLOW_LINKS);
}

From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java

/**
 * This Method generates the command required to start the compiler. It
 * generates a list of strings that can be passed to a process builder.
 * /*from  www  .  j  a  v  a  2  s . c  om*/
 * @param pathToProgramFile
 *            Where to look for the main file that will be compiled.
 * @param compilerName
 *            Which compiler to call
 * @param compilerFlags
 *            User supplied flags to be passed
 * @return List of string with the command for the process builder.
 * @throws BadCompilerSpecifiedException
 *             When no compiler is given.
 * @throws FileNotFoundException
 *             When the file to be compiled does not exist
 * @throws CompilerOutputFolderExistsException
 *             Due to slightly uncompatible CompileCheckerInterface this
 *             exception is in the declaration but it is never thrown.
 *             JavaCompileChecker uses this exception.
 */
private List<String> createCompilerInvocation(Path pathToProgramFile, String compilerName,
        List<String> compilerFlags)
        throws BadCompilerSpecifiedException, FileNotFoundException, CompilerOutputFolderExistsException {

    List<String> compilerInvocation = new LinkedList<>();
    // We need a compiler name. Without it we cannot compile anything and
    // abort.
    if (("".equals(compilerName)) || (compilerName == null)) {
        throw new BadCompilerSpecifiedException("No compiler specified.");
    } else {
        compilerInvocation.add(compilerName);
    }

    // If compiler flags are passed, append them after the compiler name.
    // If we didn't get any we append nothing.
    if ((compilerFlags != null) && (!(compilerFlags.isEmpty()))) {
        compilerInvocation.addAll(compilerFlags);
    }

    // now we tell ghc to stop after compilation because we just want to
    // see if there are syntax errors in the code
    compilerInvocation.add("-c");

    // Check for the existence of the program file we are trying to
    // compile.
    if ((pathToProgramFile == null) || (pathToProgramFile.compareTo(Paths.get("")) == 0)) {
        throw new FileNotFoundException("No file to compile specified");
    } else {
        if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // we are supposed to compile a folder. Hence we'll scan for
            // lhs files and pass them to the compiler.
            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 compiler invocation: " + e.getMessage());
            }
            for (Path matchedFile : dirWalker.getFoundFiles()) {
                compilerInvocation.add(matchedFile.toFile().getAbsolutePath());
            }

        } else if (Files.exists(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // if the file exists, just pass the file name, since the
            // compiler will
            // be confined to the directory the file is in a few lines
            // down.
            compilerInvocation.add(pathToProgramFile.toString());
        } else {
            throw new FileNotFoundException("Program file that should be compiled does not exist."
                    + "Filename : \"" + pathToProgramFile.toString() + "\"");
        }
    }
    return compilerInvocation;
}

From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java

/**
 * Creates a test file with the given name in the specified directory resolved under ${ddf.home}.
 *
 * <p><i>Note:</i> The file will be created with the filename (no directory) as its content.
 *
 * @param dir the directory where to create the test file
 * @param name the name of the test file to create in the specified directory
 * @param resource the resource to copy to the test file
 * @return a path corresponding to the test file created (relativized from ${ddf.home})
 * @throws IOException if an I/O error occurs while creating the test file
 *///from w  ww .  j av  a  2  s . c o m
public Path createFileFromResource(Path dir, String name, String resource) throws IOException {
    final File file = new File(ddfHome.resolve(dir).toFile(), name);
    final InputStream is = AbstractMigrationSupport.class.getResourceAsStream(resource);

    if (is == null) {
        throw new FileNotFoundException("resource '" + resource + "' not found");
    }
    dir.toFile().mkdirs();
    FileUtils.copyInputStreamToFile(is, file);
    final Path path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);

    return path.startsWith(ddfHome) ? ddfHome.relativize(path) : path;
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ???????????????true???./*  ww w  . ja  v  a 2s.  c  om*/
 * 
 * @param key ?
 * @return ?????true
 */
@Override
public boolean canLoad(String key, UrlTreeContext ctx) throws BadContentException {
    if (key == null) {
        return false;
    }

    if (!isValidFileName(key)) {
        return false;
    }

    String key2;
    if (key.equals("root")) {
        key2 = "";
    } else {
        key2 = key;
    }

    Path f = this.generateFileObj(key2);
    logger.debug(f.toString() + ": canload called");
    return Files.exists(f, LinkOption.NOFOLLOW_LINKS);
}

From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java

/**
 * This Method generates the command required to start the compiler. It
 * generates a list of strings that can be passed to a process builder.
 *
 * @param pathToSourceFolder/*from  ww  w. j a va2  s  .c om*/
 *            Where to look for the source files that will be compiled.
 * @param outputFolder
 *            Where .class files will be placed
 * @param compilerName
 *            Which compiler to call
 * @param compilerFlags
 *            User supplied flags to be passed
 * @throws BadCompilerSpecifiedException
 *             When no compiler is given.
 * @throws FileNotFoundException
 *             When the file to be compiled does not exist
 * @throws CompilerOutputFolderExistsException
 *             The output folder may not exist. This is thrown when it does
 *             exist.
 * @return List of string with the command for the process builder.
 */
private List<String> createCompilerInvocation(Path pathToSourceFolder, Path outputFolder, String compilerName,
        List<String> compilerFlags)
        throws BadCompilerSpecifiedException, FileNotFoundException, CompilerOutputFolderExistsException {

    List<String> compilerInvocation = new LinkedList<>();
    // Check if a compiler has been supplied. Without one we abort
    // compiling. Else we start building the compiler command.
    if (("".equals(compilerName)) || (compilerName == null)) {
        throw new BadCompilerSpecifiedException("No compiler specified.");
    } else {
        compilerInvocation.add(compilerName);
    }

    // If compiler flags are passed, append them after the compiler name.
    // If we didn't get any we append nothing. Appending empty strings or
    // nulls to the compiler invocation must be avoided, since it can cause
    // javac to crash. Hence, we ignore such entries.
    if ((compilerFlags != null) && (!(compilerFlags.isEmpty()))) {
        for (String flag : compilerFlags) {
            // If javac gets passed a "" it dies due to a bug, so avoid
            // this
            if ((flag != null) && !"".equals(flag)) {
                compilerInvocation.add(flag);
            }
        }
    }

    // Add JUnit and the current directory to the classpath.s
    compilerInvocation.add("-cp");
    String cp = ".:" + m_junitLocation.toAbsolutePath().toString();
    // Add all additional .jar files contained in javalib directory to the classpath
    if (!m_libLocation.toFile().exists()) {
        m_libLocation.toFile().mkdir();
    } else {
        for (File f : FileUtils.listFiles(m_libLocation.toFile(), new String[] { "jar" }, false)) {
            cp = cp + ":" + f.getAbsolutePath();
        }
    }
    compilerInvocation.add(cp);

    //make sure java uses utf8 for encoding
    compilerInvocation.add("-encoding");
    compilerInvocation.add("UTF-8");

    // Check for the existence of the program file we are trying to
    // compile.
    if ((pathToSourceFolder == null) || !(pathToSourceFolder.toFile().exists())) {
        throw new FileNotFoundException("No file to compile specified");
    } else {
        if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) {
            // we are supposed to compile a folder. Hence we'll scan for
            // java files and pass them to the compiler.
            List<Path> foundFiles = exploreDirectory(pathToSourceFolder);
            for (Path matchedFile : foundFiles) {
                compilerInvocation.add(matchedFile.toFile().getAbsolutePath());
            }

            compilerInvocation.add("-d");
            compilerInvocation.add(outputFolder.toAbsolutePath().toString());
        } else {
            throw new FileNotFoundException("Program file that should be compiled does not exist."
                    + "Filename : \"" + pathToSourceFolder.toString() + "\"");
        }
    }

    return compilerInvocation;
}

From source file:org.wso2.carbon.event.template.manager.core.internal.util.TemplateManagerHelper.java

/**
 * Create a JavaScript engine packed with given scripts. If two scripts have methods with same name,
 * later method will override the previous method.
 *
 * @param domain/*w w w  .  j  a v a 2  s.  co  m*/
 * @return JavaScript engine
 * @throws TemplateDeploymentException if there are any errors in JavaScript evaluation
 */
public static ScriptEngine createJavaScriptEngine(Domain domain) throws TemplateDeploymentException {

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager
            .getEngineByName(TemplateManagerConstants.JAVASCRIPT_ENGINE_NAME);

    if (scriptEngine == null) {
        // Exception will be thrown later, only if function calls are used in the template
        log.warn("JavaScript engine is not available. Function calls in the templates cannot be evaluated");
    } else {
        if (domain != null && domain.getScripts() != null && domain.getScripts().getScript() != null) {
            Path scriptDirectory = Paths.get(TemplateManagerConstants.TEMPLATE_SCRIPT_PATH);
            if (Files.exists(scriptDirectory, LinkOption.NOFOLLOW_LINKS)
                    && Files.isDirectory(scriptDirectory)) {
                for (Script script : domain.getScripts().getScript()) {
                    String src = script.getSrc();
                    String content = script.getContent();
                    if (src != null) {
                        // Evaluate JavaScript file
                        Path scriptFile = scriptDirectory.resolve(src).normalize();
                        if (Files.exists(scriptFile, LinkOption.NOFOLLOW_LINKS)
                                && Files.isReadable(scriptFile)) {
                            if (!scriptFile.startsWith(scriptDirectory)) {
                                // The script file is not in the permitted directory
                                throw new TemplateDeploymentException("Script file "
                                        + scriptFile.toAbsolutePath() + " is not in the permitted directory "
                                        + scriptDirectory.toAbsolutePath());
                            }
                            try {
                                scriptEngine
                                        .eval(Files.newBufferedReader(scriptFile, Charset.defaultCharset()));
                            } catch (ScriptException e) {
                                throw new TemplateDeploymentException("Error in JavaScript "
                                        + scriptFile.toAbsolutePath() + ": " + e.getMessage(), e);
                            } catch (IOException e) {
                                throw new TemplateDeploymentException(
                                        "Error in reading JavaScript file: " + scriptFile.toAbsolutePath());
                            }
                        } else {
                            throw new TemplateDeploymentException("JavaScript file not exist at: "
                                    + scriptFile.toAbsolutePath() + " or not readable.");
                        }
                    }
                    if (content != null) {
                        // Evaluate JavaScript content
                        try {
                            scriptEngine.eval(content);
                        } catch (ScriptException e) {
                            throw new TemplateDeploymentException(
                                    "JavaScript declared in " + domain.getName() + " has error", e);
                        }
                    }
                }
            } else {
                log.warn("Script directory not found at: " + scriptDirectory.toAbsolutePath());
            }
        }
    }

    return scriptEngine;
}