Example usage for org.apache.commons.vfs2.provider.ftp FtpFileSystemConfigBuilder getInstance

List of usage examples for org.apache.commons.vfs2.provider.ftp FtpFileSystemConfigBuilder getInstance

Introduction

In this page you can find the example usage for org.apache.commons.vfs2.provider.ftp FtpFileSystemConfigBuilder getInstance.

Prototype

public static FtpFileSystemConfigBuilder getInstance() 

Source Link

Document

Gets the singleton instance.

Usage

From source file:org.wso2.carbon.connector.util.FileConnectorUtils.java

public static FileSystemOptions init(MessageContext messageContext) {
    String setTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.SET_TIME_OUT);
    String setPassiveMode = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.SET_PASSIVE_MODE);
    String setSoTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.SET_SO_TIMEOUT);
    String setStrictHostKeyChecking = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.SET_STRICT_HOST_KEY_CHECKING);
    String setUserDirIsRoot = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.SET_USER_DIRISROOT);

    if (log.isDebugEnabled()) {
        log.debug("File init starts with " + setTimeout + "," + setPassiveMode + "," + "" + setSoTimeout + ","
                + setStrictHostKeyChecking + "," + setUserDirIsRoot);
    }/*  w ww .  j av a  2  s.  c om*/
    FileSystemOptions opts = new FileSystemOptions();
    // SSH Key checking
    try {
        if (StringUtils.isEmpty(setStrictHostKeyChecking)) {
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        } else {
            setStrictHostKeyChecking = setStrictHostKeyChecking.trim();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, setStrictHostKeyChecking);
        }
    } catch (FileSystemException e) {
        throw new SynapseTaskException("Error while configuring a " + "setStrictHostKeyChecking", e);
    }
    // Root directory set to user home
    if (StringUtils.isEmpty(setUserDirIsRoot)) {
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
    } else {
        setUserDirIsRoot = setUserDirIsRoot.trim();
        try {
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, Boolean.valueOf(setUserDirIsRoot));
        } catch (Exception e) {
            throw new SynapseTaskException("Error while configuring a " + "setUserDirIsRoot", e);
        }
    }
    // Timeout is count by Milliseconds
    if (StringUtils.isEmpty(setTimeout)) {
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, FileConstants.TIME_OUT);
    } else {
        setTimeout = setTimeout.trim();
        try {
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, Integer.parseInt(setTimeout));
        } catch (NumberFormatException e) {
            throw new SynapseTaskException("Error while configuring a " + "setTimeout", e);
        }
    }
    if (StringUtils.isEmpty(setPassiveMode)) {
        FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
        FtpsFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    } else {
        setPassiveMode = setPassiveMode.trim();
        try {
            FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, Boolean.valueOf(setPassiveMode));
            FtpsFileSystemConfigBuilder.getInstance().setPassiveMode(opts, Boolean.valueOf(setPassiveMode));
        } catch (Exception e) {
            throw new SynapseTaskException("Error while configuring a " + "setPassiveMode", e);
        }
    }
    if (StringUtils.isEmpty(setSoTimeout)) {
        FtpFileSystemConfigBuilder.getInstance().setSoTimeout(opts, FileConstants.TIME_OUT);
    } else {
        setSoTimeout = setSoTimeout.trim();
        try {
            FtpFileSystemConfigBuilder.getInstance().setSoTimeout(opts, Integer.parseInt(setSoTimeout));
        } catch (NumberFormatException e) {
            throw new SynapseTaskException("Error while configuring a " + "setSoTimeout", e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("FileConnector configuration is completed.");
    }
    return opts;
}

From source file:org.wso2.carbon.connector.util.FTPSiteUtils.java

/**
 * Get the default options for File system
 * /*w ww . ja  va 2s  . c  o m*/
 * @return
 * @throws FileSystemException
 */
public static FileSystemOptions createDefaultOptions() throws FileSystemException {
    FileSystemOptions opts = new FileSystemOptions();

    // SSH Key checking
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

    // Root directory set to user home
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

    // Timeout is count by Milliseconds

    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 100000);

    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);

    FtpFileSystemConfigBuilder.getInstance().setSoTimeout(opts, 100000);

    FtpsFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);

    return opts;

}

From source file:org.wso2.carbon.transport.file.connector.sender.VFSClientConnector.java

@Override
public Object init(CarbonMessage cMsg, CarbonCallback callback, Map<String, Object> properties)
        throws ClientConnectorException {
    //TODO: Handle FS options configuration for other protocols as well
    if (Constants.PROTOCOL_FTP.equals(properties.get("PROTOCOL"))) {
        properties.forEach((property, value) -> {
            // TODO: Add support for other FTP related configurations
            if (Constants.FTP_PASSIVE_MODE.equals(property)) {
                FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, (Boolean) value);
            }//www  . j a v  a2s  . c  o  m
        });
    }

    return Boolean.TRUE;
}

From source file:org.wso2.carbon.transport.file.connector.sender.VFSClientConnector.java

@Override
public boolean send(CarbonMessage carbonMessage, CarbonCallback carbonCallback, Map<String, String> map)
        throws ClientConnectorException {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = map.get(Constants.FILE_URI);
    String action = map.get(Constants.ACTION);
    FileType fileType;/*w  w w  .  j a  v  a2 s .  co  m*/
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {

        case Constants.CREATE:
            boolean isFolder = Boolean.parseBoolean(map.getOrDefault("create-folder", "false"));
            if (path.exists()) {
                throw new ClientConnectorException("File already exists: " + path.getName().getURI());
            }
            if (isFolder) {
                path.createFolder();
            } else {
                path.createFile();
            }
            break;
        case Constants.WRITE:
            if (!path.exists()) {
                path.createFile();
                path.refresh();
                fileType = path.getType();
            }
            if (fileType == FileType.FILE) {
                if (carbonMessage instanceof BinaryCarbonMessage) {
                    BinaryCarbonMessage binaryCarbonMessage = (BinaryCarbonMessage) carbonMessage;
                    byteBuffer = binaryCarbonMessage.readBytes();
                } else {
                    throw new ClientConnectorException("Carbon message received is not a BinaryCarbonMessage");
                }
                byte[] bytes = byteBuffer.array();
                if (map.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(map.get(Constants.APPEND)));
                } else {
                    outputStream = path.getContent().getOutputStream();
                }
                outputStream.write(bytes);
                outputStream.flush();
            }
            break;
        case Constants.DELETE:
            if (path.exists()) {
                int filesDeleted = path.delete(Selectors.SELECT_ALL);
                if (logger.isDebugEnabled()) {
                    logger.debug(filesDeleted + " files successfully deleted");
                }
            } else {
                throw new ClientConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = map.get("destination");
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new ClientConnectorException(
                        "Failed to copy file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.MOVE:
            if (path.exists()) {
                //TODO: Improve this to fix issue #331
                String destination = map.get("destination");
                FileObject newPath = fsManager.resolveFile(destination, opts);
                FileObject parent = newPath.getParent();
                if (parent != null && !parent.exists()) {
                    parent.createFolder();
                }
                if (!newPath.exists()) {
                    path.moveTo(newPath);
                } else {
                    throw new ClientConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new ClientConnectorException(
                        "Failed to move file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.READ:
            if (path.exists()) {
                //TODO: Do not assume 'path' always refers to a file
                inputStream = path.getContent().getInputStream();
                byte[] bytes = toByteArray(inputStream);
                BinaryCarbonMessage message = new BinaryCarbonMessage(ByteBuffer.wrap(bytes), true);
                message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                        org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
                carbonMessageProcessor.receive(message, carbonCallback);
            } else {
                throw new ClientConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            TextCarbonMessage message = new TextCarbonMessage(Boolean.toString(path.exists()));
            message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                    org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
            carbonMessageProcessor.receive(message, carbonCallback);
            break;
        default:
            return false;
        }
    } catch (RuntimeException e) {
        throw new ClientConnectorException("Runtime Exception occurred : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new ClientConnectorException("Exception occurred while processing file: " + e.getMessage(), e);
    } finally {
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
    return true;
}

From source file:org.wso2.carbon.transport.file.connector.server.FileConsumer.java

public FileConsumer(String id, Map<String, String> fileProperties, CarbonMessageProcessor messageProcessor)
        throws ServerConnectorException {
    this.serviceName = id;
    this.fileProperties = fileProperties;
    this.messageProcessor = messageProcessor;

    setupParams();/*from w w w.j av a  2s. c om*/
    try {
        StandardFileSystemManager fsm = new StandardFileSystemManager();
        fsm.setConfiguration(getClass().getClassLoader().getResource("providers.xml"));
        fsm.init();
        fsManager = fsm;
    } catch (FileSystemException e) {
        throw new ServerConnectorException(
                "Could not initialize File System Manager from " + "the configuration: providers.xml", e);
    }
    Map<String, String> options = parseSchemeFileOptions(fileURI);
    fso = FileTransportUtils.attachFileSystemOptions(options, fsManager);

    if (options != null && Constants.SCHEME_FTP.equals(options.get(Constants.SCHEME))) {
        FtpFileSystemConfigBuilder.getInstance().setPassiveMode(fso, true);
    }

    try {
        fileObject = fsManager.resolveFile(fileURI, fso);
    } catch (FileSystemException e) {
        throw new FileServerConnectorException(
                "Failed to resolve fileURI: " + FileTransportUtils.maskURLPassword(fileURI), e);
    }
}

From source file:org.wso2.carbon.transport.filesystem.connector.server.FileSystemConsumer.java

/**
 * Constructor for the FileSystemConsumer.
 *
 * @param id                Name of the service that creates the consumer
 * @param fileProperties    Map of property values
 * @param messageProcessor  Message processor instance
 *//*from  www. j a  va2  s  .  c o m*/
FileSystemConsumer(String id, Map<String, String> fileProperties, CarbonMessageProcessor messageProcessor,
        ServerConnectorErrorHandler errorHandler) throws ServerConnectorException {
    this.serviceName = id;
    this.fileProperties = fileProperties;
    this.messageProcessor = messageProcessor;
    this.errorHandler = errorHandler;

    setupParams();
    try {
        fsManager = VFS.getManager();

        Map<String, String> options = parseSchemeFileOptions(listeningDirURI);
        fso = FileTransportUtils.attachFileSystemOptions(options, fsManager);

        // TODO: Make this and other file related configurations configurable
        if (options != null && Constants.SCHEME_FTP.equals(options.get(Constants.SCHEME))) {
            FtpFileSystemConfigBuilder.getInstance().setPassiveMode(fso, true);
        }

        try {
            listeningDir = fsManager.resolveFile(listeningDirURI, fso);
        } catch (FileSystemException e) {
            this.errorHandler.handleError(new FileSystemServerConnectorException(
                    "Failed to resolve listeningDirURI: " + FileTransportUtils.maskURLPassword(listeningDirURI),
                    e), null, null);
        }
    } catch (FileSystemException e) {
        this.errorHandler.handleError(new ServerConnectorException(
                "Could not initialize File System Manager from " + "the configuration: providers.xml", e), null,
                null);
    }

    try {
        if (!listeningDir.isWriteable()) {
            postProcessAction = Constants.ACTION_NONE;
        }
    } catch (FileSystemException e) {
        this.errorHandler
                .handleError(new FileSystemServerConnectorException("Exception while determining file: "
                        + FileTransportUtils.maskURLPassword(listeningDirURI) + " is writable", e), null, null);
    }

    FileType fileType = getFileType(listeningDir);
    if (fileType != FileType.FOLDER) {
        this.errorHandler
                .handleError(
                        new FileSystemServerConnectorException("File system server connector is used to "
                                + "listen to a folder. But the given path does not refer to a folder."),
                        null, null);
    }
    //Initialize the thread executor based on properties
    ThreadPoolFactory.createInstance(threadPoolSize, parallelProcess);
}

From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java

public VFSClientConnectorImpl(Map<String, String> connectorConfig,
        RemoteFileSystemListener remoteFileSystemListener) {
    this.connectorConfig = connectorConfig;
    this.remoteFileSystemListener = remoteFileSystemListener;

    if (Constants.PROTOCOL_FTP.equals(connectorConfig.get(Constants.PROTOCOL))) {
        connectorConfig.forEach((property, value) -> {
            // TODO: Add support for other FTP related configurations
            if (Constants.FTP_PASSIVE_MODE.equals(property)) {
                FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, Boolean.parseBoolean(value));
            }//from   ww w  .  ja v  a 2s.  c om
        });
    }
}

From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java

@Override
public void send(RemoteFileSystemMessage message) {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = connectorConfig.get(Constants.URI);
    String action = connectorConfig.get(Constants.ACTION);
    FileType fileType;//from  www  .j  av  a2  s  . c o m
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    FileObject path = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {
        case Constants.CREATE:
            boolean isFolder = Boolean
                    .parseBoolean(connectorConfig.getOrDefault(Constants.CREATE_FOLDER, "false"));
            if (path.exists()) {
                throw new RemoteFileSystemConnectorException("File already exists: " + path.getName().getURI());
            }
            if (isFolder) {
                path.createFolder();
            } else {
                path.createFile();
            }
            break;
        case Constants.WRITE:
            if (!path.exists()) {
                path.createFile();
                path.refresh();
                fileType = path.getType();
            }
            if (fileType == FileType.FILE) {
                byteBuffer = message.getBytes();
                byte[] bytes = byteBuffer.array();
                if (connectorConfig.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(connectorConfig.get(Constants.APPEND)));
                } else {
                    outputStream = path.getContent().getOutputStream();
                }
                outputStream.write(bytes);
                outputStream.flush();
            }
            break;
        case Constants.DELETE:
            if (path.exists()) {
                int filesDeleted = path.delete(Selectors.SELECT_ALL);
                if (logger.isDebugEnabled()) {
                    logger.debug(filesDeleted + " files successfully deleted");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to copy file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.MOVE:
            if (path.exists()) {
                //TODO: Improve this to fix issue #331
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject newPath = fsManager.resolveFile(destination, opts);
                FileObject parent = newPath.getParent();
                if (parent != null && !parent.exists()) {
                    parent.createFolder();
                }
                if (!newPath.exists()) {
                    path.moveTo(newPath);
                } else {
                    throw new RemoteFileSystemConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to move file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.READ:
            if (path.exists()) {
                //TODO: Do not assume 'path' always refers to a file
                inputStream = path.getContent().getInputStream();
                byte[] bytes = toByteArray(inputStream);
                RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(ByteBuffer.wrap(bytes));
                remoteFileSystemListener.onMessage(fileContent);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(Boolean.toString(path.exists()));
            remoteFileSystemListener.onMessage(fileContent);
            break;
        default:
            break;
        }
        remoteFileSystemListener.done();
    } catch (RemoteFileSystemConnectorException | IOException e) {
        remoteFileSystemListener.onError(e);
    } finally {
        if (path != null) {
            try {
                path.close();
            } catch (FileSystemException e) {
                //Do nothing.
            }
        }
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
}

From source file:org.wso2.carbon.transport.remotefilesystem.server.RemoteFileSystemConsumer.java

/**
 * Constructor for the RemoteFileSystemConsumer.
 *
 * @param id                Name of the service that creates the consumer
 * @param fileProperties    Map of property values
 * @param listener  RemoteFileSystemListener instance to send callback
 * @throws RemoteFileSystemConnectorException if unable to start the connect to the remote server
 *///from   w  ww . j  ava  2s.c  o  m
public RemoteFileSystemConsumer(String id, Map<String, String> fileProperties,
        RemoteFileSystemListener listener) throws RemoteFileSystemConnectorException {
    this.serviceName = id;
    this.fileProperties = fileProperties;
    this.remoteFileSystemListener = listener;
    setupParams();
    try {
        fsManager = VFS.getManager();
        Map<String, String> options = parseSchemeFileOptions(listeningDirURI);
        fso = FileTransportUtils.attachFileSystemOptions(options, fsManager);
        // TODO: Make this and other file related configurations configurable
        if (options != null && Constants.SCHEME_FTP.equals(options.get(Constants.SCHEME))) {
            FtpFileSystemConfigBuilder.getInstance().setPassiveMode(fso, true);
        }
        listeningDir = fsManager.resolveFile(listeningDirURI, fso);
        if (!listeningDir.isWriteable()) {
            postProcessAction = Constants.ACTION_NONE;
        }
        FileType fileType = getFileType(listeningDir);
        if (fileType != FileType.FOLDER) {
            String errorMsg = "[" + serviceName + "] File system server connector is used to "
                    + "listen to a folder. But the given path does not refer to a folder.";
            final RemoteFileSystemConnectorException exception = new RemoteFileSystemConnectorException(
                    errorMsg);
            remoteFileSystemListener.onError(exception);
            throw exception;
        }
        //Initialize the thread executor based on properties
        threadPool = new ThreadPoolFactory(threadPoolSize);
    } catch (FileSystemException e) {
        remoteFileSystemListener.onError(e);
        throw new RemoteFileSystemConnectorException(
                "[" + serviceName + "] Unable to initialize " + "the connection with server.", e);
    }
}

From source file:pl.otros.vfs.browser.util.VFSUtils.java

/**
 * Returns a file representation/* w  w  w. ja  va  2 s. c om*/
 *
 * @param filePath The file path
 * @return a file representation
 * @throws FileSystemException
 */
public static FileObject resolveFileObject(String filePath) throws FileSystemException {
    LOGGER.info("Resolving file: {}", filePath);
    if (filePath.startsWith("sftp://")) {
        SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
        builder.setStrictHostKeyChecking(opts, "no");
        builder.setUserDirIsRoot(opts, false);
        builder.setCompression(opts, "zlib,none");

    } else if (filePath.startsWith("smb://")) {

    } else if (filePath.startsWith("ftp://")) {
        FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    }
    UserAuthenticatorFactory factory = new UserAuthenticatorFactory();

    OtrosUserAuthenticator authenticator = factory.getUiUserAuthenticator(persistentAuthStore, sessionAuthStore,
            filePath, opts);

    if (pathContainsCredentials(filePath)) {
        authenticator = null;
    }
    return resolveFileObject(filePath, opts, authenticator, persistentAuthStore, sessionAuthStore);
}