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:gpms.utils.PolicyTestUtil.java

/**
 * This creates the XACML request from a file
 *
 * @param rootDirectory/*  w  ww.  j  a va2  s. c o  m*/
 *            root directory of the request files
 * @param versionDirectory
 *            version directory of the request files
 * @param requestId
 *            request file name
 * @return String or null if any error
 */
public static String createRequest(String rootDirectory, String versionDirectory, String requestId) {

    File file = new File(".");
    StringWriter writer = null;
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.REQUEST_DIRECTORY + File.separator + requestId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        DOMSource domSource = new DOMSource(doc);
        writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Error closing stream ", e);
                // ignore any exception and return null
            }
        }
    }
    return null;
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Add a file to a ZIP archive.
 * @param zos The ZipOutputStream representing the ZIP archive.
 * @param file The File which is to be added to the ZIP archive.
 * @return True if adding succeeded./*w  ww.jav  a 2  s  .  com*/
 * @throws IOException Any exception when reading/writing data.
 */
private static boolean zipFile(final ZipOutputStream zos, final File file) throws IOException {
    if (!file.canRead()) {
        logger.error("zipFile can not read " + file.getCanonicalPath());
        return false;
    }
    zos.putNextEntry(new ZipEntry(file.getName()));
    FileInputStream fis = new FileInputStream(file);

    byte[] buffer = new byte[BUFFER_SIZE];
    int byteCount = 0;
    while ((byteCount = fis.read(buffer)) != -1) {
        zos.write(buffer, 0, byteCount);
    }
    fis.close();
    zos.closeEntry();
    return true;
}

From source file:com.thoughtworks.go.util.FileUtil.java

public static boolean isSymbolicLink(File parent, String name) throws IOException {
    if (parent == null) {
        File f = new File(name);
        parent = f.getParentFile();//from  w  ww  . j  av a 2 s.c om
        name = f.getName();
    }
    File toTest = new File(parent.getCanonicalPath(), name);
    return !toTest.getAbsolutePath().equals(toTest.getCanonicalPath());
}

From source file:com.github.fritaly.dualcommander.Utils.java

private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate,
        List<String> exclusionList) throws IOException {
    // recurse/*w  ww.  j  a v a  2  s  . c o  m*/
    File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
    if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs
        throw new IOException("Failed to list contents of " + srcDir);
    }
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (!destDir.mkdirs() && !destDir.isDirectory()) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    for (File srcFile : srcFiles) {
        File dstFile = new File(destDir, srcFile.getName());
        if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
            if (srcFile.isDirectory()) {
                doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
            } else {
                doCopyFile(srcFile, dstFile, preserveFileDate);
            }
        }
    }

    // Do this last, as the above has probably affected directory metadata
    if (preserveFileDate) {
        destDir.setLastModified(srcDir.lastModified());
    }
}

From source file:net.leegorous.jsc.JavaScriptCombiner.java

public static String translate2RelatePath(File standard, File file) throws IOException {
    if (standard.isFile())
        standard = standard.getParentFile();
    String standardPath = standard.getCanonicalPath().replaceAll("\\\\", "/");
    File target = file;/*from   w  w  w.ja  va 2  s.c  o m*/
    Stack stack = new Stack();
    if (file.isFile()) {
        stack.push(target.getName());
        target = file.getParentFile();
    }
    String targetPath = file.getCanonicalPath().replaceAll("\\\\", "/");
    StringBuffer result = new StringBuffer();
    while (!targetPath.startsWith(standardPath)) {
        standardPath = standardPath.substring(0, standardPath.lastIndexOf("/"));
        result.append("../");
    }
    while (!standardPath.equals(target.getCanonicalPath().replaceAll("\\\\", "/"))) {
        stack.push(target.getName());
        target = target.getParentFile();
    }
    while (stack.size() > 1) {
        result.append((String) stack.pop()).append("/");
    }
    if (stack.size() > 0)
        result.append((String) stack.pop());
    // System.out.println(standardPath+"\n"+targetPath);
    return result.toString();
}

From source file:com.liferay.blade.cli.command.CreateCommand.java

private static boolean _containsDir(File currentDir, File parentDir) throws Exception {
    String currentPath = currentDir.getCanonicalPath();

    String parentPath = parentDir.getCanonicalPath();

    return currentPath.startsWith(parentPath);
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchive.java

/**
 * Checks whether the path is relative./*from  w w w .j a v a2s  . c o  m*/
 * <p/>
 * {@link java.io.File#isAbsolute()} is not very testable, as its behavior is dependent upon the environment in
 * which the application is run.
 *
 * @param path
 *     the path to check
 *
 * @return false if:<ul> <li>the path starts with a slash ('/')</li> <li>the path starts with one backslash
 *         ('\')</li> <li>the path contains a directory component consisting of only two dots ('/../')</li> <li>the
 *         path starts with a windows drive letter ('C:\\')</li> </ul>
 */
private static boolean isPathRelative(String path) {
    boolean isNotRelative = false;
    File pathFile = new File(path);
    String absolutePath = pathFile.getAbsolutePath();
    String canonicalPath = null;
    try {
        canonicalPath = pathFile.getCanonicalPath();
    } catch (IOException e) {
        LOGGER.info(String.format("Error canonicalizing path '%s'", path), e);
        // Assume the path parameter is not canonical, meaning it might be unsafe.
        return false;
    }
    isNotRelative = path.startsWith("/");
    isNotRelative = isNotRelative || path.startsWith("\\");
    isNotRelative = isNotRelative || !canonicalPath.equals(absolutePath);
    isNotRelative = isNotRelative
            || (CharUtils.isAsciiAlpha(path.charAt(0)) && path.substring(1).startsWith(":\\"));

    return !isNotRelative;
}

From source file:control.LoadControler.java

public static List<CelluleType> loadCelluleTypes(String filePath) {

    File folder = new File(userPath(filePath));
    Set<File> fileSet = listFilesForFolder(folder);

    List<CelluleType> list = new ArrayList<>();

    for (File file : fileSet) {

        try {// w ww.jav  a 2s.c o m
            PropertiesReader ppr = new PropertiesReader(file.getCanonicalPath());
            Properties properties = ppr.readProperties();

            CelluleType celluleType = new CelluleType();

            try {
                celluleType.setType(properties.getProperty("nom"));

                System.out.println(celluleType.toString()); //DEBUG
                list.add(celluleType);

            } catch (NumberFormatException e) {
                e.printStackTrace();
                System.out.println("##### Erreur lors de la cration de la carte #####");
                JOptionPane.showMessageDialog(null, e);
            }
        } catch (IOException ex) {
            Logger.getLogger(LoadControler.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex);
        }

    }

    return list;
}

From source file:control.LoadControler.java

public static List<Meteo> loadMeteo(String filePath) {

    List<Meteo> list = new ArrayList<>();

    File folder = new File(userPath(filePath));

    Set<File> fileSet = listFilesForFolder(folder);

    for (File file : fileSet) {

        try {/*from w  w  w.j a va2s  .c o m*/
            PropertiesReader ppr = new PropertiesReader(file.getCanonicalPath());
            Properties properties = ppr.readProperties();

            try {
                Meteo element = new Meteo();
                element.setNom(properties.getProperty("nom"));
                element.setImage(properties.getProperty("image"));
                element.setHandicapCombat(Double.parseDouble(properties.getProperty("handicapCombat")));
                element.setHandicapTir(Double.parseDouble(properties.getProperty("handicapTir")));

                list.add(element);
                System.out.println(element.toString()); //DEBUG

            } catch (NumberFormatException e) {
                e.printStackTrace();
                System.out.println("##### Erreur lors de la cration d'une meteo #####");
                JOptionPane.showMessageDialog(null, e);
            }

        } catch (IOException ex) {
            Logger.getLogger(LoadControler.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex);
        }

    }

    return list;
}

From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java

/**
 * Checks if a directory exists; if it doesn't, it attempts to create one.
 * //from  w  w w .  ja  va2  s  .  com
 * @param directory
 * @return true if the directory exists or was successfully created, false
 *         otherwise.
 */
private static boolean ensureDirectoryExists(final File directory) {
    logger.debug("ensureDirectoryExists)");
    logger.debug("Name = " + directory.getName());
    logger.debug("AbsolutePath = " + directory.getAbsolutePath());
    try {
        logger.debug("CanonicalPath = " + directory.getCanonicalPath());
    } catch (IOException e) {
        logger.debug(e.getStackTrace().toString());
    }
    boolean success = directory.exists() || directory.mkdir();
    logger.debug("returning " + success);
    return success;
}