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:net.sf.jabb.web.action.VfsTreeAction.java

/**
 * Populate a node.// w ww . j av  a  2s  . c om
 * @param root      Relative root directory.
 * @param file      The file object.
 * @return   The node data structure which presents the file.
 * @throws FileSystemException
 */
protected JsTreeNodeData populateTreeNodeData(FileObject root, FileObject file) throws FileSystemException {
    boolean noChild = true;
    FileType type = file.getType();
    if (type.equals(FileType.FOLDER) || type.equals(FileType.FILE_OR_FOLDER)) {
        noChild = file.getChildren().length == 0;
    }
    String relativePath = root.getName().getRelativeName(file.getName());
    return populateTreeNodeData(file, noChild, relativePath);
}

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

private static void determineChangedFileContainerResources(FileObject categoryFolder, FileObject source,
        FileObject target, FileObject baseFolder, String sourceEncoding, String targetEncoding,
        OverlayStatus status, Logger log, DesignFileValidator validator)
        throws WGDesignSyncException, NoSuchAlgorithmException, IOException {

    String targetResourcePath = baseFolder.getName().getRelativeName(target.getName());
    Set<String> involvedFiles = new HashSet<String>();

    // Completely new folder is a new file container
    if (!target.exists()) {

        status.addChangedResource(WGDocument.TYPE_FILECONTAINER, source, target, categoryFolder, ChangeType.NEW,
                targetResourcePath, null);
        // Als add all subfolders
        for (FileObject sourceFile : source.getChildren()) {
            if (sourceFile.getType().equals(FileType.FOLDER)) {
                FileObject targetFile = target.resolveFile(sourceFile.getName().getBaseName());
                determineChangedFileContainerResources(categoryFolder, sourceFile, targetFile, baseFolder,
                        sourceEncoding, targetEncoding, status, log, validator);
            }//from   w w w .  j av  a  2  s  . co  m
        }
        return;
    }

    if (target.getType().equals(FileType.FILE)) {
        throw new WGDesignSyncException(
                "Unable to apply overlay. Folder '" + baseFolder.getName().getRelativeName(target.getName())
                        + " already exists as file. Delete it to enable overlay management again");
    }

    // Determine change type by iterating through source child files and compare with target
    boolean overlayChanged = false;
    boolean baseChanged = false;
    boolean directConflict = false;

    for (FileObject sourceFile : source.getChildren()) {
        if (!isValidDesignFile(sourceFile, validator)) {
            continue;
        }

        FileObject targetFile = target.resolveFile(sourceFile.getName().getBaseName());
        String fileResourcePath = baseFolder.getName().getRelativeName(targetFile.getName());

        if (sourceFile.getType().equals(FileType.FOLDER)) {
            // Descend onto subcontainer
            determineChangedFileContainerResources(categoryFolder, sourceFile, targetFile, baseFolder,
                    sourceEncoding, targetEncoding, status, log, validator);
        } else if (sourceFile.getType().equals(FileType.FILE)) {

            // File does not exist. Look if it was once deployed.
            if (!targetFile.exists()) {

                ResourceData resourceData = status.getOverlayData().getOverlayResources().get(fileResourcePath);
                if (resourceData != null) {
                    // Did already exist. But did it have the same content?
                    String newHash = MD5HashingInputStream
                            .getStreamHash(sourceFile.getContent().getInputStream());
                    if (newHash.equals(resourceData.getMd5Hash())) {
                        overlayChanged = true;
                        involvedFiles.add(sourceFile.getName().getBaseName() + " (removed in overlay)");
                    } else {
                        baseChanged = true;
                        overlayChanged = true;
                        directConflict = true;
                        involvedFiles.add(
                                sourceFile.getName().getBaseName() + " (removed in overlay, changed in base)");
                    }

                }

                // Did not yet exist. It is a new file in the base version.
                else {
                    baseChanged = true;
                    involvedFiles.add(sourceFile.getName().getBaseName() + " (new in base)");
                }

            }

            // File does exist: Determine if is updated in base since the overlay file was deployed
            else {

                ResourceData originalHash = status.getOverlayData().getOverlayResources().get(fileResourcePath);
                if (originalHash == null) {
                    log.warn("There is no information about the original deployment state of resource '"
                            + fileResourcePath + "' so its change status cannot be determined.");
                    OverlayData.ResourceData resource = new OverlayData.ResourceData();
                    resource.setMd5Hash(
                            MD5HashingInputStream.getStreamHash(sourceFile.getContent().getInputStream()));
                    status.getOverlayData().setOverlayResource(fileResourcePath, resource);
                    continue;
                }

                // First determine if the resource really changed from what was distributed
                String newHash = MD5HashingInputStream.getStreamHash(sourceFile.getContent().getInputStream());
                if (newHash.equals(originalHash.getMd5Hash())) {
                    continue;
                }

                // Determine if the target file is the same as was distributed. If not then it was user modified, so it is a conflict
                String currentHash = MD5HashingInputStream
                        .getStreamHash(targetFile.getContent().getInputStream());
                if (!currentHash.equals(originalHash.getMd5Hash())) {
                    overlayChanged = true;
                    baseChanged = true;
                    directConflict = true;
                    involvedFiles.add(sourceFile.getName().getBaseName() + " (changed in base and overlay)");
                    break;
                }

                // It is a normal change
                else {
                    baseChanged = true;
                    involvedFiles.add(sourceFile.getName().getBaseName() + " (changed in base)");
                }
            }
        }
    }

    // Test the target files. Files may have been added there, or files from the previous base version may still be present that got deleted in the new base version.
    if (!baseChanged || !overlayChanged) {
        for (FileObject targetFile : target.getChildren()) {
            FileObject sourceFile = source.resolveFile(targetFile.getName().getBaseName());
            if (!sourceFile.exists()) {

                // Look if it was deployed with the previous base version.
                String fileResourcePath = baseFolder.getName().getRelativeName(targetFile.getName());
                ResourceData resourceData = status.getOverlayData().getOverlayResources().get(fileResourcePath);
                if (resourceData != null) {
                    // Was deployed. But with same contents?
                    String targetHash = MD5HashingInputStream
                            .getStreamHash(targetFile.getContent().getInputStream());
                    if (targetHash.equals(resourceData.getMd5Hash())) {
                        // This is a file that was from previous base version and got removed in the new base version.
                        involvedFiles.add(targetFile.getName().getBaseName() + " (removed from base)");
                        baseChanged = true;
                    }

                    // File got removed in new base version, updated in overlay. Conflict.
                    else {
                        baseChanged = true;
                        overlayChanged = true;
                        directConflict = true;
                        involvedFiles.add(targetFile.getName().getBaseName()
                                + " (removed from base, changed in overlay)");
                        break;
                    }
                } else {
                    involvedFiles.add(targetFile.getName().getBaseName() + " (new in overlay)");
                    overlayChanged = true;
                }
            }
        }
    }

    // Determine change type based on the found changes
    ChangeType changeType = null;
    if (baseChanged) {
        if (overlayChanged) {
            changeType = ChangeType.CONFLICT;
        } else {
            changeType = ChangeType.CHANGED;
        }
    }

    if (changeType != null) {
        status.addChangedResource(WGDocument.TYPE_FILECONTAINER, source, target, categoryFolder, changeType,
                targetResourcePath, involvedFiles);
    }

}

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 a  va 2  s  .  co  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:net.sourceforge.fullsync.ui.FileObjectChooser.java

private void populateList() throws FileSystemException {
    FileObject[] children = activeFileObject.getChildren();
    Arrays.sort(children, (o1, o2) -> {
        try {//  w ww . j a v  a2 s .  c o m
            if ((o1.getType() == FileType.FOLDER) && (o2.getType() == FileType.FILE)) {
                return -1;
            } else if ((o1.getType() == FileType.FILE) && (o2.getType() == FileType.FOLDER)) {
                return 1;
            }
            return o1.getName().getBaseName().compareTo(o2.getName().getBaseName());
        } catch (FileSystemException fse) {
            fse.printStackTrace();
            return 0;
        }
    });

    DateFormat df = DateFormat.getDateTimeInstance();

    for (int i = 0; i < children.length; i++) {
        FileObject data = children[i];

        TableItem item;
        if (tableItems.getItemCount() <= i) {
            item = new TableItem(tableItems, SWT.NULL);
        } else {
            item = tableItems.getItem(i);
        }

        item.setText(0, data.getName().getBaseName());
        String type = data.getType().getName(); //FIXME: translate type name {file,folder}

        if (data.getType().hasContent()) {
            FileContent content = data.getContent();
            String contentType = content.getContentInfo().getContentType();
            if (null != contentType) {
                type += " (" + contentType + ")"; //$NON-NLS-1$ //$NON-NLS-2$
            }
            item.setText(1, String.valueOf(content.getSize()));
            item.setText(3, df.format(new Date(content.getLastModifiedTime())));
        } else {
            item.setText(1, ""); //$NON-NLS-1$
            item.setText(3, ""); //$NON-NLS-1$
        }
        item.setText(2, type);

        if (data.getType() == FileType.FOLDER) {
            item.setImage(imageRepository.getImage("FS_Folder_Collapsed.gif")); //$NON-NLS-1$
        } else {
            item.setImage(imageRepository.getImage("FS_File_text_plain.gif")); //$NON-NLS-1$
        }

        item.setData(data);
    }
    tableItems.setItemCount(children.length);
}

From source file:com.flicklib.folderscanner.AdvancedFolderScanner.java

/**
 * //from   www  .  j  a v  a 2  s. co  m
 * @param folder
 * @param monitor 
 * @return true, if it contained movie file
 * @throws InterruptedException 
 * @throws FileSystemException 
 */
private boolean browse(FileObject folder, AsyncMonitor monitor)
        throws InterruptedException, FileSystemException {
    URL url = folder.getURL();
    LOGGER.trace("entering " + url);
    FileObject[] files = folder.getChildren();
    if (monitor != null) {
        if (monitor.isCanceled()) {
            throw new InterruptedException("at " + url);
        }
        monitor.step("scanning " + url);
    }

    Set<String> plainFileNames = new HashSet<String>();
    int subDirectories = 0;
    int compressedFiles = 0;
    Set<String> directoryNames = new HashSet<String>();
    for (FileObject f : files) {
        if (isDirectory(f)) {
            subDirectories++;
            directoryNames.add(f.getName().getBaseName().toLowerCase());
        } else {
            String ext = getExtension(f);
            if (ext == null) {
                LOGGER.trace("Ignoring file without extension: " + f.getURL());
            } else {
                if (MovieFileType.getTypeByExtension(ext) == MovieFileType.COMPRESSED) {
                    compressedFiles++;
                }
                if (ext != null && MovieFileFilter.VIDEO_EXTENSIONS.contains(ext)) {
                    plainFileNames.add(getNameWithoutExt(f));
                }
            }
        }
    }
    // check for multiple compressed files, the case of:
    // Title_of_the_film/abc.rar
    // Title_of_the_film/abc.r01
    // Title_of_the_film/abc.r02
    if (compressedFiles > 0) {
        FileGroup fg = initStorableMovie(folder);
        fg.getLocations().add(new FileLocation(currentLabel, folder.getURL()));
        addCompressedFiles(fg, files);
        add(fg);
        return true;
    }
    if (subDirectories >= 2 && subDirectories <= 5) {
        // the case of :
        // Title_of_the_film/cd1/...
        // Title_of_the_film/cd2/...
        // with an optional sample/subs directory
        // Title_of_the_film/sample/
        // Title_of_the_film/subs/
        // Title_of_the_film/subtitles/
        // or
        // Title_of_the_film/bla1.avi
        // Title_of_the_film/bla2.avi
        // Title_of_the_film/sample/
        // Title_of_the_film/subs/
        if (isMovieFolder(directoryNames)) {
            FileGroup fg = initStorableMovie(folder);
            fg.getLocations().add(new FileLocation(currentLabel, folder.getURL()));
            for (String cdFolder : getCdFolders(directoryNames)) {
                addCompressedFiles(fg, files, cdFolder);
            }
            for (FileObject file : folder.getChildren()) {
                if (!isDirectory(file)) {
                    String ext = getExtension(file);
                    if (MovieFileFilter.VIDEO_EXT_EXTENSIONS.contains(ext)) {
                        fg.getFiles().add(createFileMeta(file, MovieFileType.getTypeByExtension(ext)));
                    }
                }
            }
            add(fg);
            return true;
        }
    }
    boolean subFolderContainMovie = false;
    for (FileObject f : files) {
        final String baseName = f.getName().getBaseName();
        if (isDirectory(f) && !baseName.equalsIgnoreCase("sample") && !baseName.startsWith(".")) {
            subFolderContainMovie |= browse(f, monitor);
        }
    }

    // We want to handle the following cases:
    // 1,
    // Title_of_the_film/abc.avi
    // Title_of_the_film/abc.srt
    // --> no subdirectory, one film -> the title should be name of the
    // directory
    //  
    // 2,
    // Title_of_the_film/abc-cd1.avi
    // Title_of_the_film/abc-cd1.srt
    // Title_of_the_film/abc-cd2.srt
    // Title_of_the_film/abc-cd2.srt
    //

    if (subDirectories > 0 && subFolderContainMovie) {
        return genericMovieFindProcess(files) || subFolderContainMovie;
    } else {

        int foundFiles = plainFileNames.size();
        switch (foundFiles) {
        case 0:
            return subFolderContainMovie;
        case 1: {
            FileGroup fg = initStorableMovie(folder);
            fg.getLocations().add(new FileLocation(currentLabel, folder.getURL()));
            addFiles(fg, files, plainFileNames.iterator().next());
            add(fg);
            return true;
        }
        case 2: {
            Iterator<String> it = plainFileNames.iterator();
            String name1 = it.next();
            String name2 = it.next();
            if (LevenshteinDistance.distance(name1, name2) < 3) {
                // the difference is -cd1 / -cd2
                FileGroup fg = initStorableMovie(folder);

                fg.getLocations().add(new FileLocation(currentLabel, folder.getURL()));
                addFiles(fg, files, name1);
                add(fg);
                return true;
            }
            // the difference is significant, we use the generic
            // solution
        }
        default: {
            return genericMovieFindProcess(files);
        }
        }
    }
}

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

/**
 * Helper method to execute file move operation.
 * //w ww . j av  a  2  s  .co m
 * @param file
 *            FileObject of the file to be moved
 * @param toDirectoryPath
 * @return true if give file was a file and it was successfully moved to
 *         destination directory. False if given file is not a file or given
 *         destination directory is not a directory
 * @throws FileSystemException
 *             If file move operation fails
 */
private boolean moveFile(FileObject file, String toDirectoryPath, boolean lockEnabled)
        throws FileSystemException {
    if (file.getType() == FileType.FILE) {
        String targetPath = toDirectoryPath + "/" + file.getName().getBaseName();
        String lockFilePath = null;
        if (lockEnabled) {
            lockFilePath = createLockFile(targetPath);
        }
        FileObject newLocation = resolveFile(targetPath);
        try {
            log.debug("About to move " + fileObjectNameForDebug(file) + " to "
                    + fileObjectNameForDebug(newLocation));

            if (options.isStreamingTransferEnabled()) {
                streamFromFileToFile(file, resolveFile(targetPath));
            } else {
                newLocation.copyFrom(file, Selectors.SELECT_SELF);
            }

            newLocation.close();
            file.delete();
            file.close();
            log.debug("File moved to " + fileObjectNameForDebug(newLocation));
        } finally {
            if (lockFilePath != null) {
                deleteLockFile(lockFilePath);
            }
        }
        return true;
    } else {
        return false;
    }
}

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

/**
 * Helper method to execute file copy operation.
 * /*  www .j ava2 s  . c  o  m*/
 * @param file
 *            FileObject of the file to be copied
 * @param targetDirectoryPath
 *            FileObject of the target directory where the file will be
 *            copied
 * @return true if give file was a file and it was successfully copied to
 *         destination directory. False if given file is not a file or given
 *         destination directory is not a directory
 * @throws FileSystemException
 *             If file copy operation fails
 */
private boolean copyFile(FileObject file, String targetDirectoryPath, boolean lockEnabled)
        throws FileSystemException {
    if (file.getType() == FileType.FILE) {
        String targetPath = targetDirectoryPath + "/" + file.getName().getBaseName();
        String lockFilePath = null;
        if (lockEnabled) {
            lockFilePath = createLockFile(targetPath);
        }
        FileObject newLocation = resolveFile(targetPath);
        try {
            log.debug("About to copy " + fileObjectNameForDebug(file) + " to "
                    + fileObjectNameForDebug(newLocation));

            if (options.isStreamingTransferEnabled()) {
                streamFromFileToFile(file, resolveFile(targetPath));
            } else {
                newLocation.copyFrom(file, Selectors.SELECT_SELF);
            }

            newLocation.close();
            file.close();
            log.debug("File copied to " + fileObjectNameForDebug(newLocation));
        } finally {
            if (lockFilePath != null) {
                deleteLockFile(lockFilePath);
            }
        }
        return true;
    } else {
        return false;
    }
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

protected void addLibDirectoryJarsToClasspath(FileObject serviceRoot, VirtualFileSystemClassLoader cl)
        throws FileSystemException {
    /*//from w ww  . j  a v a 2  s. c  o  m
     Add the jar files from the service's 'lib' directory.
     */
    FileObject libDir = serviceRoot.resolveFile(Strings.LIB);
    List<FileObject> jarFiles = Utils.findChildrenWithSuffix(libDir, Strings.DOT_JAR);
    for (FileObject jarFile : jarFiles) {
        cl.addClassPathEntry(libDir, jarFile.getName().getBaseName());
    }
}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

private void addTableItem(Table table, FileObject file) throws FileSystemException {
    if (file.getType() == FileType.FILE) {
        Item item = table.addItem(file.getName());
        item.getItemProperty(TABLE_PROP_FILE_NAME).setValue(file.getName().toString());
        item.getItemProperty(TABLE_PROP_FILE_SIZE).setValue(file.getContent().getSize());
        item.getItemProperty(TABLE_PROP_FILE_DATE).setValue(new Date(file.getContent().getLastModifiedTime()));
    }/*w  ww.j a va 2s  .  c o  m*/
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private String findServiceName(FileObject serviceArchive, FileObject serviceRoot) {
    if (serviceArchive != null) {
        return serviceArchive.getName().getBaseName();
    }/*from   w ww. ja v a  2 s .  co  m*/
    return serviceRoot.getName().getBaseName();
}