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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:org.codehaus.mojo.vfs.internal.DefaultMergeVfsMavenRepositories.java

public void merge(FileObject sourceRepo, FileObject targetRepo, File stagingDirectory, boolean dryRun)
        throws FileSystemException, IOException {
    FileObject stagingRepo = null;
    try {/*from  w w w . j  a v  a 2 s  .com*/
        stagingRepo = this.createStagingRepo(stagingDirectory);

        this.stageSource(sourceRepo, stagingRepo);

        this.mergeTargetMetadataToStageMetaData(targetRepo, stagingRepo);

        if (!dryRun) {
            this.pushStagingToTargetRepo(stagingRepo, targetRepo);
        }

    } catch (Exception e) {
        throw new RuntimeException("Unable to merge repositories.", e);
    } finally {

        if (!dryRun) {
            if (stagingRepo != null) {
                FileUtils.deleteDirectory(stagingRepo.getName().getPath());
            }
        }
    }
}

From source file:org.codehaus.mojo.vfs.internal.DefaultMergeVfsMavenRepositories.java

private void mergeTargetMetadataToStageMetaData(FileObject targetRepo, FileObject stagingRepo)
        throws IOException, XmlPullParserException {

    VfsFileSet fileset = new VfsFileSet();
    fileset.setSource(stagingRepo);/*  www.  j  a  v  a 2  s.co  m*/
    String[] includes = { "**/" + MAVEN_METADATA };
    fileset.setIncludes(includes);

    VfsFileSetManager fileSetManager = new DefaultVfsFileSetManager();
    List<FileObject> targetMetaFileObjects = fileSetManager.list(fileset);

    // Merge all metadata files
    for (FileObject sourceMetaFileObject : targetMetaFileObjects) {

        String relativeMetaPath = VfsUtils.getRelativePath(stagingRepo, sourceMetaFileObject);

        FileObject targetMetaFile = targetRepo.resolveFile(relativeMetaPath);
        FileObject stagingTargetMetaFileObject = stagingRepo.resolveFile(relativeMetaPath + IN_PROCESS_MARKER);

        try {
            stagingTargetMetaFileObject.copyFrom(targetMetaFile, Selectors.SELECT_ALL);
        } catch (FileSystemException e) {
            // We don't have an equivalent on the targetRepositoryUrl side because we have something
            // new on the sourceRepositoryUrl side so just skip the metadata merging.
            continue;
        }

        try {
            File targetMetaData = new File(stagingTargetMetaFileObject.getName().getPath());
            File sourceMetaData = new File(sourceMetaFileObject.getName().getPath());
            MavenMetadataUtils mavenMetadataUtils = new MavenMetadataUtils();
            mavenMetadataUtils.merge(targetMetaData, sourceMetaData);
            targetMetaData.delete();
        } catch (XmlPullParserException e) {
            throw new IOException(
                    "Metadata file is corrupt " + sourceMetaFileObject + " Reason: " + e.getMessage());
        }

    }

}

From source file:org.codehaus.mojo.vfs.internal.DefaultVfsDirectoryScanner.java

/**
 * Scans the given directory for files and directories. Found files are placed in a collection, based on the
 * matching of includes, excludes, and the selectors. When a directory is found, it is scanned recursively.
 *
 * @throws FileSystemException/*  w  w w.  j ava 2  s  .com*/
 * @see #includedFiles
 */
private void scanSubDir(FileObject dir, String relativePath) throws FileSystemException {

    FileObject[] children = dir.getChildren();

    for (FileObject child : children) {
        String newRelativePath = child.getName().getBaseName();
        if (!relativePath.isEmpty()) {
            newRelativePath = relativePath + "/" + child.getName().getBaseName();
        }

        if (this.isDirectory(child)) {
            if (!surelyExcluded(newRelativePath)) {
                // FIXME we need one more check to see if we really need to scan the subdir
                // to solve the case where includes="{'*'}", scanning sub-directory does not help
                // but only slow down the completion
                scanSubDir(child, newRelativePath);
            }
        } else {
            if (isIncluded(newRelativePath)) {
                if (!isExcluded(newRelativePath)) {
                    includedFiles.add(child);
                }
            }
        }
    }
}

From source file:org.codehaus.mojo.vfs.VfsFileSetManagerTest.java

@Test
public void testLocalFileListWithExcludes() throws Exception {
    String url = "file://" + basedir.getAbsolutePath();

    FileSystemManager fsManager = VFS.getManager();
    FileObject startDirectory = fsManager.resolveFile(url);

    VfsFileSet fileSet = new VfsFileSet();
    fileSet.setSource(startDirectory);/*from w  w  w.j  av a 2s  .  c o m*/
    String[] excludes = { "**/target/", "**/src/" };
    fileSet.setExcludes(excludes);

    List<FileObject> fos = fileSetManager.list(fileSet);
    Assert.assertTrue(fos.size() > 0);
    for (FileObject fo : fos) {
        //next assert will fail during release:perform since the source is checked out under target/checkout
        //Assert.assertFalse( fo.getName().getPath().contains( "/target/" ) );

        Assert.assertFalse(fo.getName().getPath().contains("/src/"));
    }

}

From source file:org.codehaus.mojo.vfs.VfsUtils.java

public static String getRelativePath(FileObject parent, FileObject child) throws FileSystemException {

    return parent.getName().getRelativeName(child.getName());
}

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

@Override
protected FileObject[] doInBackground() throws Exception {
    for (int i = 0; i < _urls.length; i++) {
        final String url = _urls[i];
        final FileObject file = _files[i];

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {//w  w  w  .jav a 2 s  .  co m
            byte[] buffer = new byte[1024];

            final HttpGet method = new HttpGet(url);

            if (!_cancelled) {
                final HttpResponse response = _httpClient.execute(method);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new InvalidHttpResponseException(url, response);
                }

                final HttpEntity responseEntity = response.getEntity();
                final long expectedSize = responseEntity.getContentLength();
                if (expectedSize > 0) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize);
                        }
                    });
                }

                inputStream = responseEntity.getContent();

                if (!file.exists()) {
                    file.createFile();
                }
                outputStream = file.getContent().getOutputStream();

                long bytes = 0;
                for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream
                        .read(buffer)) {
                    if (_cancelled) {
                        break;
                    }
                    outputStream.write(buffer, 0, numBytes);
                    bytes += numBytes;

                    final long totalBytes = bytes;
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes);
                        }
                    });
                }

                if (!_cancelled) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setFinished(file.getName().getBaseName());
                        }
                    });
                }
            }
        } catch (IOException e) {
            logger.debug("IOException occurred while downloading files", e);
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not close input stream: " + e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not flush & close output stream: " + e.getMessage(), e);
                }
            }

            _httpClient.close();
        }

        if (_cancelled) {
            logger.info("Deleting non-finished download-file '{}'", file);
            file.delete();
        }
    }

    return _files;
}

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

public void openFile(FileObject file) {
    if (file.getName().getBaseName().endsWith(FileFilters.ANALYSIS_RESULT_SER.getExtension())) {
        openAnalysisResult(file, _parentModule);
    } else {//from   w w w.  ja  v a 2s .  c om
        final Injector injector = openAnalysisJob(file);
        if (injector == null) {
            // this may happen, in which case the error was signalled to the
            // user already
            return;
        }

        final AnalysisJobBuilderWindow window = injector.getInstance(AnalysisJobBuilderWindow.class);
        window.open();

        if (_parentWindow != null && !_parentWindow.isDatastoreSet()) {
            _parentWindow.close();
        }
    }
}

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  .j  a  v a 2s. co m*/
    _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.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);
        }//from  w  w w  . j a v a  2  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;
    }
}

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

private static List<FileObject> validateVersionFolders(List<FileObject> versionFolders) {
    List<FileObject> validatedVersionFolders = new ArrayList<>();
    Integer currentMajorVersion = Version.getMajorVersion();
    if (currentMajorVersion == null) {
        return validatedVersionFolders;
    }/*from  www  . ja  v  a2s.  c om*/

    for (FileObject versionFolder : versionFolders) {
        String baseName = versionFolder.getName().getBaseName();

        String[] versionParts = baseName.split("\\.");

        try {
            int majorVersion = Integer.parseInt(versionParts[0]);
            if (majorVersion != currentMajorVersion) {
                continue;
            }
        } catch (NumberFormatException e) {
            continue;
        }

        boolean validated = true;
        for (String versionPart : versionParts) {
            if (versionPart.endsWith("-SNAPSHOT")) {
                versionPart = versionPart.substring(0, versionPart.lastIndexOf("-SNAPSHOT"));
            }
            try {
                Integer.parseInt(versionPart);
            } catch (NumberFormatException e) {
                logger.warn(
                        "Found a version folder in home directory ({}) with a part that could not be parsed to an integer: {} Removing this folder from potential upgrade candidates.",
                        baseName, versionPart);
                validated = false;
            }
        }
        if (validated) {
            validatedVersionFolders.add(versionFolder);
        }
    }
    return validatedVersionFolders;
}