Example usage for org.apache.commons.vfs FileObject isReadable

List of usage examples for org.apache.commons.vfs FileObject isReadable

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject isReadable.

Prototype

public boolean isReadable() throws FileSystemException;

Source Link

Document

Determines if this file can be read.

Usage

From source file:org.jboss.dashboard.ui.formatters.FileNavigationFileListFormatter.java

public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException {
    try {/*from  ww w .j  a  v a2  s.c om*/
        FileObject currentPath = getFileNavigationHandler().getCurrentDir();
        if (currentPath != null) {
            FileObject[] children = currentPath.getChildren();
            List sortedChildren = new ArrayList();
            for (int i = 0; i < children.length; i++) {
                FileObject child = children[i];
                if (child.getType().equals(FileType.FILE) && child.isReadable() && !child.isHidden()) {
                    if (matchesPattern(child, getFileNavigationHandler().getCurrentFilter()))
                        sortedChildren.add(child);
                }
            }
            sortFiles(sortedChildren);
            renderFiles(sortedChildren);
        }
    } catch (FileSystemException e) {
        log.error("Error: ", e);
    }
}

From source file:org.jboss.dashboard.ui.formatters.FileNavigationTreeFormatter.java

protected void renderDirectory(FileObject currentDir) throws FileSystemException {
    String dirName = currentDir.getName().getBaseName();
    setAttribute("dirName", StringUtils.defaultIfEmpty(dirName, "/"));
    setAttribute("path", currentDir.getName().getPath());
    FileObject[] children = currentDir.getChildren();
    List childDirectories = new ArrayList();
    boolean hasChildDirectories = false;
    if (children != null)
        for (int i = 0; i < children.length; i++) {
            FileObject child = children[i];
            if (child.getType().equals(FileType.FOLDER) && !child.isHidden() && child.isReadable()) {
                hasChildDirectories = true;
                childDirectories.add(child);
            }//ww w . jav  a 2s.co m
        }
    setAttribute("hasChildrenDirectories", hasChildDirectories);
    String directoryPath = currentDir.getName().getPath();
    boolean isOpen = getFileNavigationHandler().getOpenPaths().contains(directoryPath);
    setAttribute("isOpen", isOpen);
    setAttribute("isCurrent", getFileNavigationHandler().getCurrentPath().equals(directoryPath));
    renderFragment("outputDirectory");
    if (childDirectories.size() > 0) {
        sortDirectories(childDirectories);
        if (isOpen) {
            renderFragment("beforeChildren");
            for (int i = 0; i < childDirectories.size(); i++) {
                FileObject child = (FileObject) childDirectories.get(i);
                renderDirectory(child);
            }
            renderFragment("afterChildren");
        }
    }
}

From source file:org.pentaho.di.core.fileinput.FileInputList.java

public static FileInputList createFileList(VariableSpace space, String[] fileName, String[] fileMask,
        String[] excludeFileMask, String[] fileRequired, boolean[] includeSubdirs,
        FileTypeFilter[] fileTypeFilters) {
    FileInputList fileInputList = new FileInputList();

    // Replace possible environment variables...
    final String[] realfile = space.environmentSubstitute(fileName);
    final String[] realmask = space.environmentSubstitute(fileMask);
    final String[] realExcludeMask = space.environmentSubstitute(excludeFileMask);

    for (int i = 0; i < realfile.length; i++) {
        final String onefile = realfile[i];
        final String onemask = realmask[i];
        final String excludeonemask = realExcludeMask[i];
        final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
        final boolean subdirs = includeSubdirs[i];
        final FileTypeFilter filter = ((fileTypeFilters == null || fileTypeFilters[i] == null)
                ? FileTypeFilter.ONLY_FILES
                : fileTypeFilters[i]);/*from  w ww.j a v  a2  s  .  c  o  m*/

        if (Const.isEmpty(onefile)) {
            continue;
        }

        //
        // If a wildcard is set we search for files
        //
        if (!Const.isEmpty(onemask) || !Const.isEmpty(excludeonemask)) {
            try {
                FileObject directoryFileObject = KettleVFS.getFileObject(onefile, space);
                boolean processFolder = true;
                if (onerequired) {
                    if (!directoryFileObject.exists()) {
                        // if we don't find folder..no need to continue
                        fileInputList.addNonExistantFile(directoryFileObject);
                        processFolder = false;
                    } else {
                        if (!directoryFileObject.isReadable()) {
                            fileInputList.addNonAccessibleFile(directoryFileObject);
                            processFolder = false;
                        }
                    }
                }

                // Find all file names that match the wildcard in this directory
                //
                if (processFolder) {
                    if (directoryFileObject != null && directoryFileObject.getType() == FileType.FOLDER) // it's a directory
                    {
                        FileObject[] fileObjects = directoryFileObject.findFiles(new AllFileSelector() {
                            @Override
                            public boolean traverseDescendents(FileSelectInfo info) {
                                return info.getDepth() == 0 || subdirs;
                            }

                            @Override
                            public boolean includeFile(FileSelectInfo info) {
                                // Never return the parent directory of a file list.
                                if (info.getDepth() == 0) {
                                    return false;
                                }

                                FileObject fileObject = info.getFile();
                                try {
                                    if (fileObject != null && filter.isFileTypeAllowed(fileObject.getType())) {
                                        String name = info.getFile().getName().getBaseName();
                                        boolean matches = true;
                                        if (!Const.isEmpty(onemask)) {
                                            matches = Pattern.matches(onemask, name);
                                        }
                                        boolean excludematches = false;
                                        if (!Const.isEmpty(excludeonemask)) {
                                            excludematches = Pattern.matches(excludeonemask, name);
                                        }
                                        return (matches && !excludematches);
                                    }
                                    return false;
                                } catch (IOException ex) {
                                    // Upon error don't process the file.
                                    return false;
                                }
                            }
                        });
                        if (fileObjects != null) {
                            for (int j = 0; j < fileObjects.length; j++) {
                                if (fileObjects[j].exists()) {
                                    fileInputList.addFile(fileObjects[j]);
                                }
                            }
                        }
                        if (Const.isEmpty(fileObjects)) {
                            if (onerequired) {
                                fileInputList.addNonAccessibleFile(directoryFileObject);
                            }
                        }

                        // Sort the list: quicksort, only for regular files
                        fileInputList.sortFiles();
                    } else {
                        FileObject[] children = directoryFileObject.getChildren();
                        for (int j = 0; j < children.length; j++) {
                            // See if the wildcard (regexp) matches...
                            String name = children[j].getName().getBaseName();
                            boolean matches = true;
                            if (!Const.isEmpty(onemask)) {
                                matches = Pattern.matches(onemask, name);
                            }
                            boolean excludematches = false;
                            if (!Const.isEmpty(excludeonemask)) {
                                excludematches = Pattern.matches(excludeonemask, name);
                            }
                            if (matches && !excludematches) {
                                fileInputList.addFile(children[j]);
                            }

                        }
                        // We don't sort here, keep the order of the files in the archive.
                    }
                }
            } catch (Exception e) {
                if (onerequired) {
                    fileInputList.addNonAccessibleFile(new NonAccessibleFileObject(onefile));
                }
                log.logError(Const.getStackTracker(e));
            }
        } else { // A normal file...

            try {
                FileObject fileObject = KettleVFS.getFileObject(onefile, space);
                if (fileObject.exists()) {
                    if (fileObject.isReadable()) {
                        fileInputList.addFile(fileObject);
                    } else {
                        if (onerequired) {
                            fileInputList.addNonAccessibleFile(fileObject);
                        }
                    }
                } else {
                    if (onerequired) {
                        fileInputList.addNonExistantFile(fileObject);
                    }
                }
            } catch (Exception e) {
                if (onerequired) {
                    fileInputList.addNonAccessibleFile(new NonAccessibleFileObject(onefile));
                }
                log.logError(Const.getStackTracker(e));
            }
        }
    }

    return fileInputList;
}

From source file:org.pentaho.di.job.entries.fileexists.JobEntryFileExists.java

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);//from   w  w w .ja va  2s. c  om
    result.setNrErrors(0);

    if (filename != null) {
        String realFilename = getRealFilename();
        try {
            FileObject file = KettleVFS.getFileObject(realFilename, this);
            if (file.exists() && file.isReadable()) {
                logDetailed(BaseMessages.getString(PKG, "JobEntryFileExists.File_Exists", realFilename));
                result.setResult(true);
            } else {
                logDetailed(
                        BaseMessages.getString(PKG, "JobEntryFileExists.File_Does_Not_Exist", realFilename));
            }
        } catch (Exception e) {
            result.setNrErrors(1);
            logError(BaseMessages.getString(PKG, "JobEntryFileExists.ERROR_0004_IO_Exception", e.getMessage()),
                    e);
        }
    } else {
        result.setNrErrors(1);
        logError(BaseMessages.getString(PKG, "JobEntryFileExists.ERROR_0005_No_Filename_Defined"));
    }

    return result;
}

From source file:org.pentaho.di.job.entries.filesexist.JobEntryFilesExist.java

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);/* ww w .  j  a  v a  2  s.c  o m*/
    result.setNrErrors(0);
    int missingfiles = 0;
    int nrErrors = 0;

    // see PDI-10270 for details
    boolean oldBehavior = "Y"
            .equalsIgnoreCase(getVariable(Const.KETTLE_COMPATIBILITY_SET_ERROR_ON_SPECIFIC_JOB_ENTRIES, "N"));

    if (arguments != null) {
        for (int i = 0; i < arguments.length && !parentJob.isStopped(); i++) {
            FileObject file = null;

            try {
                String realFilefoldername = environmentSubstitute(arguments[i]);
                file = KettleVFS.getFileObject(realFilefoldername, this);

                if (file.exists() && file.isReadable()) // TODO: is it needed to check file for readability?
                {
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobEntryFilesExist.File_Exists",
                                realFilefoldername));
                    }
                } else {
                    missingfiles++;
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobEntryFilesExist.File_Does_Not_Exist",
                                realFilefoldername));
                    }
                }

            } catch (Exception e) {
                nrErrors++;
                missingfiles++;
                logError(
                        BaseMessages.getString(PKG, "JobEntryFilesExist.ERROR_0004_IO_Exception", e.toString()),
                        e);
            } finally {
                if (file != null) {
                    try {
                        file.close();
                        file = null;
                    } catch (IOException ex) { /* Ignore */
                    }
                }
            }
        }

    }

    result.setNrErrors(nrErrors);

    if (oldBehavior) {
        result.setNrErrors(missingfiles);
    }

    if (missingfiles == 0) {
        result.setResult(true);
    }

    return result;
}

From source file:org.pentaho.di.job.entries.talendjobexec.JobEntryTalendJobExec.java

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);//from w  w w.  j a v a2 s.  c  o m

    if (filename != null) {
        String realFilename = getRealFilename();
        try {
            FileObject file = KettleVFS.getFileObject(realFilename, this);
            if (file.exists() && file.isReadable()) {
                result = executeTalenJob(file, result, nr);
            } else {
                logDetailed(
                        BaseMessages.getString(PKG, "JobEntryTalendJobExec.File_Does_Not_Exist", realFilename));
            }
        } catch (Exception e) {
            result.setNrErrors(1);
            logError(BaseMessages.getString(PKG, "JobEntryTalendJobExec.ERROR_0004_IO_Exception",
                    e.getMessage()), e);
        }
    } else {
        result.setNrErrors(1);
        logError(BaseMessages.getString(PKG, "JobEntryTalendJobExec.ERROR_0005_No_Filename_Defined"));
    }

    return result;
}

From source file:org.sonatype.gshell.commands.bsf.ScriptCommand.java

private Object exec(final CommandContext context) throws Exception {
    assert context != null;
    IO io = context.getIo();/* w  w w.  j ava  2 s  . c  o  m*/

    FileObject cwd = fileSystemAccess.getCurrentDirectory(context.getVariables());
    FileObject file = fileSystemAccess.resolveFile(cwd, path);

    if (!file.exists()) {
        io.error("File not found: {}", file.getName()); // TODO: i18n
        return Result.FAILURE;
    } else if (!file.getType().hasContent()) {
        io.error("File has not content: {}", file.getName()); // TODO: i18n
        return Result.FAILURE;
    } else if (!file.isReadable()) {
        io.error("File is not readable: {}", file.getName()); // TODO: i18n
        return Result.FAILURE;
    }

    if (language == null) {
        language = detectLanguage(file);
    }

    BSFEngine engine = createEngine(context);

    byte[] bytes = FileUtil.getContent(file);
    String script = new String(bytes);

    log.info("Evaluating file ({}): {}", language, path); // TODO: i18n

    try {
        return engine.eval(file.getName().getBaseName(), 1, 1, script);
    } finally {
        engine.terminate();
        file.close();
    }
}

From source file:org.sonatype.gshell.commands.vfs.FileInfoCommand.java

public Object execute(final CommandContext context) throws Exception {
    assert context != null;
    IO io = context.getIo();/*w w  w.  j a  v  a  2 s.c o  m*/

    FileObject file = resolveFile(context, path);

    io.println("URL: {}", file.getURL());
    io.println("Name: {}", file.getName());
    io.println("BaseName: {}", file.getName().getBaseName());
    io.println("Extension: {}", file.getName().getExtension());
    io.println("Path: {}", file.getName().getPath());
    io.println("Scheme: {}", file.getName().getScheme());
    io.println("URI: {}", file.getName().getURI());
    io.println("Root URI: {}", file.getName().getRootURI());
    io.println("Parent: {}", file.getName().getParent());
    io.println("Type: {}", file.getType());
    io.println("Exists: {}", file.exists());
    io.println("Readable: {}", file.isReadable());
    io.println("Writeable: {}", file.isWriteable());
    io.println("Root path: {}", file.getFileSystem().getRoot().getName().getPath());

    if (file.exists()) {
        FileContent content = file.getContent();
        FileContentInfo contentInfo = content.getContentInfo();
        io.println("Content type: {}", contentInfo.getContentType());
        io.println("Content encoding: {}", contentInfo.getContentEncoding());

        try {
            // noinspection unchecked
            Map<String, Object> attrs = content.getAttributes();
            if (attrs != null && !attrs.isEmpty()) {
                io.println("Attributes:");
                for (Map.Entry<String, Object> entry : attrs.entrySet()) {
                    io.println("    {}='{}'", entry.getKey(), entry.getValue());
                }
            }
        } catch (FileSystemException e) {
            io.println("File attributes are NOT supported");
        }

        try {
            Certificate[] certs = content.getCertificates();
            if (certs != null && certs.length != 0) {
                io.println("Certificate:");
                for (Certificate cert : certs) {
                    io.println("    {}", cert);
                }
            }
        } catch (FileSystemException e) {
            io.println("File certificates are NOT supported");
        }

        if (file.getType().equals(FileType.FILE)) {
            io.println("Size: {} bytes", content.getSize());
        } else if (file.getType().hasChildren() && file.isReadable()) {
            FileObject[] children = file.getChildren();
            io.println("Directory with {} files", children.length);

            for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                io.println("#{}:{}", iterChildren, children[iterChildren].getName());
                if (iterChildren > 5) {
                    break;
                }
            }
        }

        io.println("Last modified: {}",
                DateFormat.getInstance().format(new Date(content.getLastModifiedTime())));
    } else {
        io.println("The file does not exist");
    }

    FileObjects.close(file);

    return Result.SUCCESS;
}

From source file:pt.webdetails.cpf.repository.vfs.VfsRepositoryAccess.java

public SaveFileStatus copySolutionFile(String fromFilePath, String toFilePath) throws IOException {
    try {//from www .j  a  v a2  s  . c o m
        FileObject to = resolveFile(repo, toFilePath);
        FileObject from = resolveFile(repo, fromFilePath);
        to.copyFrom(from, Selectors.SELECT_SELF);
        if (to != null && to.exists() && to.isReadable()) {
            return SaveFileStatus.OK;
        }
    } catch (Exception e) {
        log.error("Cannot copy from " + fromFilePath + " to " + toFilePath, e);
    }
    return SaveFileStatus.FAIL;
}

From source file:pt.webdetails.cpf.repository.vfs.VfsRepositoryAccess.java

public IRepositoryFile[] listRepositoryFiles(IRepositoryFileFilter fileFilter) {
    try {//from w w w.j  a  v a 2  s  . co m
        FileObject[] files = repo.getChildren();
        List<IRepositoryFile> repoFiles = new ArrayList<IRepositoryFile>();
        for (FileObject file : files) {
            if (file.exists() && file.isReadable() && file.getType().equals(FileType.FILE)) {
                IRepositoryFile repoFile = new VfsRepositoryFile(repo, file);
                if (fileFilter == null || fileFilter.accept(repoFile)) {
                    repoFiles.add(repoFile);
                }
            }
        }
        return repoFiles.toArray(new IRepositoryFile[] {});
    } catch (FileSystemException e) {
        throw new RuntimeException("Cannot list repo files", e);
    }
}