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.jsweet.input.typescriptdef.TypescriptDef2Java.java

private static void parse(Context context, File f) throws IOException {
    // context.compilationUnits.stream().map((cu) -> { return
    // cu.getFile();}).
    if (context.compilationUnits.contains(new CompilationUnit(f))) {
        // logger.info("skipping: " + f);
        return;//from  w w w.  j  a v  a 2s  . c o m
    }
    logger.info("parsing: " + f);
    // This class is automatically generated by CUP (please generate to compile)
    TypescriptDefParser parser = TypescriptDefParser.parseFile(f);
    context.compilationUnits.add(parser.compilationUnit);
    grabReferences(parser.compilationUnit);
    for (String reference : parser.compilationUnit.getReferences()) {
        String path = Util.getLibPathFromReference(reference);
        if (path != null) {
            File dep = new File(f.getParent(), path);
            if (!dep.exists()) {
                context.reportError("dependency '" + dep + "' does not exist", (Token) null);
            } else {
                File tsDefFile = parser.compilationUnit.getFile();
                boolean ignored = isIgnoredReference(tsDefFile, path);
                if (dep.getPath().contains("..")) {
                    try {
                        Path currentPath = new File("").getAbsoluteFile().toPath();
                        Path depPath = dep.getCanonicalFile().toPath();
                        logger.debug("depPath: " + depPath);
                        Path relPath = currentPath.relativize(depPath);
                        if (!relPath.toString().contains("..")) {
                            dep = relPath.toFile();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                logger.info("handling dependency: " + dep);
                if (ignored) {
                    context.getDependenciesDefinitions().add(dep);
                } else {
                    parse(context, dep);
                }
            }
        }
    }
}

From source file:org.squale.squalix.util.file.FileUtility.java

/**
 * @param pViewPath le chemin vers la vue
 * @param pSrcs la liste des noms absolus des fichiers sources
 * @param pIncludes les patterns  inclure
 * @param pExcludes les patterns  exclure
 * @param pExcludedDirs les rpertoires exclus de la compilation
 * @param pExtensions les extensions  conserver
 * @return la liste des fichiers qui ne sont pas exclus ou qui sont inclus parmi tous les fichiers des sources
 *         <code>pSrcs</code>. Les noms des fichiers sont relatifs au view path
 *///from   ww w.jav  a2 s  .  c om
public static List getIncludedFiles(String pViewPath, List pSrcs, ListParameterBO pIncludes,
        ListParameterBO pExcludes, ListParameterBO pExcludedDirs, String[] pExtensions) {
    // On rcupre le pattern pour filtrer les extensions
    // On ne rajoute pas les patterns des extensions dans les patterns
    // inclus du scanner car il se peut que l'utilisateur veuille exclure
    // une extension autorise.
    Pattern pattern = getPatternForExtensions(pExtensions);
    List includedFileNames = new ArrayList();
    // Pour chaque rpertoire source, on va crer un DirectoryScanner
    // et ainsi construire les fichiers qui doivent tre analyss
    DirectoryScanner scanner = new DirectoryScanner();
    // sensibilit  la casse
    scanner.setCaseSensitive(true);
    if (null != pIncludes) {
        String[] includesTab = transformListInTab(pIncludes.getParameters());
        scanner.setIncludes(includesTab);
    }
    List excludes = new ArrayList();
    if (null != pExcludes) {
        String[] excludesTab = transformListInTab(pExcludes.getParameters());
        scanner.setExcludes(excludesTab);
        excludes.addAll(Arrays.asList(excludesTab));
    }
    if (null != pExcludedDirs) {
        // on va construire les patterns d'exclusions avec les noms des rpertoires
        // On construit d'abord la regexp des sources car le chemin du rpertoire
        // doit tre relatif au rpertoire source et non au projet pour le filset
        String sourcesRegexp = ((String) pSrcs.get(0)).replaceFirst(pViewPath, "").replaceAll("//", "/");
        for (int i = 1; i < pSrcs.size(); i++) {
            sourcesRegexp += "|" + ((String) pSrcs.get(i)).replaceFirst(pViewPath, "").replaceAll("//", "/");
        }
        for (int i = 0; i < pExcludedDirs.getParameters().size(); i++) {
            String dir = ((StringParameterBO) pExcludedDirs.getParameters().get(i)).getValue();
            dir = dir.replaceFirst(sourcesRegexp, "");
            // On ajoute le pattern d'exclusion
            String exDir = "**/" + dir + "/**";
            excludes.add(exDir.replaceAll("//", "/"));
        }
        scanner.setExcludes((String[]) excludes.toArray(new String[excludes.size()]));
    }
    for (int i = 0; i < pSrcs.size(); i++) {
        String src = (String) pSrcs.get(i);
        File srcFile = new File(src);
        // src doit tre absolu : PRECONDITION
        try {
            if (srcFile.isDirectory()) {
                String baseName = srcFile.getCanonicalPath();
                scanner.setBasedir(srcFile.getCanonicalFile());
                scanner.scan();
                // On ajoute les noms absolus des fichiers inclus
                addAbsoluteFileNames(baseName, scanner.getIncludedFiles(), includedFileNames, pattern);
            } else {
                // On ajoute le nom absolu du fichier au fichiers inclus
                includedFileNames.add(srcFile.getCanonicalPath().replaceAll("\\\\", "/"));
            }
        } catch (IOException ioe) {
            // On loggue juste l'erreur
            LOGGER.warn(ioe.getMessage());
        }
    }
    return includedFileNames;
}

From source file:org.dspace.content.packager.PackageUtils.java

/**
 * Creates the specified file (along with all parent directories) if it doesn't already
 * exist.  If the file already exists, nothing happens.
 * //w w w .j a  v  a2 s  .  c  om
 * @param file file
 * @return boolean true if succeeded, false otherwise
 * @throws IOException if IO error
 */
public static boolean createFile(File file) throws IOException {
    boolean success = false;

    //Check if file exists
    if (!file.exists()) {
        //file doesn't exist yet, does its parent directory exist?
        File parentFile = file.getCanonicalFile().getParentFile();

        //create the parent directory structure
        if ((null != parentFile) && !parentFile.exists() && !parentFile.mkdirs()) {
            log.error("Unable to create parent directory");
        }
        //create actual file
        success = file.createNewFile();
    }
    return success;
}

From source file:org.nuxeo.ecm.webengine.model.impl.DirectoryStack.java

public void addDirectory(File dir) throws IOException {
    dirs.add(dir.getCanonicalFile());
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.directory.LocalIndexDir.java

public LocalIndexDir(File dir) throws IOException {
    this.dir = dir.getCanonicalFile();
    File indexDetails = new File(dir, IndexRootDirectory.INDEX_METADATA_FILE_NAME);
    checkState(isIndexDir(dir), "No file [%s] found in dir [%s]", INDEX_METADATA_FILE_NAME,
            dir.getAbsolutePath());//  w  ww .  ja  v a  2  s  .  c o  m
    this.indexMeta = new IndexMeta(indexDetails);
}

From source file:Main.java

/**
 * Checks, whether the child directory is a subdirectory of the base 
 * directory.//  ww w .ja  v  a2  s.  c  o  m
 *
 * @param base the base directory.
 * @param child the suspected child directory.
 * @return true, if the child is a subdirectory of the base directory.
 * @throws IOException if an IOError occured during the test.
 */
public boolean isSubDirectory(File base, File child) throws IOException {
    base = base.getCanonicalFile();
    child = child.getCanonicalFile();

    File parentFile = child;
    while (parentFile != null) {
        if (base.equals(parentFile)) {
            return true;
        }
        parentFile = parentFile.getParentFile();
    }
    return false;
}

From source file:org.geoserver.security.password.URLMasterPasswordProviderTest.java

@Test
public void testEncryption() throws Exception {
    File tmp = File.createTempFile("passwd", "tmp", new File("target"));
    tmp = tmp.getCanonicalFile();

    URLMasterPasswordProviderConfig config = new URLMasterPasswordProviderConfig();
    config.setName("test");
    config.setReadOnly(false);//from   w  ww .jav a 2 s  .c o m
    config.setClassName(URLMasterPasswordProvider.class.getCanonicalName());
    config.setURL(DataUtilities.fileToURL(tmp));
    config.setEncrypting(true);

    URLMasterPasswordProvider mpp = new URLMasterPasswordProvider();
    mpp.setSecurityManager(getSecurityManager());
    mpp.initializeFromConfig(config);
    mpp.setName(config.getName());
    mpp.doSetMasterPassword("geoserver".toCharArray());

    String encoded = IOUtils.toString(new FileInputStream(tmp));
    assertFalse("geoserver".equals(encoded));

    char[] passwd = mpp.doGetMasterPassword();
    assertTrue(Arrays.equals("geoserver".toCharArray(), passwd));
}

From source file:org.eclipse.tracecompass.internal.tmf.ui.project.wizards.importtrace.TarFileSystemObject.java

@Override
public String getSourceLocation() {
    File file = new File(fArchivePath);
    try {//from   w  w w. java  2  s .  co m
        file = file.getCanonicalFile();
    } catch (IOException e) {
        // Will still work but might have extra ../ in the path
    }
    URI uri = file.toURI();
    IPath entryPath = new Path(fFileSystemObject.getName());

    URI jarURI = entryPath.isRoot() ? URIUtil.toJarURI(uri, Path.EMPTY) : URIUtil.toJarURI(uri, entryPath);
    return URIUtil.toUnencodedString(jarURI);
}

From source file:com.enonic.cms.core.boot.HomeResolver.java

private File validatePath(final String path) {
    File dir = new File(path);

    try {/*from  w ww  . j a v  a  2 s  .c o  m*/
        dir = dir.getCanonicalFile();
    } catch (IOException e) {
        // Do nothing
    }

    if (dir.exists() && !dir.isDirectory()) {
        throw new IllegalArgumentException("Invalid home directory: [" + path + "] is not a directory");
    }

    if (!dir.exists() && dir.mkdirs()) {
        LOG.debug("Missing home directory was created in [" + dir.getAbsolutePath() + "]");
    }

    LOG.info("Home directory is set to [" + dir.getAbsolutePath() + "]");
    return dir;
}

From source file:org.corpus_tools.pepper.cli.ConvertWizardConsole.java

/**
 * Before saving, create relative URIs for Pepper job. Create a base URI to
 * deresolve relative URIs//from w  w  w  . j  a  va 2 s  . c  o  m
 * 
 * @param outputFile
 * @param pepperJob
 * @throws IOException
 */
public static void deresolveURIs(File outputFile, PepperJob pepperJob) throws IOException {
    URI base;
    if (outputFile.isDirectory()) {
        base = URI.createFileURI(outputFile.getCanonicalPath() + "/");
    } else {
        base = URI.createFileURI(outputFile.getCanonicalFile().getParentFile().getCanonicalPath() + "/");
    }
    for (StepDesc stepDesc : pepperJob.getStepDescs()) {
        if ((stepDesc.getCorpusDesc() != null) && (stepDesc.getCorpusDesc().getCorpusPath() != null)) {
            URI before = stepDesc.getCorpusDesc().getCorpusPath();
            stepDesc.getCorpusDesc()
                    .setCorpusPath(stepDesc.getCorpusDesc().getCorpusPath().deresolve(base, true, true, true));
            if (!stepDesc.getCorpusDesc().getCorpusPath().equals(before)) {
                // creates a leading './' if URI is relative
                stepDesc.getCorpusDesc()
                        .setCorpusPath(URI.createFileURI("./" + stepDesc.getCorpusDesc().getCorpusPath()));
            }
        }
    }
}