Example usage for org.apache.commons.vfs2 FileType FILE

List of usage examples for org.apache.commons.vfs2 FileType FILE

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileType FILE.

Prototype

FileType FILE

To view the source code for org.apache.commons.vfs2 FileType FILE.

Click Source Link

Document

A regular file.

Usage

From source file:org.apache.metron.stellar.common.utils.VFSClassloaderUtil.java

/**
 * Resolve a set of URIs into FileObject objects.
 * This is not recursive. The URIs can refer directly to a file or directory or an optional regex at the end.
 * (NOTE: This is NOT a glob)./*w ww  .j  a va2s .co  m*/
 * @param vfs The file system manager to use to resolve URIs
 * @param uris comma separated URIs and URI + globs
 * @return
 * @throws FileSystemException
 */
static FileObject[] resolve(FileSystemManager vfs, String uris) throws FileSystemException {
    if (uris == null) {
        return new FileObject[0];
    }

    ArrayList<FileObject> classpath = new ArrayList<>();
    for (String path : uris.split(",")) {
        path = path.trim();
        if (path.equals("")) {
            continue;
        }
        FileObject fo = vfs.resolveFile(path);
        switch (fo.getType()) {
        case FILE:
        case FOLDER:
            classpath.add(fo);
            break;
        case IMAGINARY:
            // assume its a pattern
            String pattern = fo.getName().getBaseName();
            if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
                FileObject[] children = fo.getParent().getChildren();
                for (FileObject child : children) {
                    if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
                        classpath.add(child);
                    }
                }
            } else {
                LOG.warn("ignoring classpath entry {}", fo);
            }
            break;
        default:
            LOG.warn("ignoring classpath entry {}", fo);
            break;
        }
    }
    return classpath.toArray(new FileObject[classpath.size()]);
}

From source file:org.apache.olingo.fit.utils.FSManager.java

private FSManager() throws IOException {
    fsManager = VFS.getManager();// w ww .  j  a v a  2s . com

    final FileObject basePath = fsManager
            .resolveFile(RES_PREFIX + File.separatorChar + ODataServiceVersion.V40.name());
    final String absoluteBaseFolder = basePath.getURL().getPath();

    for (FileObject fo : find(basePath, null)) {
        if (fo.getType() == FileType.FILE && !fo.getName().getBaseName().contains("Metadata")
                && !fo.getName().getBaseName().contains("metadata")) {
            final String path = fo.getURL().getPath().replace(absoluteBaseFolder,
                    "//" + ODataServiceVersion.V40.name());
            putInMemory(fo.getContent().getInputStream(), path);
        }
    }
}

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/* w  w  w .  j  a  v  a 2  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) {
    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.apache.synapse.transport.vfs.VFSTransportSender.java

private void writeFile(MessageContext msgCtx, VFSOutTransportInfo vfsOutInfo) throws AxisFault {

    FileSystemOptions fso = null;/* w ww .  j a  v a  2  s . co  m*/
    try {
        fso = VFSUtils.attachFileSystemOptions(vfsOutInfo.getOutFileSystemOptionsMap(), fsManager);
    } catch (Exception e) {
        log.error("Error while attaching VFS file system properties. " + e.getMessage());
    }

    if (vfsOutInfo != null) {
        FileObject replyFile = null;
        try {

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

            while (wasError) {

                try {
                    retryCount++;
                    replyFile = fsManager.resolveFile(vfsOutInfo.getOutFileURI(), fso);

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

                } catch (FileSystemException e) {
                    log.error("cannot resolve replyFile", e);
                    if (maxRetryCount <= retryCount) {
                        handleException("cannot resolve replyFile repeatedly: " + e.getMessage(), e);
                    }
                }

                if (wasError) {
                    try {
                        Thread.sleep(reconnectionTimeout);
                    } catch (InterruptedException e2) {
                        e2.printStackTrace();
                    }
                }
            }

            //If the reply folder does not exists create the folder structure
            if (vfsOutInfo.isForceCreateFolder()) {
                String strPath = vfsOutInfo.getOutFileURI();
                int iIndex = strPath.indexOf("?");
                if (iIndex > -1) {
                    strPath = strPath.substring(0, iIndex);
                }
                //Need to add a slash otherwise vfs consider this as a file
                if (!strPath.endsWith("/") || !strPath.endsWith("\\")) {
                    strPath += "/";
                }
                FileObject replyFolder = fsManager.resolveFile(strPath, fso);
                if (!replyFolder.exists()) {
                    replyFile.createFolder();
                }
            }

            if (replyFile.exists()) {
                if (replyFile.getType() == FileType.FOLDER) {
                    // we need to write a file containing the message to this folder
                    FileObject responseFile = fsManager.resolveFile(replyFile,
                            VFSUtils.getFileName(msgCtx, vfsOutInfo));

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(responseFile, vfsOutInfo, fso);
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, true, fso);
                        VFSUtils.releaseLock(fsManager, responseFile, fso);
                    } else {
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, false, fso);
                    }

                } else if (replyFile.getType() == FileType.FILE) {

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(replyFile, vfsOutInfo, fso);
                        populateResponseFile(replyFile, msgCtx, append, true, fso);
                        VFSUtils.releaseLock(fsManager, replyFile, fso);
                    } else {
                        populateResponseFile(replyFile, msgCtx, append, false, fso);
                    }

                } else {
                    handleException("Unsupported reply file type : " + replyFile.getType() + " for file : "
                            + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()));
                }
            } else {
                // if file locking is not disabled acquire the lock before uploading the file
                if (vfsOutInfo.isFileLockingEnabled()) {
                    acquireLockForSending(replyFile, vfsOutInfo, fso);
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, true, fso);
                    VFSUtils.releaseLock(fsManager, replyFile, fso);
                } else {
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, false, fso);
                }
            }
        } catch (FileSystemException e) {
            handleException(
                    "Error resolving reply file : " + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()), e);
        } finally {
            if (replyFile != null) {
                try {/*
                     if (fsManager != null && replyFile.getParent() != null && replyFile.getParent().getFileSystem() != null) {
                     fsManager.closeFileSystem(replyFile.getParent().getFileSystem());
                     }*/
                    replyFile.close();
                } catch (FileSystemException ignore) {
                }
            }
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}

From source file:org.celeria.minecraft.backup.ArchiveWorldTaskTest.java

@Before
public void setUpFile() throws Exception {
    when(file.getType()).thenReturn(FileType.FILE);
    when(file.getName()).thenReturn(fileName);
}

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

/**
 * This method lists contents of a file or folder
 * @param file/*w ww.  jav a2s  .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.cloudifysource.esc.installer.filetransfer.VfsFileTransfer.java

@Override
public void copyFiles(final InstallationDetails details, final Set<String> excludedFiles,
        final List<File> additionalFiles, final long endTimeMillis)
        throws TimeoutException, InstallerException {

    logger.fine("Copying files to: " + host + " from local dir: " + localDir.getName().getPath() + " excluding "
            + excludedFiles.toString());

    try {/* w w  w.j  av  a2s.  c om*/

        if (remoteDir.exists()) {
            FileType type = remoteDir.getType();
            if (!type.equals(FileType.FOLDER)) {
                throw new InstallerException("The remote location: " + remoteDir.getName().getFriendlyURI()
                        + " exists but is not a directory");
            }

            if (deleteRemoteDirectoryContents) {
                logger.info("Deleting contents of remote directory: " + remoteDir.getName().getFriendlyURI());
                remoteDir.delete(new FileDepthSelector(1, Integer.MAX_VALUE));
            }
            FileObject[] children = remoteDir.getChildren();
            if (children.length > 0) {

                throw new InstallerException(
                        "The remote directory: " + remoteDir.getName().getFriendlyURI() + " is not empty");
            }
        }

        remoteDir.copyFrom(localDir, new FileSelector() {

            @Override
            public boolean includeFile(final FileSelectInfo fileInfo) throws Exception {
                if (excludedFiles.contains(fileInfo.getFile().getName().getBaseName())) {
                    logger.fine(fileInfo.getFile().getName().getBaseName() + " excluded");
                    return false;

                }
                final FileObject remoteFile = fileSystemManager.resolveFile(remoteDir,
                        localDir.getName().getRelativeName(fileInfo.getFile().getName()));

                if (!remoteFile.exists()) {
                    logger.fine(fileInfo.getFile().getName().getBaseName() + " missing on server");
                    return true;
                }

                if (fileInfo.getFile().getType() == FileType.FILE) {
                    final long remoteSize = remoteFile.getContent().getSize();
                    final long localSize = fileInfo.getFile().getContent().getSize();
                    final boolean res = localSize != remoteSize;
                    if (res) {
                        logger.fine(fileInfo.getFile().getName().getBaseName() + " different on server");
                    }
                    return res;
                }
                return false;

            }

            @Override
            public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception {
                return true;
            }
        });

        for (final File file : additionalFiles) {
            logger.fine("copying file: " + file.getAbsolutePath() + " to remote directory");
            final FileObject fileObject = fileSystemManager.resolveFile("file:" + file.getAbsolutePath());
            final FileObject remoteFile = remoteDir.resolveFile(file.getName());
            remoteFile.copyFrom(fileObject, new AllFileSelector());
        }

        logger.fine("Copying files to: " + host + " completed.");
    } catch (final FileSystemException e) {
        throw new InstallerException("Failed to copy files to remote host " + host + ": " + e.getMessage(), e);

    }
    checkTimeout(endTimeMillis);

}

From source file:org.datacleaner.bootstrap.Bootstrap.java

/**
 * Looks up a file, either based on a user requested filename (typically a
 * CLI parameter, may be a URL) or by a relative filename defined in the
 * system-/*ww  w  . ja  v a 2  s .c o m*/
 * 
 * @param userRequestedFilename
 *            the user requested filename, may be null
 * @param localFilename
 *            the relative filename defined by the system
 * @param userPreferences
 * @return
 * @throws FileSystemException
 */
private FileObject resolveFile(final String userRequestedFilename, final String localFilename,
        UserPreferences userPreferences) throws FileSystemException {
    final File dataCleanerHome = DataCleanerHome.getAsFile();
    if (userRequestedFilename == null) {
        File file = new File(dataCleanerHome, localFilename);
        return VFSUtils.toFileObject(file);
    } else {
        String lowerCaseFilename = userRequestedFilename.toLowerCase();
        if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) {
            if (!GraphicsEnvironment.isHeadless()) {
                // download to a RAM file.
                final FileObject targetDirectory = VFSUtils.getFileSystemManager()
                        .resolveFile("ram:///datacleaner/temp");
                if (!targetDirectory.exists()) {
                    targetDirectory.createFolder();
                }

                final URI uri;
                try {
                    uri = new URI(userRequestedFilename);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e);
                }

                final WindowContext windowContext = new SimpleWindowContext();

                MonitorConnection monitorConnection = null;

                // check if URI points to DC monitor. If so, make sure
                // credentials are entered.
                if (userPreferences != null && userPreferences.getMonitorConnection() != null) {
                    monitorConnection = userPreferences.getMonitorConnection();
                    if (monitorConnection.matchesURI(uri)) {
                        if (monitorConnection.isAuthenticationEnabled()) {
                            if (monitorConnection.getEncodedPassword() == null) {
                                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(
                                        windowContext, userPreferences);
                                dialog.openBlocking();
                            }
                            monitorConnection = userPreferences.getMonitorConnection();
                        }
                    }
                }

                try (MonitorHttpClient httpClient = getHttpClient(monitorConnection)) {

                    final String[] urls = new String[] { userRequestedFilename };
                    final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls);

                    final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames,
                            windowContext, httpClient, monitorConnection);

                    assert files.length == 1;

                    final FileObject ramFile = files[0];

                    if (logger.isInfoEnabled()) {
                        final InputStream in = ramFile.getContent().getInputStream();
                        try {
                            final String str = FileHelper
                                    .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8");
                            logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str);
                        } finally {
                            FileHelper.safeClose(in);
                        }
                    }

                    final String scheme = uri.getScheme();
                    final int defaultPort;
                    if ("http".equals(scheme)) {
                        defaultPort = 80;
                    } else {
                        defaultPort = 443;
                    }

                    final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(),
                            defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery());

                    AbstractFileSystem fileSystem = (AbstractFileSystem) VFSUtils.getBaseFileSystem();
                    return new DelegateFileObject(fileName, fileSystem, ramFile);
                } finally {
                    userPreferences.setMonitorConnection(monitorConnection);
                }

            }
        }

        return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename);
    }
}

From source file:org.datacleaner.user.DataCleanerHome.java

private static boolean isUsable(FileObject candidate) throws FileSystemException {
    if (candidate != null) {
        if (candidate.exists() && candidate.getType() == FileType.FOLDER) {
            FileObject conf = candidate.resolveFile("conf.xml");
            if (conf.exists() && conf.getType() == FileType.FILE) {
                return true;
            }/*w  w w . j a v a 2  s  .co m*/
        }
    }
    return false;
}

From source file:org.eobjects.datacleaner.bootstrap.Bootstrap.java

/**
 * Looks up a file, either based on a user requested filename (typically a
 * CLI parameter, may be a URL) or by a relative filename defined in the
 * system-//from  www . j a v  a  2s . co  m
 * 
 * @param userRequestedFilename
 *            the user requested filename, may be null
 * @param localFilename
 *            the relative filename defined by the system
 * @param userPreferences
 * @return
 * @throws FileSystemException
 */
private FileObject resolveFile(final String userRequestedFilename, final String localFilename,
        UserPreferences userPreferences) throws FileSystemException {
    final FileObject dataCleanerHome = DataCleanerHome.get();
    if (userRequestedFilename == null) {
        return dataCleanerHome.resolveFile(localFilename);
    } else {
        String lowerCaseFilename = userRequestedFilename.toLowerCase();
        if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) {
            if (!GraphicsEnvironment.isHeadless()) {
                // download to a RAM file.
                final FileObject targetDirectory = VFSUtils.getFileSystemManager()
                        .resolveFile("ram:///datacleaner/temp");
                if (!targetDirectory.exists()) {
                    targetDirectory.createFolder();
                }

                final URI uri;
                try {
                    uri = new URI(userRequestedFilename);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e);
                }

                final WindowContext windowContext = new SimpleWindowContext();

                @SuppressWarnings("resource")
                MonitorHttpClient httpClient = new SimpleWebServiceHttpClient();
                MonitorConnection monitorConnection = null;

                // check if URI points to DC monitor. If so, make sure
                // credentials are entered.
                if (userPreferences != null && userPreferences.getMonitorConnection() != null) {
                    monitorConnection = userPreferences.getMonitorConnection();
                    if (monitorConnection.matchesURI(uri)) {
                        if (monitorConnection.isAuthenticationEnabled()) {
                            if (monitorConnection.getEncodedPassword() == null) {
                                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(
                                        windowContext, userPreferences);
                                dialog.openBlocking();
                            }
                            monitorConnection = userPreferences.getMonitorConnection();
                            httpClient = monitorConnection.getHttpClient();
                        }
                    }
                }

                try {

                    final String[] urls = new String[] { userRequestedFilename };
                    final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls);

                    final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames,
                            windowContext, httpClient, monitorConnection);

                    assert files.length == 1;

                    final FileObject ramFile = files[0];

                    if (logger.isInfoEnabled()) {
                        final InputStream in = ramFile.getContent().getInputStream();
                        try {
                            final String str = FileHelper
                                    .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8");
                            logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str);
                        } finally {
                            FileHelper.safeClose(in);
                        }
                    }

                    final String scheme = uri.getScheme();
                    final int defaultPort;
                    if ("http".equals(scheme)) {
                        defaultPort = 80;
                    } else {
                        defaultPort = 443;
                    }

                    final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(),
                            defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery());

                    AbstractFileSystem fileSystem = (AbstractFileSystem) dataCleanerHome.getFileSystem();
                    return new DelegateFileObject(fileName, fileSystem, ramFile);
                } finally {
                    httpClient.close();

                    userPreferences.setMonitorConnection(monitorConnection);
                }

            }
        }

        return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename);
    }
}