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:org.jruyi.launcher.Main.java

private static File[] getLibJars() throws Exception {
    // Home Dir/*from  ww  w  .jav  a 2 s .co m*/
    File homeDir;
    String temp = System.getProperty(JRUYI_HOME_DIR);
    if (temp == null) {
        String classpath = System.getProperty("java.class.path");
        int index = classpath.toLowerCase().indexOf("jruyi-launcher");
        int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
        if (index >= start) {
            temp = classpath.substring(start, index);
            homeDir = new File(temp).getCanonicalFile().getParentFile();
        } else
            // use current dir
            homeDir = new File(System.getProperty("user.dir"));
    } else
        homeDir = new File(temp);

    homeDir = homeDir.getCanonicalFile();

    System.setProperty(JRUYI_HOME_DIR, homeDir.getCanonicalPath());

    return new File(homeDir, "lib").listFiles(new JarFileFilter());
}

From source file:org.wso2.developerstudio.eclipse.utils.file.FileUtils.java

private static List<String> getPathList(File f) {
    List<String> l = new ArrayList<String>();
    File r;/*from  w w  w .  ja v  a 2  s . co m*/
    try {
        r = f.getCanonicalFile();
        while (r != null) {
            l.add(r.getName());
            r = r.getParentFile();
        }
    } catch (IOException e) {
        e.printStackTrace();
        l = null;
    }
    return l;
}

From source file:com.depas.utils.FileUtils.java

public static String extractPathRelativeToDirectory(File chrootIn, File absolutePathIn) {
    if (chrootIn == null || absolutePathIn == null) {
        throw new IllegalArgumentException("The arguments must be non-null.");
    }/* ww w .jav a  2 s  . co m*/
    File chroot = chrootIn;
    File absolutePath = absolutePathIn;

    // Canonization will turn things like "/home/dpa/dir/../dir" into "/home/dpa/dir".
    try {
        chroot = chroot.getCanonicalFile();
    } catch (Exception ex) {
        logger.warn("Failed to obtain canonical form of the 'chroot' file [" + chroot.toString() + "].", ex);
    }
    try {
        absolutePath = absolutePath.getCanonicalFile();
    } catch (Exception ex) {
        logger.warn(
                "Failed to obtain canonical form of the 'absolutePath' file [" + absolutePath.toString() + "].",
                ex);
    }

    String result = "";
    String delim = "";

    // safety limit of 200 iterations in case there is a loop in the file system
    for (int i = 0; i < 200 && absolutePath.getParentFile() != null; i++) {
        if (chroot.equals(absolutePath)) {
            return !result.isEmpty() ? result : ".";
        }
        result = absolutePath.getName() + delim + result;
        delim = "/";
        absolutePath = absolutePath.getParentFile();
    }

    // could not find a match
    return null;
}

From source file:com.github.mjdetullio.jenkins.plugins.multibranch.TemplateDrivenMultiBranchProject.java

/**
 * Migrates {@code SyncBranchesTrigger} to {@link hudson.triggers.TimerTrigger} and copies the
 * template's {@code hudson.security.AuthorizationMatrixProperty} to the parent as a
 * {@code com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty}.
 *
 * @throws IOException if errors reading/modifying files during migration
 *///from  w  w w . j a v a2 s  .  c  o m
@SuppressWarnings(UNUSED)
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void migrate() throws IOException {
    final String projectAmpStartTag = "<hudson.security.AuthorizationMatrixProperty>";

    final File projectsDir = new File(Jenkins.getActiveInstance().getRootDir(), "jobs");

    if (!projectsDir.getCanonicalFile().isDirectory()) {
        return;
    }

    List<File> configFiles = getConfigFiles(projectsDir);

    for (final File configFile : configFiles) {
        String xml = FileUtils.readFileToString(configFile);

        // Rename and wrap trigger open tag
        xml = xml.replaceFirst("(?m)^  <syncBranchesTrigger>(\r?\n)    <spec>",
                "  <triggers>\n    <hudson.triggers.TimerTrigger>\n      <spec>");

        // Rename and wrap trigger close tag
        xml = xml.replaceFirst("(?m)^  </syncBranchesTrigger>",
                "    </hudson.triggers.TimerTrigger>\n  </triggers>");

        // Copy AMP from template if parent does not have a properties tag
        if (!xml.matches("(?ms).+(\r?\n)  <properties.+")
                // Long line is long
                && xml.matches(
                        "(?ms).*<((freestyle|maven)-multi-branch-project|com\\.github\\.mjdetullio\\.jenkins\\.plugins\\.multibranch\\.(FreeStyle|Maven)MultiBranchProject)( plugin=\".*?\")?.+")) {

            File templateConfigFile = new File(new File(configFile.getParentFile(), TEMPLATE), "config.xml");

            if (templateConfigFile.isFile()) {
                String templateXml = FileUtils.readFileToString(templateConfigFile);

                int start = templateXml.indexOf(projectAmpStartTag);
                int end = templateXml.indexOf("</hudson.security.AuthorizationMatrixProperty>");

                if (start != -1 && end != -1) {
                    String ampSettings = templateXml.substring(start + projectAmpStartTag.length(), end);

                    xml = xml.replaceFirst("(?m)^  ", "  <properties>\n    "
                            + "<com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty>"
                            + ampSettings
                            + "</com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty>"
                            + "\n  </properties>\n  ");
                }
            }
        }

        FileUtils.writeStringToFile(configFile, xml);
    }
}

From source file:org.openflexo.toolbox.FileUtils.java

/**
 * @param file/* ww w  . j  av a2s  .  c  o m*/
 * @param wd
 * @return
 * @throws IOException
 */
public static String makeFilePathRelativeToDir(File file, File dir) throws IOException {
    file = file.getCanonicalFile();
    dir = dir.getCanonicalFile();
    String d = dir.getCanonicalPath().replace('\\', '/');
    String f = file.getCanonicalPath().replace('\\', '/');
    int i = 0;
    while (i < d.length() && i < f.length() && d.charAt(i) == f.charAt(i)) {
        i++;
    }
    String common = d.substring(0, i);
    if (!new File(common).exists()) {
        if (common.indexOf('/') > -1) {
            common = common.substring(0, common.lastIndexOf('/') + 1);
        }
        if (!new File(common).exists()) {
            System.err.println("WARNING\tNothing in common between\n" + file.getAbsolutePath() + " and\n"
                    + dir.getAbsolutePath());
            return file.getAbsolutePath();
        }
    }
    File commonFather = new File(common);
    File parentDir = dir;
    StringBuilder sb = new StringBuilder();
    while (parentDir != null && !commonFather.equals(parentDir)) {
        sb.append("../");
        parentDir = parentDir.getParentFile();
    }
    sb.append(f.substring(common.length()));
    if (sb.charAt(0) == '/') {
        return sb.substring(1);
    }
    return sb.toString();
}

From source file:spoon.IncrementalLauncher.java

private static Set<File> getAllJavaFiles(Set<File> resources) {
    Set<File> javaFiles = new HashSet<>();
    for (File e : resources) {
        if (e.isDirectory()) {
            Collection<File> files = FileUtils.listFiles(e, new SuffixFileFilter(".java"),
                    TrueFileFilter.INSTANCE);
            files.forEach(f -> {/*from w  w  w .j a v a2  s . co m*/
                try {
                    javaFiles.add(f.getCanonicalFile());
                } catch (IOException e1) {
                    throw new SpoonException("unable to locate input source file: " + f);
                }
            });
        } else if (e.isFile() && e.getName().endsWith(".java")) {
            try {
                javaFiles.add(e.getCanonicalFile());
            } catch (IOException e1) {
                throw new SpoonException("unable to locate input source file: " + e);
            }
        }
    }
    return javaFiles;
}

From source file:kenh.xscript.ScriptUtils.java

/**
 * Get xScript instance./*from  w  w w .  j  a  v  a2s  . co m*/
 * @param file
 * @param env
 * @return
 * @throws UnsupportedScriptException
 */
public static final Element getInstance(File file, Environment env) throws UnsupportedScriptException {

    if (file == null || !file.exists())
        return null;

    if (env == null)
        env = new Environment();

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new FileInputStream(file));
        String home = file.getCanonicalFile().getParent();
        if (env != null) {
            if (!env.containsVariable(Constant.VARIABLE_HOME))
                env.setPublicVariable(Constant.VARIABLE_HOME, home, false);
        }
        return getInstance(doc, env);
    } catch (UnsupportedScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new UnsupportedScriptException(null, e);
    }
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object cd(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    assertSingleArgument(args);// w  w w  .j a v  a  2 s.  c o m
    MongoScope mongoScope = (MongoScope) thisObj;
    String newDirPath = Context.toString(args[0]);
    String result = null;
    try {
        File newCwd = resolveFilePath(mongoScope, newDirPath);
        if (newCwd.isDirectory()) {
            mongoScope.setCwd(newCwd.getCanonicalFile());
        } else
            result = "change directory failed";
    } catch (IOException e) {
        result = "change directory failed: " + e.getMessage();
    }
    return result;
}

From source file:com.aoyetech.fee.commons.utils.FileUtils.java

/**
 * copy from commons-io . Compares the contents of two files to determine if
 * they are equal or not.// www .j a va  2 s.  co  m
 * <p>
 * This method checks to see if the two files are different lengths or if
 * they point to the same file, before resorting to byte-by-byte comparison
 * of the contents.
 * <p>
 * Code origin: Avalon
 * 
 * @param file1 the first file
 * @param file2 the second file
 * @return true if the content of the files are equal or they both don't
 *         exist, false otherwise
 * @throws IOException in case of an I/O error
 * @see org.apache.commons.io.FileUtils
 */
public static boolean contentEquals(final File file1, final File file2) throws IOException {
    final boolean file1Exists = file1.exists();
    if (file1Exists != file2.exists()) {
        return false;
    }

    if (!file1Exists) {
        // two not existing files are equal
        return true;
    }

    if (file1.isDirectory() || file2.isDirectory()) {
        // don't want to compare directory contents
        throw new IOException("Can't compare directories, only files");
    }

    if (file1.length() != file2.length()) {
        // lengths differ, cannot be equal
        return false;
    }

    if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
        // same file
        return true;
    }

    InputStream input1 = null;
    InputStream input2 = null;
    try {
        input1 = new FileInputStream(file1);
        input2 = new FileInputStream(file2);
        return IOUtils.contentEquals(input1, input2);

    } finally {
        IOUtils.closeQuietly(input1);
        IOUtils.closeQuietly(input2);
    }
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

private static boolean isSymlink(File file) throws IOException {
    File fileInCanonicalDir = null;
    if (file.getParent() == null) {
        fileInCanonicalDir = file;/*ww w . j  ava 2s.  c  o  m*/
    } else {
        File canonicalDir = file.getParentFile().getCanonicalFile();
        fileInCanonicalDir = new File(canonicalDir, file.getName());
    }
    return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
}