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

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

Introduction

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

Prototype

boolean isReadable() throws FileSystemException;

Source Link

Document

Determines if this file can be read.

Usage

From source file:com.stratuscom.harvester.classloading.VirtualFileSystemClassLoader.java

/**
 * Find the all the file objects for a resource by searching through all the
 * classpath entries that have been set up.
 *
 * @param name//from   www  .ja v  a  2s  .co m
 * @return
 */
public List<FileObject> findResourceFileObjects(String name) {
    List<FileObject> foList = new ArrayList<FileObject>();
    for (ClasspathEntry cpEntry : classpathEntries) {
        try {
            FileObject fo = cpEntry.resolveFile(name);
            if (fo != null && fo.isReadable()) {
                foList.add(fo);
            }
        } catch (FileSystemException ex) {
            Logger.getLogger(VirtualFileSystemClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return foList;
}

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

public Properties readStartProperties(FileObject serviceRoot)
        throws FileSystemException, LocalizedRuntimeException, IOException {
    /*/*from  w  w  w  .ja v a  2  s .  c o  m*/
     Read the start.properties file.
     */
    FileObject startProperties = serviceRoot.resolveFile(Strings.START_PROPERTIES);
    if (startProperties == null || !startProperties.getType().equals(FileType.FILE)
            || !startProperties.isReadable()) {
        throw new LocalizedRuntimeException(MessageNames.BUNDLE_NAME, MessageNames.CANT_READ_START_PROPERTIES,
                new Object[] { Strings.START_PROPERTIES, serviceRoot.getName().getBaseName() });
    }
    Properties startProps = propertiesFileReader.getProperties(startProperties);
    return startProps;
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java

/**
 * Search for files that match the given regex pattern and create a list
 * Then process each of these files and update the status of the scan on
 * the poll table// w  w  w.jav  a2  s .  c  o  m
 * @param entry the poll table entry for the scan
 * @param fileURI the file or directory to be scanned
 */
private void scanFileOrDirectory(final PollTableEntry entry, String fileURI) {

    FileObject fileObject = null;

    //TODO : Trying to make the correct URL out of the malformed one.
    if (fileURI.contains("vfs:")) {
        fileURI = fileURI.substring(fileURI.indexOf("vfs:") + 4);
    }

    if (log.isDebugEnabled()) {
        log.debug("Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }

    boolean wasError = true;
    int retryCount = 0;
    int maxRetryCount = entry.getMaxRetryCount();
    long reconnectionTimeout = entry.getReconnectTimeout();

    while (wasError) {
        try {
            retryCount++;
            fileObject = fsManager.resolveFile(fileURI);

            if (fileObject == null) {
                log.error("fileObject is null");
                throw new FileSystemException("fileObject is null");
            }

            wasError = false;

        } catch (FileSystemException e) {
            if (retryCount >= maxRetryCount) {
                processFailure(
                        "Repeatedly failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI), e,
                        entry);
                return;
            } else {
                log.warn("Failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI)
                        + ", in attempt " + retryCount + ", " + e.getMessage() + " Retrying in "
                        + reconnectionTimeout + " milliseconds.");
            }
        }

        if (wasError) {
            try {
                Thread.sleep(reconnectionTimeout);
            } catch (InterruptedException e2) {
                log.error("Thread was interrupted while waiting to reconnect.", e2);
            }
        }
    }

    try {
        if (fileObject.exists() && fileObject.isReadable()) {

            entry.setLastPollState(PollTableEntry.NONE);
            FileObject[] children = null;
            try {
                children = fileObject.getChildren();
            } catch (FileNotFolderException ignored) {
            } catch (FileSystemException ex) {
                log.error(ex.getMessage(), ex);
            }

            // if this is a file that would translate to a single message
            if (children == null || children.length == 0) {
                boolean isFailedRecord = false;
                if (entry.getMoveAfterMoveFailure() != null) {
                    isFailedRecord = isFailedRecord(fileObject, entry);
                }

                if (fileObject.getType() == FileType.FILE && !isFailedRecord) {
                    if (!entry.isFileLockingEnabled()
                            || (entry.isFileLockingEnabled() && VFSUtils.acquireLock(fsManager, fileObject))) {
                        try {
                            processFile(entry, fileObject);
                            entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                            metrics.incrementMessagesReceived();

                        } catch (AxisFault e) {
                            logException("Error processing File URI : " + fileObject.getName(), e);
                            entry.setLastPollState(PollTableEntry.FAILED);
                            metrics.incrementFaultsReceiving();
                        }

                        try {
                            moveOrDeleteAfterProcessing(entry, fileObject);
                        } catch (AxisFault axisFault) {
                            logException("File object '" + fileObject.getURL().toString() + "' "
                                    + "cloud not be moved", axisFault);
                            entry.setLastPollState(PollTableEntry.FAILED);
                            String timeStamp = VFSUtils.getSystemTime(entry.getFailedRecordTimestampFormat());
                            addFailedRecord(entry, fileObject, timeStamp);
                        }
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject);
                            if (log.isDebugEnabled()) {
                                log.debug("Removed the lock file '" + fileObject.toString()
                                        + ".lock' of the file '" + fileObject.toString());
                            }
                        }
                    } else if (log.isDebugEnabled()) {
                        log.debug("Couldn't get the lock for processing the file : " + fileObject.getName());
                    } else if (isFailedRecord) {
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject);
                        }
                        // schedule a cleanup task if the file is there
                        if (fsManager.resolveFile(fileObject.getURL().toString()) != null
                                && removeTaskState == STATE_STOPPED
                                && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, fileObject));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + fileObject.getURL() + "' has been marked as a failed"
                                    + " record, it will not process");
                        }
                    }
                }

            } else {
                int failCount = 0;
                int successCount = 0;
                int processCount = 0;
                Integer iFileProcessingInterval = entry.getFileProcessingInterval();
                Integer iFileProcessingCount = entry.getFileProcessingCount();

                if (log.isDebugEnabled()) {
                    log.debug("File name pattern : " + entry.getFileNamePattern());
                }
                for (FileObject child : children) {
                    //skipping *.lock file
                    if (child.getName().getBaseName().endsWith(".lock")) {
                        continue;
                    }
                    boolean isFailedRecord = false;
                    if (entry.getMoveAfterMoveFailure() != null) {
                        isFailedRecord = isFailedRecord(child, entry);
                    }

                    if (entry.getFileNamePattern() != null
                            && child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        //child's file name matches the file name pattern
                        //now we try to get the lock and process
                        if (log.isDebugEnabled()) {
                            log.debug("Matching file : " + child.getName().getBaseName());
                        }

                        if ((!entry.isFileLockingEnabled()
                                || (entry.isFileLockingEnabled() && VFSUtils.acquireLock(fsManager, child)))
                                && !isFailedRecord) {
                            //process the file
                            try {
                                if (log.isDebugEnabled()) {
                                    log.debug("Processing file :" + child);
                                }
                                processCount++;
                                processFile(entry, child);
                                successCount++;
                                // tell moveOrDeleteAfterProcessing() file was success
                                entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                                metrics.incrementMessagesReceived();

                            } catch (Exception e) {
                                logException("Error processing File URI : " + child.getName(), e);
                                failCount++;
                                // tell moveOrDeleteAfterProcessing() file failed
                                entry.setLastPollState(PollTableEntry.FAILED);
                                metrics.incrementFaultsReceiving();
                            }
                            //skipping un-locking file if failed to do delete/move after process
                            boolean skipUnlock = false;
                            try {
                                moveOrDeleteAfterProcessing(entry, child);
                            } catch (AxisFault axisFault) {
                                logException(
                                        "File object '" + child.getURL().toString()
                                                + "'cloud not be moved, will remain in \"locked\" state",
                                        axisFault);
                                skipUnlock = true;
                                failCount++;
                                entry.setLastPollState(PollTableEntry.FAILED);
                                String timeStamp = VFSUtils
                                        .getSystemTime(entry.getFailedRecordTimestampFormat());
                                addFailedRecord(entry, child, timeStamp);
                            }
                            // if there is a failure or not we'll try to release the lock
                            if (entry.isFileLockingEnabled() && !skipUnlock) {
                                VFSUtils.releaseLock(fsManager, child);
                            }
                        }
                    } else if (entry.getFileNamePattern() != null
                            && !child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        //child's file name does not match the file name pattern
                        if (log.isDebugEnabled()) {
                            log.debug("Non-Matching file : " + child.getName().getBaseName());
                        }
                    } else if (isFailedRecord) {
                        //it is a failed record
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, child);
                            VFSUtils.releaseLock(fsManager, fileObject);
                        }
                        if (fsManager.resolveFile(child.getURL().toString()) != null
                                && removeTaskState == STATE_STOPPED
                                && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, child));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + fileObject.getURL()
                                    + "' has been marked as a failed record, it will not " + "process");
                        }
                    }

                    if (iFileProcessingInterval != null && iFileProcessingInterval > 0) {
                        try {
                            if (log.isDebugEnabled()) {
                                log.debug("Put the VFS processor to sleep for : " + iFileProcessingInterval);
                            }
                            Thread.sleep(iFileProcessingInterval);
                        } catch (InterruptedException ie) {
                            log.error("Unable to set the interval between file processors." + ie);
                        }
                    } else if (iFileProcessingCount != null && iFileProcessingCount <= processCount) {
                        break;
                    }
                }

                if (failCount == 0 && successCount > 0) {
                    entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                } else if (successCount == 0 && failCount > 0) {
                    entry.setLastPollState(PollTableEntry.FAILED);
                } else {
                    entry.setLastPollState(PollTableEntry.WITH_ERRORS);
                }
            }

            // processing of this poll table entry is complete
            long now = System.currentTimeMillis();
            entry.setLastPollTime(now);
            entry.setNextPollTime(now + entry.getPollInterval());

        } else if (log.isDebugEnabled()) {
            log.debug("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "."
                    + " Reason: "
                    + (fileObject.exists()
                            ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!")
                            : "The file does not exists!"));
        }
        onPollCompletion(entry);
    } catch (FileSystemException e) {
        processFailure("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e,
                entry);
    }
}

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

@Test
public void testIsReadable() throws Exception {
    FileObject fo = manager.resolveFile(TEST_DIR1);
    Assert.assertNotNull(fo);/*from www. j  ava2  s.c om*/
    Assert.assertFalse(fo.exists());

    // Create the test file
    FileObject file = createTestFile(hdfs);
    Assert.assertTrue(file.isReadable());
}

From source file:org.apache.commons.vfs2.example.ShowProperties.java

public static void main(final String[] args) {
    if (args.length == 0) {
        System.err.println("Please pass the name of a file as parameter.");
        System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
        return;//from   w w  w .  j  av  a  2  s .co  m
    }
    for (final String arg : args) {
        try {
            final FileSystemManager mgr = VFS.getManager();
            System.out.println();
            System.out.println("Parsing: " + arg);
            final FileObject file = mgr.resolveFile(arg);
            System.out.println("URL: " + file.getURL());
            System.out.println("getName(): " + file.getName());
            System.out.println("BaseName: " + file.getName().getBaseName());
            System.out.println("Extension: " + file.getName().getExtension());
            System.out.println("Path: " + file.getName().getPath());
            System.out.println("Scheme: " + file.getName().getScheme());
            System.out.println("URI: " + file.getName().getURI());
            System.out.println("Root URI: " + file.getName().getRootURI());
            System.out.println("Parent: " + file.getName().getParent());
            System.out.println("Type: " + file.getType());
            System.out.println("Exists: " + file.exists());
            System.out.println("Readable: " + file.isReadable());
            System.out.println("Writeable: " + file.isWriteable());
            System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
            if (file.exists()) {
                if (file.getType().equals(FileType.FILE)) {
                    System.out.println("Size: " + file.getContent().getSize() + " bytes");
                } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
                    final FileObject[] children = file.getChildren();
                    System.out.println("Directory with " + children.length + " files");
                    for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                        System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                        if (iterChildren > SHOW_MAX) {
                            break;
                        }
                    }
                }
                System.out.println("Last modified: "
                        + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
            } else {
                System.out.println("The file does not exist");
            }
            file.close();
        } catch (final FileSystemException ex) {
            ex.printStackTrace();
        }
    }
}

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

/**
 * Search for files that match the given regex pattern and create a list
 * Then process each of these files and update the status of the scan on
 * the poll table// ww  w  . j a v  a 2s.co  m
 * @param entry the poll table entry for the scan
 * @param fileURI the file or directory to be scanned
 */
private void scanFileOrDirectory(final PollTableEntry entry, String fileURI) {
    FileSystemOptions fso = null;
    setFileSystemClosed(false);
    try {
        fso = VFSUtils.attachFileSystemOptions(entry.getVfsSchemeProperties(), fsManager);
    } catch (Exception e) {
        log.error("Error while attaching VFS file system properties. " + e.getMessage());
    }

    FileObject fileObject = null;

    //TODO : Trying to make the correct URL out of the malformed one.
    if (fileURI.contains("vfs:")) {
        fileURI = fileURI.substring(fileURI.indexOf("vfs:") + 4);
    }

    if (log.isDebugEnabled()) {
        log.debug("Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }

    boolean wasError = true;
    int retryCount = 0;
    int maxRetryCount = entry.getMaxRetryCount();
    long reconnectionTimeout = entry.getReconnectTimeout();

    while (wasError) {
        try {
            retryCount++;
            fileObject = fsManager.resolveFile(fileURI, fso);

            if (fileObject == null) {
                log.error("fileObject is null");
                throw new FileSystemException("fileObject is null");
            }

            wasError = false;

        } catch (FileSystemException e) {
            if (retryCount >= maxRetryCount) {
                processFailure(
                        "Repeatedly failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI), e,
                        entry);
                closeFileSystem(fileObject);
                return;
            } else {
                log.warn("Failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI)
                        + ", in attempt " + retryCount + ", " + e.getMessage() + " Retrying in "
                        + reconnectionTimeout + " milliseconds.");
            }
        }

        if (wasError) {
            try {
                Thread.sleep(reconnectionTimeout);
            } catch (InterruptedException e2) {
                log.error("Thread was interrupted while waiting to reconnect.", e2);
            }
        }
    }

    try {
        if (fileObject.exists() && fileObject.isReadable()) {

            entry.setLastPollState(PollTableEntry.NONE);
            FileObject[] children = null;
            try {
                children = fileObject.getChildren();
            } catch (FileNotFolderException ignored) {
            } catch (FileSystemException ex) {
                log.error(ex.getMessage(), ex);
            }

            // if this is a file that would translate to a single message
            if (children == null || children.length == 0) {
                boolean isFailedRecord = false;
                if (entry.getMoveAfterMoveFailure() != null) {
                    isFailedRecord = isFailedRecord(fileObject, entry);
                }

                if (fileObject.getType() == FileType.FILE && !isFailedRecord) {
                    boolean runPostProcess = true;
                    if (!entry.isFileLockingEnabled() || (entry.isFileLockingEnabled()
                            && acquireLock(fsManager, fileObject, entry, fso))) {
                        try {
                            if (fileObject.getType() == FileType.FILE) {
                                processFile(entry, fileObject);
                                entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                                metrics.incrementMessagesReceived();
                            } else {
                                runPostProcess = false;
                            }

                        } catch (AxisFault e) {
                            if (e.getCause() instanceof FileNotFoundException) {
                                log.warn("Error processing File URI : "
                                        + VFSUtils.maskURLPassword(fileObject.getName().toString())
                                        + ". This can be due to file moved from another process.");
                                runPostProcess = false;
                            } else {
                                logException("Error processing File URI : "
                                        + VFSUtils.maskURLPassword(fileObject.getName().getURI()), e);
                                entry.setLastPollState(PollTableEntry.FAILED);
                                metrics.incrementFaultsReceiving();
                            }
                        }
                        if (runPostProcess) {
                            try {
                                moveOrDeleteAfterProcessing(entry, fileObject, fso);
                            } catch (AxisFault axisFault) {
                                logException("File object '"
                                        + VFSUtils.maskURLPassword(fileObject.getURL().toString()) + "' "
                                        + "cloud not be moved", axisFault);
                                entry.setLastPollState(PollTableEntry.FAILED);
                                String timeStamp = VFSUtils
                                        .getSystemTime(entry.getFailedRecordTimestampFormat());
                                addFailedRecord(entry, fileObject, timeStamp);
                            }
                        }
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject, fso);
                            if (log.isDebugEnabled()) {
                                log.debug("Removed the lock file '"
                                        + VFSUtils.maskURLPassword(fileObject.toString())
                                        + ".lock' of the file '"
                                        + VFSUtils.maskURLPassword(fileObject.toString()));
                            }
                        }
                    } else if (log.isDebugEnabled()) {
                        log.debug("Couldn't get the lock for processing the file : "
                                + VFSUtils.maskURLPassword(fileObject.getName().getURI()));
                    } else if (isFailedRecord) {
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject, fso);
                        }
                        // schedule a cleanup task if the file is there
                        if (fsManager.resolveFile(fileObject.getURL().toString(), fso) != null
                                && removeTaskState == STATE_STOPPED
                                && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, fileObject, fso));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                                    + "' has been marked as a failed" + " record, it will not process");
                        }
                    }
                }

            } else {
                int failCount = 0;
                int successCount = 0;
                int processCount = 0;
                Integer iFileProcessingInterval = entry.getFileProcessingInterval();
                Integer iFileProcessingCount = entry.getFileProcessingCount();

                if (log.isDebugEnabled()) {
                    log.debug("File name pattern : " + entry.getFileNamePattern());
                }
                // Sort the files
                String strSortParam = entry.getFileSortParam();
                if (strSortParam != null) {
                    log.debug("Start Sorting the files.");
                    boolean bSortOrderAsscending = entry.isFileSortAscending();
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Sorting the files by : " + strSortParam + ". (" + bSortOrderAsscending + ")");
                    }
                    if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_NAME) && bSortOrderAsscending) {
                        Arrays.sort(children, new FileNameAscComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_NAME)
                            && !bSortOrderAsscending) {
                        Arrays.sort(children, new FileNameDesComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_SIZE) && bSortOrderAsscending) {
                        Arrays.sort(children, new FileSizeAscComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_SIZE)
                            && !bSortOrderAsscending) {
                        Arrays.sort(children, new FileSizeDesComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
                            && bSortOrderAsscending) {
                        Arrays.sort(children, new FileLastmodifiedtimestampAscComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
                            && !bSortOrderAsscending) {
                        Arrays.sort(children, new FileLastmodifiedtimestampDesComparator());
                    }
                    log.debug("End Sorting the files.");
                }
                for (FileObject child : children) {
                    //skipping *.lock file
                    if (child.getName().getBaseName().endsWith(".lock")) {
                        continue;
                    }
                    boolean isFailedRecord = false;
                    if (entry.getMoveAfterMoveFailure() != null) {
                        isFailedRecord = isFailedRecord(child, entry);
                    }

                    if (entry.getFileNamePattern() != null
                            && child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        //child's file name matches the file name pattern
                        //now we try to get the lock and process
                        if (log.isDebugEnabled()) {
                            log.debug("Matching file : " + child.getName().getBaseName());
                        }
                        boolean runPostProcess = true;
                        if ((!entry.isFileLockingEnabled() || (entry.isFileLockingEnabled()
                                && VFSUtils.acquireLock(fsManager, child, fso))) && !isFailedRecord) {
                            //process the file
                            try {
                                if (log.isDebugEnabled()) {
                                    log.debug("Processing file :" + VFSUtils.maskURLPassword(child.toString()));
                                }
                                processCount++;

                                if (child.getType() == FileType.FILE) {
                                    processFile(entry, child);
                                    successCount++;
                                    // tell moveOrDeleteAfterProcessing() file was success
                                    entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                                    metrics.incrementMessagesReceived();
                                } else {
                                    runPostProcess = false;
                                }
                            } catch (Exception e) {
                                if (e.getCause() instanceof FileNotFoundException) {
                                    log.warn("Error processing File URI : "
                                            + VFSUtils.maskURLPassword(child.getName().toString())
                                            + ". This can be due to file moved from another process.");
                                    runPostProcess = false;
                                } else {
                                    logException("Error processing File URI : "
                                            + VFSUtils.maskURLPassword(child.getName().getURI()), e);
                                    failCount++;
                                    // tell moveOrDeleteAfterProcessing() file failed
                                    entry.setLastPollState(PollTableEntry.FAILED);
                                    metrics.incrementFaultsReceiving();
                                }
                            }
                            //skipping un-locking file if failed to do delete/move after process
                            boolean skipUnlock = false;
                            if (runPostProcess) {
                                try {
                                    moveOrDeleteAfterProcessing(entry, child, fso);
                                } catch (AxisFault axisFault) {
                                    logException(
                                            "File object '"
                                                    + VFSUtils.maskURLPassword(child.getURL().toString())
                                                    + "'cloud not be moved, will remain in \"locked\" state",
                                            axisFault);
                                    skipUnlock = true;
                                    failCount++;
                                    entry.setLastPollState(PollTableEntry.FAILED);
                                    String timeStamp = VFSUtils
                                            .getSystemTime(entry.getFailedRecordTimestampFormat());
                                    addFailedRecord(entry, child, timeStamp);
                                }
                            }
                            // if there is a failure or not we'll try to release the lock
                            if (entry.isFileLockingEnabled() && !skipUnlock) {
                                VFSUtils.releaseLock(fsManager, child, fso);
                            }
                        }
                    } else if (entry.getFileNamePattern() != null
                            && !child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        //child's file name does not match the file name pattern
                        if (log.isDebugEnabled()) {
                            log.debug("Non-Matching file : " + child.getName().getBaseName());
                        }
                    } else if (isFailedRecord) {
                        //it is a failed record
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, child, fso);
                            VFSUtils.releaseLock(fsManager, fileObject, fso);
                        }
                        if (fsManager.resolveFile(child.getURL().toString()) != null
                                && removeTaskState == STATE_STOPPED
                                && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, child, fso));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                                    + "' has been marked as a failed record, it will not " + "process");
                        }
                    }

                    if (iFileProcessingInterval != null && iFileProcessingInterval > 0) {
                        try {
                            if (log.isDebugEnabled()) {
                                log.debug("Put the VFS processor to sleep for : " + iFileProcessingInterval);
                            }
                            Thread.sleep(iFileProcessingInterval);
                        } catch (InterruptedException ie) {
                            log.error("Unable to set the interval between file processors." + ie);
                        }
                    } else if (iFileProcessingCount != null && iFileProcessingCount <= processCount) {
                        break;
                    }
                }

                if (failCount == 0 && successCount > 0) {
                    entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                } else if (successCount == 0 && failCount > 0) {
                    entry.setLastPollState(PollTableEntry.FAILED);
                } else {
                    entry.setLastPollState(PollTableEntry.WITH_ERRORS);
                }
            }

            // processing of this poll table entry is complete
            long now = System.currentTimeMillis();
            entry.setLastPollTime(now);
            entry.setNextPollTime(now + entry.getPollInterval());

        } else if (log.isDebugEnabled()) {
            log.debug("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "."
                    + " Reason: "
                    + (fileObject.exists()
                            ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!")
                            : "The file does not exists!"));
        }
        onPollCompletion(entry);
    } catch (FileSystemException e) {
        processFailure("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e,
                entry);
    } catch (Exception ex) {
        processFailure("Un-handled exception thrown when processing the file : ", ex, entry);
    } finally {
        closeFileSystem(fileObject);
    }
}

From source file:org.clever.Common.Storage.VirtualFileSystem.java

/**
 * This method lists contents of a file or folder
 * @param file/*from  w w  w.jav  a  2 s.  c o  m*/
 * @return
 * @throws FileSystemException 
 */
public String ls(FileObject file) throws FileSystemException {
    String str = "Contents of " + file.getName() + "\n";
    if (file.exists()) {
        if (file.getType().equals(FileType.FILE)) {
            str = str + "Size: " + file.getContent().getSize() + " bytes\n" + "Last modified: "
                    + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())) + "\n"
                    + "Readable: " + file.isReadable() + "\n" + "Writeable: " + file.isWriteable() + "\n";
            return str;
        } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
            FileObject[] children = file.getChildren();
            str = str = "Directory with " + children.length + " files \n" + "Readable: " + file.isReadable()
                    + "\n" + "Writeable: " + file.isWriteable() + "\n\n";
            //str=str+"Last modified: " +DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime()))+"\n" ;
            for (int i = 0; i < children.length; i++) {
                str = str + children[i].getName().getBaseName() + "\n";
            }
        }
    } else {
        str = str + "The file does not exist";
    }
    return str;
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * Returns for the file the input stream.
 *
 * @return input stream of the file with the content
 * @throws EFapsException on error/*from  w w  w  .ja v a 2  s  . co m*/
 */
@Override
public InputStream read() throws EFapsException {
    StoreResourceInputStream in = null;
    try {
        final FileObject file = this.manager
                .resolveFile(this.storeFileName + VFSStoreResource.EXTENSION_NORMAL);
        if (!file.isReadable()) {
            VFSStoreResource.LOG.error("file for " + this.storeFileName + " not readable");
            throw new EFapsException(VFSStoreResource.class, "#####file not readable");
        }
        in = new VFSStoreResourceInputStream(this, file);
    } catch (final FileSystemException e) {
        VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e);
        throw new EFapsException(VFSStoreResource.class, "read.Throwable", e);
    } catch (final IOException e) {
        VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e);
        throw new EFapsException(VFSStoreResource.class, "read.Throwable", e);
    }
    return in;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

private JsTreeFile resourceAsJsTreeFile(FileObject resource, boolean folderDetails, boolean fileDetails,
        boolean showHiddenFiles) throws FileSystemException {
    String lid = resource.getName().getPath();
    String rootPath = this.root.getName().getPath();
    // lid must be a relative path from rootPath
    if (lid.startsWith(rootPath))
        lid = lid.substring(rootPath.length());
    if (lid.startsWith("/"))
        lid = lid.substring(1);//from   w w  w .  j a v  a 2 s.c  o m

    String title = "";
    String type = "drive";
    if (!"".equals(lid)) {
        type = resource.getType().getName();
        title = resource.getName().getBaseName();
    }
    JsTreeFile file = new JsTreeFile(title, lid, type);

    file.setHidden(this.isFileHidden(resource));

    if ("file".equals(type)) {
        String icon = resourceUtils.getIcon(title);
        file.setIcon(icon);
        file.setSize(resource.getContent().getSize());
        file.setOverSizeLimit(file.getSize() > resourceUtils.getSizeLimit(title));
    }

    try {
        if (folderDetails && ("folder".equals(type) || "drive".equals(type))) {
            if (resource.getChildren() != null) {
                long totalSize = 0;
                long fileCount = 0;
                long folderCount = 0;
                for (FileObject child : resource.getChildren()) {
                    if (showHiddenFiles || !this.isFileHidden(child)) {
                        if ("folder".equals(child.getType().getName())) {
                            ++folderCount;
                        } else if ("file".equals(child.getType().getName())) {
                            ++fileCount;
                            totalSize += child.getContent().getSize();
                        }
                    }
                }
                file.setTotalSize(totalSize);
                file.setFileCount(fileCount);
                file.setFolderCount(folderCount);
            }
        }

        final Calendar date = Calendar.getInstance();
        date.setTimeInMillis(resource.getContent().getLastModifiedTime());
        // In order to have a readable date
        file.setLastModifiedTime(new SimpleDateFormat(this.datePattern).format(date.getTime()));

        file.setReadable(resource.isReadable());
        file.setWriteable(resource.isWriteable());

    } catch (FileSystemException fse) {
        // we don't want that exception during retrieving details 
        // of the folder breaks  all this method ...
        log.error("Exception during retrieveing details on " + lid
                + " ... maybe broken symbolic links or whatever ...", fse);
    }

    return file;
}

From source file:org.obiba.opal.web.FilesResource.java

private Response moveTo(FileObject destinationFolder, Iterable<String> sourcesPath) throws IOException {
    // destination check
    String destinationPath = destinationFolder.getName().getPath();
    if (destinationFolder.getType() != FileType.FOLDER)
        return Response.status(Status.BAD_REQUEST).entity("Destination must be a folder: " + destinationPath)
                .build();//  ww  w.ja  va  2  s .c o  m

    // sources check
    for (String sourcePath : sourcesPath) {
        FileObject sourceFile = resolveFileInFileSystem(sourcePath);
        if (!sourceFile.exists())
            getPathNotExistResponse(sourcePath);
        if (!sourceFile.isReadable()) {
            return Response.status(Status.FORBIDDEN).entity("Source file is not readable: " + sourcePath)
                    .build();
        }
        if (!sourceFile.isWriteable()) {
            return Response.status(Status.FORBIDDEN).entity("Source file cannot be moved: " + sourcePath)
                    .build();
        }
    }

    // do action
    for (String sourcePath : sourcesPath) {
        FileObject sourceFile = resolveFileInFileSystem(sourcePath);
        FileObject destinationFile = resolveFileInFileSystem(
                destinationPath + "/" + sourceFile.getName().getBaseName());
        sourceFile.moveTo(destinationFile);
    }

    return Response.ok().build();
}