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.echocat.jomon.process.local.daemon.LocalProcessDaemon.java

@Nonnull
protected File getDirectoryOfEnvironmentVariable(@Nonnull String name, @Nonnull SubPath subPath)
        throws IOException {
    final File baseDirectory = getBaseDirectoryOfEnvironmentVariable(name);
    final File directory;
    if (subPath == inBaseDirectory) {
        directory = baseDirectory;/* w ww.ja v a2  s  .  c  o m*/
    } else {
        directory = new File(baseDirectory, subPath.getValue());
        if (!directory.exists()) {
            throw new IllegalStateException("In the current environment points the " + name
                    + " environment variable to " + directory + " but it does not exists.");
        }
        if (!directory.isDirectory()) {
            throw new IllegalStateException("In the current environment points the " + name
                    + " environment variable to " + directory + " but it is not a directory.");
        }
    }
    return directory.getCanonicalFile();
}

From source file:com.netspective.commons.io.UriAddressableUniqueFileLocator.java

/**
 * Creates a new file resource locator that will use the specified directory
 * as the base directory for loading templates.
 *
 * @param baseDir the base directory for loading templates
 *///from  w w  w.  j  a v a  2  s .  co  m
public UriAddressableUniqueFileLocator(final String rootUrl, final File baseDir, final boolean cacheLocations)
        throws IOException {
    this.rootUrl = rootUrl;
    this.cacheLocations = cacheLocations;
    try {
        Object[] retval = (Object[]) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                if (!baseDir.exists()) {
                    throw new FileNotFoundException(baseDir + " does not exist.");
                }
                if (!baseDir.isDirectory()) {
                    throw new IOException(baseDir + " is not a directory.");
                }
                Object[] retval = new Object[2];
                retval[0] = baseDir.getCanonicalFile();
                retval[1] = ((File) retval[0]).getPath() + File.separatorChar;
                return retval;
            }
        });
        this.baseDir = (File) retval[0];
        this.canonicalPath = (String) retval[1];
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
}

From source file:de.jwi.jfm.Folder.java

private String pasteClipboard(HttpSession session) throws OutOfSyncException, IOException {
    ClipBoardContent clipBoardContent = (ClipBoardContent) session.getAttribute("clipBoardContent");
    if (clipBoardContent == null) {
        return "nothing in clipboard";
    }/*from w ww.  j  a  v a2  s .  co m*/

    for (int i = 0; i < clipBoardContent.selectedfiles.length; i++) {
        File f = clipBoardContent.selectedfiles[i];
        File f1 = f.getParentFile();

        if (myFile.getCanonicalFile().equals(f1.getCanonicalFile())) {
            return "same folder";
        }
    }

    for (int i = 0; i < clipBoardContent.selectedfiles.length; i++) {
        File f = clipBoardContent.selectedfiles[i];

        if (clipBoardContent.contentType == ClipBoardContent.COPY_CONTENT) {
            if (f.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(f, myFile);
            } else {
                FileUtils.copyFileToDirectory(f, myFile, true);
            }
        }
        if (clipBoardContent.contentType == ClipBoardContent.CUT_CONTENT) {
            if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, myFile, false);
            } else {
                FileUtils.moveFileToDirectory(f, myFile, false);
            }
        }
        if (clipBoardContent.contentType == ClipBoardContent.CUT_CONTENT) {
            session.removeAttribute("clipBoardContent");
        }
    }

    return "";
}

From source file:edu.buffalo.cse.pigout.parser.QueryParserDriver.java

private FetchFileRet getMacroFile(String fname) {
    FetchFileRet localFileRet = null;//from ww  w  . j  a v  a 2  s.  co m
    try {
        if (fnameMap.get(fname) != null) {
            localFileRet = fnameMap.get(fname);
        } else {
            try {
                File localFile = QueryParserUtils.getFileFromImportSearchPath(fname);
                localFileRet = localFile == null ? FileLocalizer.fetchFile(this.context.getProperties(), fname)
                        : new FetchFileRet(localFile.getCanonicalFile(), false);
            } catch (FileNotFoundException e) {
                // ignore this since we'll attempt to load as a resource before failing
                LOG.debug(String.format("Macro file %s was not found", fname));
            }

            // try loading the macro file as a resource in case it is packaged in a registered jar
            if (localFileRet == null) {
                LOG.debug(String.format("Attempting to load macro file %s as a resource", fname));

                try {
                    localFileRet = FileLocalizer.fetchResource(fname);
                    LOG.debug(String.format("Found macro file %s as resource", fname));
                } catch (ResourceNotFoundException e) {
                    LOG.debug(String.format("Macro file %s was not found as resource either", fname));
                    LOG.error(String.format("Failed to find macro file %s", fname));
                    throw new ExecException("file '" + fname + "' does not exist.", 101, PigException.INPUT);
                }
            }

            fnameMap.put(fname, localFileRet);
        }
    } catch (IOException e) {
        throw new RuntimeException("Unable to fetch macro file '" + fname + "'", e);
    }
    return localFileRet;
}

From source file:nz.govt.natlib.ndha.manualdeposit.metadata.ApplicationData.java

public void loadData(final String fileName) throws IOException {
    String xmlFileName = fileName;
    if (xmlFileName == null) {
        return;/*from w w  w.  j av a 2s  .com*/
    }
    File xmlFile = new File(xmlFileName);
    LOG.debug(xmlFile.getCanonicalFile());
    if (!xmlFile.exists()) { // Search for it
        final ClassLoader contextClassLoader = PropertiesUtil.getContextClassLoaderInternal();
        final Enumeration<URL> urls = PropertiesUtil.getResources(contextClassLoader, xmlFileName);
        if ((urls == null) || (!urls.hasMoreElements())) {
            LOG.error("Application Data file not found - " + xmlFileName);
            throw new FileNotFoundException(xmlFileName + " not found");
        }
        final URL xmlFileNameURL = (URL) urls.nextElement();
        xmlFile = new File(xmlFileNameURL.getPath());
        xmlFileName = xmlFile.getPath();
    }
    loadFromXML(xmlFileName);
    dataLoaded = true;
}

From source file:org.mitre.provenance.capture.linux.PROCtor.java

/**
 * Processes a PID identified by a particular /proc filesystem path, and creates the necessary provenance objects.
 * @param procPID//from   w  w  w.ja v a2s . c o m
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws PLUSException
 */
protected void processPID(File procPID) throws IOException, NoSuchAlgorithmException, PLUSException {
    if (!procPID.exists()) {
        log.warning("PID " + procPID + " doesn't exist.");
        return;
    }

    PLUSInvocation inv = createOrRetrieveInvocation(procPID);
    if (inv == null)
        return;

    String[] fileDescriptors = null;
    File fds = new File(procPID, "fd");
    fileDescriptors = fds.list();

    if (fileDescriptors == null) {
        return;
    } // No permissions here.

    ProvenanceCollection pcol = new ProvenanceCollection();

    boolean revisiting = false;

    if (client.exists(inv) != null)
        revisiting = true;
    else
        pcol.addNode(inv);

    List<String> inputs = new ArrayList<String>();
    List<String> outputs = new ArrayList<String>();
    List<String> related = new ArrayList<String>();

    for (String fdName : fileDescriptors) {
        File fdFile = new File(fds, fdName);

        // We get the canonical file to resolve the procfs symlink, so that 
        // we're gathering metadata about the file, and not a symlink to the file.
        File canonical = fdFile.getCanonicalFile();

        boolean previouslyWritten = false;
        PLUSObject fdObj = null;

        // This is what will let us know whether the file was open for input/output, or whatever.
        ProcFDInfo fdInfo = getFDInfo(procPID, fdName);
        if (fdInfo == null) {
            log.warning("Couldn't get fdInfo for " + procPID + "/fdinfo/" + fdName);
            continue;
        }

        try {
            fdObj = createOnlyIfNew(canonical);
        } catch (ExistsException e) {
            // There is a valid file here, but we've already seen it.  That means don't add it
            // to the collection or try to re-write it.
            previouslyWritten = true;
            fdObj = e.getObject();
        }

        if (fdObj == null)
            continue;

        if (!previouslyWritten) {
            fdObj.getMetadata().put("unix:fd", fdName);
            pcol.addNode(fdObj);
        }

        // It's an output if we're appending to it, creating it, writing only to it, or truncating it.
        if (fdInfo.O_APPEND() || fdInfo.O_CREAT() || fdInfo.O_WRONLY() || fdInfo.O_TRUNC())
            outputs.add("" + fdObj.getMetadata().get(UUID_KEY));
        // It's an input if we're read only.
        else if (fdInfo.O_RDONLY())
            inputs.add("" + fdObj.getMetadata().get(UUID_KEY));
        else if (fdInfo.O_RDWR())
            related.add("" + fdObj.getMetadata().get(UUID_KEY));
        else {
            log.warning("Ambiguous mode for " + procPID + "/fdinfo/" + fdName + ": " + fdInfo.getFlags());
        }

        if (fdFile.canWrite())
            outputs.add("" + fdObj.getMetadata().get(UUID_KEY));
        else
            inputs.add("" + fdObj.getMetadata().get(UUID_KEY));

        String file_uuid = "" + fdObj.getMetadata().get(UUID_KEY);

        if (previouslyWritten)
            pcol.addNonProvenanceEdge(new NonProvenanceEdge(fdObj, file_uuid, UUID_KEY));
    }

    for (String id : inputs) {
        PLUSObject o = (PLUSObject) cache.get(id);
        if (o != null)
            pcol.addEdge(new PLUSEdge(o, inv));
    }

    for (String id : outputs) {
        PLUSObject o = (PLUSObject) cache.get(id);
        if (o != null)
            pcol.addEdge(new PLUSEdge(inv, o));
    }

    for (String id : related) {
        // Just mark these as "contributing".
        PLUSObject o = (PLUSObject) cache.get(id);
        if (o != null)
            pcol.addEdge(new PLUSEdge(o, inv, PLUSWorkflow.DEFAULT_WORKFLOW, PLUSEdge.EDGE_TYPE_CONTRIBUTED));
    }

    boolean written = false;

    if (pcol.countNodes() > 0)
        written = client.report(pcol);

    if (written)
        log.info((revisiting ? "REVISITED" : "NEW") + ": " + inv.getMetadata().get("cmdline") + " PID "
                + inv.getMetadata().get("pid") + " => " + inputs.size() + " inputs, " + outputs.size()
                + " outputs.  Total written=" + written);
}

From source file:de.jwi.jfm.Folder.java

private String copyOrMove(boolean move, String[] selectedIDs, String target)
        throws IOException, OutOfSyncException {
    if ((selectedIDs == null) || (selectedIDs.length == 0)) {
        return "No file selected";
    }/*w  w  w . j a v a 2s. com*/

    File f1 = getTargetFile(target);

    if ((null == f1) || (myFile.getCanonicalFile().equals(f1.getCanonicalFile()))) {
        return "illegal target file";
    }

    if ((!f1.isDirectory()) && (selectedIDs.length > 1)) {
        return "target is not a directory";
    }

    StringBuffer sb = new StringBuffer();

    File fx = null;

    for (int i = 0; i < selectedIDs.length; i++) {
        File f = checkAndGet(selectedIDs[i]);

        if (null == f) {
            throw new OutOfSyncException();
        }

        if (!f1.isDirectory()) {
            fx = f1;
        } else {
            fx = new File(f1, f.getName());
        }

        if (move) {
            if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, fx, true);
            } else {
                if (!f.renameTo(fx)) {
                    sb.append(f.getName()).append(" ");
                }
            }
        } else {
            try {
                if (f.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(f, fx);
                } else {
                    FileUtils.copyFile(f, fx, true);
                }
            } catch (IOException e) {
                sb.append(f.getName()).append(" ");
            }
        }
    }

    String s = sb.toString();

    if (!"".equals(s)) {
        String op = move ? "move" : "copy";
        return "failed to " + op + " " + s + " to " + f1.toString();
    }

    return "";
}

From source file:org.apache.ivy.core.retrieve.RetrieveTest.java

private void assertLink(String filename) throws IOException {
    // if the OS is known to support symlink, check that the file is a symlink,
    // otherwise just check the file exist.

    File file = new File(filename);
    assertTrue("The file " + filename + " doesn't exist", file.exists());

    String os = System.getProperty("os.name");
    if (os.equals("Linux") || os.equals("Solaris") || os.equals("FreeBSD") || os.equals("Mac OS X")) {
        // these OS should support symnlink, so check that the file is actually a symlink.
        // this is done be checking that the canonical path is different from the absolute
        // path./*www  . j  av a 2  s . c  om*/
        File absFile = file.getAbsoluteFile();
        File canFile = file.getCanonicalFile();
        assertFalse("The file " + filename + " isn't a symlink", absFile.equals(canFile));
    }
}

From source file:org.finra.dm.tools.uploader.UploaderController.java

/**
 * Returns the list of File objects created from the specified list of local files after they are validated for existence and read access.
 *
 * @param localDir the local path to directory to be used to construct the relative absolute paths for the files to be validated
 * @param manifestFiles the list of manifest files that contain file paths relative to <code>localDir</code> to be validated.
 *
 * @return the list of validated File objects
 * @throws IllegalArgumentException if <code>localDir</code> or local files are not valid
 * @throws IOException if there is a filesystem query issue to construct a canonical form of an abstract file path
 *//*from   ww  w.j  a  v a 2  s . c o  m*/
protected List<File> getValidatedLocalFiles(String localDir, List<ManifestFile> manifestFiles)
        throws IllegalArgumentException, IOException {
    // Create a "directory" file and ensure it is valid.
    File directory = new File(localDir);

    if (!directory.isDirectory() || !directory.canRead()) {
        throw new IllegalArgumentException(
                String.format("Invalid local base directory: %s", directory.getAbsolutePath()));
    }

    // For each file path from the list, create Java "File" objects to the real file location (i.e. with the directory
    // prepended to it), and verify that the file exists. If not, an IllegalArgumentException will be thrown.
    String basedir = directory.getAbsolutePath();
    List<File> resultFiles = new ArrayList<>();

    for (ManifestFile manifestFile : manifestFiles) {
        // Create a "real file" that points to the actual file on the file system (i.e. directory + manifest file path).
        String realFullPathFileName = Paths.get(basedir, manifestFile.getFileName()).toFile().getPath();
        realFullPathFileName = realFullPathFileName.replaceAll("\\\\", "/");
        File realFile = new File(realFullPathFileName);

        // Verify that the file exists and is readable.
        DmFileUtils.verifyFileExistsAndReadable(realFile);

        // Verify that the name of the actual file on the file system exactly matches the name of the real file on the file system.
        // This will handle potential case issues on Windows systems. Note that the canonical file gives the actual file name on the system.
        // The non-canonical file gives the name as it was specified in the manifest.
        String realFileName = realFile.getName();
        String manifestFileName = realFile.getCanonicalFile().getName();

        if (!realFileName.equals(manifestFileName)) {
            throw new IllegalArgumentException("Manifest filename \"" + manifestFileName
                    + "\" does not match actual filename \"" + realFileName + "\".");
        }

        resultFiles.add(realFile);
    }

    return resultFiles;
}

From source file:org.rhq.plugins.jslee.JainSleeServerDiscoveryComponent.java

private Set<DiscoveredResourceDetails> discoverExternalJBossAsProcesses(
        ResourceDiscoveryContext discoveryContext) throws Exception {
    Set<DiscoveredResourceDetails> resources = new HashSet<DiscoveredResourceDetails>();
    List<ProcessScanResult> autoDiscoveryResults = discoveryContext.getAutoDiscoveredProcesses();

    for (ProcessScanResult autoDiscoveryResult : autoDiscoveryResults) {
        ProcessInfo processInfo = autoDiscoveryResult.getProcessInfo();
        if (log.isDebugEnabled())
            log.debug("Discovered JBoss AS process: " + processInfo);

        JBossInstanceInfo cmdLine;/* www.jav  a 2s  .c  o  m*/
        try {
            cmdLine = new JBossInstanceInfo(processInfo);
        } catch (Exception e) {
            log.error("Failed to process JBoss AS command line: " + Arrays.asList(processInfo.getCommandLine()),
                    e);
            continue;
        }

        // TODO : Make sure its Mobicents 2.0.0.BETA2 and above here, because after this we are looking for folder
        // mobicents-slee
        // Skip it if it's an AS/EAP/SOA-P version we don't support.
        JBossInstallationInfo installInfo = cmdLine.getInstallInfo();
        // if (!isSupportedProduct(installInfo)) {
        // // continue;
        // }

        File installHome = new File(cmdLine.getSystemProperties().getProperty(JBossProperties.HOME_DIR));
        File configDir = new File(cmdLine.getSystemProperties().getProperty(JBossProperties.SERVER_HOME_DIR));

        // The config dir might be a symlink - call getCanonicalFile() to resolve it if so, before
        // calling isDirectory() (isDirectory() returns false for a symlink, even if it points at
        // a directory).
        try {
            if (!configDir.getCanonicalFile().isDirectory()) {
                log.warn("Skipping discovery for JBoss AS process " + processInfo
                        + ", because configuration dir '" + configDir
                        + "' does not exist or is not a directory.");
                continue;
            }
        } catch (IOException e) {
            log.error("Skipping discovery for JBoss AS process " + processInfo + ", because configuration dir '"
                    + configDir + "' could not be canonicalized.", e);
            continue;
        }

        File mobicentsSlee = new File(
                cmdLine.getSystemProperties().getProperty(MobicentsJSleeProperties.JSLEE_HOME_DIR));
        try {
            if (!mobicentsSlee.getCanonicalFile().isDirectory()) {
                log.warn("Skipping discovery for Mobicents JAIN SLEE process " + processInfo
                        + ", because Mobicents dir " + mobicentsSlee.getCanonicalFile().getAbsolutePath()
                        + " does not exist or is not a directory.");
                continue;
            }
        } catch (IOException e) {
            log.error("Skipping discovery for Mobicents JAIN SLEE process " + processInfo
                    + ", because Mobicents dir could not be canonicalized.", e);
            continue;
        }

        Configuration pluginConfiguration = discoveryContext.getDefaultPluginConfiguration();

        String jnpURL = getJnpURL(cmdLine, installHome, configDir);

        // TODO? Set the connection type - local or remote

        // Set the required props...
        pluginConfiguration
                .put(new PropertySimple(ApplicationServerPluginConfigurationProperties.NAMING_URL, jnpURL));
        pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.HOME_DIR,
                installHome.getAbsolutePath()));
        pluginConfiguration.put(
                new PropertySimple(ApplicationServerPluginConfigurationProperties.SERVER_HOME_DIR, configDir));

        pluginConfiguration.put(new PropertySimple(MobicentsJSleeProperties.JSLEE_HOME_DIR,
                cmdLine.getSystemProperties().getProperty(MobicentsJSleeProperties.JSLEE_HOME_DIR)));

        // Set the optional props...
        pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.SERVER_NAME,
                cmdLine.getSystemProperties().getProperty(JBossProperties.SERVER_NAME)));
        pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.BIND_ADDRESS,
                cmdLine.getSystemProperties().getProperty(JBossProperties.BIND_ADDRESS)));

        pluginConfiguration
                .put(new PropertySimple(ApplicationServerPluginConfigurationProperties.SERVER_TMP_DIR,
                        cmdLine.getSystemProperties().getProperty(JBossProperties.SERVER_TEMP_DIR)));
        JBossASDiscoveryUtils.UserInfo userInfo = JBossASDiscoveryUtils.getJmxInvokerUserInfo(configDir);
        if (userInfo != null) {
            pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.PRINCIPAL,
                    userInfo.getUsername()));
            pluginConfiguration.put(new PropertySimple(
                    ApplicationServerPluginConfigurationProperties.CREDENTIALS, userInfo.getPassword()));
        }

        String javaHome = processInfo.getEnvironmentVariable(JAVA_HOME_ENV_VAR);
        if (javaHome == null && log.isDebugEnabled()) {
            log.debug("JAVA_HOME environment variable not set in JBoss AS process - defaulting "
                    + ApplicationServerPluginConfigurationProperties.JAVA_HOME
                    + " connection property to the plugin container JRE dir.");
            javaHome = System.getenv(JAVA_HOME_ENV_VAR);
        }

        pluginConfiguration
                .put(new PropertySimple(ApplicationServerPluginConfigurationProperties.JAVA_HOME, javaHome));

        initLogEventSourcesConfigProp(configDir, pluginConfiguration);

        // TODO: Init props that have static defaults.
        // setPluginConfigurationDefaults(pluginConfiguration);

        DiscoveredResourceDetails resourceDetails = createResourceDetails(discoveryContext, pluginConfiguration,
                processInfo, installInfo);
        resources.add(resourceDetails);
    }
    return resources;
}