Example usage for java.io File getCanonicalFile

List of usage examples for java.io File getCanonicalFile

Introduction

In this page you can find the example usage for java.io File getCanonicalFile.

Prototype

public File getCanonicalFile() throws IOException 

Source Link

Document

Returns the canonical form of this abstract pathname.

Usage

From source file:nl.opengeogroep.filesetsync.server.stripes.FilesetBaseActionBean.java

@ValidationMethod
public void checkFileset() throws IOException {

    if (fileset == null) {
        getContext().getValidationErrors()
                .addGlobalError(new SimpleError("Fileset path not found: " + filesetPath));
        return;//from  www.j  a v  a 2 s . com
    }

    File filesetRoot = new File(fileset.getPath());
    if (!filesetRoot.exists()) {
        log.error("local path does not exist for requested fileset path " + filesetPath + ": "
                + fileset.getPath());
        getContext().getValidationErrors()
                .addGlobalError(new SimpleError("Fileset does not exist on server: " + filesetPath));
        return;
    }

    // Check if subPath does not navigate with .. outside of fileset path
    // Note that .. may be stripped from HttpServletRequest.getPathInfo()
    // but Stripes also supports GET /filesetsync-server/fileset/list?filesetPath=/some/../../secret/file
    if (subPath.length() != 0) {
        if (!filesetRoot.isDirectory()) {
            getContext().getValidationErrors()
                    .addGlobalError(new SimpleError("Fileset path does not exist: " + filesetPath));
            return;
        }
        File subFile = new File(fileset.getPath() + subPath);
        subFile = subFile.getCanonicalFile();
        if (!subFile.exists()) {
            getContext().getValidationErrors()
                    .addGlobalError(new SimpleError("Fileset path does not exist: " + filesetPath));
            return;
        }

        filesetRoot = filesetRoot.getCanonicalFile();

        File parent = subFile;
        while (parent != null && !parent.equals(filesetRoot)) {
            parent = parent.getParentFile();
        }
        if (parent == null) {
            log.info(String.format(
                    "requested fileset path \"%s\" does not exist or is not subdir of fileset root \"%s\"",
                    filesetPath, fileset.getPath()));
            getContext().getValidationErrors()
                    .addGlobalError(new SimpleError("Fileset path does not exist: " + filesetPath));
            return;
        }
    }
}

From source file:org.apache.maven.plugin.surefire.booterclient.ForkConfigurationTest.java

public void testCurrentWorkingDirectoryPropagationIncludingForkNumberExpansion()
        throws IOException, SurefireBooterForkException {
    // SUREFIRE-1136
    File baseDir = new File(FileUtils.getTempDirectory(),
            "SUREFIRE-1136-" + RandomStringUtils.randomAlphabetic(3));
    baseDir.mkdirs();//from   w  ww  . j  a  v  a  2s .c  o m
    baseDir.deleteOnExit();

    File cwd = new File(baseDir, "fork_${surefire.forkNumber}");

    ForkConfiguration config = getForkConfiguration(null, "java", cwd.getCanonicalFile());
    Commandline commandLine = config.createCommandLine(Collections.<String>emptyList(), true, false, null, 1);

    File forkDirectory = new File(baseDir, "fork_1");
    forkDirectory.deleteOnExit();
    assertTrue(forkDirectory.getCanonicalPath()
            .equals(commandLine.getShell().getWorkingDirectory().getCanonicalPath()));
}

From source file:org.pieShare.pieShareApp.service.folderService.FilderServiceBase.java

@Override
public String relativizeFilePath(File file) {
    try {/*from w w  w  .  j  a v  a 2 s .c o m*/
        String pathBase = this.userService.getUser().getPieShareConfiguration().getWorkingDir()
                .getCanonicalFile().toString();
        String pathAbsolute = file.getCanonicalFile().toString();
        String relative = new File(pathBase).toURI().relativize(new File(pathAbsolute).toURI()).getPath();
        return relative;
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error in creating relativ file path!", ex);
    }
    return null;
}

From source file:org.dbgl.util.FileUtils.java

private static File canonicalTo(final File base, final String path) {
    File file = new File(path);
    if (file.isAbsolute()) {
        try {/* w ww .  j  a va  2  s. c  o  m*/
            return file.getCanonicalFile();
        } catch (IOException e) {
            return file.getAbsoluteFile();
        }
    } else {
        try {
            return new File(base, file.getPath()).getCanonicalFile();
        } catch (IOException e) {
            return new File(base, file.getPath()).getAbsoluteFile();
        }
    }
}

From source file:dk.cubing.liveresults.uploader.configuration.Configuration.java

/**
 * @param engine// w w  w .ja  v a 2  s.co m
 */
public Configuration(ResultsEngine engine) {
    this.engine = engine;
    try {
        File configFile = new File(new File(".").getAbsolutePath() + "/conf/config.properties");
        if (!configFile.getCanonicalFile().exists()) {
            configFile = new File(ClassLoader.getSystemResource("config.properties").getFile());
        }
        log.debug("Config file: {}", configFile.getCanonicalFile());
        config = new PropertiesConfiguration(configFile.getCanonicalFile());
        config.setReloadingStrategy(new ResultsConfigReloadingStrategy(engine));
    } catch (Exception e) {
        log.error("Could not load configuration file", e);
        engine.shutdown();
    }
}

From source file:org.xwiki.environment.internal.ServletEnvironmentTest.java

@Test
public void getTemporaryDirectory() throws Exception {
    File tmpDir = new File("tmpdir");
    this.environment.setTemporaryDirectory(tmpDir);
    assertEquals(tmpDir.getCanonicalFile(), this.environment.getTemporaryDirectory().getCanonicalFile());
}

From source file:com.kolich.blog.components.GitRepository.java

@Injectable
public GitRepository(@Required final ServletContext context, @Required final BlogEventBus eventBus)
        throws Exception {
    eventBus_ = eventBus;// w w w. j av  a 2s.c o  m
    executor_ = newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("blog-git-puller").build());
    final File repoDir = getRepoDir(context);
    logger__.info("Activated repository path: {}", repoDir.getCanonicalFile());
    // If were not in dev mode, and the clone path doesn't exist or we need to force clone from
    // scratch, do that now.
    final boolean clone = (!repoDir.exists() || shouldCloneOnStartup__);
    if (!isDevMode__ && clone) {
        logger__.info("Clone path does not exist, or we were asked to re-clone. Cloning from: {}",
                blogRepoCloneUrl__);
        // Recursively delete the existing clone of the repo, if it exists, and clone the repository.
        FileUtils.deleteDirectory(repoDir);
        Git.cloneRepository().setURI(blogRepoCloneUrl__).setDirectory(repoDir).setBranch("master").call();
    }
    // Construct a new pointer to the repository on disk.
    repo_ = new FileRepositoryBuilder().setWorkTree(repoDir).readEnvironment().build();
    git_ = new Git(repo_);
    logger__.info("Successfully initialized repository at: {}", repo_);
}

From source file:org.kepler.ssh.LocalDelete.java

/**
 * Test if a File is a symbolic link. It returns true if the file is a
 * symbolic link, false otherwise. Exception: if the symlink points to
 * itself, it returns false. Sorry. How does it work: it compares the
 * canonical path and the absolute path of the file. The former gives the
 * referred file of a link and thus differs from the absolute path of the
 * link itself./*from   w ww  . j  a v  a 2s. co  m*/
 */
private static boolean isSymbolicLink(File f) {

    if (f == null)
        return false;
    if (!f.exists())
        return false;

    // special case: path ends with .., which can never be a symlink, right?
    // Note: symlink/.. refers to the directory containing the symlink and
    // not the link itself
    // special case: path ends with ., it is the same
    // Note: symlink/. refers to the pointed directory and not the link
    // itself
    // They are handled here because they would result in true in later
    // tests.
    if (f.getName().equals("..") || f.getName().equals("."))
        return false;

    // to see if this file is actually a symbolic link to a directory,
    // we want to get its canonical path - that is, we follow the link to
    // the file it's actually linked to
    File canf;
    try {
        canf = f.getCanonicalFile();
    } catch (IOException e) {
        log.error("Cannot get canonical filename of file " + f.getPath());
        return true;
    }

    // we need to get the absolute path
    // Unfortunately File.getAbsolutePath() does not eliminate . and ..
    // thus the equality test fails for paths containing them.
    // Let's do some magic with the parent dir name and get the absolute
    // path this way.

    File absf;
    File parent = f.getParentFile();
    if (parent == null) {
        // no problem, we have a single (relative) file name
        absf = f.getAbsoluteFile();
    } else {
        // eliminate . and .. from the parent path, using getCanonicalFile()
        try {
            parent = parent.getCanonicalFile();
        } catch (IOException e) {
            log.error("Cannot get canonical filename of file " + parent.getPath());
        }
        // recreate the absolute filename
        // Note: if f's name is .., this would not be eliminated here. See
        // pre-test above
        absf = new File(parent, f.getName());
    }

    if (isDebugging)
        log.debug(
                "File " + f.getPath() + "\nCanonical =  " + canf.getPath() + "\nAbsolute = " + absf.getPath());

    // a symbolic link has a different canonical path than its actual path,
    // unless it's a link to itself
    return (!canf.equals(absf));
}

From source file:org.apache.tomcat.util.compat.JdkCompat.java

/**
 *  Return the URI for the given file. Originally created for
 *  o.a.c.loader.WebappClassLoader/*from  ww  w.j av  a  2 s  .co  m*/
 *
 *  @param File to wrap into URI
 *  @return A URI as a URL
 */
public URL getURI(File file) throws MalformedURLException {

    File realFile = file;
    try {
        realFile = realFile.getCanonicalFile();
    } catch (IOException e) {
        // Ignore
    }

    return realFile.toURL();
}

From source file:org.nuxeo.runtime.model.impl.ComponentPersistence.java

public void loadPersistedComponent(File file) throws IOException {
    file = file.getCanonicalFile();
    if (file.isFile() && file.getName().endsWith(".xml")) {
        File parent = file.getParentFile();
        if (root.equals(parent)) {
            deploy(sysrc, file);/*from w  ww  . j a  v a  2  s .  c o  m*/
            return;
        } else {
            String symbolicName = parent.getName();
            parent = parent.getParentFile();
            if (root.equals(parent)) {
                RuntimeContext rc = getContext(symbolicName);
                if (rc != null) {
                    deploy(rc, file);
                    return;
                }
            }
        }
    }
    throw new IllegalArgumentException("Invalid component file location or bundle not found");
}