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

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

Introduction

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

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:com.seer.datacruncher.spring.IsSuccessfulConnectionController.java

private String checkServiceRunning(int service, String connID) {

    String success = "true";
    String url = "";
    ConnectionsEntity conn = connectionsDao.find(Long.parseLong(connID));
    DefaultFileSystemManager fsManager = null;
    FileObject fileObject = null;
    String userName = "";
    String password = "";
    String hostName = "";
    String port = "";
    String inputDirectory = "";
    String fileName = "";
    int connType = 1;

    if (conn != null) {
        userName = conn.getUserName();/*from   w  ww  . j  a v a  2s. c o m*/
        password = conn.getPassword();
        hostName = conn.getHost();
        port = conn.getPort();
        inputDirectory = conn.getDirectory();
        fileName = conn.getFileName();
        connType = conn.getIdConnType();

    }

    if (connType == GenericType.DownloadTypeConn) {
        if (fileName == null || fileName.trim().length() == 0) {
            return "false";
        } else {
            fileName = "/" + fileName;
        }
    } else {
        fileName = "";
    }

    try {
        fsManager = (DefaultFileSystemManager) VFS.getManager();
        if (service == Servers.SAMBA.getDbCode()) {
            if (!fsManager.hasProvider("smb")) {
                fsManager.addProvider("smb", new SmbFileProvider());
            }
            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory
                    + fileName;
        } else if (service == Servers.HTTP.getDbCode()) {
            if (!fsManager.hasProvider("http")) {
                fsManager.addProvider("http", new HttpFileProvider());
            }
            url = "http://" + hostName + ":" + port + "/" + inputDirectory + fileName;
        } else if (service == Servers.FTP.getDbCode()) {
            if (!fsManager.hasProvider("ftp")) {
                fsManager.addProvider("ftp", new FtpFileProvider());
            }
            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory
                    + fileName;
        }

        fileObject = fsManager.resolveFile(url);

        if (fileObject == null || !fileObject.exists()) {
            success = "false";
        }

        if (connType == GenericType.DownloadTypeConn) {
            if (fileObject.getType().equals(FileType.IMAGINARY)) {
                success = "false";
            }
            byte data[] = new byte[(int) fileObject.getContent().getSize()];
            fileObject.getContent().getInputStream().read(data);
        }

    } catch (Exception ex) {
        success = "false";
    } finally {
        try {
            if (fileObject != null) {
                fileObject.close();
            }
            if (fsManager != null) {
                fsManager.freeUnusedResources();
                fsManager.close();
                fsManager = null;
            }
        } catch (Exception ex) {

        } finally {
            fileObject = null;
            fsManager = null;
        }
    }

    return success;
}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Returns a VFS file object for a folder. If the  folder does not exist it is created.
 * @param parent The parent folder of the retrieved folder
 * @param name The name of the folder to retrieve
 * @return The folder//from  w w  w. j  a  v  a2s  .c  o m
 * @throws IOException
 */
public static FileObject getOrCreateFolder(FileObject parent, String name) throws IOException {
    if (!parent.getType().equals(FileType.FOLDER)) {
        throw new IllegalArgumentException("Parent file is no folder: " + parent.getName().getPathDecoded());
    }

    FileObject folder = parent.resolveFile(name);
    if (!folder.exists()) {
        if (!folder.getFileSystem().hasCapability(Capability.CREATE)) {
            throw new IOException("File system of file " + folder.getURL().toString() + " is read only");
        }
        folder.createFolder();
    }
    if (!folder.getType().equals(FileType.FOLDER)) {
        throw new IllegalArgumentException("There is already a file of this name: " + name);
    }
    return folder;
}

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

private List<ModuleFile> getModuleFiles(int type, FileObject dir, String prefix, String category)
        throws WGDesignSyncException, FileSystemException {

    // Find the valid suffixes for the type: Standard plus registered conversions
    Set<String> suffixes = new HashSet<String>();
    suffixes.add(getFileStandardSuffix(type, category));
    for (ModuleDefinition def : _core.getModuleRegistry()
            .getModulesForType(DesignResourceConversionModuleType.class).values()) {
        DesignResourceConversionProperties props = (DesignResourceConversionProperties) def.getProperties();
        if (props.getDesignType() == type
                && (props.getCodeType() == null || props.getCodeType().equals(category))) {
            for (String sfx : props.getSuffixes()) {
                suffixes.add("." + sfx);
            }//from w ww.  j a v  a2s  .  c om
        }
    }

    List<ModuleFile> moduleFiles = new ArrayList<ModuleFile>();
    if (dir == null || !dir.exists()) {
        return moduleFiles;
    }

    FileObject[] files = dir.getChildren();
    if (files == null) {
        throw new WGDesignSyncException("Cannot collect files from directory '" + dir.getName().getPathDecoded()
                + "'. Please verify directory existence.");
    }

    FileObject file;
    for (int i = 0; i < files.length; i++) {
        file = files[i];
        if (!isValidDesignFile(file)) {
            continue;
        }
        if (file.getType().equals(FileType.FOLDER)) {
            if (file.getName().getBaseName().equals(DesignDirectory.NAME_METADATADIR)) {
                continue;
            }
            String newPrefix = (prefix.trim().equals("") ? file.getName().getBaseName().toLowerCase()
                    : prefix + DIRECTORY_DIVIDER + file.getName().getBaseName().toLowerCase());
            moduleFiles.addAll(getModuleFiles(type, file, newPrefix, category));
        } else {
            // Test the file suffix
            if (!suffixes.contains("." + file.getName().getExtension())) {
                continue;
            }
            moduleFiles.add(new ModuleFile(file, prefix, category, type));
        }
    }

    return moduleFiles;

}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Resolves an eventually present directory link file (variant with Commons VFS file objects). Use this with folders that either may be used themselves or that contain a directory link pointing to the directory to use.
 * @param file The directory that might contain a directory link file.
 * @return Either the path that an available directory link file points to or the given directory itself again.
 *///ww w. ja  v a 2 s. co  m
public static FileObject resolveDirLink(FileObject file) throws FileSystemException {

    if (file != null && file.exists()) {
        if (file.getType().equals(FileType.FOLDER)) {
            FileObject link = file.resolveFile(DIRLINK_FILE);
            if (link.exists()) {
                // dir link present resolve

                Document doc;
                try {
                    InputStream fileInputStream = link.getContent().getInputStream();
                    String linkLocation = readDirLinkLocation(fileInputStream);
                    if (linkLocation != null) {
                        if (linkLocation.startsWith("../")) {
                            return file.resolveFile(linkLocation);
                        } else {
                            return file.getFileSystem().resolveFile(linkLocation);
                        }
                    }
                } catch (Exception e) {
                    Logger.getLogger("wga.utils")
                            .error("Unable to resolve dir link. '" + link.getName().getPath() + "'.", e);
                }
            }
        }
    }
    // no dir link or file does not exist - just return
    return file;

}

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/*from  w  ww  . j a  va  2  s . com*/
 * @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:com.sonicle.webtop.mail.Service.java

public void processRequestCloudFile(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {//from  w w w  . j av  a 2 s. c  om
        String subject = ServletUtils.getStringParameter(request, "subject", true);
        String path = "/Uploads";
        int sid = vfsmanager.getMyDocumentsStoreId();
        FileObject fo = vfsmanager.getStoreFile(sid, path);
        if (!fo.exists())
            fo.createFolder();

        String dirname = PathUtils
                .sanitizeFolderName(DateTimeUtils.createYmdHmsFormatter(environment.getProfile().getTimeZone())
                        .print(DateTimeUtils.now()) + " - " + subject);

        FileObject dir = fo.resolveFile(dirname);
        if (!dir.exists())
            dir.createFolder();

        JsonResult jsres = new JsonResult();
        jsres.put("storeId", sid);
        jsres.put("filePath", path + "/" + dirname + "/");
        jsres.printTo(out);
    } catch (Exception ex) {
        logger.error("Request cloud file failure", ex);
        new JsonResult(ex).printTo(out);
    }
}

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

/** Tells if a file or folder with the given path exists.
 * @param filePath filePath the path of the file to check
 * @return true if it exosts, otherwise false */
public boolean exists(String filePath) {
    File.verifyFilePath(filePath);
    try {/* w  w  w .j  av  a 2  s  .  c  om*/
        FileObject file = getFileObject(filePath);
        file.refresh();
        boolean result = file.exists();
        logger.debug("File '{}' {}", filePath, (result ? "exists" : "does not exist"));
        return result;
    } catch (IOException e) {
        throw new TechnicalException("Error checking file presence", e);
    }
}

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

protected boolean checkWritable(FileObject file, boolean overwrite) {
    try {/*from  w  w  w.j av a 2  s.  c o m*/
        if (file.exists()) {
            if (overwrite) {
                file.delete();
            } else {
                throw new FunctionalFailure("File expected to be absent: " + pathFromRoot(file));
            }
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        throw new TechnicalException("Error checking file", e);
    }
}

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

/** Tells if a file or folder with the given path exists. */
@Override/*from   w  ww . j a v a  2s  .  com*/
public boolean exists(String filePath) {
    FileUtil.verifyFilePath(filePath);
    try {
        FileObject file = getFileObject(filePath);
        file.refresh();
        boolean result = file.exists();
        LOGGER.debug("File '{}' {}", filePath, (result ? "exists" : "does not exist"));
        return result;
    } catch (FileSystemException e) {
        throw new TechnicalException("Error checking file presence", e);
    }
}

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

private boolean checkWritable(FileObject file, boolean overwrite) {
    try {// ww  w  .  j  av  a2  s .c  o m
        if (file.exists()) {
            if (overwrite) {
                file.delete();
            } else {
                throw new FunctionalFailure("File expected to be absent: " + pathFromRoot(file));
            }
            return true;
        } else {
            return false;
        }
    } catch (FileSystemException e) {
        throw new TechnicalException("Error checking file", e);
    }
}