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:de.innovationgate.wgpublisher.design.fs.DesignFileDocument.java

private long determineLastModifiedTime(FileObject mdFile) throws FileSystemException, WGDesignSyncException,
        InstantiationException, IllegalAccessException, IOException {
    long mdLastModifiedTime = Long.MIN_VALUE;
    if (mdFile.exists()) {
        mdLastModifiedTime = getLastModifiedTime(mdFile);
    }// w  ww. ja v  a2s .c  om
    long codeLastModifiedTime = getLastModifiedTime(getCodeFile());

    long lastModified = Math.max(mdLastModifiedTime, codeLastModifiedTime);
    if (getType() == WGDocument.TYPE_FILECONTAINER && _manager.isStrictFCDateDetermination()) {
        lastModified = determineFileContainerLastModified();
    }
    return lastModified;
}

From source file:com.sonicle.webtop.mail.MultipartIterator.java

/**
 * Creates a file on disk from the current mulitpart element
 * @param fileName the name of the multipart file
 *//*from w  ww .j  a v  a  2  s  . c o m*/
protected FileObject createVFSFile(String filename) throws IOException {

    FileObject vfsfile = fileObjectDir.resolveFile(filename);
    int n = 0;
    String xfilename = filename;
    String xext = null;
    int ix = xfilename.lastIndexOf(".");
    if (ix > 0) {
        xext = xfilename.substring(ix + 1);
        xfilename = xfilename.substring(0, ix);
    }
    while (vfsfile.exists()) {
        ++n;
        filename = xfilename + " (" + n + ")";
        if (xext != null)
            filename += "." + xext;
        vfsfile = fileObjectDir.resolveFile(filename);
    }
    OutputStream fos = vfsfile.getContent().getOutputStream();
    try {
        writeStream(fos);
    } catch (IOException exc) {
        vfsfile.delete();
    }
    return vfsfile;
}

From source file:maspack.fileutil.FileCacher.java

public boolean copy(URIx from, URIx to, FileTransferMonitor monitor) throws FileSystemException {

    FileObject fromFile = null;
    FileObject toFile = null;/*from  w  ww  .  java 2s.  c  om*/

    // clear authenticators
    setAuthenticator(fsOpts, null);
    setIdentityFactory(fsOpts, null);

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (toFile == null && cancel == false) {
        toFile = resolveRemote(to);
    }

    cancel = false;
    while (fromFile == null && cancel == false) {
        fromFile = resolveRemote(from);
    }

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

    if (toFile == null) {
        throw new FileSystemException("Cannot find destination <" + to.toString() + ">",
                new FileNotFoundException("<" + to.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(fromFile, toFile, -1, fromFile.getName().getBaseName());
        monitor.start();
        monitor.fireStartEvent(toFile);
    }

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

        if (monitor != null) {
            monitor.fireCompleteEvent(toFile);
        }
    } catch (Exception e) {
        throw new FileTransferException(
                "Failed to complete transfer of " + fromFile.getURL() + " to " + toFile.getURL(), e);
    } finally {
        // close files if we need to
        fromFile.close();
        toFile.close();
        if (monitor != null) {
            monitor.release(toFile);
            monitor.stop();
        }
    }

    return true;

}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public List<FSDesignResourceState> retrieveFSDesignResourceState(RemoteSession session, String path)
        throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }//from w ww . ja v  a  2s.  c  o m

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    WGADesignSource source = _core.getDesignManager().getDesignSources()
            .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
    if (source instanceof FileSystemDesignSource) {
        FileSystemDesignSource fsSource = (FileSystemDesignSource) source;
        try {
            fsSource.getDir().refresh();
            FileObject base = fsSource.getDir().resolveFile(path);
            if (base.exists()) {
                return createStates(base, base);
            }
        } catch (Exception e) {
            throw new WGAServiceException(e);
        }
    }
    return new ArrayList<FSDesignResourceState>();
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void initializeOverlay(RemoteSession session, PluginInfo pluginInfo, String designFolder)
        throws WGAServiceException {

    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    try {//ww  w  . j a v a 2s .co  m
        fsManager.init();
        if (!isAdminServiceEnabled()) {
            throw new WGAServiceException("Administrative services are disabled");
        }

        if (!isAdminSession(session)) {
            throw new WGAServiceException("You need an administrative login to access this service.");
        }

        WGAPlugin basePlugin = _core.getPluginSet().getPluginsByInstallationKey()
                .get(pluginInfo.getInstallationKey());
        if (basePlugin == null) {
            throw new WGAServiceException(
                    "No plugin is installed with installation key " + pluginInfo.getInstallationKey());
        }
        WGDatabase pluginDB = _core.getContentdbs().get(basePlugin.buildDatabaseKey());
        if (pluginDB == null) {
            throw new WGAServiceException(
                    "Plugin database not connected for plugin " + basePlugin.getIdentification());
        }

        FileSystemDesignSource fsDesignSource = (FileSystemDesignSource) _core.getDesignManager()
                .getDesignSources().get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
        WGADesign overlayDesign = fsDesignSource.getDesign(designFolder);
        if (overlayDesign == null) {
            throw new WGAServiceException("File Directory Design '" + designFolder + "' does not exist");
        }

        String designFolderLocation = fsDesignSource.getDesignLocation(overlayDesign);

        FileObject designFolderObj = fsManager.resolveFile(designFolderLocation);
        if (!designFolderObj.exists() || !designFolderObj.getType().equals(FileType.FOLDER)) {
            throw new WGAServiceException(
                    "Design folder '" + designFolder + "' cannot be found or is no folder");
        }

        // Determine design encoding of folder to import to
        DesignDefinition designDef = null;
        FileObject designDefFile = designFolderObj.resolveFile("design.xml");
        if (designDefFile.exists()) {
            designDef = DesignDefinition.load(designDefFile);
        }

        CSConfig csConfig = null;
        FileObject csConfigFile = designFolderObj.resolveFile("files/system/csconfig.xml");
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }

        String designEncoding = FileSystemDesignManager.determineDesignEncoding(designDef, csConfig);

        // Trigger overlay init/uprade process
        OverlayStatus status = FileSystemDesignProvider.determineOverlayStatus(
                (FileSystemDesignProvider) pluginDB.getDesignProvider(), basePlugin.getPluginID(),
                designFolderObj, designEncoding, _core.getLog(), _core.getDesignFileValidator());
        FileSystemDesignProvider.upgradeOverlay((FileSystemDesignProvider) pluginDB.getDesignProvider(),
                basePlugin.getPluginID(), status, designFolderObj, designEncoding, _core.getLog(),
                _core.getDesignFileValidator());

        // Disconnect consumer apps
        WGADesignManager designManager = _core.getDesignManager();
        for (WGDatabase consumerDb : _core.getContentdbs().values()) {

            WGDesignProvider provider = consumerDb.getDesignProvider();
            if (provider instanceof OverlayDesignProvider) {
                OverlayDesignProvider overlayProvider = (OverlayDesignProvider) provider;
                if (overlayProvider.getOverlay() instanceof FileSystemDesignProvider) {
                    FileSystemDesignProvider fsProvider = (FileSystemDesignProvider) overlayProvider
                            .getOverlay();
                    if (fsProvider.getBaseFolder().equals(designFolderObj)) {
                        _core.removeContentDB(consumerDb.getDbReference());
                    }
                }
            }
        }

        // Run update content dbs to reconnect
        _core.updateContentDBs();

    } catch (Exception e) {
        if (e instanceof WGAServiceException) {
            throw (WGAServiceException) e;
        } else {
            throw new WGAServiceException("Overlay initialisation failed.", e);
        }
    } finally {
        fsManager.close();
    }

}

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

private static boolean performChange(ChangedDocument changedDocument,
        FileSystemDesignProvider originalDesignProvider, OverlayStatus status, String targetEncoding,
        FileObject baseFolder, Logger log, DesignFileValidator validator) throws FileSystemException,
        NoSuchAlgorithmException, UnsupportedEncodingException, IOException, WGDesignSyncException {

    boolean conflictFileCreated = false;
    log.info("Updating overlay resource " + changedDocument.getDocumentKey());

    // Find files which represent the document in source and target
    FileObject sourceDocFile = originalDesignProvider.getBaseFolder()
            .resolveFile(changedDocument.getSourceFilePath());
    FileObject targetDocFile = baseFolder.resolveFile(changedDocument.getTargetFilePath());

    // Collect files to copy and delete
    Map<FileObject, FileObject> filesToCopy = new HashMap<FileObject, FileObject>();
    List<FileObject> filesToDelete = new ArrayList<FileObject>();

    // Collect for file containers: Must traverse container content
    if (changedDocument.getDocumentKey().getDocType() == WGDocument.TYPE_FILECONTAINER) {

        if (changedDocument.getChangeType() == ChangeType.NEW) {
            targetDocFile.createFolder();
        }//  w w  w  .  ja  v a  2  s. c om

        // Copy all files in container from the source to the target 
        for (FileObject sourceFile : sourceDocFile.getChildren()) {
            if (sourceFile.getType().equals(FileType.FILE)) {
                if (!isValidDesignFile(sourceFile, validator)) {
                    continue;
                }
                filesToCopy.put(sourceFile, targetDocFile.resolveFile(sourceFile.getName().getBaseName()));
            }
        }

        // Delete all files in target that were deployed with previous base version but are deleted in current base version 
        for (FileObject targetFile : targetDocFile.getChildren()) {
            if (targetFile.getType().equals(FileType.FILE)) {
                if (!isValidDesignFile(targetFile, validator)) {
                    continue;
                }

                FileObject sourceFile = sourceDocFile.resolveFile(targetFile.getName().getBaseName());
                if (sourceFile.exists()) {
                    continue;
                }

                // Only delete those that were deployed with previous base version and have unaltered content
                String resourcePath = baseFolder.getName().getRelativeName(targetFile.getName());
                ResourceData resourceData = status.getOverlayData().getOverlayResources().get(resourcePath);
                if (resourceData != null) {
                    String hash = MD5HashingInputStream.getStreamHash(targetFile.getContent().getInputStream());
                    if (resourceData.getMd5Hash().equals(hash)) {
                        filesToDelete.add(targetFile);
                    }
                }
            }
        }

    }

    // Collect for anything else
    else {
        filesToCopy.put(sourceDocFile, targetDocFile);
    }

    // Copy files
    for (Map.Entry<FileObject, FileObject> files : filesToCopy.entrySet()) {

        FileObject sourceFile = files.getKey();
        FileObject targetFile = files.getValue();
        String resourcePath = baseFolder.getName().getRelativeName(targetFile.getName());

        if (changedDocument.getChangeType() == ChangeType.CONFLICT) {
            // Do a test if the current file is conflicting. If so we write to a conflict file instead
            InputStream in = new BufferedInputStream(sourceFile.getContent().getInputStream());
            String currentHash = MD5HashingInputStream.getStreamHash(in);
            ResourceData deployedHash = status.getOverlayData().getOverlayResources().get(resourcePath);
            boolean skipConflict = false;

            // Conflict on file container: A single file might just be missing in the target. We can safely copy that to the target without treating as conflict (#00002440)
            if (deployedHash == null
                    && changedDocument.getDocumentKey().getDocType() == WGDocument.TYPE_FILECONTAINER
                    && !targetFile.exists()) {
                skipConflict = true;
            }

            if (!skipConflict && (deployedHash == null || !deployedHash.getMd5Hash().equals(currentHash))) {
                targetFile = createConflictFile(targetFile);
                conflictFileCreated = true;
                log.warn("Modified overlay resource " + resourcePath
                        + " is updated in base design. We write the updated base version to conflict file for manual resolution: "
                        + baseFolder.getName().getRelativeName(targetFile.getName()));
            }
        }

        // Write file
        InputStream in = new BufferedInputStream(sourceFile.getContent().getInputStream());
        MD5HashingOutputStream out = new MD5HashingOutputStream(
                new BufferedOutputStream(targetFile.getContent().getOutputStream(false)));

        // Update resource data
        resourceInToOut(in, originalDesignProvider.getFileEncoding(), out, targetEncoding);
        OverlayData.ResourceData resourceData = new OverlayData.ResourceData();
        resourceData.setMd5Hash(out.getHash());
        status.getOverlayData().setOverlayResource(resourcePath, resourceData);

    }

    // Delete files
    for (FileObject fileToDelete : filesToDelete) {
        String resourcePath = baseFolder.getName().getRelativeName(fileToDelete.getName());
        fileToDelete.delete();
        status.getOverlayData().removeOverlayResource(resourcePath);
    }

    return conflictFileCreated;

}

From source file:com.sonicle.webtop.vfs.VfsManager.java

private NewTargetFile getNewTargetFileObject(int storeId, String parentPath, String name, boolean overwrite)
        throws FileSystemException, WTException {
    String newPath = FilenameUtils.separatorsToUnix(FilenameUtils.concat(parentPath, name));

    if (overwrite) {
        return new NewTargetFile(newPath, getTargetFileObject(storeId, newPath));
    } else {//from   w  ww .j ava 2  s  .co  m
        FileObject newFo = getTargetFileObject(storeId, newPath);
        if (!newFo.exists()) {
            return new NewTargetFile(newPath, newFo);
        } else {
            String ext = FilenameUtils.getExtension(name);
            String suffix = StringUtils.isBlank(ext) ? "" : "." + ext;
            String baseName = FilenameUtils.getBaseName(name);
            int i = 0;
            do {
                i++;
                final String newName = baseName + " (" + i + ")" + suffix;
                newPath = FilenameUtils.separatorsToUnix(FilenameUtils.concat(parentPath, newName));
                newFo = getTargetFileObject(storeId, newPath);
            } while (newFo.exists());
            return new NewTargetFile(newPath, newFo);
        }
    }
}

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

protected FileObject getScriptTypeFolder(String folderName) throws FileSystemException, WGDesignSyncException {
    FileObject scriptFolder = getScriptFolder();
    if (scriptFolder.exists()) {
        FileObject typeFolder = scriptFolder.resolveFile(folderName);
        if (typeFolder.exists()) {
            return typeFolder;
        }//from  ww  w. j a  v  a2 s. com
    }

    return null;
}

From source file:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

/**
 * Copy file.//from   ww  w.  java2  s. co  m
 * 
 * @param from the from
 * @param to the to
 * 
 * @throws MotuException the motu exception
 */
public void copyFile(FileObject from, FileObject to) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(FileObject, FileObject) - entering");
    }

    try {
        if ((to.exists()) && (to.getType() == FileType.FOLDER)) {
            throw new MotuException(String.format(
                    "File copy from '%s' to '%s' is rejected: the destination already exists and is a folder. You were about to loose all of the content of '%s' ",
                    from.getName().toString(), to.getName().toString(), to.getName().toString()));
        }
        this.copyFrom(from, to, Selectors.SELECT_ALL);
    } catch (MotuException e) {
        LOG.error("copyFile(FileObject, FileObject)", e);

        throw e;
    } catch (Exception e) {
        LOG.error("copyFile(FileObject, FileObject)", e);

        // throw new MotuException(String.format("Unable to copy file '%s' to '%s'",
        // foSrc.getURL().toString(), foDest.getURL().toString()), e);
        throw new MotuException(String.format("Unable to copy file '%s' to '%s'", from.getName().toString(),
                to.getName().toString()), e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(FileObject, FileObject) - exiting");
    }
}

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

/**
 * @param doInitSync/*w  w w.  j  av a 2  s  .co m*/
 * @return
 * @throws WGAPIException
 * @throws IOException
 * @throws WGDesignSyncException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvalidCSConfigVersionException
 */
protected boolean init() throws WGAPIException, IOException, WGDesignSyncException, InstantiationException,
        IllegalAccessException, InvalidCSConfigVersionException {

    // Determine the state of the directory
    FileObject syncInfoFile = getSyncInfoFile();

    if (!syncInfoFile.exists()) {

        // A new directory. Do initial deployment
        if (isEditable()) {
            _log.info("Performing initial deployment of design to directory '"
                    + getBaseFolder().getURL().toString() + "'");
            _fileEncoding = _core.getWgaConfiguration().getDesignConfiguration().getDefaultEncoding();
            doInitialDeployment(_designKey);
            return true;
        } else {
            throw new WGDesignSyncException(
                    "Cannot perform initial deploy because the file system is readonly: "
                            + getBaseFolder().getURL().toString());
        }
    } else {
        // Determine if syncdata file is present. If so, use this directory
        // as sync directory.
        getOrCreateFolders();
        updateConfiguration();
        return false;

    }

}