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.FileSystemDesignProvider.java

public static void createDowngradeFiles(FileSystemDesignProvider originalDesignProvider, OverlayData data,
        FileObject targetFolder, String targetEncoding, Logger log) throws Exception {

    for (Map.Entry<String, ResourceData> resourceEntry : data.getOverlayResources().entrySet()) {

        boolean changed = false;
        FileObject targetFile = targetFolder.resolveFile(resourceEntry.getKey());
        if (targetFile.exists()) {
            InputStream in = new BufferedInputStream(targetFile.getContent().getInputStream(), 4096);
            MD5HashingOutputStream out = new MD5HashingOutputStream(new NullOutputStream());
            resourceInToOut(in, targetEncoding, out, targetEncoding);
            if (!out.getHash().equals(resourceEntry.getValue().getMd5Hash())) {
                changed = true;/*from   w  ww  .  ja va  2 s.c  o  m*/
            }
        } else {
            changed = true;
        }

        if (changed == true) {
            String basePath = getOverlayResourcePathInBaseDesign(resourceEntry.getKey());
            FileObject sourceFile = originalDesignProvider.getBaseFolder().resolveFile(basePath);
            if (sourceFile.exists()) {
                FileObject conflictFile = createConflictFile(targetFile);
                log.info("Writing downgrade file of modified overlay resource " + resourceEntry.getKey()
                        + " to conflict file: "
                        + targetFolder.getName().getRelativeName(conflictFile.getName()));
                InputStream in = new BufferedInputStream(sourceFile.getContent().getInputStream(), 4096);
                OutputStream out = new BufferedOutputStream(conflictFile.getContent().getOutputStream(), 4096);
                resourceInToOut(in, originalDesignProvider.getFileEncoding(), out, targetEncoding);
            } else {
                log.warn("Overlay resource '" + resourceEntry.getKey()
                        + "' does not exist any more in the current base design version.");
            }
        }

    }

}

From source file:fulcrum.xml.Parser.java

/**
 * Only provides parsing functions to the "fulcrum.xml" package.
 * /* ww  w. java2  s  .  c  om*/
 * @see Document
 * 
 * @param fileLocation
 * @param document
 * @throws ParseException
 */
protected void parse(String fileLocation, Document document) throws ParseException {
    FileObject fileObj = null;
    try {
        fileObj = fsManager.resolveFile(fileLocation);

        if (fileObj != null && fileObj.exists() && fileObj.isReadable()) {
            FileContent content = fileObj.getContent();
            InputStream is = content.getInputStream();
            int size = is.available();
            LOGGER.debug("Total File Size: " + size + " bytes");
            byte[] buffer = new byte[size];
            is.read(buffer, 0, size);
            LOGGER.debug("Start parsing");
            parse(buffer, document);
            LOGGER.debug("Finished paring");
            buffer = null;
            content.close();
            fileObj.close();
        }
    } catch (Exception e) {
        throw new ParseException(e);
    }
}

From source file:com.seer.datacruncher.services.scheduler.PlannerSetStatusJob.java

private boolean checkServiceRunning(ConnectionsEntity conn) {

    boolean success = true;
    String url = "";
    DefaultFileSystemManager fsManager = null;
    String userName = "";
    String password = "";
    String hostName = "";
    String port = "";
    String inputDirectory = "";
    String fileName = "";

    if (conn != null) {
        userName = conn.getUserName();/*from  w  w w . j  a  v a  2 s .  co  m*/
        password = conn.getPassword();
        hostName = conn.getHost();
        port = conn.getPort();
        inputDirectory = conn.getDirectory();
        fileName = conn.getFileName();
    }

    if (conn.getIdConnType() == GenericType.DownloadTypeConn) {
        if (fileName == null || fileName.trim().length() == 0) {
            return false;
        }
        inputDirectory = inputDirectory + "/" + fileName;
    }
    try {
        fsManager = (DefaultFileSystemManager) VFS.getManager();
        if (conn.getService() == Servers.SAMBA.getDbCode()) {
            if (!fsManager.hasProvider("smb")) {
                fsManager.addProvider("smb", new SmbFileProvider());
            }
            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory;
        } else if (conn.getService() == Servers.HTTP.getDbCode()) {
            if (!fsManager.hasProvider("http")) {
                fsManager.addProvider("http", new HttpFileProvider());
            }
            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
        } else if (conn.getService() == Servers.FTP.getDbCode()) {
            if (!fsManager.hasProvider("ftp")) {
                fsManager.addProvider("ftp", new FtpFileProvider());
            }
            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory;
        }

        final FileObject fileObject = fsManager.resolveFile(url);

        if (fileObject == null || !fileObject.exists()) {
            success = false;
        }

    } catch (Exception ex) {
        success = false;
    } finally {
        if (fsManager != null)
            fsManager.close();
    }
    return success;
}

From source file:de.innovationgate.wgpublisher.design.sync.FileContainerDeployment.java

public void resetUpdateInformation()
        throws InstantiationException, IllegalAccessException, IOException, WGDesignSyncException {

    FileObject folder = getCodeFile();
    Map files = new HashMap();
    FileObject[] folderFiles = folder.getChildren();
    FileObject folderFile;//from  w w  w . j  a va  2s.  co  m
    for (int i = 0; i < folderFiles.length; i++) {

        folderFile = folderFiles[i];
        if (isExcludedFileContainerFile(folderFile)) {
            continue;
        }

        ContainerFile containerFile = new ContainerFile(folderFile);
        files.put(containerFile.getName(), containerFile);
    }
    _files = files;

    FileObject metadataFile = getMetadataFile();
    if (metadataFile.exists()) {
        _timestampOfMetadataFile = metadataFile.getContent().getLastModifiedTime();
    }

}

From source file:net.dempsy.distconfig.apahcevfs.ApacheVfsPropertiesReader.java

@Override
public VersionedProperties read(final PropertiesWatcher watcher) throws IOException {
    final FileObject latest = getLatest(parentDirObj);
    final int ver = latest == null ? -1 : getVersion(latest);
    final VersionedProperties ret = new VersionedProperties(ver, Utils.read(latest));
    if (watcher != null) {
        // if there's a watcher ....
        final FileObject next = nextFile(latest, parentDirObj);
        final Proxy proxy = new Proxy(next, watcher);
        next.getFileSystem().addListener(next, proxy);

        // but now, if the file exists due to a race condition, lets at least address that.
        if (next.exists())
            proxy.doIt();/*from   w  w w.  j a  va2 s .  c om*/
    }
    return ret;
}

From source file:functionaltests.dataspaces.TestUserSpace.java

@Test
public void testUserSpace() throws Throwable {

    File in = tmpFolder.newFolder("input_space");
    String inPath = in.getAbsolutePath();

    File out = tmpFolder.newFolder("output_space");
    String outPath = out.getAbsolutePath();

    FileSystemManager fsManager = VFSFactory.createDefaultFileSystemManager();

    Scheduler sched = schedulerHelper.getSchedulerInterface();
    String userURI = sched.getUserSpaceURIs().get(0);
    assertTrue(userURI.startsWith("file:"));
    log("User URI is " + userURI);
    String userPath = new File(new URI(userURI)).getAbsolutePath();

    FileObject pathReplaceFO = fsManager.resolveFile(userURI + "/" + pathReplaceFile);

    if (pathReplaceFO.exists()) {
        pathReplaceFO.delete();/*from ww w  .j  a  va 2 s.  c  o  m*/
    }

    /**
     * Writes inFiles in INPUT
     */
    writeFiles(inFiles, inPath);
    File testPathRepl = new File(inPath + File.separator + pathReplaceFile);
    testPathRepl.createNewFile();
    PrintWriter out2 = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testPathRepl))));
    out2.print(pathReplaceFile);
    out2.close();

    TaskFlowJob job = new TaskFlowJob();
    job.setName(this.getClass().getSimpleName());
    job.setInputSpace(in.toURI().toURL().toString());
    job.setOutputSpace(out.toURI().toURL().toString());

    JavaTask A = new JavaTask();
    A.setExecutableClassName("org.ow2.proactive.scheduler.examples.EmptyTask");
    A.setForkEnvironment(new ForkEnvironment());
    A.setName("A");
    for (String[] file : inFiles) {
        A.addInputFiles(file[0], InputAccessMode.TransferFromInputSpace);
        A.addOutputFiles(file[0] + ".glob.A", OutputAccessMode.TransferToUserSpace);
    }
    A.setPreScript(new SimpleScript(scriptA, "groovy"));
    job.addTask(A);

    JavaTask B = new JavaTask();
    B.setExecutableClassName("org.ow2.proactive.scheduler.examples.EmptyTask");
    B.setForkEnvironment(new ForkEnvironment());
    B.setName("B");
    B.addDependence(A);
    for (String[] file : inFiles) {
        B.addInputFiles(file[0] + ".glob.A", InputAccessMode.TransferFromUserSpace);
        B.addOutputFiles(file[0] + ".out", OutputAccessMode.TransferToOutputSpace);
    }
    B.setPreScript(new SimpleScript(scriptB, "groovy"));
    job.addTask(B);

    JobId id = sched.submit(job);
    schedulerHelper.waitForEventJobFinished(id);

    JobResult jr = schedulerHelper.getJobResult(id);
    Assert.assertFalse(jr.hadException());

    /**
     * check: inFiles > IN > LOCAL A > GLOBAL > LOCAL B > OUT
     */
    for (String[] inFile : inFiles) {
        File f = new File(outPath + File.separator + inFile[0] + ".out");
        assertTrue("File does not exist: " + f.getAbsolutePath(), f.exists());
        Assert.assertEquals("Original and copied files differ", inFile[1], FileUtils.readFileToString(f));
        File inf = new File(inPath + File.separator + inFile[0]);
    }

    /**
     * check that the file produced is accessible in the global user space via the scheduler API
     */

    for (String[] file : inFiles) {
        FileObject outFile = fsManager.resolveFile(userURI + "/" + file[0] + ".glob.A");
        log("Checking existence of " + outFile.getURL());
        assertTrue(outFile.getURL() + " exists", outFile.exists());

        File outFile2 = new File(userPath, file[0] + ".glob.A");
        log("Checking existence of " + outFile2);
        assertTrue(outFile2 + " exists", outFile2.exists());
    }

}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

/**
 * /*from   w  w  w. ja  va2s  .  c om*/
 * 
 * @param root
 *            
 * @param path
 *            
 * @return
 * @throws FileSystemException
 */
protected FileObject getTargetFileObject(FileObject root, String path) throws FileSystemException {
    FileObject out = root.resolveFile(path, NameScope.DESCENDENT);
    if (!out.exists()) {
        out.createFile();
    }
    return out;
}

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

public static boolean upgradeOverlay(FileSystemDesignProvider originalDesignProvider, PluginID baseId,
        OverlayStatus status, FileObject targetFolder, String targetEncoding, Logger log,
        DesignFileValidator validator) throws Exception {

    if (!status.isUpdatedBaseDesign() && !status.isNewOverlay()) {
        throw new WGDesignSyncException(
                "Used base plugin is no higher version than overlay compliance version. Cannot perform upgrade");
    }//from w  w w .ja  v a 2  s .co  m

    if (status.isNewOverlay()) {
        log.info("Initializing empty overlay");
    } else {
        log.info("Upgrading overlay from base design version " + status.getCompliantBaseVersion() + " to "
                + status.getCurrentBaseVersion());
    }

    // Creating new folders (Done separately because there may be empty folders in the overlay which would not be created via resource changes)
    for (String folder : status.getNewFolders()) {
        FileObject targetFile = targetFolder.resolveFile(folder);
        if (!targetFile.exists()) {
            log.info("Adding new overlay folder "
                    + targetFolder.getName().getRelativeName(targetFile.getName()));
            targetFile.createFolder();
        }
    }

    // Perform resource changes
    boolean conflictFileCreated = false;
    for (ChangedDocument resource : status.getChangedDocuments().values()) {
        if (performChange(resource, originalDesignProvider, status, targetEncoding, targetFolder, log,
                validator)) {
            conflictFileCreated = true;
        }
    }

    // Overwrite plugin version
    status.getOverlayData().setBasepluginVersion(baseId.getVersion().toString());

    // Write new overlay data file
    FileObject targetFCFolder = targetFolder.resolveFile(DesignDirectory.FOLDERNAME_FILES);
    FileObject systemFC = targetFCFolder.resolveFile("system");
    FileObject overlayDataFile = systemFC.resolveFile(OverlayDesignProvider.OVERLAY_DATA_FILE);
    OutputStream out = new BufferedOutputStream(overlayDataFile.getContent().getOutputStream(false));
    status.getOverlayData().write(out);
    out.flush();
    out.close();

    // Eventually update base-csconfig.xml
    FileObject baseCsConfigFile = originalDesignProvider.getFilesFolder().resolveFile("system/csconfig.xml");
    if (baseCsConfigFile.exists()) {
        String sourceHash = MD5HashingInputStream.getStreamHash(baseCsConfigFile.getContent().getInputStream());
        String targetHash = "";
        FileObject baseCsConfigFileOnOverlay = systemFC.resolveFile("base-csconfig.xml");
        if (baseCsConfigFileOnOverlay.exists()) {
            targetHash = MD5HashingInputStream
                    .getStreamHash(baseCsConfigFileOnOverlay.getContent().getInputStream());
        }
        if (!sourceHash.equals(targetHash)) {
            baseCsConfigFileOnOverlay.delete();
            FileUtil.copyContent(baseCsConfigFile, baseCsConfigFileOnOverlay);
        }
    }

    // Eventually update the dependency to the base plugin on csconfig.xml's plugin config
    FileObject overlayCsConfigFile = systemFC.resolveFile("csconfig.xml");
    if (overlayCsConfigFile.exists()) {
        CSConfig overlayCsConfig = CSConfig.load(overlayCsConfigFile);
        if (overlayCsConfig.getPluginConfig() != null) {
            boolean dependencyUpdated = false;
            for (PluginID id : overlayCsConfig.getPluginConfig().getDependencies()) {
                if (id.getUniqueName().equals(baseId.getUniqueName())
                        && !id.getVersion().equals(baseId.getVersion())) {
                    Version dependencyVersion = new Version(baseId.getVersion().getMajorVersion(),
                            baseId.getVersion().getMinorVersion(), baseId.getVersion().getMaintenanceVersion(),
                            baseId.getVersion().getPatchVersion(), 0);
                    id.setVersion(dependencyVersion);
                    dependencyUpdated = true;
                }
            }

            if (dependencyUpdated) {
                log.info("Updating dependency to base plugin in overlay plugin to new version "
                        + baseId.getVersion());
                overlayCsConfig.write(overlayCsConfigFile);
            }
        }
    }

    // Read/Write design configuration model to ensure correct storage versions of csconfig.xml (#00003634)
    FileObject designDefinitionFile = DesignDirectory.getDesignDefinitionFile(targetFolder);
    WGADesignConfigurationModel model = new WGADesignConfigurationModel(
            new File(designDefinitionFile.getName().getPath()));
    model.saveChanges();

    // Clear the overlay status
    status.overlayWasUpgraded();

    return conflictFileCreated;

}

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

public static OverlayStatus determineOverlayStatus(FileSystemDesignProvider sourceDesignProvider,
        PluginID baseId, FileObject targetDirectory, String targetEncoding, Logger log,
        DesignFileValidator validator) throws Exception {

    OverlayStatus status = new OverlayStatus();

    // Copy an overlay flag file to the system file container
    FileObject targetFCFolder = targetDirectory.resolveFile(DesignDirectory.FOLDERNAME_FILES);
    FileObject systemFC = targetFCFolder.resolveFile("system");
    if (!systemFC.exists()) {
        systemFC.createFolder();/*from w w w .j  a  va  2  s. c  o m*/
    }

    // Import overlay data, if available
    FileObject overlayDataFile = systemFC.resolveFile(OverlayDesignProvider.OVERLAY_DATA_FILE);
    if (overlayDataFile.exists()) {
        try {
            InputStream in = new BufferedInputStream(overlayDataFile.getContent().getInputStream());
            status.setOverlayData(OverlayData.read(in));
            in.close();
        } catch (Exception e) {
            log.error("Exception reading overlay status. Creating new status file", e);
        }

        if (status.getOverlayData() != null
                && !status.getOverlayData().getBasepluginName().equals(baseId.getUniqueName())) {
            throw new WGDesignSyncException("The overlay folder '" + targetDirectory.getName().getPath()
                    + "' is used with plugin '" + status.getOverlayData().getBasepluginName() + "' not '"
                    + baseId.getUniqueName() + "'. Overlay status determination was canceled.");
        }
    }

    Version providerVersion = baseId.getVersion();
    if (status.getOverlayData() == null) {
        OverlayData overlayData = new OverlayData();
        overlayData.setBasepluginName(baseId.getUniqueName());
        status.setOverlayData(overlayData);
        status.setNewOverlay(true);
        overlayData.setInitialBasepluginVersion(providerVersion.toString());
    }

    // Test for version compatibility between base design and overlay

    status.setCurrentBaseVersion(providerVersion);
    if (status.getOverlayData().getBasepluginVersion() != null) {
        Version baseVersion = new Version(status.getOverlayData().getBasepluginVersion());

        // Base design version is different than the compliance version of the overlay. Look if it higher (=upgrade) or lower (=error)
        if (!providerVersion.equals(baseVersion)
                || providerVersion.getBuildVersion() != baseVersion.getBuildVersion()) {
            if (providerVersion.compareTo(baseVersion) >= 0 || (providerVersion.equals(baseVersion)
                    && providerVersion.getBuildVersion() > baseVersion.getBuildVersion())) {
                status.setUpdatedBaseDesign(true);
            } else if (providerVersion.compareTo(baseVersion) < 0) {
                throw new WGDesignSyncException("The used base design version (" + providerVersion.toString()
                        + ") is lower than the compliant version for the overlay ("
                        + status.getOverlayData().getBasepluginVersion() + ").");
            }
        }

    }

    if (status.isUpdatedBaseDesign()) {
        log.info("Used version of base design is " + providerVersion.toString()
                + ". Overlay currently complies with base design version "
                + status.getOverlayData().getBasepluginVersion() + ". The overlay can be upgraded.");
    }

    // Gather changed resources in base design, so we can priorize them against the overlay resources
    FileObject sourceTmlFolder = sourceDesignProvider.getTmlFolder();
    FileObject targetTmlFolder = targetDirectory.resolveFile(DesignDirectory.FOLDERNAME_TML);
    if (sourceTmlFolder.exists() && sourceTmlFolder.getType().equals(FileType.FOLDER)) {
        for (FileObject mediaKeyFolder : sourceTmlFolder.getChildren()) {
            FileObject overlayFolder = mediaKeyFolder.resolveFile(OverlayDesignProvider.OVERLAY_FOLDER);
            if (overlayFolder.exists()) {
                FileObject targetMediaKeyFolder = targetTmlFolder
                        .resolveFile(mediaKeyFolder.getName().getBaseName());
                determineChangedResources(WGDocument.TYPE_TML, targetMediaKeyFolder, overlayFolder,
                        targetMediaKeyFolder, targetDirectory, sourceDesignProvider.getFileEncoding(),
                        targetEncoding, status, log, validator);
            }
        }
    }

    FileObject targetScriptFolder = targetDirectory.resolveFile(DesignDirectory.FOLDERNAME_SCRIPT);
    FileObject sourceScriptFolder = sourceDesignProvider.getScriptFolder();
    if (sourceScriptFolder.exists() && sourceScriptFolder.getType().equals(FileType.FOLDER)) {
        for (FileObject scriptTypeFolder : sourceScriptFolder.getChildren()) {
            FileObject overlayFolder = scriptTypeFolder.resolveFile(OverlayDesignProvider.OVERLAY_FOLDER);
            if (overlayFolder.exists()) {
                FileObject targetScriptTypeFolder = targetScriptFolder
                        .resolveFile(scriptTypeFolder.getName().getBaseName());
                determineChangedResources(WGDocument.TYPE_CSSJS, targetScriptTypeFolder, overlayFolder,
                        targetScriptTypeFolder, targetDirectory, sourceDesignProvider.getFileEncoding(),
                        targetEncoding, status, log, validator);
            }
        }
    }

    FileObject overlayFolder = sourceDesignProvider.getFilesFolder()
            .resolveFile(OverlayDesignProvider.OVERLAY_FOLDER);
    if (overlayFolder.exists()) {
        determineChangedFileContainerResources(targetFCFolder, overlayFolder, targetFCFolder, targetDirectory,
                null, null, status, log, validator);
    }

    return status;

}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void delete(String path) throws PublishException {
    String fullPath = targetFullPath(builder.getPath(), path);
    logger.debug("Delete file's path is {}", path);

    try {/*from w ww  .  ja  va2s  .  c  om*/
        FileObject root = getRootFileObject();
        path = path.replace("\\", "/").replace("//", "/");
        if (path.indexOf("/") == 0) {
            path = path.substring(1);
        }
        FileObject target = getTargetFileObject(root, path);

        if (target.exists()) {
            target.delete();
        }
        target.close();
        root.close();
    } catch (FileSystemException e) {
        logger.error("Delete {} file delete is error:{}", fullPath, e);
        throw new PublishException(e);
    }
}