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

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

Introduction

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

Prototype

FileObject getParent() throws FileSystemException;

Source Link

Document

Returns the folder that contains this file.

Usage

From source file:org.aludratest.service.file.impl.FileActionImpl.java

private void getOrCreateDirectory(FileObject directory) {
    FileObject root = configuration.getRootFolder();
    if (!root.equals(directory)) {
        try {/*from  www  .j ava  2  s .c  o m*/
            getOrCreateDirectory(directory.getParent());
            directory.createFolder();
        } catch (FileSystemException e) {
            throw new TechnicalException("Error creating directory", e);
        }
    }
}

From source file:org.aludratest.service.file.impl.FileInteractionImpl.java

/** Renames or moves a file or folder.
 * @param fromPath the file/folder to rename/move
 * @param toPath the new name/location of the file/folder
 * @param overwrite flag which indicates if an existing file may be overwritten by the operation
 * @return true if a formerly existing file was overwritten.
 * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
@Override//  w  w  w  .  j a va2 s . com
public boolean move(String fromPath, String toPath, boolean overwrite) {
    assertWritingPermitted("move()");
    File.verifyFilePath(fromPath);
    File.verifyFilePath(toPath);
    try {
        FileObject target = getFileObject(toPath);
        boolean existedBefore = checkWritable(target, overwrite); // NOSONAR
        getOrCreateDirectory(target.getParent());
        getFileObject(fromPath).moveTo(target);
        logger.debug("Moved {} to {}", fromPath, toPath);
        return existedBefore;
    } catch (IOException e) {
        throw new TechnicalException("Error moving file" + fromPath + " -> " + toPath, e);
    }
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader.java

static FileObject[] resolve(FileSystemManager vfs, String uris, ArrayList<FileObject> pathsToMonitor)
        throws FileSystemException {
    if (uris == null)
        return new FileObject[0];

    ArrayList<FileObject> classpath = new ArrayList<FileObject>();

    pathsToMonitor.clear();// w  w w . j a  v  a2  s.  c  o m

    for (String path : uris.split(",")) {

        path = path.trim();

        if (path.equals(""))
            continue;

        path = AccumuloClassLoader.replaceEnvVars(path, System.getenv());

        FileObject fo = vfs.resolveFile(path);

        switch (fo.getType()) {
        case FILE:
        case FOLDER:
            classpath.add(fo);
            pathsToMonitor.add(fo);
            break;
        case IMAGINARY:
            // assume its a pattern
            String pattern = fo.getName().getBaseName();
            if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
                pathsToMonitor.add(fo.getParent());
                FileObject[] children = fo.getParent().getChildren();
                for (FileObject child : children) {
                    if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
                        classpath.add(child);
                    }
                }
            } else {
                log.warn("ignoring classpath entry " + fo);
            }
            break;
        default:
            log.warn("ignoring classpath entry " + fo);
            break;
        }

    }

    return classpath.toArray(new FileObject[classpath.size()]);
}

From source file:org.apache.accumulo.start.classloader.vfs.providers.ReadOnlyHdfsFileProviderTest.java

@Test
public void testDoListChildren() throws Exception {
    FileObject fo = manager.resolveFile(TEST_DIR1);
    Assert.assertNotNull(fo);/*from   w  w  w.  j a  va  2 s  . c  o  m*/
    Assert.assertFalse(fo.exists());

    // Create the test file
    FileObject file = createTestFile(hdfs);
    FileObject dir = file.getParent();

    FileObject[] children = dir.getChildren();
    Assert.assertTrue(children.length == 1);
    Assert.assertTrue(children[0].getName().equals(file.getName()));

}

From source file:org.apache.metron.common.utils.VFSClassloaderUtil.java

/**
 * Resolve a set of URIs into FileObject objects.
 * This is not recursive. The URIs can refer directly to a file or directory or an optional regex at the end.
 * (NOTE: This is NOT a glob).//from   w  w  w.  j av  a  2 s  .c  om
 * @param vfs The file system manager to use to resolve URIs
 * @param uris comma separated URIs and URI + globs
 * @return
 * @throws FileSystemException
 */
static FileObject[] resolve(FileSystemManager vfs, String uris) throws FileSystemException {
    if (uris == null) {
        return new FileObject[0];
    }

    ArrayList<FileObject> classpath = new ArrayList<>();
    for (String path : uris.split(",")) {
        path = path.trim();
        if (path.equals("")) {
            continue;
        }
        FileObject fo = vfs.resolveFile(path);
        switch (fo.getType()) {
        case FILE:
        case FOLDER:
            classpath.add(fo);
            break;
        case IMAGINARY:
            // assume its a pattern
            String pattern = fo.getName().getBaseName();
            if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
                FileObject[] children = fo.getParent().getChildren();
                for (FileObject child : children) {
                    if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
                        classpath.add(child);
                    }
                }
            } else {
                LOG.warn("ignoring classpath entry " + fo);
            }
            break;
        default:
            LOG.warn("ignoring classpath entry " + fo);
            break;
        }
    }
    return classpath.toArray(new FileObject[classpath.size()]);
}

From source file:org.apache.metron.stellar.common.utils.VFSClassloaderUtil.java

/**
 * Resolve a set of URIs into FileObject objects.
 * This is not recursive. The URIs can refer directly to a file or directory or an optional regex at the end.
 * (NOTE: This is NOT a glob).// www .  j  ava  2  s  .  com
 * @param vfs The file system manager to use to resolve URIs
 * @param uris comma separated URIs and URI + globs
 * @return
 * @throws FileSystemException
 */
static FileObject[] resolve(FileSystemManager vfs, String uris) throws FileSystemException {
    if (uris == null) {
        return new FileObject[0];
    }

    ArrayList<FileObject> classpath = new ArrayList<>();
    for (String path : uris.split(",")) {
        path = path.trim();
        if (path.equals("")) {
            continue;
        }
        FileObject fo = vfs.resolveFile(path);
        switch (fo.getType()) {
        case FILE:
        case FOLDER:
            classpath.add(fo);
            break;
        case IMAGINARY:
            // assume its a pattern
            String pattern = fo.getName().getBaseName();
            if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
                FileObject[] children = fo.getParent().getChildren();
                for (FileObject child : children) {
                    if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
                        classpath.add(child);
                    }
                }
            } else {
                LOG.warn("ignoring classpath entry {}", fo);
            }
            break;
        default:
            LOG.warn("ignoring classpath entry {}", fo);
            break;
        }
    }
    return classpath.toArray(new FileObject[classpath.size()]);
}

From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java

private void closeFileSystem(FileObject fileObject) {
    try {/*from   w  ww . j a va2  s  .  c  om*/
        //Close the File system if it is not already closed by the finally block of processFile method
        if (fileObject != null && !isFileSystemClosed() && fsManager != null && fileObject.getParent() != null
                && fileObject.getParent().getFileSystem() != null) {
            fsManager.closeFileSystem(fileObject.getParent().getFileSystem());
            fileObject.close();
            setFileSystemClosed(true);
        }
    } catch (FileSystemException warn) {
        //  log.warn("Cannot close file after processing : " + file.getName().getPath(), warn);
        // ignore the warning, since we handed over the stream close job to AutocloseInputstream..
    }
}

From source file:org.datacleaner.actions.SaveAnalysisJobActionListener.java

@Override
public void actionPerformed(ActionEvent event) {
    final String actionCommand = event.getActionCommand();

    _window.setStatusLabelNotice();//from w w w  . jav  a  2s. com
    _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB);

    AnalysisJob analysisJob = null;
    try {
        _window.applyPropertyValues();
        analysisJob = _analysisJobBuilder.toAnalysisJob();
    } catch (Exception e) {
        if (e instanceof NoResultProducingComponentsException) {
            int result = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "You job does not have any result-producing components in it, and is thus 'incomplete'. Do you want to save it anyway?",
                    "No result producing components in job", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
            if (result == JOptionPane.YES_OPTION) {
                analysisJob = _analysisJobBuilder.toAnalysisJob(false);
            } else {
                return;
            }
        } else {
            String detail = _window.getStatusLabelText();
            if (LABEL_TEXT_SAVING_JOB.equals(detail)) {
                detail = e.getMessage();
            }
            WidgetUtils.showErrorMessage("Errors in job",
                    "Please fix the errors that exist in the job before saving it:\n\n" + detail, e);
            return;
        }
    }

    final FileObject existingFile = _window.getJobFile();

    final FileObject file;
    if (existingFile == null || ACTION_COMMAND_SAVE_AS.equals(actionCommand)) {
        // ask the user to select a file to save to ("Save as" scenario)
        final DCFileChooser fileChooser = new DCFileChooser(_userPreferences.getAnalysisJobDirectory());
        fileChooser.setFileFilter(FileFilters.ANALYSIS_XML);

        final int result = fileChooser.showSaveDialog(_window.toComponent());
        if (result != JFileChooser.APPROVE_OPTION) {
            return;
        }
        final FileObject candidate = fileChooser.getSelectedFileObject();

        final boolean exists;
        try {
            final String baseName = candidate.getName().getBaseName();
            if (!baseName.endsWith(".xml")) {
                final FileObject parent = candidate.getParent();
                file = parent.resolveFile(baseName + FileFilters.ANALYSIS_XML.getExtension());
            } else {
                file = candidate;
            }
            exists = file.exists();
        } catch (FileSystemException e) {
            throw new IllegalStateException("Failed to prepare file for saving", e);
        }

        if (exists) {
            int overwrite = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "Are you sure you want to overwrite the file '" + file.getName() + "'?",
                    "Overwrite existing file?", JOptionPane.YES_NO_OPTION);
            if (overwrite != JOptionPane.YES_OPTION) {
                return;
            }
        }
    } else {
        // overwrite existing file ("Save" scenario).
        file = existingFile;
    }

    try {
        final FileObject parent = file.getParent();
        final File parentFile = VFSUtils.toFile(parent);
        if (parentFile != null) {
            _userPreferences.setAnalysisJobDirectory(parentFile);
        }
    } catch (FileSystemException e) {
        logger.warn("Failed to determine parent of {}: {}", file, e.getMessage());
    }

    final AnalysisJobMetadata existingMetadata = analysisJob.getMetadata();
    final String jobName = existingMetadata.getJobName();
    final String jobVersion = existingMetadata.getJobVersion();

    final String author;
    if (Strings.isNullOrEmpty(existingMetadata.getAuthor())) {
        author = System.getProperty("user.name");
    } else {
        author = existingMetadata.getAuthor();
    }

    final String jobDescription;
    if (Strings.isNullOrEmpty(existingMetadata.getJobDescription())) {
        jobDescription = "Created with DataCleaner " + Version.getEdition() + " " + Version.getVersion();
    } else {
        jobDescription = existingMetadata.getJobDescription();
    }

    final JaxbJobWriter writer = new JaxbJobWriter(_configuration,
            new JaxbJobMetadataFactoryImpl(author, jobName, jobDescription, jobVersion));

    OutputStream outputStream = null;
    try {
        outputStream = file.getContent().getOutputStream();
        writer.write(analysisJob, outputStream);
    } catch (IOException e1) {
        throw new IllegalStateException(e1);
    } finally {
        FileHelper.safeClose(outputStream);
    }

    if (file instanceof DelegateFileObject) {
        // this "file" is probably a HTTP URL resource (often provided by DC
        // monitor)
        final DelegateFileObject delegateFileObject = (DelegateFileObject) file;
        final String scheme = file.getName().getScheme();

        if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
            final String uri = delegateFileObject.getName().getURI();
            final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();
            if (monitorConnection.matchesURI(uri) && monitorConnection.isAuthenticationEnabled()
                    && monitorConnection.getEncodedPassword() == null) {
                // password is not configured, ask for it.
                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(_window.getWindowContext(),
                        _userPreferences);
                dialog.openBlocking();
            }

            final PublishJobToMonitorActionListener publisher = new PublishJobToMonitorActionListener(
                    delegateFileObject, _window.getWindowContext(), _userPreferences);
            publisher.actionPerformed(event);
        } else {
            throw new UnsupportedOperationException("Unexpected delegate file object: " + delegateFileObject
                    + " (delegate: " + delegateFileObject.getDelegateFile() + ")");
        }
    } else {
        _userPreferences.addRecentJobFile(file);
    }

    _window.setJobFile(file);

    _window.setStatusLabelNotice();
    _window.setStatusLabelText("Saved job to file " + file.getName().getBaseName());
}

From source file:org.datacleaner.user.DataCleanerHome.java

private static FileObject copyIfNonExisting(FileObject candidate, FileSystemManager manager, String filename)
        throws FileSystemException {
    FileObject file = candidate.resolveFile(filename);
    if (file.exists()) {
        logger.info("File already exists in DATACLEANER_HOME: " + filename);
        return file;
    }//from  ww w  . j a  va 2s.  c  om
    FileObject parentFile = file.getParent();
    if (!parentFile.exists()) {
        parentFile.createFolder();
    }

    final ResourceManager resourceManager = ResourceManager.get();
    final URL url = resourceManager.getUrl("datacleaner-home/" + filename);
    if (url == null) {
        return null;
    }

    InputStream in = null;
    OutputStream out = null;
    try {
        in = url.openStream();
        out = file.getContent().getOutputStream();

        FileHelper.copy(in, out);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        FileHelper.safeClose(in, out);
    }

    return file;
}

From source file:org.datacleaner.user.upgrade.DataCleanerHomeUpgrader.java

private FileObject findUpgradeCandidate(FileObject target) throws FileSystemException {
    FileObject parentFolder = target.getParent();

    List<FileObject> versionFolders = new ArrayList<>();
    FileObject[] allFoldersInParent = parentFolder.findFiles(new FileDepthSelector(1, 1));
    for (FileObject folderInParent : allFoldersInParent) {
        final String folderInParentName = folderInParent.getName().getBaseName();
        if (folderInParent.getType().equals(FileType.FOLDER)
                && (!folderInParentName.equals(target.getName().getBaseName()))
                && (!candidateBlacklist.contains(folderInParentName))) {
            versionFolders.add(folderInParent);
        }/* w  w w  . j  a  va2  s .c  o m*/
    }

    List<FileObject> validatedVersionFolders = validateVersionFolders(versionFolders);

    if (!validatedVersionFolders.isEmpty()) {

        List<String> versions = new ArrayList<>();
        for (FileObject validatedVersionFolder : validatedVersionFolders) {
            String baseName = validatedVersionFolder.getName().getBaseName();
            versions.add(baseName);
        }

        final Comparator<String> comp = new VersionComparator();
        String latestVersion = Collections.max(versions, comp);
        FileObject latestVersionFolder = null;
        for (FileObject validatedVersionFolder : validatedVersionFolders) {
            if (validatedVersionFolder.getName().getBaseName().equals(latestVersion)) {
                latestVersionFolder = validatedVersionFolder;
            }
        }
        return latestVersionFolder;
    } else {
        return null;
    }
}