Example usage for org.apache.commons.vfs2.impl StandardFileSystemManager StandardFileSystemManager

List of usage examples for org.apache.commons.vfs2.impl StandardFileSystemManager StandardFileSystemManager

Introduction

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

Prototype

StandardFileSystemManager

Source Link

Usage

From source file:fr.cls.atoll.motu.library.misc.ftp.TestFtp.java

public static void testVFS(String user, String pwd, String scheme, String host, String file) {

    StandardFileSystemManager fsManager = null;

    try {//from w ww.  ja  va  2  s  .c  o  m
        fsManager = new StandardFileSystemManager();
        fsManager.setLogger(_LOG);

        StaticUserAuthenticator auth = new StaticUserAuthenticator(null, user, pwd);

        fsManager.setConfiguration(ConfigLoader.getInstance().get(Organizer.getVFSProviderConfig()));
        fsManager.setCacheStrategy(CacheStrategy.ON_RESOLVE);
        // fsManager.addProvider("moi", new DefaultLocalFileProvider());
        fsManager.init();

        FileSystemOptions opts = new FileSystemOptions();
        FileSystemConfigBuilder fscb = fsManager.getFileSystemConfigBuilder(scheme);
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

        System.out.println(fsManager.getProviderCapabilities(scheme));

        if (fscb instanceof FtpFileSystemConfigBuilder) {
            FtpFileSystemConfigBuilder ftpFscb = (FtpFileSystemConfigBuilder) fscb;
            ftpFscb.setUserDirIsRoot(opts, true);
            ftpFscb.setPassiveMode(opts, true);

        }
        if (fscb instanceof HttpFileSystemConfigBuilder) {
            HttpFileSystemConfigBuilder httpFscb = (HttpFileSystemConfigBuilder) fscb;
            httpFscb.setProxyHost(opts, "proxy.cls.fr");
            httpFscb.setProxyPort(opts, 8080);

        }
        if (fscb instanceof SftpFileSystemConfigBuilder) {
            SftpFileSystemConfigBuilder sftpFscb = (SftpFileSystemConfigBuilder) fscb;
            sftpFscb.setUserDirIsRoot(opts, false);

            // TrustEveryoneUserInfo trustEveryoneUserInfo = new TrustEveryoneUserInfo();
            // trustEveryoneUserInfo.promptYesNo("eddfsdfs");
            // sftpFscb.setUserInfo(opts, new TrustEveryoneUserInfo());
            sftpFscb.setTimeout(opts, 5000);
            // SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            // SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

        }
        // FileObject fo =
        // fsManager.resolveFile("ftp://ftp.cls.fr/pub/oceano/AVISO/NRT-SLA/maps/rt/j2/h/msla_rt_j2_err_21564.nc.gz",
        // opts);

        // String uri = String.format("%s://%s/%s", scheme, host, file);
        // String uri = String.format("%s://%s/", scheme, host);
        // FileObject originBase = fsManager.resolveFile(uri, opts);
        // fsManager.setBaseFile(originBase);

        File tempDir = new File("c:/tempVFS");
        // File tempFile = File.createTempFile("AsciiEnvisat", ".txt", tempDir);
        File hostFile = new File(file);
        String fileName = hostFile.getName();
        File newFile = new File(tempDir, fileName);
        newFile.createNewFile();

        DefaultFileReplicator dfr = new DefaultFileReplicator(tempDir);
        fsManager.setTemporaryFileStore(dfr);
        // System.out.println(fsManager.getBaseFile());
        // System.out.println(dfr);
        // System.out.println(fsManager.getTemporaryFileStore());

        // FileObject ff = fsManager.resolveFile("sftp://t:t@CLS-EARITH.pc.cls.fr/AsciiEnvisat.txt",
        // opts);
        String uri = String.format("%s://%s/%s", scheme, host, file);
        FileObject ff = fsManager.resolveFile(uri, opts);
        FileObject dest = fsManager.toFileObject(newFile);

        //ff.getContent().getInputStream();
        dest.copyFrom(ff, Selectors.SELECT_ALL);
        //dest.copyFrom(ff, Selectors.SELECT_ALL);

        //            
        // URL url = ff.getURL();
        //            
        // url.openConnection();
        // URLConnection conn = url.openConnection();
        // InputStream in = conn.getInputStream();
        // in.close();

        // InputStream in = ff.getContent().getInputStream();

    } catch (FileSystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // fsManager.close();
        // fsManager.freeUnusedResources();
    }

}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void initializeOverlay(RemoteSession session, PluginInfo pluginInfo, String designFolder)
        throws WGAServiceException {

    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    try {//from   ww  w.j  a v  a2s  . com
        fsManager.init();
        if (!isAdminServiceEnabled()) {
            throw new WGAServiceException("Administrative services are disabled");
        }

        if (!isAdminSession(session)) {
            throw new WGAServiceException("You need an administrative login to access this service.");
        }

        WGAPlugin basePlugin = _core.getPluginSet().getPluginsByInstallationKey()
                .get(pluginInfo.getInstallationKey());
        if (basePlugin == null) {
            throw new WGAServiceException(
                    "No plugin is installed with installation key " + pluginInfo.getInstallationKey());
        }
        WGDatabase pluginDB = _core.getContentdbs().get(basePlugin.buildDatabaseKey());
        if (pluginDB == null) {
            throw new WGAServiceException(
                    "Plugin database not connected for plugin " + basePlugin.getIdentification());
        }

        FileSystemDesignSource fsDesignSource = (FileSystemDesignSource) _core.getDesignManager()
                .getDesignSources().get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
        WGADesign overlayDesign = fsDesignSource.getDesign(designFolder);
        if (overlayDesign == null) {
            throw new WGAServiceException("File Directory Design '" + designFolder + "' does not exist");
        }

        String designFolderLocation = fsDesignSource.getDesignLocation(overlayDesign);

        FileObject designFolderObj = fsManager.resolveFile(designFolderLocation);
        if (!designFolderObj.exists() || !designFolderObj.getType().equals(FileType.FOLDER)) {
            throw new WGAServiceException(
                    "Design folder '" + designFolder + "' cannot be found or is no folder");
        }

        // Determine design encoding of folder to import to
        DesignDefinition designDef = null;
        FileObject designDefFile = designFolderObj.resolveFile("design.xml");
        if (designDefFile.exists()) {
            designDef = DesignDefinition.load(designDefFile);
        }

        CSConfig csConfig = null;
        FileObject csConfigFile = designFolderObj.resolveFile("files/system/csconfig.xml");
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }

        String designEncoding = FileSystemDesignManager.determineDesignEncoding(designDef, csConfig);

        // Trigger overlay init/uprade process
        OverlayStatus status = FileSystemDesignProvider.determineOverlayStatus(
                (FileSystemDesignProvider) pluginDB.getDesignProvider(), basePlugin.getPluginID(),
                designFolderObj, designEncoding, _core.getLog(), _core.getDesignFileValidator());
        FileSystemDesignProvider.upgradeOverlay((FileSystemDesignProvider) pluginDB.getDesignProvider(),
                basePlugin.getPluginID(), status, designFolderObj, designEncoding, _core.getLog(),
                _core.getDesignFileValidator());

        // Disconnect consumer apps
        WGADesignManager designManager = _core.getDesignManager();
        for (WGDatabase consumerDb : _core.getContentdbs().values()) {

            WGDesignProvider provider = consumerDb.getDesignProvider();
            if (provider instanceof OverlayDesignProvider) {
                OverlayDesignProvider overlayProvider = (OverlayDesignProvider) provider;
                if (overlayProvider.getOverlay() instanceof FileSystemDesignProvider) {
                    FileSystemDesignProvider fsProvider = (FileSystemDesignProvider) overlayProvider
                            .getOverlay();
                    if (fsProvider.getBaseFolder().equals(designFolderObj)) {
                        _core.removeContentDB(consumerDb.getDbReference());
                    }
                }
            }
        }

        // Run update content dbs to reconnect
        _core.updateContentDBs();

    } catch (Exception e) {
        if (e instanceof WGAServiceException) {
            throw (WGAServiceException) e;
        } else {
            throw new WGAServiceException("Overlay initialisation failed.", e);
        }
    } finally {
        fsManager.close();
    }

}

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

/** Creates a new FileServiceConfiguration object which wraps the given Preferences object.
 * /*from   www.j  ava  2  s  .  c om*/
 * @param configuration Preferences configuration object to wrap.
 * 
 * @throws FileSystemException If an exception occurs when applying the configuration to the VFS Config Builders. */
public FileServiceConfiguration(Preferences configuration) throws FileSystemException {
    this.configuration = new ValidatingPreferencesWrapper(configuration);

    // Configure secured access
    FileSystemOptions fileSystemOptions = new FileSystemOptions();
    String protocol = getProtocol();
    String baseUrl = getBaseUrl();
    String user = getUser();
    String password = getPassword();

    if (user != null || password != null) {
        UserAuthenticator authenticator = new StaticUserAuthenticator(protocol, user, password);
        DefaultFileSystemConfigBuilder builder = DefaultFileSystemConfigBuilder.getInstance();
        builder.setUserAuthenticator(fileSystemOptions, authenticator);
    }
    if ("ftp".equals(protocol)) {
        FtpFileSystemConfigBuilder builder = FtpFileSystemConfigBuilder.getInstance();
        builder.setUserDirIsRoot(fileSystemOptions, false);
        builder.setDataTimeout(fileSystemOptions, getTimeout());
        builder.setSoTimeout(fileSystemOptions, getTimeout());
        builder.setPassiveMode(fileSystemOptions, true);
    }

    // configure FileObject for root folder
    this.manager = new StandardFileSystemManager();
    this.manager.init();
    this.rootFolder = manager.resolveFile(protocol + "://" + baseUrl, fileSystemOptions);

    // access all configuration element in order to verify a complete configuration
    getEncoding();
    getLinefeed();
    getPollingDelay();
    getWaitMaxRetries();
    getTimeout();
    getRootFolder();
    getFileObject("/");
    getHost();
    isWritingPermitted();

}

From source file:org.anarres.filechooser.impl.vfs2.VFSJFileChooserTest.java

@Test
public void testFileChooser() throws Exception {
    StandardFileSystemManager manager = new StandardFileSystemManager();
    manager.init();//  w  w  w.j  a va2 s .  co m

    final FileObject root = manager.resolveFile("ram:/");
    FileObject foo = root.resolveFile("foo");
    foo.createFolder();
    foo.resolveFile("foo0").createFile();
    foo.resolveFile("foo1").createFile();
    root.resolveFile("bar").createFile();

    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                CommonsVfs2JFileChooser chooser = new CommonsVfs2JFileChooser();
                chooser.setMultiSelectionEnabled(true);
                chooser.setCurrentDirectory(root);
                VFSJFileChooser.RETURN_TYPE ret = chooser.showOpenDialog(null);
                LOG.info("RETURN_TYPE = " + ret);
                LOG.info("Selected FO  = " + chooser.getSelectedFile());
                LOG.info("Selected FOs = " + Arrays.toString(chooser.getSelectedFiles()));
                print(chooser.getSelectedFile());
                for (FileObject file : chooser.getSelectedFiles()) {
                    print(file);
                }
            } catch (FileSystemException e) {
                throw new RuntimeException(e);
            }
        }
    });

    Robot robot = BasicRobot.robotWithCurrentAwtHierarchy();
    robot.waitForIdle();

    VFSJFileChooserFixture<FileObject> chooser = VFSJFileChooserFinder.<FileObject>findFileChooser()
            .using(robot);
    // Thread.sleep(2000);
    chooser.setCurrentDirectory(foo);
    // Thread.sleep(2000);
    chooser.approve();
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function returns a new private StandardFileSystemManager. It is the caller's responsibility to close the
 * manager and release any resources associated with its file systems.
 *//*from www.  j  a  va  2  s .  c o m*/
public static FileSystemManagerWrapper getNewManager() throws FileSystemException {
    // create new file system manager
    final StandardFileSystemManager fsManager = new StandardFileSystemManager();
    fsManager.setConfiguration(VFSUtilities.class.getResource("vfs-providers.xml")); //$NON-NLS-1$
    fsManager.init();

    configureManager(fsManager);

    return new FileSystemManagerWrapper(fsManager, FILE_SYSTEM_MANAGER_DELEGATE);
}

From source file:org.schedoscope.export.ftp.upload.Uploader.java

private void initFileSystem(Configuration conf, boolean passive, boolean userIsRoot) throws IOException {

    this.fsManager = new StandardFileSystemManager();
    this.fsManager.init();
    this.opts = new FileSystemOptions();

    // configure hdfs file system
    HdfsFileSystemConfigBuilder.getInstance().setConfigConfiguration(opts, conf);

    // configure sftp file system
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, userIsRoot);

    // configure ftp file system
    FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, userIsRoot);
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, passive);
}

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

public static StandardFileSystemManager getManager() {
    StandardFileSystemManager fsm = null;
    try {/*from   w w  w. j a v a2s.  c  o m*/
        fsm = new StandardFileSystemManager();
        fsm.init();
    } catch (FileSystemException e) {
        log.error("Unable to get FileSystemManager: " + e.getMessage(), e);
    }
    return fsm;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java

public FilePollingConsumer(Properties vfsProperties, String name, SynapseEnvironment synapseEnvironment,
        long scanInterval) {
    this.vfsProperties = vfsProperties;
    this.name = name;
    this.synapseEnvironment = synapseEnvironment;
    this.scanInterval = scanInterval;
    this.lastRanTime = null;

    setupParams();//from   w w w .j a v a 2  s. c om
    try {
        StandardFileSystemManager fsm = new StandardFileSystemManager();
        fsm.setConfiguration(getClass().getClassLoader().getResource("providers.xml"));
        fsm.init();
        fsManager = fsm;
    } catch (Exception e) {
        log.error(e);
        throw new RuntimeException(e);
    }
    //Setup SFTP Options
    try {
        fso = VFSUtils.attachFileSystemOptions(parseSchemeFileOptions(fileURI), fsManager);
    } catch (Exception e) {
        log.warn("Unable to set the sftp Options", e);
        fso = null;
    }
}

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  a v a2 s .  c o  m
    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:pl.otros.vfs.browser.util.VFSUtils.java

/**
 * Returns the global filesystem manager
 *
 * @return the global filesystem manager
 */// w  w  w . ja v  a2 s.c om
public static FileSystemManager getFileSystemManager() {
    aLock.readLock().lock();

    try {
        if (fileSystemManager == null) {
            try {
                StandardFileSystemManager fm = new StandardFileSystemManager();
                fm.setCacheStrategy(CacheStrategy.MANUAL);
                fm.init();
                LOGGER.info("Supported schemes: {} ", Joiner.on(", ").join(fm.getSchemes()));
                fileSystemManager = fm;
            } catch (Exception exc) {
                throw new RuntimeException(exc);
            }
        }

        return fileSystemManager;
    } finally {
        aLock.readLock().unlock();
    }
}