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:com.l2jfree.tools.NewLineChecker.java

private static void parse(File f) throws IOException {
    if (f.isDirectory()) {
        for (File f2 : f.listFiles(FILTER))
            parse(f2);/* w w w. j  ava2 s  .  co m*/
        return;
    }

    final String input = FileUtils.readFileToString(f);
    final List<String> inputLines = FileUtils.readLines(f);

    final int r = StringUtils.countMatches(input, "\r");
    final int n = StringUtils.countMatches(input, "\n");
    final int rn = StringUtils.countMatches(input, "\r\n");

    final char lastChar = input.charAt(input.length() - 1);
    boolean missingNewline = false;

    if (lastChar != '\r' && lastChar != '\n') {
        System.out.println("--- " + f.getCanonicalPath());
        System.out.println(lastChar);

        MISSING_NEWLINE++;

        missingNewline = true;
    }

    // fully "\r\n"
    if (r == n && r == rn && n == rn) {
        RN++;
        if (missingNewline)
            FileUtils.writeLines(f, inputLines, "\r\n");
        return;
    }

    // fully "\n"
    if (r == 0 && rn == 0) {
        N++;
        System.out.println("n " + f.getName());
        if (missingNewline)
            FileUtils.writeLines(f, inputLines, "\n");
        return;
    }

    System.out.println("--- " + f.getCanonicalPath());
    System.out.println("r: " + r);
    System.out.println("n: " + n);
    System.out.println("rn: " + rn);

    FileUtils.writeLines(f, inputLines, f.getName().endsWith(".sh") ? "\n" : "\r\n");

    // fully "\r"
    if (n == 0 && rn == 0) {
        R++;
        return;
    }

    // mixed
    MIXED++;
}

From source file:de.uzk.hki.da.utils.Utilities.java

private static boolean fileReferenceInXmlIsValid(String reference, File metadataFile) throws IOException {
    boolean isValid = false;
    File referencedFile = new File(metadataFile.getParentFile(), reference);
    logger.debug("Check reference " + reference + " in metadata file " + metadataFile);
    if (referencedFile.exists()) {
        logger.debug("File " + referencedFile.getAbsolutePath() + " exists.");
        File sipMain = new File(metadataFile.getParentFile(), "");
        logger.debug("Check if file is inside a sip canidate " + sipMain);
        if (referencedFile.getCanonicalPath().startsWith(sipMain.getCanonicalPath())) {
            logger.debug("File " + referencedFile + " is inside a sip");
            isValid = true;//  www  .j  a v a  2 s .co m
        }
    }
    return isValid;
}

From source file:eu.cloud4soa.governance.ems.util.ExecutionManagementUtil.java

public static String getBeanstalkAdapterPath() {
    System.out.println(ExecutionManagementUtil.class.getClassLoader()
            .getResourceAsStream("extras/BeanstalkC4SAdapter-1.0-SNAPSHOT.war"));
    String path = "";
    try {//from w w w. ja v  a 2  s .c  om
        InputStream inputStream = ExecutionManagementUtil.class.getClassLoader()
                .getResourceAsStream("extras/BeanstalkC4SAdapter-1.0-SNAPSHOT.war");
        // write the inputStream to a FileOutputStream
        File tmp_file = new File(
                System.getProperty("java.io.tmpdir") + "/" + "BeanstalkC4SAdapter-1.0-SNAPSHOT.war");
        OutputStream out = new FileOutputStream(tmp_file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        inputStream.close();
        out.flush();
        out.close();

        logger.debug("New file created!");

        path = tmp_file.getCanonicalPath();
        logger.debug(path);
    } catch (IOException e) {
        logger.debug(e.getMessage());
    }

    return path;
}

From source file:eu.cloud4soa.governance.ems.util.ExecutionManagementUtil.java

public static String getCloudBeesAdapterPath() {
    //        System.out.println( ClassLoader.getSystemResource("extras/CloudBeesC4SAdapter-1.0-SNAPSHOT.war"));
    System.out.println(ExecutionManagementUtil.class.getClassLoader()
            .getResourceAsStream("extras/CloudBeesC4SAdapter-1.0-SNAPSHOT.war"));
    String path = "";
    try {// w  w  w .j  a v a2 s .com
        //        InputStream inputStream=ClassLoader.getSystemResourceAsStream("extras/CloudBeesC4SAdapter-1.0-SNAPSHOT.war");
        InputStream inputStream = ExecutionManagementUtil.class.getClassLoader()
                .getResourceAsStream("extras/CloudBeesC4SAdapter-1.0-SNAPSHOT.war");
        // write the inputStream to a FileOutputStream
        File tmp_file = new File(
                System.getProperty("java.io.tmpdir") + "/" + "CloudBeesC4SAdapter-1.0-SNAPSHOT.war");
        OutputStream out = new FileOutputStream(tmp_file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        inputStream.close();
        out.flush();
        out.close();

        logger.debug("New file created!");

        path = tmp_file.getCanonicalPath();
        logger.debug(path);
    } catch (IOException e) {
        logger.debug(e.getMessage());
    }

    return path;
}

From source file:eu.cloud4soa.governance.ems.util.ExecutionManagementUtil.java

public static String getCloudFoundryAdapterPath() {
    System.out.println(ExecutionManagementUtil.class.getClassLoader()
            .getResourceAsStream("extras/CloudFoundryC4SAdapter-1.0-SNAPSHOT.war"));
    String path = "";
    try {/*w ww. j a va 2s  .  c  o m*/
        InputStream inputStream = ExecutionManagementUtil.class.getClassLoader()
                .getResourceAsStream("extras/CloudFoundryC4SAdapter-1.0-SNAPSHOT.war");
        // write the inputStream to a FileOutputStream
        File tmp_file = new File(
                System.getProperty("java.io.tmpdir") + "/" + "CloudFoundryC4SAdapter-1.0-SNAPSHOT.war");
        OutputStream out = new FileOutputStream(tmp_file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        inputStream.close();
        out.flush();
        out.close();

        logger.debug("New file created!");

        path = tmp_file.getCanonicalPath();
        logger.debug(path);
    } catch (IOException e) {
        logger.debug(e.getMessage());
    }

    return path;
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.VersionControlHelper.java

public static void checkinTemporaryBuildConfigFolder(final TFSTeamProjectCollection connection,
        final String tempFolderPath, final String serverFolder, final boolean deleteTempFolder)
        throws IOException {
    Check.notNull(connection, "connection"); //$NON-NLS-1$
    final File tempDir = new File(tempFolderPath);
    if (!tempDir.exists()) {
        throw new IllegalArgumentException("The passed local folder + " + tempFolderPath + " does not exist."); //$NON-NLS-1$ //$NON-NLS-2$
    }//w w w  . j av a2s .c  om

    final VersionControlClient server = connection.getVersionControlClient();

    final WorkingFolder[] mappings = new WorkingFolder[] {
            new WorkingFolder(serverFolder, tempDir.getCanonicalPath(), WorkingFolderType.MAP) };

    Workspace workspace = null;
    try {
        String workspaceName = System.currentTimeMillis() + "_" + "TFSBuildTemporaryWorkspace" //$NON-NLS-1$//$NON-NLS-2$
                + LocalHost.getShortName();
        if (workspaceName.length() > 64) {
            workspaceName = workspaceName.substring(0, 64);
        }

        workspace = server.createWorkspace(mappings, workspaceName,
                Messages.getString("VersionControlHelper.TemporaryWorkspaceDescription"), //$NON-NLS-1$
                WorkspaceLocation.SERVER, null);

        final File[] files = tempDir.listFiles();
        final List<String> filePaths = new ArrayList<String>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile() && files[i].canRead()) {
                filePaths.add(files[i].getCanonicalPath());
            }
        }
        final int numPended = workspace.pendAdd(filePaths.toArray(new String[filePaths.size()]), false,
                FileEncoding.UTF_8, LockLevel.UNCHANGED, GetOptions.NONE, PendChangesOptions.NONE);

        if (numPended > 0) {
            workspace.checkIn(workspace.getPendingChanges().getPendingChanges(),
                    Messages.getString("VersionControlHelper.BuildCheckinComment")); //$NON-NLS-1$
        } else if (numPended == 0) {
            throw new IllegalArgumentException(
                    Messages.getString("VersionControlHelper.InvalidServerPathText")); //$NON-NLS-1$
        }
    } finally {
        // delete workspace;
        if (workspace != null) {
            server.deleteWorkspace(workspace);
        }
    }

}

From source file:net.shopxx.util.CompressUtils.java

public static void archive(File[] srcFiles, File destFile, String archiverName) {
    Assert.notNull(destFile);/* w ww  . j  a v a2  s .  c om*/
    Assert.state(!destFile.exists() || destFile.isFile());
    Assert.hasText(archiverName);

    File parentFile = destFile.getParentFile();
    if (parentFile != null) {
        parentFile.mkdirs();
    }
    ArchiveOutputStream archiveOutputStream = null;
    try {
        archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiverName,
                new BufferedOutputStream(new FileOutputStream(destFile)));
        if (ArrayUtils.isNotEmpty(srcFiles)) {
            for (File srcFile : srcFiles) {
                if (srcFile == null || !srcFile.exists()) {
                    continue;
                }
                Set<File> files = new HashSet<File>();
                if (srcFile.isFile()) {
                    files.add(srcFile);
                }
                if (srcFile.isDirectory()) {
                    files.addAll(FileUtils.listFilesAndDirs(srcFile, TrueFileFilter.INSTANCE,
                            TrueFileFilter.INSTANCE));
                }
                String basePath = FilenameUtils.getFullPath(srcFile.getCanonicalPath());
                for (File file : files) {
                    try {
                        String entryName = FilenameUtils.separatorsToUnix(
                                StringUtils.substring(file.getCanonicalPath(), basePath.length()));
                        ArchiveEntry archiveEntry = archiveOutputStream.createArchiveEntry(file, entryName);
                        archiveOutputStream.putArchiveEntry(archiveEntry);
                        if (file.isFile()) {
                            InputStream inputStream = null;
                            try {
                                inputStream = new BufferedInputStream(new FileInputStream(file));
                                IOUtils.copy(inputStream, archiveOutputStream);
                            } catch (FileNotFoundException e) {
                                throw new RuntimeException(e.getMessage(), e);
                            } catch (IOException e) {
                                throw new RuntimeException(e.getMessage(), e);
                            } finally {
                                IOUtils.closeQuietly(inputStream);
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    } finally {
                        archiveOutputStream.closeArchiveEntry();
                    }
                }
            }
        }
    } catch (ArchiveException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(archiveOutputStream);
    }
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static ArrayList<String> readFileLines(File directory, boolean descendIntoSubDirectories)
        throws IOException {
    ArrayList<String> resultList = new ArrayList<String>(256);
    String[] extensions = new String[] { "jpg", "JPG", "jpeg", "png", "gif", "tif", "tiff" };

    System.out.print("Getting all images in " + directory.getCanonicalPath() + " "
            + ((descendIntoSubDirectories) ? "including" : "not including") + " those in subdirectories");
    java.util.List<File> files = (LinkedList<File>) org.apache.commons.io.FileUtils.listFiles(directory,
            extensions, descendIntoSubDirectories);
    System.out.println(" ~ Found " + files.size() + " images");
    for (File file : files) {
        resultList.add(file.getCanonicalPath());
    }/*from   w  ww  .  j a  va  2  s  . co m*/

    return resultList;
}

From source file:dynamicrefactoring.util.io.FileManager.java

/**
 * Crea una copia de un directorio en una ruta de destino determinada.
 * //from   w  ww  . j  av  a2s. co m
 * @param original
 *            directorio que se debe copiar.
 * @param destination
 *            directorio en que se crear la copia del original y todo su
 *            contenido.
 * 
 * @return <code>true</code> si se consigue realizar la copia completa con
 *         xito; <code>false</code> en caso contrario.
 * 
 * @throws IOException
 *             si se produce un error al crear el directorio destino o al
 *             copiar el contenido.
 */
public static boolean copyFolder(String original, String destination) throws IOException {

    File input = new File(original);
    File output = new File(destination);

    // Si ambos directorios existen y son directorios.
    if (input.exists() && input.isDirectory())
        if (output.exists() && output.isDirectory()) {

            // Se obtiene la ruta del directorio que se debe crear en destino.
            String newPath = output.getCanonicalPath() + File.separatorChar + input.getName(); //$NON-NLS-1$
            // Si ya existe o se consigue crear.
            if (new File(newPath).exists() || createDir(newPath)) {
                File[] files = input.listFiles();
                for (File next : files) {
                    // Se copian sus ficheros uno a uno.
                    if (next.isFile())
                        copyFile(next, new File((newPath + File.separatorChar + next.getName())));
                    else if (next.isDirectory())
                        copyFolder(next.getPath(), newPath);
                }
                return true;
            }
        }
    return false;
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs)
        throws IOException {
    Attributes attrs;//from w ww  . j ava  2s . c  o  m
    if (jar.getManifest() == null)
        return null;

    JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME);
    if (manifest_entry == null)
        manifest_entry = jar.stream()
                .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst()
                .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check.

    attrs = jar.getManifest().getMainAttributes();

    String modSide = attrs.getValue(LibraryManager.MODSIDE);
    if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide))
        return null;

    if (attrs.containsKey(MODCONTAINSDEPS)) {
        for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) {
            if (!dep.endsWith(".jar")) {
                FMLLog.log.error("Contained Dep is not a jar file: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
            }

            if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null)
                dep = "META-INF/libraries/" + dep;

            JarEntry depEntry = jar.getJarEntry(dep);
            if (depEntry == null) {
                FMLLog.log.error("Contained Dep is not in the jar: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
            }

            String depEndName = new File(dep).getName(); // extract last part of name
            if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
                FMLLog.log.error("Skipping dep at request: {}", dep);
                continue;
            }

            Attributes meta = null;
            byte[] data = null;
            byte[] manifest_data = null;

            JarEntry metaEntry = jar.getJarEntry(dep + ".meta");
            if (metaEntry != null) {
                manifest_data = readAll(jar.getInputStream(metaEntry));
                meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
            } else {
                data = readAll(jar.getInputStream(depEntry));
                try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar...
                {
                    ZipEntry ze = null;
                    while ((ze = zi.getNextEntry()) != null) {
                        if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
                            manifest_data = readAll(zi);
                            meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
                            break;
                        }
                    }
                }
            }

            if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13?
            {
                boolean found = false;
                for (File dir : modDirs) {
                    File target = new File(dir, depEndName);
                    if (target.exists()) {
                        FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction",
                                target.getCanonicalPath());
                        found = true;
                    }
                }
                if (!found) {
                    File target = new File(modDirs[0], depEndName);
                    FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(),
                            target.getCanonicalPath());
                    try {
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(),
                                target.getCanonicalPath());
                        extractPacked(target, modlist, modDirs);
                    } catch (IOException e) {
                        FMLLog.log.error("An error occurred extracting dependency", e);
                    }
                }
            } else {
                try {
                    Artifact artifact = readArtifact(modlist.getRepository(), meta);
                    File target = artifact.getFile();
                    if (target.exists()) {
                        FMLLog.log.debug(
                                "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction",
                                dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
                        if (!ENABLE_AUTO_MOD_MOVEMENT) {
                            Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
                            if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                            {
                                modlist.add(artifact);
                            }
                        }
                    } else {
                        FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());

                        if (artifact.isSnapshot()) {
                            SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta());
                            json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5)));
                            json.write(artifact.getSnapshotMeta());
                        }

                        if (!DISABLE_EXTERNAL_MANIFEST) {
                            File meta_target = new File(target.getAbsolutePath() + ".meta");
                            Files.write(manifest_data, meta_target);
                        }
                        Pair<?, ?> child = extractPacked(target, modlist, modDirs);
                        if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                        {
                            modlist.add(artifact);
                        }
                    }
                } catch (NumberFormatException nfe) {
                    FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage(
                            "An error occurred extracting dependency. Invalid Timestamp: {}",
                            meta.getValue(TIMESTAMP)), nfe);
                } catch (IOException e) {
                    FMLLog.log.error("An error occurred extracting dependency", e);
                }
            }
        }
    }

    if (attrs.containsKey(MAVEN_ARTIFACT)) {
        Artifact artifact = readArtifact(modlist.getRepository(), attrs);
        modlist.add(artifact);
        return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry)));
    }
    return null;
}