Example usage for org.apache.commons.vfs2 FileSystemException FileSystemException

List of usage examples for org.apache.commons.vfs2 FileSystemException FileSystemException

Introduction

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

Prototype

public FileSystemException(final Throwable throwable) 

Source Link

Document

Constructs wrapper exception.

Usage

From source file:com.google.code.docbook4j.XslURIResolver.java

public Source resolve(String href, String base) throws TransformerException {

    log.debug("Resolving href={} for base={}", href, base);

    if (href == null || href.trim().length() == 0)
        return null;

    if (docbookXslBase == null && href.startsWith("res:") && href.endsWith("docbook.xsl")) {
        try {//www .j  a va  2s  . c o m
            docbookXslBase = FileObjectUtils.resolveFile(href).getParent().getURL().toExternalForm();
        } catch (FileSystemException e) {
            docbookXslBase = null;
        }
    }

    String normalizedBase = null;
    if (base != null) {
        try {
            normalizedBase = FileObjectUtils.resolveFile(base).getParent().getURL().toExternalForm();
        } catch (FileSystemException e) {
            normalizedBase = null;
        }
    }

    try {

        FileObject urlFileObject = FileObjectUtils.resolveFile(href, normalizedBase);

        if (!urlFileObject.exists())
            throw new FileSystemException("File object not found: " + urlFileObject);

        return new StreamSource(urlFileObject.getContent().getInputStream(),
                urlFileObject.getURL().toExternalForm());

    } catch (FileSystemException e) {

        // not exists for given base? try with docbook base...
        try {
            if (docbookXslBase != null) {
                FileObject urlFileObject = FileObjectUtils.resolveFile(href, docbookXslBase);
                return new StreamSource(urlFileObject.getContent().getInputStream(),
                        urlFileObject.getURL().toExternalForm());
            }

        } catch (FileSystemException e1) {
            // do nothing.
        }

        log.error("Error resolving href=" + href + " for base=" + base, e);
    }

    return null;

}

From source file:com.gs.obevo.util.vfs.FileObject.java

public URI getURI() {
    try {//from  w w  w.  ja v  a  2  s.  c  o m
        // Doing some URL encoding here (e.g. replacing sharp, spaces)
        // TODO want a general way to handle the URL encoding; may need improvements from commons VFS ...
        return new URI(this.getName().getURI().replace("#", "%23").replace(" ", "%20").replace("{", "%7B")
                .replace("}", "%7D"));
    } catch (URISyntaxException e) {
        throw new VFSFileSystemException(new FileSystemException(e));
    }
}

From source file:com.gs.obevo.util.vfs.FileObject.java

public URL getURLDa() {
    try {//from w w  w .j  av  a  2 s . c  om
        return this.getURI().toURL();
    } catch (MalformedURLException e) {
        throw new VFSFileSystemException(new FileSystemException(e));
    }
}

From source file:com.streamsets.pipeline.lib.remote.TestFTPRemoteConnector.java

protected void testVerifyAndReconnectHelper(RemoteConnector connector) throws Exception {
    FTPRemoteConnectorForTest con = (FTPRemoteConnectorForTest) connector;
    // We'll fail the first call to remoteDir.getChildren, which will cause verifyAndReconnect to replace remoteDir with
    // a new one//from w w  w.j a va  2  s. co  m
    con.remoteDir = Mockito.spy(con.remoteDir);
    FileObject originalRemoteDir = con.remoteDir;
    Mockito.when(con.remoteDir.getChildren()).thenThrow(new FileSystemException(""));
    connector.verifyAndReconnect();
    Assert.assertNotEquals(originalRemoteDir, con.remoteDir);
    verifyConnection(connector);
}

From source file:com.github.junrar.vfs2.provider.rar.RARFileSystem.java

@Override
public void init() throws FileSystemException {
    super.init();

    try {//  ww  w . j a v  a  2  s .co m
        try {
            archive = new Archive(new VFSVolumeManager(parentLayer));
            // Build the index
            List<RARFileObject> strongRef = new ArrayList<RARFileObject>(100);
            for (final FileHeader header : archive.getFileHeaders()) {
                AbstractFileName name = (AbstractFileName) getFileSystemManager().resolveName(getRootName(),
                        UriParser.encode(header.getFileNameString()));

                // Create the file
                RARFileObject fileObj;
                if (header.isDirectory() && getFileFromCache(name) != null) {
                    fileObj = (RARFileObject) getFileFromCache(name);
                    fileObj.setHeader(header);
                    continue;
                }

                fileObj = createRARFileObject(name, header);
                putFileToCache(fileObj);
                strongRef.add(fileObj);
                fileObj.holdObject(strongRef);

                // Make sure all ancestors exist
                RARFileObject parent;
                for (AbstractFileName parentName = (AbstractFileName) name
                        .getParent(); parentName != null; fileObj = parent, parentName = (AbstractFileName) parentName
                                .getParent()) {
                    // Locate the parent
                    parent = (RARFileObject) getFileFromCache(parentName);
                    if (parent == null) {
                        parent = createRARFileObject(parentName, null);
                        putFileToCache(parent);
                        strongRef.add(parent);
                        parent.holdObject(strongRef);
                    }

                    // Attach child to parent
                    parent.attachChild(fileObj.getName());
                }
            }

        } catch (RarException e) {
            throw new FileSystemException(e);
        } catch (IOException e) {
            throw new FileSystemException(e);
        }
    } finally {
        // closeCommunicationLink();
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.FSManager.java

public FileObject resolve(final String path) throws FileSystemException {
    FileObject res = fsManager.resolveFile(MEM_PREFIX + path);

    if (!res.exists()) {
        res = fsManager.resolveFile(RES_PREFIX + path);
    }// w w  w  .j a  v  a2s .  c o m

    if (!res.exists()) {
        throw new FileSystemException("Unresolved path " + path);
    }

    return res;
}

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

/**
 * Send the given message over the VFS transport
 *
 * @param msgCtx the axis2 message context
 * @throws AxisFault on error// w  w  w  . jav a2 s . c  om
 */
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    if (waitForSynchronousResponse(msgCtx)) {
        throw new AxisFault("The VFS transport doesn't support synchronous responses. "
                + "Please use the appropriate (out only) message exchange pattern.");
    }

    VFSOutTransportInfo vfsOutInfo = null;

    if (targetAddress != null) {
        vfsOutInfo = new VFSOutTransportInfo(targetAddress, globalFileLockingFlag);
    } else if (outTransportInfo != null && outTransportInfo instanceof VFSOutTransportInfo) {
        vfsOutInfo = (VFSOutTransportInfo) outTransportInfo;
    }

    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());

                    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 (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);
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, true);
                        VFSUtils.releaseLock(fsManager, responseFile);
                    } else {
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, false);
                    }

                } 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);
                        populateResponseFile(replyFile, msgCtx, append, true);
                        VFSUtils.releaseLock(fsManager, replyFile);
                    } else {
                        populateResponseFile(replyFile, msgCtx, append, false);
                    }

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

From source file:com.sludev.commons.vfs2.provider.azure.AzFileProvider.java

/**
 * Callback for handling the create File-System event
 * /*www. jav  a 2s.c o  m*/
 * @param rootName
 * @param fileSystemOptions
 * @return
 * @throws FileSystemException 
 */
@Override
protected FileSystem doCreateFileSystem(FileName rootName, FileSystemOptions fileSystemOptions)
        throws FileSystemException {
    AzFileSystem fileSystem = null;
    GenericFileName genRootName = (GenericFileName) rootName;

    StorageCredentials storageCreds;
    CloudStorageAccount storageAccount;
    CloudBlobClient client;

    FileSystemOptions currFSO = (fileSystemOptions != null) ? fileSystemOptions : getDefaultFileSystemOptions();
    UserAuthenticator ua = DefaultFileSystemConfigBuilder.getInstance().getUserAuthenticator(currFSO);

    UserAuthenticationData authData = null;
    try {
        authData = ua.requestAuthentication(AUTHENTICATOR_TYPES);

        String currAcct = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(genRootName.getUserName())));

        String currKey = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(genRootName.getPassword())));

        storageCreds = new StorageCredentialsAccountAndKey(currAcct, currKey);
        storageAccount = new CloudStorageAccount(storageCreds);

        client = storageAccount.createCloudBlobClient();

        fileSystem = new AzFileSystem(genRootName, client, fileSystemOptions);
    } catch (URISyntaxException ex) {
        throw new FileSystemException(ex);
    } finally {
        UserAuthenticatorUtils.cleanup(authData);
    }

    return fileSystem;
}

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 w  w.  j a va  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) {

    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:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to create lock file for multithreading.
 * //from  ww  w  .  ja  v a  2  s  .  c  om
 * @param targetPath
 *            Target file path
 * @return URI of lock file
 * @throws FileSystemException
 *             If lock file creation fails
 */
private String createLockFile(String targetPath) throws FileSystemException {
    FileObject lockFile = resolveFile(lockFilePath(targetPath));
    log.debug("About to create lock file: " + fileObjectNameForDebug(lockFile));
    if (lockFile.exists()) {
        throw new FileSystemException("Lock file " + fileObjectNameForDebug(lockFile)
                + " already exists, refusing to create lock file");
    }
    lockFile.createFile();
    log.debug("Created lock file " + fileObjectNameForDebug(lockFile));

    String uri = lockFile.getName().getURI();

    lockFile.close();

    return uri;
}