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

int delete(FileSelector selector) throws FileSystemException;

Source Link

Document

Deletes all descendants of this file that match a selector.

Usage

From source file:org.pentaho.hadoop.shim.HadoopConfigurationLocatorTest.java

@BeforeClass
public static void setup() throws Exception {
    // Create a test hadoop configuration "a"
    FileObject ramRoot = VFS.getManager().resolveFile(HADOOP_CONFIGURATIONS_PATH);
    FileObject aConfigFolder = ramRoot.resolveFile("a");
    if (aConfigFolder.exists()) {
        aConfigFolder.delete(new AllFileSelector());
    }/* w  w  w.  ja  v a 2  s  . c  o  m*/
    aConfigFolder.createFolder();

    assertEquals(FileType.FOLDER, aConfigFolder.getType());

    // Create the properties file for the configuration as hadoop-configurations/a/config.properties
    configFile = aConfigFolder.resolveFile("config.properties");
    Properties p = new Properties();
    p.setProperty("name", "Test Configuration A");
    p.setProperty("classpath", "");
    p.setProperty("ignore.classes", "");
    p.setProperty("library.path", "");
    p.setProperty("required.classes", HadoopConfigurationLocatorTest.class.getName());
    p.store(configFile.getContent().getOutputStream(), "Test Configuration A");
    configFile.close();

    // Create the implementation jar
    FileObject implJar = aConfigFolder.resolveFile("a-config.jar");
    implJar.createFile();

    // Use ShrinkWrap to create the jar and write it out to VFS
    JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "a-configuration.jar")
            .addAsServiceProvider(HadoopShim.class, MockHadoopShim.class).addClass(MockHadoopShim.class);
    archive.as(ZipExporter.class).exportTo(implJar.getContent().getOutputStream());
}

From source file:org.pentaho.hadoop.shim.HadoopExcludeJarsTest.java

@BeforeClass
public static void setup() throws Exception {
    // Create a test hadoop configuration
    FileObject ramRoot = VFS.getManager().resolveFile(HADOOP_CONFIGURATIONS_PATH);
    if (ramRoot.exists()) {
        ramRoot.delete(new AllFileSelector());
    }//from  w  w  w  . j  a v  a2  s  .  com
    ramRoot.createFolder();

    // Create the implementation jars
    ramRoot.resolveFile("xercesImpl-2.9.1.jar").createFile();
    ramRoot.resolveFile("xml-apis-1.3.04.jar").createFile();
    ramRoot.resolveFile("xml-apis-ext-1.3.04.jar").createFile();
    ramRoot.resolveFile("xerces-version-1.8.0.jar").createFile();
    ramRoot.resolveFile("xercesImpl2-2.9.1.jar").createFile();
    ramRoot.resolveFile("pentaho-hadoop-shims-api-61.2016.04.01-196.jar").createFile();
    ramRoot.resolveFile("commands-3.3.0-I20070605-0010.jar").createFile();
    ramRoot.resolveFile("postgresql-9.3-1102-jdbc4.jar").createFile();
    ramRoot.resolveFile("trilead-ssh2-build213.jar").createFile();
    ramRoot.resolveFile("trilead-ssh2-build215.jar").createFile();
}

From source file:org.pentaho.hadoop.shim.HadoopRunningOnClusterTest.java

@BeforeClass
public static void setup() throws Exception {
    // Create a test hadoop configuration
    FileObject ramRoot = VFS.getManager().resolveFile(CONFIG_PROPERTY_CLASSPATH);
    if (ramRoot.exists()) {
        ramRoot.delete(new AllFileSelector());
    }/*from www .  ja va2  s. c  o m*/
    ramRoot.createFolder();

    // Create the implementation jars
    ramRoot.resolveFile("hadoop-mapreduce-client-app-2.7.0-mapr-1602.jar").createFile();
    ramRoot.resolveFile("hadoop-mapreduce-client-common-2.7.0-mapr-1602.jar").createFile();
    ramRoot.resolveFile("hadoop-mapreduce-client-contrib-2.7.0-mapr-1602.jar").createFile();
    ramRoot.resolveFile("hadoop-mapreduce-client-core-2.7.0-mapr-1602.jar").createFile();
    ramRoot.resolveFile("hadoop-mapreduce-client-hs-2.7.0-mapr-1602.jar").createFile();

    pmrFolder = tempFolder.newFolder("pmr");
    urlTestResources = Thread.currentThread().getContextClassLoader().getResource(PMR_PROPERTIES);
    Files.copy(Paths.get(urlTestResources.toURI()), Paths.get(pmrFolder.getAbsolutePath(), PMR_PROPERTIES));
}

From source file:org.wso2.carbon.transport.file.connector.sender.VFSClientConnector.java

@Override
public boolean send(CarbonMessage carbonMessage, CarbonCallback carbonCallback, Map<String, String> map)
        throws ClientConnectorException {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = map.get(Constants.FILE_URI);
    String action = map.get(Constants.ACTION);
    FileType fileType;/*from   www  .  j a  va 2  s . co m*/
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {

        case Constants.CREATE:
            boolean isFolder = Boolean.parseBoolean(map.getOrDefault("create-folder", "false"));
            if (path.exists()) {
                throw new ClientConnectorException("File already exists: " + path.getName().getURI());
            }
            if (isFolder) {
                path.createFolder();
            } else {
                path.createFile();
            }
            break;
        case Constants.WRITE:
            if (!path.exists()) {
                path.createFile();
                path.refresh();
                fileType = path.getType();
            }
            if (fileType == FileType.FILE) {
                if (carbonMessage instanceof BinaryCarbonMessage) {
                    BinaryCarbonMessage binaryCarbonMessage = (BinaryCarbonMessage) carbonMessage;
                    byteBuffer = binaryCarbonMessage.readBytes();
                } else {
                    throw new ClientConnectorException("Carbon message received is not a BinaryCarbonMessage");
                }
                byte[] bytes = byteBuffer.array();
                if (map.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(map.get(Constants.APPEND)));
                } else {
                    outputStream = path.getContent().getOutputStream();
                }
                outputStream.write(bytes);
                outputStream.flush();
            }
            break;
        case Constants.DELETE:
            if (path.exists()) {
                int filesDeleted = path.delete(Selectors.SELECT_ALL);
                if (logger.isDebugEnabled()) {
                    logger.debug(filesDeleted + " files successfully deleted");
                }
            } else {
                throw new ClientConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = map.get("destination");
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new ClientConnectorException(
                        "Failed to copy file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.MOVE:
            if (path.exists()) {
                //TODO: Improve this to fix issue #331
                String destination = map.get("destination");
                FileObject newPath = fsManager.resolveFile(destination, opts);
                FileObject parent = newPath.getParent();
                if (parent != null && !parent.exists()) {
                    parent.createFolder();
                }
                if (!newPath.exists()) {
                    path.moveTo(newPath);
                } else {
                    throw new ClientConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new ClientConnectorException(
                        "Failed to move file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.READ:
            if (path.exists()) {
                //TODO: Do not assume 'path' always refers to a file
                inputStream = path.getContent().getInputStream();
                byte[] bytes = toByteArray(inputStream);
                BinaryCarbonMessage message = new BinaryCarbonMessage(ByteBuffer.wrap(bytes), true);
                message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                        org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
                carbonMessageProcessor.receive(message, carbonCallback);
            } else {
                throw new ClientConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            TextCarbonMessage message = new TextCarbonMessage(Boolean.toString(path.exists()));
            message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                    org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
            carbonMessageProcessor.receive(message, carbonCallback);
            break;
        default:
            return false;
        }
    } catch (RuntimeException e) {
        throw new ClientConnectorException("Runtime Exception occurred : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new ClientConnectorException("Exception occurred while processing file: " + e.getMessage(), e);
    } finally {
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
    return true;
}

From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java

@Override
public void send(RemoteFileSystemMessage message) {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = connectorConfig.get(Constants.URI);
    String action = connectorConfig.get(Constants.ACTION);
    FileType fileType;// w  w w. j  a va  2  s  .co m
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    FileObject path = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {
        case Constants.CREATE:
            boolean isFolder = Boolean
                    .parseBoolean(connectorConfig.getOrDefault(Constants.CREATE_FOLDER, "false"));
            if (path.exists()) {
                throw new RemoteFileSystemConnectorException("File already exists: " + path.getName().getURI());
            }
            if (isFolder) {
                path.createFolder();
            } else {
                path.createFile();
            }
            break;
        case Constants.WRITE:
            if (!path.exists()) {
                path.createFile();
                path.refresh();
                fileType = path.getType();
            }
            if (fileType == FileType.FILE) {
                byteBuffer = message.getBytes();
                byte[] bytes = byteBuffer.array();
                if (connectorConfig.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(connectorConfig.get(Constants.APPEND)));
                } else {
                    outputStream = path.getContent().getOutputStream();
                }
                outputStream.write(bytes);
                outputStream.flush();
            }
            break;
        case Constants.DELETE:
            if (path.exists()) {
                int filesDeleted = path.delete(Selectors.SELECT_ALL);
                if (logger.isDebugEnabled()) {
                    logger.debug(filesDeleted + " files successfully deleted");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to copy file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.MOVE:
            if (path.exists()) {
                //TODO: Improve this to fix issue #331
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject newPath = fsManager.resolveFile(destination, opts);
                FileObject parent = newPath.getParent();
                if (parent != null && !parent.exists()) {
                    parent.createFolder();
                }
                if (!newPath.exists()) {
                    path.moveTo(newPath);
                } else {
                    throw new RemoteFileSystemConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to move file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.READ:
            if (path.exists()) {
                //TODO: Do not assume 'path' always refers to a file
                inputStream = path.getContent().getInputStream();
                byte[] bytes = toByteArray(inputStream);
                RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(ByteBuffer.wrap(bytes));
                remoteFileSystemListener.onMessage(fileContent);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(Boolean.toString(path.exists()));
            remoteFileSystemListener.onMessage(fileContent);
            break;
        default:
            break;
        }
        remoteFileSystemListener.done();
    } catch (RemoteFileSystemConnectorException | IOException e) {
        remoteFileSystemListener.onError(e);
    } finally {
        if (path != null) {
            try {
                path.close();
            } catch (FileSystemException e) {
                //Do nothing.
            }
        }
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
}

From source file:se.kth.hopsworks.zeppelin.notebook.repo.FSNotebookRepo.java

@Override
public void remove(String noteId) throws IOException {
    FileObject rootDir = fsManager.resolveFile(getPath("/"));
    FileObject projectDir = rootDir.resolveFile(this.project.getName(), NameScope.CHILD);
    if (!projectDir.exists() || !isDirectory(projectDir)) {
        // no project dir
        return;/*from  www  .  j a va  2 s . c om*/
    }
    FileObject noteDir = projectDir.resolveFile(noteId, NameScope.CHILD);

    if (!noteDir.exists()) {
        // nothing to do
        return;
    }

    if (!isDirectory(noteDir)) {
        // it is not look like zeppelin note savings
        throw new IOException("Can not remove " + noteDir.getName().toString());
    }

    noteDir.delete(Selectors.SELECT_SELF_AND_CHILDREN);
}

From source file:tain.kr.test.vfs.v01.Shell.java

/**
 * Does an 'rm' command.//from w  w  w  .j av  a2 s  . c  o m
 */
private void rm(final String[] cmd) throws Exception {

    if (cmd.length < 2) {
        throw new Exception("USAGE: rm <path>");
    }

    final FileObject file = mgr.resolveFile(cwd, cmd[1]);
    file.delete(Selectors.SELECT_SELF);
}

From source file:tain.kr.test.vfs.v01.TestVfs2FilehandleService.java

@Test
public void testCreateFile() throws Exception {

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(this.absoluteFilePath);
    final FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    // delete a file
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());// ww  w .  ja v a 2 s . c  o  m

    // create a file
    file.createFile();
    assertTrue(file.exists());
}

From source file:tain.kr.test.vfs.v01.TestVfs2FilehandleService.java

@Test
public void testAccessFile() throws Exception {

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(this.absoluteFilePath);
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    //   /*from  w  w  w.  j av a2 s .c o m*/
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());

    //  
    file.createFile();
    assertTrue(file.exists());

    FileContent fileContent = file.getContent();
    assertEquals(0, fileContent.getSize());

    //  
    String string = "test.";
    OutputStream os = fileContent.getOutputStream();

    try {
        os.write(string.getBytes());
        os.flush();
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }
    assertNotSame(0, fileContent.getSize());

    //  
    StringBuffer sb = new StringBuffer();
    FileObject writtenFile = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileContent writtenContents = writtenFile.getContent();
    InputStream is = writtenContents.getInputStream();

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }

    //  
    assertEquals(sb.toString(), string);
}

From source file:tain.kr.test.vfs.v01.TestVfs2FilehandleService.java

@Test
public void testCaching() throws Exception {

    String path = TestVfs2FilehandleService.class.getResource("").getPath();
    if (flag)// www .  j  av a2s  . c o m
        System.out.printf("[%s]\n", path);

    String testFolder = path + "/testfolder";
    FileSystemManager manager = VFS.getManager();

    FileObject scratchFolder = manager.resolveFile(testFolder);

    // testfolder    
    scratchFolder.delete(Selectors.EXCLUDE_SELF);

    FileObject file = manager.resolveFile(path + "/testfolder/dummy.txt");
    file.createFile();

    //  Manager 
    DefaultFileSystemManager fs = new DefaultFileSystemManager();
    fs.setFilesCache(manager.getFilesCache());

    // zip, jar, tgz, tar, tbz2, file
    if (!fs.hasProvider("file")) {
        fs.addProvider("file", new DefaultLocalFileProvider());
    }

    fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
    fs.init();

    //   
    FileObject foBase2 = fs.resolveFile(testFolder);
    if (flag)
        System.out.printf("## scratchFolder.getName().getPath() : %s\n", scratchFolder.getName().getPath());

    FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());

    //   
    FileObject[] fos = cachedFolder.getChildren();
    assertFalse(contains(fos, "file1.txt"));

    // 
    scratchFolder.resolveFile("file1.txt").createFile();

    //  
    // BUT cachedFolder    
    fos = cachedFolder.getChildren();
    assertFalse(contains(fos, "file1.txt"));

    // 
    cachedFolder.refresh();
    //  
    fos = cachedFolder.getChildren();
    assertTrue(contains(fos, "file1.txt"));
}