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

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

Introduction

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

Prototype

boolean delete() throws FileSystemException;

Source Link

Document

Deletes this file.

Usage

From source file:com.msopentech.odatajclient.testservice.utils.FSManager.java

public void deleteFile(final String relativePath) {

    for (Accept accept : Accept.values()) {
        final String path = getAbsolutePath(relativePath, accept);
        LOG.info("Delete {}", path);

        try {//from  w w w.  j  a v a  2s.  c  o m
            final FileObject fileObject = fsManager.resolveFile(MEM_PREFIX + path);

            if (fileObject.exists()) {
                fileObject.delete();
            }
        } catch (IOException ignore) {
            // ignore exception
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.remote.FTPRemoteDownloadSourceDelegate.java

@Override
void delete(String remotePath) throws IOException {
    FileObject fileObject = getChild(remotePath);
    fileObject.delete();
}

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 w  w w.java2s.  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

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

    try {//from www .j a  v a  2s.  c  o  m
        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);
    }
}

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 .j  av  a  2  s. c  o  m*/

        // 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.sludev.commons.vfs2.provider.azure.AzFileProviderTest.java

@Test
public void A007_deleteFile() throws Exception {
    String currAccountStr = testProperties.getProperty("azure.account.name");
    String currKey = testProperties.getProperty("azure.account.key");
    String currContainerStr = testProperties.getProperty("azure.test0001.container.name");
    String currHost = testProperties.getProperty("azure.host"); // <account>.blob.core.windows.net
    String currFileNameStr;/*from  w  ww .jav a 2 s.  c  om*/

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(AzConstants.AZSBSCHEME, new AzFileProvider());
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", AzConstants.AZSBSCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);

    log.info(String.format("deleting '%s'", currUriStr));

    Boolean delRes = currFile.delete();
    Assert.assertTrue(delRes);
}

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

protected static FileObject createConflictFile(FileObject targetFile) throws FileSystemException {
    String conflictFileName = targetFile.getName().getBaseName() + "_ovlconflict."
            + targetFile.getName().getExtension();
    targetFile = targetFile.getParent().resolveFile(conflictFileName);
    if (targetFile.exists()) {
        targetFile.delete();
    }//  w w  w.j av a  2 s . co  m
    return targetFile;
}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to delete lock file./*  w  w  w . j  a  v  a  2 s .c om*/
 * 
 * @param lockFilePath
 *            Lock file to be deleted
 * @throws FileSystemException
 *             If lock file deletion fails
 */
private void deleteLockFile(String lockFilePath) throws FileSystemException {
    FileObject lockFile = resolveFile(lockFilePath);
    log.debug("Deleting lock file: " + fileObjectNameForDebug(lockFile));
    lockFile.delete();
    lockFile.close();
}

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProviderTest.java

/**
 * Delete a previously uploaded file./*from w  w  w .j  a  v  a  2 s .c  om*/
 * 
 * @throws Exception 
 */
@Test
public void A006_deleteFile() throws Exception {
    String currAccountStr = testProperties.getProperty("s3.access.id");
    String currKey = testProperties.getProperty("s3.access.secret");
    String currContainerStr = testProperties.getProperty("s3.test0001.bucket.name");
    String currHost = testProperties.getProperty("s3.host");
    String currRegion = testProperties.getProperty("s3.region");
    String currFileNameStr;

    SS3FileProvider currSS3 = new SS3FileProvider();

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(SS3Constants.S3SCHEME, currSS3);
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", SS3Constants.S3SCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);

    log.info(String.format("deleting '%s'", currUriStr));

    Boolean delRes = currFile.delete();
    Assert.assertTrue(delRes);
}

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   ww  w.  j  a va2s  .c om

    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;

}