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:com.redhat.rcm.version.mgr.VersionManager.java

protected List<PomPeek> peekAtPomHierarchy(final File topPom, final VersionManagerSession session)
        throws IOException {
    final LinkedList<File> pendingPoms = new LinkedList<File>();
    pendingPoms.add(topPom.getCanonicalFile());

    final String topDir = topPom.getParentFile().getCanonicalPath();

    final Set<File> seen = new HashSet<File>();
    final List<PomPeek> peeked = new ArrayList<PomPeek>();

    while (!pendingPoms.isEmpty()) {
        final File pom = pendingPoms.removeFirst();
        seen.add(pom);/*from   w ww . ja v  a 2s.c  o  m*/

        logger.info("PEEK: " + pom);

        final PomPeek peek = new PomPeek(pom);
        final FullProjectKey key = peek.getKey();
        if (key != null) {
            session.addPeekPom(key, pom);
            peeked.add(peek);

            final File dir = pom.getParentFile();

            final String relPath = peek.getParentRelativePath();
            if (relPath != null) {
                logger.info("Found parent relativePath: " + relPath + " in pom: " + pom);
                File parent = new File(dir, relPath);
                if (parent.isDirectory()) {
                    parent = new File(parent, "pom.xml");
                }

                logger.info("Looking for parent POM: " + parent);

                parent = parent.getCanonicalFile();
                if (parent.getParentFile().getCanonicalPath().startsWith(topDir) && parent.exists()
                        && !seen.contains(parent) && !pendingPoms.contains(parent)) {
                    pendingPoms.add(parent);
                } else {
                    logger.info("Skipping reference to non-existent parent relativePath: '" + relPath + "' in: "
                            + pom);
                }
            }

            final Set<String> modules = peek.getModules();
            if (modules != null && !modules.isEmpty()) {
                for (final String module : modules) {
                    logger.info("Found module: " + module + " in pom: " + pom);
                    File modPom = new File(dir, module);
                    if (modPom.isDirectory()) {
                        modPom = new File(modPom, "pom.xml");
                    }

                    logger.info("Looking for module POM: " + modPom);

                    if (modPom.getParentFile().getCanonicalPath().startsWith(topDir) && modPom.exists()
                            && !seen.contains(modPom) && !pendingPoms.contains(modPom)) {
                        pendingPoms.addLast(modPom);
                    } else {
                        logger.info("Skipping reference to non-existent module: '" + module + "' in: " + pom);
                    }
                }
            }
        } else {
            logger.info("Skipping " + pom + " as its a template file.");
        }
    }

    return peeked;
}

From source file:dk.netarkivet.archive.bitarchive.BitarchiveAdmin.java

/**
 * Method for updating the filelist for a given basedir.
 * /* w w w  .  j  a va  2s.c  om*/
 * @param basedir The basedir to update the filelist for.
 * @throws ArgumentNotValid If basedir is null or if it not a proper 
 * directory.
 * @throws UnknownID If the basedir cannot be found both the archivedFiles 
 * map or the archiveTime map.
 * @throws IOFailure If it is not possible to retrieve the canonical file 
 * for the basedir.
 */
public void updateFileList(File basedir) throws ArgumentNotValid, UnknownID, IOFailure {
    ArgumentNotValid.checkNotNull(basedir, "File basedir");
    // ensure that it is the CanonicalFile for the directory.
    try {
        basedir = basedir.getCanonicalFile();
    } catch (IOException e) {
        throw new IOFailure("Could not retrieve canonical path for file '" + basedir, e);
    }
    if (!basedir.isDirectory()) {
        throw new ArgumentNotValid("The directory '" + basedir.getPath() + " is not a proper directory.");
    }
    if (!archivedFiles.containsKey(basedir) || !archiveTime.containsKey(basedir)) {
        throw new UnknownID("The directory '" + basedir + "' is not known "
                + "by the settings. Known directories are: " + archivedFiles.keySet());
    }

    log.debug("Updating the filelist for '" + basedir + "'.");
    File filedir = new File(basedir, Constants.FILE_DIRECTORY_NAME);
    if (!checkArchiveDir(filedir)) {
        throw new UnknownID("The directory '" + filedir + "' is not an " + " archive directory.");
    }

    String[] dirContent = filedir.list();
    List<String> filenames = new ArrayList<String>(dirContent.length);
    for (String file : dirContent) {
        // ensure that only files are handled
        if ((new File(filedir, file)).isFile()) {
            filenames.add(file);
        } else {
            log.warn("The file '" + file + "' in directory " + filedir.getPath() + " is not a proper file.");
        }
    }
    archivedFiles.put(basedir, filenames);
    archiveTime.put(basedir, filedir.lastModified());
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Returns the canonical file for the file without throwing a checked
 * exception. A potential {@link IOException} is converted into a
 * {@link RuntimeException}/* w  ww.  j a  v a 2 s. c  o  m*/
 * 
 * @param file
 *            File to return the canonical file for or <code>null</code>.
 * 
 * @return Canonical file for the given argument or <code>null</code> if the
 *         input was <code>null</code>.
 */
public static File getCanonicalFile(final File file) {
    if (file == null) {
        return null;
    }
    try {
        return file.getCanonicalFile();
    } catch (final IOException ex) {
        throw new RuntimeException("Couldn't get canonical file for: " + file, ex);
    }
}

From source file:org.mitre.provenance.capture.linux.PROCtor.java

public boolean isSymlink(File file) throws IOException {
    if (file == null)
        return false;

    File canon;
    if (file.getParent() == null)
        canon = file;/*from  w ww  .j a va2s .  com*/
    else {
        File canonDir = file.getParentFile().getCanonicalFile();
        canon = new File(canonDir, file.getName());
    }

    return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

From source file:org.cloudifysource.esc.shell.commands.BootstrapCloud.java

private void copySecurityFiles(final String providerDirectory) throws Exception {

    final File defaultSecuritySourceFile = new File(DEFAULT_SECURITY_FILE_PATH);

    if (securityProfile.equalsIgnoreCase(CloudifyConstants.SPRING_PROFILE_NON_SECURE)) {
        // copy the default security file (defines no security) to the upload folder
        FileUtils.copyFile(defaultSecuritySourceFile, defaultSecurityTargetFile);
    } else {/*  w  w w .  j  a v  a 2 s  .c o m*/
        // handle the configuration file
        if (StringUtils.isNotBlank(securityFilePath)) {
            final File securitySourceFile = new File(securityFilePath);
            if (!securitySourceFile.isFile()) {
                throw new Exception("Security configuration file not found: " + securityFilePath);
            }

            // copy to the cloud provider's folder, to be copied to all management servers remote directory
            if (!securitySourceFile.getCanonicalFile().equals(defaultSecurityTargetFile.getCanonicalFile())) {
                FileUtils.copyFile(securitySourceFile, defaultSecurityTargetFile);
            }
        } else {
            // TODO : should we use the default security location and assume it was edited by the user?
            // securityFilePath = CLOUDIFY_HOME + "/config/security/spring-security.xml";
            throw new IllegalArgumentException("-security-file is missing or empty");
        }

        // handle the keystore file
        if (StringUtils.isNotBlank(keystore)) {
            final File keystoreSourceFile = new File(keystore);
            if (!keystoreSourceFile.isFile()) {
                throw new Exception("Keystore file not found: " + keystore);
            }

            // copy to the override folder, to be copied to all management servers as well
            final File defaultKeystoreTargetFile = new File(
                    providerDirectory + PATH_SEPARATOR + CloudifyConstants.KEYSTORE_FILE_NAME);
            if (!keystoreSourceFile.getCanonicalFile().equals(defaultKeystoreTargetFile.getCanonicalFile())) {
                FileUtils.copyFile(keystoreSourceFile, defaultKeystoreTargetFile);
            }
        }
    }
}

From source file:org.mrgeo.cmd.ingest.IngestImage.java

List<String> getInputs(String arg, boolean recurse, final Configuration conf, boolean existsCheck,
        boolean argIsDir) {
    List<String> inputs = new LinkedList<>();

    File f;//from  w  w w  . j  a  va  2s.c o  m
    try {
        f = new File(new URI(arg));
    } catch (URISyntaxException | IllegalArgumentException ignored) {
        f = new File(arg);
    }

    // recurse through directories
    if (f.isDirectory()) {
        File[] dir = f.listFiles();
        if (dir != null) {
            for (File s : dir) {
                try {
                    if (s.isFile() || (s.isDirectory() && recurse)) {
                        inputs.addAll(getInputs(s.getCanonicalFile().toURI().toString(), recurse, conf, false,
                                s.isDirectory()));
                    }
                } catch (IOException ignored) {
                }
            }
        }
    } else if (f.isFile()) {
        // is this a geospatial image file?
        try {
            System.out.print("*** checking (local file) " + f.getCanonicalPath());
            String name = f.getCanonicalFile().toURI().toString();

            if (skippreprocessing) {
                if (firstInput) {
                    firstInput = false;
                    Dataset dataset = GDALUtils.open(name);

                    if (dataset != null) {
                        try {
                            calculateMinimalParams(dataset);
                        } finally {
                            GDALUtils.close(dataset);
                        }
                    }
                }
                inputs.add(name);
                local = true;

                System.out.println(" accepted ***");
            } else {
                Dataset dataset = GDALUtils.open(name);

                if (dataset != null) {
                    calculateParams(dataset);

                    GDALUtils.close(dataset);
                    inputs.add(name);

                    local = true;

                    System.out.println(" accepted ***");
                } else {
                    System.out.println(" can't load ***");
                }
            }
        } catch (IOException ignored) {
            System.out.println(" can't load ***");
        }
    } else {
        try {

            Path p = new Path(arg);
            FileSystem fs = HadoopFileUtils.getFileSystem(conf, p);

            if (!existsCheck || fs.exists(p)) {
                boolean isADirectory = argIsDir;
                if (existsCheck) {
                    FileStatus status = fs.getFileStatus(p);
                    isADirectory = status.isDirectory();
                }

                if (isADirectory && recurse) {
                    FileStatus[] files = fs.listStatus(p);
                    for (FileStatus file : files) {
                        inputs.addAll(getInputs(file.getPath().toUri().toString(), true, conf, false,
                                file.isDirectory()));
                    }
                } else {
                    // is this a geospatial image file?
                    System.out.print("*** checking  " + p.toString());
                    String name = p.toUri().toString();

                    if (skippreprocessing) {
                        if (firstInput) {
                            firstInput = false;
                            Dataset dataset = GDALUtils.open(name);

                            if (dataset != null) {
                                try {
                                    calculateMinimalParams(dataset);
                                } finally {
                                    GDALUtils.close(dataset);
                                }
                            }
                        }
                        inputs.add(name);
                        System.out.println(" accepted ***");
                    } else {

                        Dataset dataset = GDALUtils.open(name);

                        if (dataset != null) {
                            calculateParams(dataset);

                            GDALUtils.close(dataset);
                            inputs.add(name);

                            System.out.println(" accepted ***");
                        } else {
                            System.out.println(" can't load ***");
                        }
                    }
                }
            }
        } catch (IOException ignored) {
        }

    }

    return inputs;
}

From source file:de.innovationgate.wgpublisher.design.fs.DesignFileDocument.java

private String getProperCaseFileName(FileObject codeFile) {

    // Try to find right case of file on case-insensitive file systems
    if (codeFile instanceof LocalFile) {
        try {/*from   w w w  .  j a  v a  2  s .co m*/
            String uri = getManager().getCore().getURLEncoder().encodePath(codeFile.getName().getURI());
            File nativeFile = new File(new URI(uri));
            return nativeFile.getCanonicalFile().getName();
        } catch (Exception e) {
            LOG.error("Exception determining proper name case of local file " + codeFile.getName().getPath(),
                    e);
        }
    }

    return codeFile.getName().getBaseName();

}

From source file:org.apache.pig.parser.QueryParserDriver.java

private FetchFileRet getMacroFile(String fname) {
    FetchFileRet localFileRet = null;/*w  w w  . ja v a 2  s  .  c o  m*/
    try {
        if (fnameMap.get(fname) != null) {
            localFileRet = fnameMap.get(fname);
        } else {
            try {
                File localFile = QueryParserUtils.getFileFromImportSearchPath(fname);
                localFileRet = localFile == null ? FileLocalizer.fetchFile(pigContext.getProperties(), fname)
                        : new FetchFileRet(localFile.getCanonicalFile(), false);
            } catch (FileNotFoundException e) {
                // ignore this since we'll attempt to load as a resource before failing
                LOG.debug(String.format("Macro file %s was not found", fname));
            }

            // try loading the macro file as a resource in case it is packaged in a registered jar
            if (localFileRet == null) {
                LOG.debug(String.format("Attempting to load macro file %s as a resource", fname));

                try {
                    localFileRet = FileLocalizer.fetchResource(fname);
                    LOG.debug(String.format("Found macro file %s as resource", fname));
                } catch (ResourceNotFoundException e) {
                    LOG.debug(String.format("Macro file %s was not found as resource either", fname));
                    LOG.error(String.format("Failed to find macro file %s", fname));
                    throw new ExecException("file '" + fname + "' does not exist.", 101, PigException.INPUT);
                }
            }

            fnameMap.put(fname, localFileRet);
        }
    } catch (IOException e) {
        throw new RuntimeException("Unable to fetch macro file '" + fname + "'", e);
    }
    return localFileRet;
}

From source file:com.adito.upgrade.GUIUpgrader.java

void checkInstallations() {
    File oldDir = new File(source.getText());
    try {//from w ww  .  ja  v  a2  s  . com
        if (!oldDir.exists() || !oldDir.isDirectory()) {
            throw new Exception(oldDir.getAbsolutePath() + " does not exists or is not a directory");
        }
        File newDir = new File(target.getText());
        if (!newDir.exists() || !newDir.isDirectory()) {
            throw new Exception(newDir.getAbsolutePath() + " does not exists or is not a directory");
        }
        if (oldDir.getCanonicalFile().equals(newDir.getCanonicalFile())) {
            throw new Exception("Source and target installation directories are identical");
        }
        File oldDbDir = new File(oldDir, "db");
        File newDbDir = new File(newDir, "db");
        if (!new File(newDir, "db").exists()) {
            throw new Exception("Target does not appear to be an installation.");
        }
        if (!new File(oldDir, "db").exists()) {
            throw new Exception("Source does not appear to be does not appear to be an installation.");
        }
        if (!new File(newDir, "install").exists()) {
            throw new Exception("Target installation does not appear to be 0.2.5+");
        }
        if (!new File(new File(oldDir, "db"), "explorer_accounts.data").exists()) {
            throw new Exception("Source installation does not appear to be 0.1.15+");
        }

        upgrades = new ArrayList();
        upgrades.add(new UserUpgrade(oldDbDir, newDbDir));
        upgrades.add(new AuthSchemeUpgrade(oldDbDir, newDbDir));
        upgrades.add(new TunnelsUpgrade(oldDbDir, newDbDir));
        upgrades.add(new NetworkPlacesUpgrade(oldDbDir, newDbDir));
        upgrades.add(new WebForwardsUpgrade(oldDbDir, newDbDir));
        upgrades.add(new IPRestrictionsUpgrade(oldDbDir, newDbDir));
        upgrades.add(new ApplicationShortcutsUpgrade(oldDbDir, newDbDir));
        upgrades.add(new ReplacementsUpgrade(oldDbDir, newDbDir));
        addUpgradeSelectionComponent();

    } catch (Exception e) {
        removeUpgradeSelectionComponent();
        upgrades = null;
        upgradeSelectionPanel.add(new JLabel("<html>" + e.getMessage() + "</html>"));
        upgradeSelectionPanel.revalidate();
    }
}

From source file:org.apache.catalina.startup.TldConfig.java

/**
 * Returns a map of the paths to all JAR files that are accessible to the
 * webapp and will be scanned for TLDs.//w w  w .j a v a2s .c  o  m
 *
 * The map always includes all the JARs under WEB-INF/lib, as well as
 * shared JARs in the classloader delegation chain of the webapp's
 * classloader.
 *
 * The latter constitutes a Tomcat-specific extension to the TLD search
 * order defined in the JSP spec. It allows tag libraries packaged as JAR
 * files to be shared by web applications by simply dropping them in a 
 * location that all web applications have access to (e.g.,
 * <CATALINA_HOME>/common/lib).
 *
 * The set of shared JARs to be scanned for TLDs is narrowed down by
 * the <tt>noTldJars</tt> class variable, which contains the names of JARs
 * that are known not to contain any TLDs.
 *
 * @return Map of JAR file paths
 */
private Map getJarPaths() {

    HashMap jarPathMap = null;

    ClassLoader webappLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader loader = webappLoader;
    while (loader != null) {
        if (loader instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) loader).getURLs();
            for (int i = 0; i < urls.length; i++) {
                // Expect file URLs
                // This is definitely not as clean as using JAR URLs either
                // over file or the custom jndi handler, but a lot less
                // buggy overall
                File file = new File(urls[i].getFile());
                try {
                    file = file.getCanonicalFile();
                } catch (IOException e) {
                    // Ignore
                }
                if (!file.exists()) {
                    continue;
                }
                String path = file.getAbsolutePath();
                if (!path.endsWith(".jar")) {
                    continue;
                }
                /*
                 * Scan all JARs from WEB-INF/lib, plus any shared JARs
                 * that are not known not to contain any TLDs
                 */
                if (loader == webappLoader || noTldJars == null || !noTldJars.contains(file.getName())) {
                    if (jarPathMap == null) {
                        jarPathMap = new HashMap();
                        jarPathMap.put(path, file);
                    } else if (!jarPathMap.containsKey(path)) {
                        jarPathMap.put(path, file);
                    }
                }
            }
        }
        loader = loader.getParent();
    }

    return jarPathMap;
}