Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

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

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:edu.unc.lib.dl.util.FileUtils.java

/**
 * Safely returns a File object for a "file:" URL. The base and root directories are both considered to be the dir.
 * URLs that point outside of that directory will throw an IOException.
 *
 * @param url/*from ww w.  j  ava2  s .com*/
 *           the URL
 * @param dir
 *           the directory within which to resolve the "file:" URL.
 * @return a File object
 * @throws IOException
 *            when URL improperly formatted or points outside of the dir.
 */
public static File getFileForUrl(String url, File dir) throws IOException {
    File result = null;

    // remove any file: prefix and beginning slashes or backslashes
    Matcher m = filePathPattern.matcher(url);

    if (m.find()) {
        String path = m.group(3); // grab the path group
        path = path.replaceAll("\\\\", File.pathSeparator);
        result = new File(dir, path);
        if (result.getCanonicalPath().startsWith(dir.getCanonicalPath())) {
            return result;
        } else {
            throw new IOException("Bad locator for a file in SIP:" + url);
        }
    } else {
        throw new IOException("Bad locator for a file in SIP:" + url);
    }
}

From source file:eu.riscoss.dataproviders.providers.FossologyDataProvider.java

/**
 * Parses a LicensesCfg file//from   ww  w . ja  va2s.com
 * @param target
 * @return HashMap: License Types, each with a Collection of Licenses
 * @throws IOException
 */
protected static HashMap<String, Collection<String>> parseLicensesFile(String target) throws IOException {
    HashMap<String, Collection<String>> result = new HashMap<String, Collection<String>>();
    Document document;
    if (target.startsWith("http")) {
        document = Jsoup.connect(target).get();
    } else {
        File file = new File(target);
        System.out.println("Fossology config file used: " + file.getCanonicalPath());
        document = Jsoup.parse(file, "UTF-8", "http://localhost");
    }

    //        System.out.println(document.outerHtml());

    Elements licensesLinks = document.getElementsByAttribute("id");

    for (Element element : licensesLinks) {
        String licenseName = element.child(0).text();
        if (element.children().size() > 1) {
            String s = element.child(1).text();
            Collection<String> licensesList = Arrays.asList(s.split("\\s*\\|\\s*")); //("\\s*\\|\\s*"));

            //xDebug            System.out.println("Analysed license type: "+licenseName+": "+licensesList);
            result.put(licenseName, licensesList);
        }
    }

    return result;
}

From source file:com.android.repository.util.InstallerUtil.java

/**
 * Checks to see whether {@code path} is a valid install path. Specifically, checks whether
 * there are any existing packages installed in parents or children of {@code path}. Returns
 * {@code true} if the path is valid. Otherwise returns {@code false} and logs a warning.
 */// ww w . jav  a 2 s .c  om
public static boolean checkValidPath(@NonNull File path, @NonNull RepoManager manager,
        @NonNull ProgressIndicator progress) {
    try {
        String check = path.getCanonicalPath() + File.separator;

        for (LocalPackage p : manager.getPackages().getLocalPackages().values()) {
            String existing = p.getLocation().getCanonicalPath() + File.separator;
            if (!existing.equals(check)) {
                boolean childExists = existing.startsWith(check);
                boolean parentExists = check.startsWith(existing);
                if (childExists || parentExists) {
                    StringBuilder message = new StringBuilder();
                    message.append("Trying to install into ").append(check).append(" but package \"")
                            .append(p.getDisplayName()).append("\" already exists at ").append(existing)
                            .append(". It must be deleted or moved away before installing into a ")
                            .append(childExists ? "parent" : "child").append(" directory.");
                    progress.logWarning(message.toString());
                    return false;
                }
            }
        }
    } catch (IOException e) {
        progress.logWarning("Error while trying to check install path validity", e);
        return false;
    }

    return true;
}

From source file:com.frostwire.android.gui.util.FileUtils.java

public static boolean deleteEmptyDirectoryRecursive(File directory) {
    // make sure we only delete canonical children of the parent file we
    // wish to delete. I have a hunch this might be an issue on OSX and
    // Linux under certain circumstances.
    // If anyone can test whether this really happens (possibly related to
    // symlinks), I would much appreciate it.
    String canonicalParent;//w  w  w  .  j  a va  2 s  .  c o m
    try {
        canonicalParent = directory.getCanonicalPath();
    } catch (IOException ioe) {
        return false;
    }

    if (!directory.isDirectory()) {
        return false;
    }

    boolean canDelete = true;

    File[] files = directory.listFiles();
    for (int i = 0; i < files.length; i++) {
        try {
            if (!files[i].getCanonicalPath().startsWith(canonicalParent))
                continue;
        } catch (IOException ioe) {
            canDelete = false;
        }

        if (!deleteEmptyDirectoryRecursive(files[i])) {
            canDelete = false;
        }
    }

    return canDelete ? directory.delete() : false;
}

From source file:com.kylinolap.job.hadoop.AbstractHadoopJob.java

public static KylinConfig loadKylinPropsAndMetadata(Configuration conf) throws IOException {
    File metaDir = new File("meta");
    System.setProperty(KylinConfig.KYLIN_CONF, metaDir.getAbsolutePath());
    System.out.println("The absolute path for meta dir is " + metaDir.getAbsolutePath());
    KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
    kylinConfig.setMetadataUrl(metaDir.getCanonicalPath());
    return kylinConfig;
}

From source file:ffx.algorithms.ClusterStructures.java

/**
 * Utility method which attempts to generate a file Path using the canonical
 * path string, else uses the absolute path.
 *
 * @param file To find path of/*  w w  w . ja  va 2 s.  com*/
 * @return Canonical or absolute path.
 */
public static Path generatePath(File file) {
    Path path;
    try {
        path = Paths.get(file.getCanonicalPath());
    } catch (IOException ex) {
        path = Paths.get(file.getAbsolutePath());
    }
    return path;
}

From source file:com.ibm.amc.FileManager.java

/**
 * Generate the name of a working file to upload to. Working files are located in the WAMT
 * Repository in a folder corresponding to the requester's user ID under the 'upload' folder.
 * //from www  .  j  a va 2s. c  om
 * @return The working File
 * @throws IOException
 *             if something bad occurs while creating a the working file
 */
public static File createUploadFile() throws IOException {
    if (logger.isEntryEnabled())
        logger.entry("createUploadFile");

    File uploadDir = getUploadDirectory();

    if (!uploadDir.exists()) {
        if (!uploadDir.mkdirs()) {
            throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED",
                    uploadDir.getPath());
        }
    }

    File f = File.createTempFile(FILE_PREFIX, FILE_SUFFIX, uploadDir);
    if (logger.isEntryEnabled())
        logger.exit("createUploadFile", f.getCanonicalPath());
    return f;
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Generates a new key. Should be used manually and only when creating a new
 * key is necessary. WARNING: If the keys in the KeyStore files are replaced
 * then we will not be able to decrypt passwords that were encrypted with
 * the old keys./* ww  w  . j a  va  2s  .  c  om*/
 *
 * @param keypass
 *            char[] with the keypass that will gain access to the key
 *            (currently hard coded in)
 * @throws IOException
 */
@SuppressWarnings("unused")
private static Key setKey(final char[] keypass, final File keyFile) throws Exception {

    Key key = null;
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(keyFile.getCanonicalPath());
        key = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM).generateKey();
        final KeyStore keystore = KeyStore.getInstance(KEYSTORE_TYPE);
        keystore.load(null, null);
        keystore.setKeyEntry(KEY_ALIAS, key, keypass, null);
        keystore.store(output, keypass);
    } finally {
        if (output != null) {
            output.close();
        }
    }

    return key;
}

From source file:de.prozesskraft.pkraft.Perlcode.java

/**
 * writes a Process-Step as Perlcode//from   w w  w.j a v a2 s.  c o m
 * @param process
 * @param stepname
 * @param outputDir
 * @throws IOException
 */
private static void writeStepAsPerlcode(Process process, String stepname, java.io.File outputDir,
        boolean nolist) throws IOException {
    if (process.isStep(stepname)) {
        // step ueber den namen heraussuchen
        Step step = process.getStep(stepname);
        System.err.println("generating perlcode for step " + stepname);

        writeFile.writeFile(new java.io.File(outputDir.getCanonicalPath() + "/" + step.getWork().getCommand()),
                step.getStepAsPerlScript(nolist));
    } else {
        System.err.println("stepname " + stepname + " is unknown in process " + process.getName());
        exiter();
    }
}

From source file:com.docd.purefm.utils.PFMFileUtils.java

/**
 * Returns canonical path or absolute path if failed
 *
 * @param file File to get full path/* w w w  .j a  v a  2 s. c  om*/
 * @return canonical path or absolute path if failed
 */
@NonNull
public static String fullPath(@NonNull final File file) {
    try {
        return file.getCanonicalPath();
    } catch (IOException e) {
        return file.getAbsolutePath();
    }
}