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.symbian.driver.core.processors.EmulatorPreProcessor.java

/**
 * @param lFile/*from w ww .  j av  a 2s  . c om*/
 * @return The backed up file.
 * @throws IOException
 */
public static final File backupFile(File lFile) throws IOException {
    if (lFile.isFile()) {

        LOGGER.info("Backup file: " + lFile);
        File lFileBackup = new File(lFile.getCanonicalPath() + BACKUP);

        if (!lFile.renameTo(lFileBackup)) {

            LOGGER.warning("Overwriting previous backup file at: " + lFileBackup + "; with: " + lFile);
            lFileBackup.delete();

            if (!lFile.renameTo(lFileBackup)) {
                throw new IOException("Could not backup old file: " + lFile);
            }
        }

        return lFileBackup;
    }

    return null;
}

From source file:com.ikon.omr.OMRHelper.java

/**
 * trainingTemplate/* w ww  .j av  a2  s. co m*/
 */
public static Map<String, File> trainingTemplate(File template)
        throws IOException, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException,
        MissingParameterException, WrongParameterException {
    Map<String, File> fileMap = new HashMap<String, File>();
    Gray8Image grayimage = ImageUtil.readImage(template.getCanonicalPath());
    ImageManipulation image = new ImageManipulation(grayimage);
    image.locateConcentricCircles();
    image.locateMarks();
    File ascFile = FileUtils.createTempFile();
    File configFile = FileUtils.createTempFile();
    image.writeAscTemplate(ascFile.getCanonicalPath());
    image.writeConfig(configFile.getCanonicalPath());
    fileMap.put(ASC_FILE, ascFile);
    fileMap.put(CONFIG_FILE, configFile);
    return fileMap;
}

From source file:com.frostwire.gui.library.M3UPlaylist.java

/**
 * Call this when you want to save the contents of the playlist.
 * NOTE: only local files can be saved in M3U format, filters out URLs 
 * that are not part of the local filesystem
 * @exception IOException Throw when save failed.
 * @exception IOException Throw when save failed.
 *//*from w  ww.  j ava  2s  .  c  om*/
public static void save(String fileName, List<File> files) throws IOException {
    File playListFile = new File(fileName);
    // if all songs are new, just get rid of the old file.  this may
    // happen if a delete was done....
    if (files.size() == 0) {
        //            if (playListFile.exists()) {
        //                playListFile.delete();
        //            }
        return;
    }

    PrintWriter m3uFile = null;
    try {
        m3uFile = new PrintWriter(new FileWriter(playListFile.getCanonicalPath(), false));

        m3uFile.write(M3U_HEADER);
        m3uFile.println();

        for (File currFile : files) {
            // only save files that are local to the file system
            if (currFile.isFile()) {
                File locFile;
                locFile = new File(currFile.toURI());

                // first line of song description...
                m3uFile.write(SONG_DELIM);
                m3uFile.write(SEC_DELIM);
                // try to write out seconds info....
                //if( currFile.getProperty(PlayListItem.LENGTH) != null )
                //    m3uFile.write("" + currFile.getProperty(PlayListItem.LENGTH) + ",");
                //else
                m3uFile.write("" + -1 + ",");
                m3uFile.write(currFile.getName());
                m3uFile.println();
                // canonical path follows...
                m3uFile.write(locFile.getCanonicalPath());
                m3uFile.println();
            }
        }
    } finally {
        IOUtils.closeQuietly(m3uFile);
    }
}

From source file:captor.app.CaptorOptionsParser.java

protected static String getDefaultInstallPath() {
    String[] installPathnames = new String[2];
    File installPath = null;

    installPathnames[0] = System.getenv("CAPTOR_HOME");
    installPathnames[1] = System.getProperty("user.dir") + File.separator + "..";

    for (String path : installPathnames) {
        if (path != null) {
            installPath = new File(path);
            if (installPath.exists() && installPath.isDirectory()) {
                break;
            } else {
                installPath = null;//from  w w w . ja  va2 s . co m
            }
        }
    }

    try {
        return installPath.getCanonicalPath();
    } catch (IOException e) {
    }
    return null;
}

From source file:eu.europeana.enrichment.common.Utils.java

private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException {
    // This will hold a list of directories matching the pckgname. There may
    // be//  w w w.  j av a2 s. co m
    // more than one if a package is split over multiple jars/paths
    Queue<File> directories = new LinkedList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname);
    }

    Set<String> classes = new HashSet<String>();
    // For every directory identified capture all the .class files
    while (!directories.isEmpty()) {
        File directory = directories.poll();
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                // we are only interested in .class files
                if (file.getCanonicalPath().endsWith(".class")) {
                    String fileName = file.getPath().substring(directory.getPath().length() + 1);
                    pckgname = file.getPath()
                            .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1);
                    pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator))
                            .replaceAll("\\" + File.separator, ".");
                    // if (!fileName.matches("(.+)\\$\\d\\.class"))
                    // removes the .class extension
                    classes.add(fileName.substring(0, fileName.length() - 6));
                }
                // Add subdirs
                if (file.isDirectory()) {
                    directories.add(file);
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:com.limegroup.gnutella.util.Launcher.java

/**
 * Launches the file whose abstract path is specified in the <tt>File</tt>
 * parameter. This method will not launch any file with .exe, .vbs, .lnk,
 * .bat, .sys, or .com extensions, diplaying an error if one of the file is
 * of one of these types./*w w  w .  j a v a2 s  .  c o m*/
 * 
 * @param path
 *            The path of the file to launch
 * @return an object for accessing the launch process; null, if the process
 *         can be represented (e.g. the file was launched through a native
 *         call)
 * @throws IOException
 *             if the file cannot be launched
 * @throws SecurityException
 *             if the file has an extension that is not allowed
 */
public static LimeProcess launchFile(File file) throws IOException, SecurityException {

    List<String> forbiddenExtensions = Arrays.asList("exe", "vbs", "lnk", "bat", "sys", "com", "js", "scpt");

    if (file.isFile() && forbiddenExtensions.contains(FilenameUtils.getExtension(file.getName()))) {
        throw new SecurityException();
    }

    String path = file.getCanonicalPath();

    if (OSUtils.isWindows()) {
        launchFileWindows(path);
        return null;
    } else if (OSUtils.isMacOSX()) {
        return launchFileMacOSX(path);
    } else {
        // Other OS, use helper apps
        return launchFileOther(path);
    }
}

From source file:com.microsoftopentechnologies.windowsazurestorage.helper.CredentialMigration.java

public static void upgradeStorageConfig() throws Exception {

    File sourceFile = new File(Utils.getWorkDirectory(), Constants.LEGACY_STORAGE_CONFIG_FILE);
    try {/*from   w  ww  .  j a v a  2s. co  m*/
        //check if we need to upgrade (i.e. if we have prior version of 0.3.2 storage plugin)
        if (!sourceFile.exists()) {
            return;
        }

        LOGGER.log(Level.INFO, sourceFile + " exists, upgrade will start now...");

        File backUp = backupFile(sourceFile.getCanonicalPath());
        List<StorageAccountInfo> oldStorages = getOldStorageConfig(sourceFile);

        if (oldStorages.size() > 0) {
            for (StorageAccountInfo sa : oldStorages) {
                String storageAccount = sa.getStorageAccName();
                String storageAccountKey = sa.getStorageAccountKey();
                String storageBlobURL = sa.getBlobEndPointURL();

                AzureCredentials.StorageAccountCredential u = new AzureCredentials.StorageAccountCredential(
                        storageAccount, storageAccountKey, storageBlobURL);
                AzureCredentials cred = CredentialsMatchers.firstOrNull(
                        CredentialsProvider.lookupCredentials(AzureCredentials.class, Jenkins.getInstance(),
                                ACL.SYSTEM, Collections.<DomainRequirement>emptyList()),
                        CredentialsMatchers.withId(u.getId()));
                if (cred != null) {
                    return;
                }

                LOGGER.log(Level.INFO,
                        "Moving Storage Account names and their keys to credential store, a creddential Id will be created for each pair of account name and key.");

                // no matching, so make our own.
                AzureCredentials tempCred = new AzureCredentials(CredentialsScope.GLOBAL,
                        Utils.getMD5(storageAccount.concat(storageAccountKey)),
                        "credential for " + storageAccount, storageAccount, storageAccountKey, storageBlobURL);
                final SecurityContext securityContext = ACL.impersonate(ACL.SYSTEM);

                try {
                    CredentialsStore s = CredentialsProvider.lookupStores(Jenkins.getInstance()).iterator()
                            .next();
                    try {
                        s.addCredentials(Domain.global(), tempCred);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } finally {

                    SecurityContextHolder.setContext(securityContext);

                } // end finally

            } //end for

        } // end if

        LOGGER.log(Level.INFO, "Migrated successfully, deleting legacy config files...");
        removeFile(sourceFile.getCanonicalPath());
        removeFile(backUp.getCanonicalPath());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return;

}

From source file:com.github.technosf.posterer.modules.commons.config.CommonsConfiguratorPropertiesImpl.java

/**
 * Creates a config builder for the given file
 * <p>/*from ww  w.j ava 2s.  c  om*/
 * The builder handles I/O tasks
 * 
 * @param file
 *            the config file
 * @return the builder
 * @throws IOException
 */
@SuppressWarnings("null")
private static FileBasedConfigurationBuilder<XMLConfiguration> createBuilder(File file) throws IOException {
    XMLBuilderParameters xmlParams = PARAMS.xml().setThrowExceptionOnMissing(true).setValidating(false)
            .setEncoding("UTF-8").setFileName(file.getCanonicalPath())
            .setExpressionEngine(new XPathExpressionEngine());

    return new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class).configure(xmlParams);

}

From source file:com.silverpeas.admin.components.Instanciateur.java

private synchronized static void buildWAComponentList() throws IOException, JAXBException, XMLStreamException {
    Collection<File> files = getFileList();
    for (File xmlFile : files) {
        String componentName = FilenameUtils.getBaseName(xmlFile.getName());
        SilverTrace.info("admin", "Instanciateur.buildWAComponentList",
                "admin.MSG_INFO_BUILD_WA_COMPONENT_LIST",
                "component name: '" + componentName + "', full path: '" + xmlFile.getCanonicalPath() + "'");
        componentsByName.put(componentName, loadComponent(xmlFile));
    }/*from   w w w .  ja va 2  s.  co m*/
}

From source file:Main.java

/**
 * Add a zip entry into the provided <code>ZipOutputStream</code>. The zip
 * entry is the part of <code>filePathToZip</code> truncated with the
 * <code>baseFolderPath</code>.
 * <p>/*w w w .  java2  s .c  o m*/
 * So a file or folder <code>c:\my\base\folder\my\file\to\zip.txt</code>
 * will be added in archive using <code>my/file/to/zip.txt</code> entry.
 */
public static void addZipEntry(ZipOutputStream zos, File fileToZip, File baseFolder) {
    if (!baseFolder.isDirectory()) {
        throw new IllegalArgumentException(baseFolder.getPath() + " is not a directory.");
    }

    if (fileToZip.isDirectory()) {
        final File[] files = fileToZip.listFiles();
        for (final File file : files) {
            addZipEntry(zos, file, baseFolder);
        }
    } else {
        final String filePathToZip;
        final int start;
        try {
            filePathToZip = fileToZip.getCanonicalPath();
            start = baseFolder.getCanonicalPath().length() + 1;
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }

        final int end = filePathToZip.length();
        String entryName = filePathToZip.substring(start, end);
        entryName = entryName.replace(File.separatorChar, '/');
        final FileInputStream inputStream;
        try {
            inputStream = new FileInputStream(filePathToZip);
        } catch (final FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
        addEntryInputStream(zos, entryName, inputStream);
    }
}