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

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

Introduction

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

Prototype

public FileSystemOptions() 

Source Link

Document

Creates a new instance.

Usage

From source file:com.web.server.EJBDeployer.java

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;/*www .jav  a 2s.c o  m*/
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            Thread.currentThread().getContextClassLoader());
                    ConfigurationBuilder config = new ConfigurationBuilder();
                    config.addUrls(ClasspathHelper.forClassLoader(classLoader));
                    config.addClassLoader(classLoader);
                    org.reflections.Reflections reflections = new org.reflections.Reflections(config);
                    EJBContainer container = EJBContainer
                            .getInstance("file:///" + scanJarFile.getAbsolutePath(), config);
                    container.inject();
                    Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
                    Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
                    Object obj;
                    System.gc();
                    if (cls.size() > 0) {
                        ejbContext = new EJBContext();
                        ejbContext.setJarPath(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        for (Class<?> ejbInterface : cls) {
                            //BeanPool.getInstance().create(ejbInterface);
                            obj = BeanPool.getInstance().get(ejbInterface);
                            System.out.println(obj);
                            ProxyFactory factory = new ProxyFactory();
                            obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                                    servicesRegistryPort);
                            String remoteBinding = container.getRemoteBinding(ejbInterface);
                            System.out.println(remoteBinding + " for EJB" + obj);
                            if (remoteBinding != null) {
                                //registry.unbind(remoteBinding);
                                registry.rebind(remoteBinding, (Remote) obj);
                                ejbContext.put(remoteBinding, obj.getClass());
                            }
                            //registry.rebind("name", (Remote) obj);
                        }
                        jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    System.out.println("Class Message Driven" + clsMessageDriven);
                    if (clsMessageDriven.size() > 0) {
                        System.out.println("Class Message Driven");
                        MDBContext mdbContext;
                        ConcurrentHashMap<String, MDBContext> mdbContexts;
                        if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                mdbContexts);
                        MDBContext mdbContextOld;
                        for (Class<?> mdbBean : clsMessageDriven) {
                            String classwithpackage = mdbBean.getName();
                            System.out.println("class package" + classwithpackage);
                            classwithpackage = classwithpackage.replace("/", ".");
                            System.out.println("classList:" + classwithpackage.replace("/", "."));
                            try {
                                if (!classwithpackage.contains("$")) {
                                    //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                                    //System.out.println();
                                    if (!mdbBean.isInterface()) {
                                        Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                        if (classServicesAnnot != null) {
                                            for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                                if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                                    MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                                    ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                            .activationConfig();
                                                    mdbContext = new MDBContext();
                                                    mdbContext.setMdbName(messageDrivenAnnot.name());
                                                    for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                        if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATIONTYPE)) {
                                                            mdbContext.setDestinationType(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATION)) {
                                                            mdbContext.setDestination(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                            mdbContext.setAcknowledgeMode(
                                                                    activationConfigProperty.propertyValue());
                                                        }
                                                    }
                                                    if (mdbContext.getDestinationType()
                                                            .equals(Queue.class.getName())) {
                                                        mdbContextOld = null;
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld != null
                                                                    && mdbContext.getDestination().equals(
                                                                            mdbContextOld.getDestination())) {
                                                                throw new Exception(
                                                                        "Only one MDB can listen to destination:"
                                                                                + mdbContextOld
                                                                                        .getDestination());
                                                            }
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Queue queue = (Queue) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(queue);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Queue=" + queue);
                                                    } else if (mdbContext.getDestinationType()
                                                            .equals(Topic.class.getName())) {
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld.getConsumer() != null)
                                                                mdbContextOld.getConsumer()
                                                                        .setMessageListener(null);
                                                            if (mdbContextOld.getSession() != null)
                                                                mdbContextOld.getSession().close();
                                                            if (mdbContextOld.getConnection() != null)
                                                                mdbContextOld.getConnection().close();
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Topic topic = (Topic) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(topic);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Topic=" + topic);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    classLoader.close();
                    System.out.println(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

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  w w.  j  a  v  a 2s . 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:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

/**
 * Resolve file.//  w  w w  . j ava 2  s  . c om
 * 
 * @param baseFile the base file
 * @param file the file
 * 
 * @return the file object
 * 
 * @throws MotuException the motu exception
 */
public FileObject resolveFile(FileObject baseFile, final String file) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveFile(FileObject, String) - entering");
    }

    FileObject fileObject = null;
    open();
    if (opts == null) {
        opts = new FileSystemOptions();
    }

    try {

        // setSchemeOpts(baseFile.getName().getScheme());
        setSchemeOpts(baseFile.getURL());

        fileObject = standardFileSystemManager.resolveFile(baseFile, file, opts);

    } catch (FileSystemException e) {
        throw new MotuException(
                String.format("Unable to resolve uri '%s/%s' ", baseFile.getName().toString(), file), e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveFile(FileObject, String) - exiting");
    }
    return fileObject;

}

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

/** Creates a new FileServiceConfiguration object which wraps the given Preferences object.
 * /*from  w  w  w . ja v  a2  s.c  o  m*/
 * @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.apache.synapse.commons.vfs.VFSUtils.java

public static FileSystemOptions attachFileSystemOptions(Map<String, String> options,
        FileSystemManager fsManager)//from   w  ww  .  j  a v a  2s . c  o  m
        throws FileSystemException, InstantiationException, IllegalAccessException {
    if (options == null) {
        return null;
    }

    FileSystemOptions opts = new FileSystemOptions();
    DelegatingFileSystemOptionsBuilder delegate = new DelegatingFileSystemOptionsBuilder(fsManager);

    if (VFSConstants.SCHEME_SFTP.equals(options.get(VFSConstants.SCHEME))) {
        for (String key : options.keySet()) {
            for (VFSConstants.SFTP_FILE_OPTION o : VFSConstants.SFTP_FILE_OPTION.values()) {
                if (key.equals(o.toString()) && null != options.get(key)) {
                    delegate.setConfigString(opts, VFSConstants.SCHEME_SFTP, key.toLowerCase(),
                            options.get(key));
                }
            }
        }
    }

    return opts;
}

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

/**
 * This method makes the URI resolver/*from w  w  w.j  av a  2  s .co m*/
 * @param vfsD
 * @param uri
 * @param content
 * @return
 * @throws FileSystemException 
 */
public FileObject resolver(VFSDescription vfsD, String uri, String content) throws FileSystemException {
    StaticUserAuthenticator auth = new StaticUserAuthenticator(null, vfsD.getAuth().getUsername(),
            vfsD.getAuth().getPassword());
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
    FileSystemManager fsManager = VFS.getManager();
    FileObject file = fsManager.resolveFile(uri, opts);
    FileObject file1 = fsManager.resolveFile(file, content);
    return file1;
}

From source file:org.cloudifysource.esc.installer.filetransfer.SftpFileTransfer.java

@Override
protected void initVFSManager(final InstallationDetails details, final long endTimeMillis)
        throws InstallerException {
    try {/*from w ww  . j  a va 2 s  .c  o m*/
        this.opts = new FileSystemOptions();

        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

        final Object preferredAuthenticationMethods = details.getCustomData()
                .get(CloudifyConstants.INSTALLER_CUSTOM_DATA_SFTP_PREFERRED_AUTHENTICATION_METHODS_KEY);

        if (preferredAuthenticationMethods != null) {
            if (String.class.isInstance(preferredAuthenticationMethods)) {

                SftpFileSystemConfigBuilder.getInstance().setPreferredAuthentications(opts,
                        (String) preferredAuthenticationMethods);
            } else {
                throw new IllegalArgumentException("Was expecti`ng a string value for custom data field '"
                        + CloudifyConstants.INSTALLER_CUSTOM_DATA_SFTP_PREFERRED_AUTHENTICATION_METHODS_KEY
                        + "', got a; " + preferredAuthenticationMethods.getClass().getName());
            }
        }

        final String keyFile = details.getKeyFile();

        if (keyFile != null && !keyFile.isEmpty()) {
            final File temp = new File(keyFile);
            if (!temp.exists()) {
                throw new InstallerException("Could not find key file: " + temp + ". KeyFile " + keyFile
                        + " that was passed in the installation Details does not exist");
            }
            SftpFileSystemConfigBuilder.getInstance().setIdentities(opts, new File[] { temp });
        }

        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts,
                installerConfiguration.getFileTransferConnectionTimeoutMillis());
        this.fileSystemManager = VFS.getManager();
    } catch (final FileSystemException e) {
        throw new InstallerException("Failed to set up file transfer: " + e.getMessage(), e);

    }
}

From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.CleanGSFilesByonTest.java

/**
 * Checks whether the files or folders exist on a remote host.
 * The returned value depends on the last parameter - "allMustExist".
 * If allMustExist is True the returned value is True only if all listed objects exist.
 * If allMustExist is False, the returned value is True if at least one object exists.
 * /* w w w.  j av a2 s  .com*/
 * @param host The host to connect to
 * @param username The name of the user that deletes the file/folder
 * @param password The password of the above user
 * @param keyFile The key file, if used
 * @param fileSystemObjects The files or folders to delete
 * @param fileTransferMode SCP for secure copy in Linux, or CIFS for windows file sharing
 * @param allMustExist If set to True the function will return True only if all listed objects exist.
 *          If set to False, the function will return True if at least one object exists.
 * @return depends on allMustExist
 * @throws IOException Indicates the deletion failed
 */
public static boolean fileSystemObjectsExist(final String host, final String username, final String password,
        final String keyFile, final List<String> fileSystemObjects, final FileTransferModes fileTransferMode,
        final boolean allMustExist) throws IOException {

    boolean objectsExist;
    if (allMustExist) {
        objectsExist = true;
    } else {
        objectsExist = false;
    }

    if (!fileTransferMode.equals(FileTransferModes.SCP)) {
        //TODO Support get with CIFS as well
        throw new IOException("File resolving is currently not supported for this file transfer protocol ("
                + fileTransferMode + ")");
    }

    final FileSystemOptions opts = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
    if (keyFile != null && !keyFile.isEmpty()) {
        final File temp = new File(keyFile);
        if (!temp.isFile()) {
            throw new FileNotFoundException("Could not find key file: " + temp);
        }
        SftpFileSystemConfigBuilder.getInstance().setIdentities(opts, new File[] { temp });
    }

    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, SFTP_DISCONNECT_DETECTION_TIMEOUT_MILLIS);
    final FileSystemManager mng = VFS.getManager();

    String scpTargetBase, scpTarget;
    if (password != null && !password.isEmpty()) {
        scpTargetBase = "sftp://" + username + ':' + password + '@' + host;
    } else {
        scpTargetBase = "sftp://" + username + '@' + host;
    }

    FileObject remoteDir = null;
    try {
        for (final String fileSystemObject : fileSystemObjects) {
            scpTarget = scpTargetBase + fileSystemObject;
            remoteDir = mng.resolveFile(scpTarget, opts);
            if (remoteDir.exists()) {
                if (!allMustExist) {
                    objectsExist = true;
                    break;
                }
            } else {
                if (allMustExist) {
                    objectsExist = false;
                    break;
                }
            }
        }
    } finally {
        if (remoteDir != null) {
            mng.closeFileSystem(remoteDir.getFileSystem());
        }
    }

    return objectsExist;
}

From source file:org.esupportail.portlet.filemanager.portlet.PortletControllerDownloadEvent.java

@EventMapping(EsupFileManagerConstants.DOWNLOAD_REQUEST_QNAME_STRING)
public void downloadEvent(EventRequest request, EventResponse response) {

    log.info("PortletControllerDownloadEvent.downloadEvent from EsupFilemanager is called");

    // INIT     /*from w  w w .  ja v  a  2s . c o m*/
    portletController.init(request);

    PortletPreferences prefs = request.getPreferences();
    String[] prefsDefaultPathes = prefs.getValues(PortletController.PREF_DEFAULT_PATH, null);

    boolean showHiddenFiles = "true".equals(prefs.getValue(PortletController.PREF_SHOW_HIDDEN_FILES, "false"));
    userParameters.setShowHiddenFiles(showHiddenFiles);

    UploadActionType uploadOption = UploadActionType.valueOf(prefs
            .getValue(PortletController.PREF_UPLOAD_ACTION_EXIST_FILE, UploadActionType.OVERRIDE.toString()));
    userParameters.setUploadOption(uploadOption);

    serverAccess.initializeServices(userParameters);

    // DefaultPath
    String defaultPath = serverAccess.getFirstAvailablePath(userParameters, prefsDefaultPathes);

    // Event   
    final Event event = request.getEvent();
    final DownloadRequest downloadRequest = (DownloadRequest) event.getValue();

    String fileUrl = downloadRequest.getUrl();

    // FS     
    boolean success = false;
    try {
        FileSystemManager fsManager = VFS.getManager();

        FileSystemOptions fsOptions = new FileSystemOptions();

        FileObject file = fsManager.resolveFile(fileUrl, fsOptions);
        FileContent fc = file.getContent();
        String baseName = fc.getFile().getName().getBaseName();
        InputStream inputStream = fc.getInputStream();

        success = serverAccess.putFile(defaultPath, baseName, inputStream, userParameters,
                userParameters.getUploadOption());
    } catch (FileSystemException e) {
        log.error("putFile failed for this downloadEvent", e);
    }

    //Build the result object
    final DownloadResponse downloadResponse = new DownloadResponse();
    if (success)
        downloadResponse.setSummary("Upload OK");
    else
        downloadResponse.setSummary("Upload Failed");

    //Add the result to the results and send the event
    response.setEvent(EsupFileManagerConstants.DOWNLOAD_RESPONSE_QNAME, downloadResponse);

}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
protected void open(SharedUserPortletParameters userParameters) {
    super.open(userParameters);
    try {//from ww  w  .j  av  a2  s. c  o m
        if (!isOpened()) {
            FileSystemOptions fsOptions = new FileSystemOptions();

            if (ftpControlEncoding != null)
                FtpFileSystemConfigBuilder.getInstance().setControlEncoding(fsOptions, ftpControlEncoding);

            if (sftpSetUserDirIsRoot) {
                SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fsOptions, true);
                FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fsOptions, true);
            }

            if (!strictHostKeyChecking) {
                SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
            }

            FtpFileSystemConfigBuilder.getInstance().setPassiveMode(fsOptions, ftpPassiveMode);

            if (userAuthenticatorService != null) {
                UserAuthenticator userAuthenticator = null;
                if (ClassUtils.isAssignable(UserCasAuthenticatorService.class,
                        userAuthenticatorService.getClass())) {
                    userAuthenticator = new DynamicUserAuthenticator(userAuthenticatorService, userParameters);
                } else {
                    UserPassword userPassword = userAuthenticatorService.getUserPassword(userParameters);
                    userAuthenticator = new StaticUserAuthenticator(userPassword.getDomain(),
                            userPassword.getUsername(), userPassword.getPassword());
                }
                DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(fsOptions, userAuthenticator);
            }

            fsManager = VFS.getManager();
            root = fsManager.resolveFile(uri, fsOptions);
        }
    } catch (FileSystemException fse) {
        throw new EsupStockException(fse);
    }
}