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

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

Introduction

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

Prototype


@Override
public FileObject resolveFile(final String uri, final FileSystemOptions fileSystemOptions)
        throws FileSystemException 

Source Link

Document

Locate a file by URI, use the FileSystemOptions for file-system creation.

Usage

From source file:fr.cls.atoll.motu.processor.wps.TestVFS.java

public static void testBugDoReplicateFile() {

    StandardFileSystemManager standardFileSystemManager = new StandardFileSystemManager();
    standardFileSystemManager.setLogger(LogFactory.getLog(VFS.class));
    standardFileSystemManager.setClassLoader(TestVFS.class.getClassLoader());
    try {//from  ww  w.  j  a  v  a 2s . c o  m
        URL configUrl = new URL(
                "file:/J:/dev/atoll-v2/atoll-motu/atoll-motu-library/src/main/resources/motuVFSProvider.xml");
        standardFileSystemManager.setConfiguration(configUrl);
        standardFileSystemManager.setCacheStrategy(CacheStrategy.ON_CALL);
        standardFileSystemManager.init();

        String uri = "jar:file:/C:/Documents%20and%20Settings/dearith/.m2/repository/org/jvnet/ogc/iso-19139-d_2006_05_04-schema/1.0.0-PATCH-CLS/iso-19139-d_2006_05_04-schema-1.0.0-PATCH-CLS.jar!/schema/iso19139";
        FileSystemOptions opts = new FileSystemOptions();

        FileObject fileObject = standardFileSystemManager.resolveFile(uri, opts);

    } catch (FileSystemException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

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 {// w  w w  .  j  a va  2 s . c om
        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: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;/*w w w.j  a v a 2s  . com*/
    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:org.wso2.carbon.connector.FileAppend.java

/**
 * @param destination    Location if the file
 * @param content        Content that is going to be added
 * @param encoding       Encoding type/*from ww  w. jav a2  s . com*/
 * @param messageContext The message context that is generated for processing the file
 * @return true/false
 */
private boolean appendFile(String destination, String content, String encoding, MessageContext messageContext) {
    OutputStream out = null;
    boolean resultStatus = false;
    FileObject fileObj = null;
    StandardFileSystemManager manager = null;
    try {
        manager = FileConnectorUtils.getManager();
        fileObj = manager.resolveFile(destination, FileConnectorUtils.init(messageContext));
        if (!fileObj.exists()) {
            fileObj.createFile();
        }
        out = fileObj.getContent().getOutputStream(true);
        if (StringUtils.isEmpty(encoding)) {
            IOUtils.write(content, out, DEFAULT_ENCODING);
        } else {
            IOUtils.write(content, out, encoding);
        }
        resultStatus = true;

        if (log.isDebugEnabled()) {
            log.debug("File appending completed. " + destination);
        }
    } catch (IOException e) {
        handleException("Error while appending a file.", e, messageContext);
    } finally {
        try {
            if (fileObj != null) {
                //close the file object
                fileObj.close();
            }
        } catch (FileSystemException e) {
            log.error("Error while closing FileObject: " + e.getMessage(), e);
        }
        try {
            if (out != null) {
                //close the output stream
                out.close();
            }
        } catch (IOException e) {
            log.error("Error while closing OutputStream: " + e.getMessage(), e);
        }
        if (manager != null) {
            //close the StandardFileSystemManager
            manager.close();
        }
    }
    return resultStatus;
}

From source file:org.wso2.carbon.connector.FileAppendConnector.java

/**
 * Add the content into file.//w w  w . j a  v  a2  s  .c  o m
 *
 * @param messageContext The message context that is generated for processing the file.
 * @return true, if the content is successfully appended.
 * @throws FileSystemException On error parsing the file name, determining if the file exists and creating the
 * file.
 */
private boolean appendFile(MessageContext messageContext) throws FileSystemException {
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    String content = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.CONTENT);
    String encoding = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.ENCODING);
    if (StringUtils.isEmpty(encoding)) {
        encoding = FileConstants.DEFAULT_ENCODING;
    }
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    OutputStream out = null;
    FileObject fileObj = null;
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    try {
        fileObj = manager.resolveFile(destination, opts);
        if (!fileObj.exists()) {
            fileObj.createFile();
        }
        // True, if the content should be appended.
        out = fileObj.getContent().getOutputStream(true);
        IOUtils.write(content, out, encoding);
        if (log.isDebugEnabled()) {
            log.debug("File appending completed. " + destination);
        }
    } catch (IOException e) {
        throw new SynapseException("Error while appending content", e);
    } finally {
        try {
            if (fileObj != null) {
                // close the file object
                fileObj.close();
            }
        } catch (FileSystemException e) {
            log.error("Error while closing FileObject", e);
        }
        try {
            if (out != null) {
                // close the output stream
                out.close();
            }
        } catch (IOException e) {
            log.error("Error while closing OutputStream", e);
        }
        // close the StandardFileSystemManager
        manager.close();
    }
    return true;
}

From source file:org.wso2.carbon.connector.FileArchiveConnector.java

/**
 * Archive a file/folder.//  ww w.ja va2s .co m
 *
 * @param messageContext The message context that is generated for processing the file.
 * @return return true, if the file/folder is successfully archived, false, if not.
 * @throws FileSystemException On error parsing the file name, determining if the file exists and getting file type.
 */
private boolean fileCompress(MessageContext messageContext) throws FileSystemException {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    FileObject fileObj = manager.resolveFile(source, opts);
    FileObject destObj = manager.resolveFile(destination, opts);
    if (!fileObj.exists()) {
        log.error("The File location does not exist.");
        return false;
    }
    if (FileType.FOLDER.equals(fileObj.getType())) {
        List<FileObject> fileList = new ArrayList<>();
        addAllFilesToList(fileObj, fileList);
        writeZipFiles(fileObj, destObj, fileList);
    } else {
        ZipOutputStream outputStream = null;
        InputStream fileIn = null;
        try {
            outputStream = new ZipOutputStream(destObj.getContent().getOutputStream());
            fileIn = fileObj.getContent().getInputStream();
            ZipEntry zipEntry = new ZipEntry(fileObj.getName().getBaseName());
            outputStream.putNextEntry(zipEntry);
            int length;
            while ((length = fileIn.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (IOException e) {
            throw new SynapseException("Error while writing an array of bytes to the ZipOutputStream", e);
        } finally {
            try {
                // close the file object
                fileObj.close();
            } catch (FileSystemException e) {
                log.error("Error while closing the source FileObject", e);
            }
            try {
                // close the file object
                destObj.close();
            } catch (FileSystemException e) {
                log.error("Error while closing the destination FileObject", e);
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("Error while closing ZipOutputStream", e);
            }
            try {
                if (fileIn != null) {
                    fileIn.close();
                }
            } catch (IOException e) {
                log.error("Error while closing InputStream:", e);
            }
            // close the StandardFileSystemManager
            manager.close();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("File archiving completed." + destination);
    }
    return true;
}

From source file:org.wso2.carbon.connector.FileArchives.java

/**
 * @param messageContext The message context that is generated for processing the file
 * @param source         The file to be archived
 * @param destination    Destination of the archived file
 * @return return status/*from   w ww  .  j av a 2  s. c  o  m*/
 * @throws SynapseException
 */
private boolean fileCompress(MessageContext messageContext, String source, String destination) {
    boolean resultStatus = false;
    StandardFileSystemManager manager;
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    try {
        manager = FileConnectorUtils.getManager();
        FileObject fileObj = manager.resolveFile(source, opts);
        FileObject destObj = manager.resolveFile(destination, opts);
        if (fileObj.exists()) {
            if (fileObj.getType() == FileType.FOLDER) {
                List<FileObject> fileList = new ArrayList<FileObject>();
                getAllFiles(fileObj, fileList, messageContext);
                writeZipFiles(fileObj, destObj, fileList, messageContext);
            } else {
                ZipOutputStream outputStream = null;
                InputStream fileIn = null;
                try {
                    outputStream = new ZipOutputStream(destObj.getContent().getOutputStream());
                    fileIn = fileObj.getContent().getInputStream();
                    ZipEntry zipEntry = new ZipEntry(fileObj.getName().getBaseName());
                    outputStream.putNextEntry(zipEntry);
                    int length;
                    while ((length = fileIn.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, length);
                    }
                } catch (Exception e) {
                    log.error("Unable to compress a file." + e.getMessage());
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        log.error("Error while closing ZipOutputStream: " + e.getMessage(), e);
                    }
                    try {
                        if (fileIn != null) {
                            fileIn.close();
                        }
                    } catch (IOException e) {
                        log.error("Error while closing InputStream: " + e.getMessage(), e);
                    }
                    manager.close();
                }
            }
            resultStatus = true;

            if (log.isDebugEnabled()) {
                log.debug("File archiving completed." + destination);
            }
        } else {
            log.error("The File location does not exist.");
            resultStatus = false;
        }
    } catch (IOException e) {
        handleException("Unable to process the zip file", e, messageContext);
    }
    return resultStatus;
}

From source file:org.wso2.carbon.connector.FileCopy.java

/**
 * Copy files/*from   www. j a  v a2 s . c o m*/
 *
 * @param source         Location of the file
 * @param destination    new file location
 * @param filePattern    pattern of the file
 * @param messageContext The message context that is generated for processing the file
 * @param opts           FileSystemOptions
 * @return return a resultStatus
 */
private boolean copyFile(String source, String destination, String filePattern, MessageContext messageContext,
        FileSystemOptions opts) {
    boolean resultStatus = false;
    StandardFileSystemManager manager = null;
    try {
        manager = FileConnectorUtils.getManager();
        FileObject souFile = manager.resolveFile(source, opts);
        FileObject destFile = manager.resolveFile(destination, opts);
        if (StringUtils.isNotEmpty(filePattern)) {
            FileObject[] children = souFile.getChildren();
            for (FileObject child : children) {
                if (child.getType() == FileType.FILE) {
                    copy(source, destination, filePattern, opts);
                } else if (child.getType() == FileType.FOLDER) {
                    String newSource = source + File.separator + child.getName().getBaseName();
                    copyFile(newSource, destination, filePattern, messageContext, opts);
                }
            }
            resultStatus = true;
        } else {
            if (souFile.exists()) {
                if (souFile.getType() == FileType.FILE) {
                    InputStream fileIn = null;
                    OutputStream fileOut = null;
                    try {
                        String name = souFile.getName().getBaseName();
                        FileObject outFile = manager.resolveFile(destination + File.separator + name, opts);
                        //TODO make parameter sense
                        fileIn = souFile.getContent().getInputStream();
                        fileOut = outFile.getContent().getOutputStream();
                        IOUtils.copyLarge(fileIn, fileOut);
                        resultStatus = true;
                    } catch (FileSystemException e) {
                        log.error("Error while copying a file " + e.getMessage());
                    } finally {
                        try {
                            if (fileOut != null) {
                                fileOut.close();
                            }
                        } catch (Exception e) {
                            log.error("Error while closing OutputStream: " + e.getMessage(), e);
                        }
                        try {
                            if (fileIn != null) {
                                fileIn.close();
                            }
                        } catch (Exception e) {
                            log.error("Error while closing InputStream: " + e.getMessage(), e);
                        }
                    }
                } else if (souFile.getType() == FileType.FOLDER) {
                    destFile.copyFrom(souFile, Selectors.SELECT_ALL);
                    resultStatus = true;
                }
                if (log.isDebugEnabled()) {
                    log.debug("File copying completed from " + source + "to" + destination);
                }
            } else {
                log.error("The File Location does not exist.");
                resultStatus = false;
            }
        }
        return resultStatus;
    } catch (IOException e) {
        handleException("Unable to copy a file/folder", e, messageContext);
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
    return resultStatus;
}

From source file:org.wso2.carbon.connector.FileCopy.java

/**
 * @param source      file location/*from   w  ww  . java2  s .  c om*/
 * @param destination target file location
 * @param filePattern pattern of the file
 * @param opts        FileSystemOptions
 * @throws IOException
 */
private void copy(String source, String destination, String filePattern, FileSystemOptions opts)
        throws IOException {
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileObject souFile = manager.resolveFile(source, opts);
    FileObject[] children = souFile.getChildren();
    FilePattenMatcher patternMatcher = new FilePattenMatcher(filePattern);
    for (FileObject child : children) {
        try {
            if (patternMatcher.validate(child.getName().getBaseName())) {
                String name = child.getName().getBaseName();
                FileObject outFile = manager.resolveFile(destination + File.separator + name, opts);
                outFile.copyFrom(child, Selectors.SELECT_FILES);
            }
        } catch (IOException e) {
            log.error("Error occurred while copying a file. " + e.getMessage(), e);
        }
    }
    manager.close();
}

From source file:org.wso2.carbon.connector.FileCopyConnector.java

/**
 * Copy the file or folder from source to destination.
 *
 * @param messageContext The message context that is generated for processing the file.
 * @param opts           FileSystemOptions.
 * @return return true, if file/folder is successfully copied.
 *///w w  w.jav  a  2 s  .  c  o m
private boolean copyFile(String source, MessageContext messageContext, FileSystemOptions opts) {
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_PATTERN);
    String includeParentDir = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.INCLUDE_PARENT_DIRECTORY);
    boolean includeParentDirectory = FileConstants.DEFAULT_INCLUDE_PARENT_DIRECTORY;

    if (StringUtils.isNotEmpty(includeParentDir)) {
        includeParentDirectory = Boolean.parseBoolean(includeParentDir);
    }
    boolean resultStatus = false;
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileObject souFile = null;
    FileObject destFile = null;
    try {
        souFile = manager.resolveFile(source, opts);
        destFile = manager.resolveFile(destination, opts);
        if (!souFile.exists()) {
            log.error("The File Location does not exist.");
            return false;
        }
        if (StringUtils.isNotEmpty(filePattern)) {
            FileObject[] children = souFile.getChildren();
            for (FileObject child : children) {
                if (FileType.FILE.equals(child.getType())) {
                    copy(child, destination, filePattern, opts, manager);
                } else if (FileType.FOLDER.equals(child.getType())) {
                    String newSource = source + File.separator + child.getName().getBaseName();
                    copyFile(newSource, messageContext, opts);
                }
            }
        } else {
            if (FileType.FILE.equals(souFile.getType())) {
                String name = souFile.getName().getBaseName();
                FileObject outFile = manager.resolveFile(destination + File.separator + name, opts);
                outFile.copyFrom(souFile, Selectors.SELECT_ALL);
            } else if (FileType.FOLDER.equals(souFile.getType())) {
                if (includeParentDirectory) {
                    destFile = manager
                            .resolveFile(destination + File.separator + souFile.getName().getBaseName(), opts);
                    destFile.createFolder();
                }
                destFile.copyFrom(souFile, Selectors.SELECT_ALL);
            }
            if (log.isDebugEnabled()) {
                log.debug("File copying completed from " + source + "to" + destination);
            }
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Unable to copy a file/folder", e);
    } finally {
        manager.close();
    }
    try {
        souFile.close();
        destFile.close();
    } catch (FileSystemException e) {
        log.error("Error while closing the FileObject", e);
    }
    return true;
}