Example usage for org.apache.commons.vfs2 FileObject exists

List of usage examples for org.apache.commons.vfs2 FileObject exists

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject exists.

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

void createWorkDirectoryFor(ApplicationEnvironment env) throws IOException {
    FileObject managerDir = fileUtility.getWorkingDirectory(env.getApplicationManagerName());
    FileObject workingDir = managerDir.resolveFile(env.getServiceName());
    if (!workingDir.exists()) {
        workingDir.createFolder();//from  w w w  .  j a  va2 s. c om
    }
    File workingDirFile = new File(workingDir.getName().getPath());
    env.setWorkingDirectory(workingDirFile);
}

From source file:maspack.fileutil.FileCacher.java

public InputStream getInputStream(URIx uri) throws FileSystemException {

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }//from  ww w .  j ava 2s.c  o  m

    if (remoteFile == null || !remoteFile.exists()) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // open stream content
    InputStream stream = null;
    try {
        stream = remoteFile.getContent().getInputStream();
    } catch (Exception e) {
        remoteFile.close();
        throw new RuntimeException("Failed to open " + remoteFile.getURL(), e);
    } finally {
    }

    return stream;

}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

public void exportServiceCodebaseJars(FileObject serviceRoot, CodebaseContext codebaseContext)
        throws FileSystemException {
    /*//from w  w w .  j a va  2 s.c om
     Register the service's codebase jars with the codebase service.
     */
    FileObject libDlDir = serviceRoot.resolveFile(Strings.LIB_DL);
    /* Don't bother if there is no lib-dl (e.g. for simple clients) */
    if (libDlDir.exists()) {
        List<FileObject> dljarFiles = Utils.findChildrenWithSuffix(libDlDir, Strings.DOT_JAR);
        for (FileObject jarFile : dljarFiles) {
            codebaseContext.addFile(jarFile);
        }
    }
}

From source file:com.sludev.commons.vfs.simpleshell.SimpleShell.java

/**
 * Does a 'cat' command./*w  w  w  .  j  a va  2 s  .  c  o  m*/
 * 
 * @param cmd
 * @throws SimpleShellException
 */
public void cat(String[] cmd) throws SimpleShellException {
    if (cmd.length < 2) {
        throw new SimpleShellException("USAGE: cat <path>");
    }

    // Locate the file
    FileObject file;
    try {
        file = mgr.resolveFile(cwd, cmd[1]);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving file '%s'", cmd[1]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        if (file.exists() == false) {
            // Can't cat a file that doesn't exist
            System.out.println(String.format("File '%s' does not exist", cmd[1]));
            return;
        }
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error exists() on file '%s'", cmd[1]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        if (file.getType() != FileType.FILE) {
            // Only cat files
            System.out.println(String.format("File '%s' is not an actual file.", cmd[1]));
            return;
        }
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error getType() on file '%s'", cmd[1]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        // Dump the contents to System.out
        FileUtil.writeContent(file, System.out);
    } catch (IOException ex) {
        String errMsg = String.format("Error WriteContent() on file '%s'", cmd[1]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    System.out.println();
}

From source file:maspack.fileutil.FileCacher.java

public File cache(URIx uri, File cacheFile, FileTransferMonitor monitor) throws FileSystemException {

    // For atomic operation, first download to temporary directory
    File tmpCacheFile = new File(cacheFile.getAbsolutePath() + TMP_EXTENSION);
    URIx cacheURI = new URIx(cacheFile.getAbsoluteFile());
    URIx tmpCacheURI = new URIx(tmpCacheFile.getAbsoluteFile());
    FileObject localTempFile = manager.resolveFile(tmpCacheURI.toString(true));
    FileObject localCacheFile = manager.resolveFile(cacheURI.toString(true));

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }/*from  w  w w . j a va2s .c  om*/

    if (remoteFile == null || !remoteFile.exists()) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(localTempFile, remoteFile, -1, cacheFile.getName());
        monitor.start();
        monitor.fireStartEvent(localTempFile);
    }

    // transfer content
    try {
        if (remoteFile.isFile()) {
            localTempFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        } else if (remoteFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            localTempFile.copyFrom(remoteFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(localTempFile);
        }
    } catch (Exception e) {
        // try to delete local file
        localTempFile.delete();
        throw new RuntimeException(
                "Failed to complete transfer of " + remoteFile.getURL() + " to " + localTempFile.getURL(), e);
    } finally {
        // close files if we need to
        localTempFile.close();
        remoteFile.close();
        if (monitor != null) {
            monitor.release(localTempFile);
            monitor.stop();
        }

    }

    // now that the copy is complete, do a rename operation
    try {
        if (tmpCacheFile.isDirectory()) {
            SafeFileUtils.moveDirectory(tmpCacheFile, cacheFile);
        } else {
            SafeFileUtils.moveFile(tmpCacheFile, cacheFile);
        }
    } catch (Exception e) {
        localCacheFile.delete(); // delete if possible
        throw new RuntimeException("Failed to atomically move " + "to " + localCacheFile.getURL(), e);
    }

    return cacheFile;

}

From source file:com.sludev.commons.vfs.simpleshell.SimpleShell.java

/**
 * Does a 'cp' command.//from   ww w  .j  av a  2 s  . c om
 * 
 * @param cmd
 * @throws SimpleShellException
 */
public void cp(String[] cmd) throws SimpleShellException {
    if (cmd.length < 3) {
        throw new SimpleShellException("USAGE: cp <src> <dest>");
    }

    FileObject src = null;
    try {
        src = mgr.resolveFile(cwd, cmd[1]);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving source file '%s'", cmd[1]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    FileObject dest = null;
    try {
        dest = mgr.resolveFile(cwd, cmd[2]);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving destination file '%s'", cmd[2]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        if (dest.exists() && dest.getType() == FileType.FOLDER) {
            dest = dest.resolveFile(src.getName().getBaseName());
        }
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error resolving folder '%s'", cmd[2]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }

    try {
        dest.copyFrom(src, Selectors.SELECT_ALL);
    } catch (FileSystemException ex) {
        String errMsg = String.format("Error copyFrom() file '%s' to '%s'", cmd[1], cmd[2]);
        //log.error( errMsg, ex);
        throw new SimpleShellException(errMsg, ex);
    }
}

From source file:hadoopInstaller.installation.HostInstallation.java

private FileObject sftpConnect() throws InstallationError {
    FileObject remoteDirectory;
    log.debug("HostInstallation.SFTP.Connect.Start", //$NON-NLS-1$
            host.getHostname(), host.getUsername());
    try {/*from   w ww  .  j  a  v a  2  s. c  o  m*/
        String uri = new URI("sftp", host.getUsername(), //$NON-NLS-1$
                host.getHostname(), host.getPort(), host.getInstallationDirectory(), null, null).toString();
        remoteDirectory = VFS.getManager().resolveFile(uri, installer.getSftpOptions());
    } catch (URISyntaxException | FileSystemException e) {
        throw new InstallationError(e, "HostInstallation.SFTP.Connect.End", //$NON-NLS-1$
                host.getHostname());
    }
    try {
        if (!remoteDirectory.exists()) {
            remoteDirectory.createFolder();
        }
    } catch (FileSystemException e) {
        throw new InstallationError(e, "HostInstallation.CouldNotCreate", //$NON-NLS-1$
                remoteDirectory.getName().getURI(), host.getUsername());
    }
    log.debug("HostInstallation.SFTP.Connect.Success", //$NON-NLS-1$
            host.getHostname(), host.getUsername());
    return remoteDirectory;
}

From source file:de.innovationgate.wgpublisher.design.fs.DesignFileDocument.java

private long determineFileContainerLastModified()
        throws WGDesignSyncException, InstantiationException, IllegalAccessException, IOException {

    // Throw all dates that may symbolize changes to a list
    List<Long> dates = new ArrayList<Long>();

    // Directory date
    dates.add(getLastModifiedTime(getCodeFile()));

    // Metadata date
    FileObject mdFile = getMetadataFile();
    if (mdFile.exists()) {
        dates.add(mdFile.getContent().getLastModifiedTime());
    }//from ww  w . java  2s.c om

    // Container File dates
    List<FileObject> files = getFileContainerFiles();
    FileObject file;

    for (int i = 0; i < files.size(); i++) {
        file = (FileObject) files.get(i);
        if (isExcludedFileContainerFile(file)) {
            continue;
        }

        dates.add(file.getContent().getLastModifiedTime());
    }

    // Sort and take the highest
    Collections.sort(dates);
    return dates.get(dates.size() - 1);

}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java

private static void determineChangedFileContainerResources(FileObject categoryFolder, FileObject source,
        FileObject target, FileObject baseFolder, String sourceEncoding, String targetEncoding,
        OverlayStatus status, Logger log, DesignFileValidator validator)
        throws WGDesignSyncException, NoSuchAlgorithmException, IOException {

    String targetResourcePath = baseFolder.getName().getRelativeName(target.getName());
    Set<String> involvedFiles = new HashSet<String>();

    // Completely new folder is a new file container
    if (!target.exists()) {

        status.addChangedResource(WGDocument.TYPE_FILECONTAINER, source, target, categoryFolder, ChangeType.NEW,
                targetResourcePath, null);
        // Als add all subfolders
        for (FileObject sourceFile : source.getChildren()) {
            if (sourceFile.getType().equals(FileType.FOLDER)) {
                FileObject targetFile = target.resolveFile(sourceFile.getName().getBaseName());
                determineChangedFileContainerResources(categoryFolder, sourceFile, targetFile, baseFolder,
                        sourceEncoding, targetEncoding, status, log, validator);
            }//from   ww w. j av  a  2  s .co  m
        }
        return;
    }

    if (target.getType().equals(FileType.FILE)) {
        throw new WGDesignSyncException(
                "Unable to apply overlay. Folder '" + baseFolder.getName().getRelativeName(target.getName())
                        + " already exists as file. Delete it to enable overlay management again");
    }

    // Determine change type by iterating through source child files and compare with target
    boolean overlayChanged = false;
    boolean baseChanged = false;
    boolean directConflict = false;

    for (FileObject sourceFile : source.getChildren()) {
        if (!isValidDesignFile(sourceFile, validator)) {
            continue;
        }

        FileObject targetFile = target.resolveFile(sourceFile.getName().getBaseName());
        String fileResourcePath = baseFolder.getName().getRelativeName(targetFile.getName());

        if (sourceFile.getType().equals(FileType.FOLDER)) {
            // Descend onto subcontainer
            determineChangedFileContainerResources(categoryFolder, sourceFile, targetFile, baseFolder,
                    sourceEncoding, targetEncoding, status, log, validator);
        } else if (sourceFile.getType().equals(FileType.FILE)) {

            // File does not exist. Look if it was once deployed.
            if (!targetFile.exists()) {

                ResourceData resourceData = status.getOverlayData().getOverlayResources().get(fileResourcePath);
                if (resourceData != null) {
                    // Did already exist. But did it have the same content?
                    String newHash = MD5HashingInputStream
                            .getStreamHash(sourceFile.getContent().getInputStream());
                    if (newHash.equals(resourceData.getMd5Hash())) {
                        overlayChanged = true;
                        involvedFiles.add(sourceFile.getName().getBaseName() + " (removed in overlay)");
                    } else {
                        baseChanged = true;
                        overlayChanged = true;
                        directConflict = true;
                        involvedFiles.add(
                                sourceFile.getName().getBaseName() + " (removed in overlay, changed in base)");
                    }

                }

                // Did not yet exist. It is a new file in the base version.
                else {
                    baseChanged = true;
                    involvedFiles.add(sourceFile.getName().getBaseName() + " (new in base)");
                }

            }

            // File does exist: Determine if is updated in base since the overlay file was deployed
            else {

                ResourceData originalHash = status.getOverlayData().getOverlayResources().get(fileResourcePath);
                if (originalHash == null) {
                    log.warn("There is no information about the original deployment state of resource '"
                            + fileResourcePath + "' so its change status cannot be determined.");
                    OverlayData.ResourceData resource = new OverlayData.ResourceData();
                    resource.setMd5Hash(
                            MD5HashingInputStream.getStreamHash(sourceFile.getContent().getInputStream()));
                    status.getOverlayData().setOverlayResource(fileResourcePath, resource);
                    continue;
                }

                // First determine if the resource really changed from what was distributed
                String newHash = MD5HashingInputStream.getStreamHash(sourceFile.getContent().getInputStream());
                if (newHash.equals(originalHash.getMd5Hash())) {
                    continue;
                }

                // Determine if the target file is the same as was distributed. If not then it was user modified, so it is a conflict
                String currentHash = MD5HashingInputStream
                        .getStreamHash(targetFile.getContent().getInputStream());
                if (!currentHash.equals(originalHash.getMd5Hash())) {
                    overlayChanged = true;
                    baseChanged = true;
                    directConflict = true;
                    involvedFiles.add(sourceFile.getName().getBaseName() + " (changed in base and overlay)");
                    break;
                }

                // It is a normal change
                else {
                    baseChanged = true;
                    involvedFiles.add(sourceFile.getName().getBaseName() + " (changed in base)");
                }
            }
        }
    }

    // Test the target files. Files may have been added there, or files from the previous base version may still be present that got deleted in the new base version.
    if (!baseChanged || !overlayChanged) {
        for (FileObject targetFile : target.getChildren()) {
            FileObject sourceFile = source.resolveFile(targetFile.getName().getBaseName());
            if (!sourceFile.exists()) {

                // Look if it was deployed with the previous base version.
                String fileResourcePath = baseFolder.getName().getRelativeName(targetFile.getName());
                ResourceData resourceData = status.getOverlayData().getOverlayResources().get(fileResourcePath);
                if (resourceData != null) {
                    // Was deployed. But with same contents?
                    String targetHash = MD5HashingInputStream
                            .getStreamHash(targetFile.getContent().getInputStream());
                    if (targetHash.equals(resourceData.getMd5Hash())) {
                        // This is a file that was from previous base version and got removed in the new base version.
                        involvedFiles.add(targetFile.getName().getBaseName() + " (removed from base)");
                        baseChanged = true;
                    }

                    // File got removed in new base version, updated in overlay. Conflict.
                    else {
                        baseChanged = true;
                        overlayChanged = true;
                        directConflict = true;
                        involvedFiles.add(targetFile.getName().getBaseName()
                                + " (removed from base, changed in overlay)");
                        break;
                    }
                } else {
                    involvedFiles.add(targetFile.getName().getBaseName() + " (new in overlay)");
                    overlayChanged = true;
                }
            }
        }
    }

    // Determine change type based on the found changes
    ChangeType changeType = null;
    if (baseChanged) {
        if (overlayChanged) {
            changeType = ChangeType.CONFLICT;
        } else {
            changeType = ChangeType.CHANGED;
        }
    }

    if (changeType != null) {
        status.addChangedResource(WGDocument.TYPE_FILECONTAINER, source, target, categoryFolder, changeType,
                targetResourcePath, involvedFiles);
    }

}

From source file:de.innovationgate.wgpublisher.design.fs.DesignFileDocument.java

private boolean isDesignCacheValid(Data cacheData, FileObject mdFile, long lastModified)
        throws FileSystemException {
    return cacheData != null && cacheData.getLastModified() >= lastModified
            && cacheData.isMdFileExists() == mdFile.exists()
            && cacheData.getEncoding().equals(_manager.getFileEncoding());
}