Example usage for org.apache.commons.vfs2 FileObject getName

List of usage examples for org.apache.commons.vfs2 FileObject getName

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

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

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

    lockFile.close();

    return uri;
}

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

@Override
public void fileChanged(FileChangeEvent arg0) throws Exception {
    try {//from  w w w .  j a v a  2  s . c o m
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            fileDeleted(arg0);
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    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(baseFile.getName().getURI(), 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(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                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(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            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(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), 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(baseFile.getName().getURI() + " Deployed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

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

@Override
public void fileCreated(FileChangeEvent arg0) throws Exception {
    try {// w w w . j a  va  2 s.c  o  m
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            System.out.println(baseFile.getName().getURI());
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    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(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> clsStateless = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (clsStateless.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : clsStateless) {
                    //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(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            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(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), 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(baseFile.getName().getURI() + " Deployed");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected FileObject getFileContainerFile(String name) throws FileSystemException, WGDesignSyncException {

    // First step: Fast lookup for the given file in the given and lower case
    FileObject file = getCodeFile().resolveFile(name);
    if (file.exists()) {
        return (!isExcludedFileContainerFile(file) ? file : null);
    }/*from  www  .  j  a v a  2 s .co  m*/

    file = getCodeFile().resolveFile(name.toLowerCase());
    if (file.exists()) {
        return (!isExcludedFileContainerFile(file) ? file : null);
    }

    // Second step: Slow but case insensitive search for file 
    Iterator<FileObject> files = getFileContainerFiles().iterator();
    while (files.hasNext()) {
        file = files.next();
        if (file.getName().getBaseName().equalsIgnoreCase(name)) {
            return (!isExcludedFileContainerFile(file) ? file : null);
        }
    }

    return null;

}

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

/**
 * Process a single file through Axis2/*from w ww  .j  av a 2  s .c  om*/
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        metrics.incrementBytesReceived(content.getSize());

        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);

        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }

        MessageContext msgContext = entry.createMessageContext();

        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }

        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }

        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                    new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }

        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                        msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

            handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *//
                    contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }

    } catch (FileSystemException e) {
        handleException("Error reading file content or attributes : " + file, e);

    } finally {
        try {
            file.close();
        } catch (FileSystemException warn) {
            //  log.warn("Cannot close file after processing : " + file.getName().getPath(), warn);
            // ignore the warning, since we handed over the stream close job to AutocloseInputstream..
        }
    }
}

From source file:de.innovationgate.wgpublisher.design.fs.DesignFileDocument.java

private String getProperCaseFileName(FileObject codeFile) {

    // Try to find right case of file on case-insensitive file systems
    if (codeFile instanceof LocalFile) {
        try {/* ww  w  .  j  a v  a  2  s  .  c om*/
            String uri = getManager().getCore().getURLEncoder().encodePath(codeFile.getName().getURI());
            File nativeFile = new File(new URI(uri));
            return nativeFile.getCanonicalFile().getName();
        } catch (Exception e) {
            LOG.error("Exception determining proper name case of local file " + codeFile.getName().getPath(),
                    e);
        }
    }

    return codeFile.getName().getBaseName();

}

From source file:hadoopInstaller.installation.HostInstallation.java

private FileObject sftpConnect() throws InstallationError {
    FileObject remoteDirectory;
    log.debug("HostInstallation.SFTP.Connect.Start", //$NON-NLS-1$
            host.getHostname(), host.getUsername());
    try {//from ww w .  j  a  va 2  s . c o m
        String uri = new URI("sftp", host.getUsername(), //$NON-NLS-1$
                host.getHostname(), host.getPort(), host.getInstallationDirectory(), null, null).toString();
        remoteDirectory = VFS.getManager().resolveFile(uri, installer.getSftpOptions());
    } catch (URISyntaxException | FileSystemException e) {
        throw new InstallationError(e, "HostInstallation.SFTP.Connect.End", //$NON-NLS-1$
                host.getHostname());
    }
    try {
        if (!remoteDirectory.exists()) {
            remoteDirectory.createFolder();
        }
    } catch (FileSystemException e) {
        throw new InstallationError(e, "HostInstallation.CouldNotCreate", //$NON-NLS-1$
                remoteDirectory.getName().getURI(), host.getUsername());
    }
    log.debug("HostInstallation.SFTP.Connect.Success", //$NON-NLS-1$
            host.getHostname(), host.getUsername());
    return remoteDirectory;
}

From source file:de.innovationgate.wgpublisher.design.sync.FileContainerDeployment.java

public void performUpdate(WGDatabase db)
        throws IOException, WGException, InstantiationException, IllegalAccessException, WGDesignSyncException {

    FileObject codeFile = getCodeFile();
    // Check if file has been deleted in the meantime
    if (!codeFile.exists()) {
        return;//w  w w . j a v  a  2s  . co m
    }

    WGFileContainer con = (WGFileContainer) db.getDocumentByDocumentKey(getDocumentKey());
    if (con == null) {
        WGDocumentKey docKey = new WGDocumentKey(getDocumentKey());
        con = db.createFileContainer(docKey.getName());
        con.save();
    }

    // Find new and updated files
    FileObject[] filesArray = codeFile.getChildren();
    if (filesArray == null) {
        throw new WGDesignSyncException("Cannot collect files from directory '"
                + codeFile.getName().getPathDecoded() + "'. Please verify directory existence.");
    }

    List<FileObject> files = new ArrayList<FileObject>(Arrays.asList(filesArray));
    Collections.sort(files, new FileNameComparator());

    FileObject file;
    Map existingFiles = new HashMap();
    for (int i = 0; i < files.size(); i++) {
        file = (FileObject) files.get(i);
        if (isExcludedFileContainerFile(file)) {
            continue;
        }

        ContainerFile containerFile = getContainerFile(file);
        if (containerFile != null) {
            if (existingFiles.containsKey(containerFile.getName())) {
                // Possible in case-sensitive file systems. Another file of the same name with another case is in the dir.
                continue;
            }

            if (file.getContent().getLastModifiedTime() != containerFile.getTimestamp()) {
                doRemoveFile(con, file.getName().getBaseName());
                doSaveDocument(con);
                doAttachFile(con, file);
                doSaveDocument(con);
                containerFile.setTimestamp(file.getContent().getLastModifiedTime());
            }
        } else {
            containerFile = new ContainerFile(file);
            if (con.hasFile(file.getName().getBaseName())) {
                doRemoveFile(con, file.getName().getBaseName());
                doSaveDocument(con);
            }
            doAttachFile(con, file);
            doSaveDocument(con);
        }
        existingFiles.put(containerFile.getName(), containerFile);
    }

    // Remove deleted files from container
    _files = existingFiles;
    List fileNamesInContainer = WGUtils.toLowerCase(con.getFileNames());
    fileNamesInContainer.removeAll(existingFiles.keySet());
    Iterator deletedFiles = fileNamesInContainer.iterator();
    while (deletedFiles.hasNext()) {
        con.removeFile((String) deletedFiles.next());
        con.save();
    }

    // Update metadata and save
    FCMetadata metaData = (FCMetadata) readMetaData();
    metaData.writeToDocument(con);
    con.save();
    FileObject metadataFile = getMetadataFile();
    if (metadataFile.exists()) {
        _timestampOfMetadataFile = metadataFile.getContent().getLastModifiedTime();
    }

    // We wont do this here, since this would rebuild all ContainerFiles, which is not neccessary
    // Instead we have updated just the metadata file timestamp
    // resetUpdateInformation();
}

From source file:de.innovationgate.wgpublisher.design.sync.FileContainerDeployment.java

public boolean isUpdated()
        throws InstantiationException, IllegalAccessException, IOException, WGDesignSyncException {

    FileObject metadataFile = getMetadataFile();
    if (metadataFile.exists() && metadataFile.getContent().getLastModifiedTime() != _timestampOfMetadataFile) {
        return true;
    }/*ww  w  .j a  va  2  s.  c o  m*/

    List<FileObject> files = getFileContainerFiles();
    Collections.sort(files, new FileNameComparator());

    FileObject file;
    List<String> existingFiles = new ArrayList<String>();

    // Check for new and updated files
    for (int i = 0; i < files.size(); i++) {
        file = (FileObject) files.get(i);
        if (isExcludedFileContainerFile(file)) {
            continue;
        }

        ContainerFile containerFile = getContainerFile(file);
        if (containerFile == null) {
            return true;
        } else if (existingFiles.contains(containerFile.getName().toLowerCase())) {

            // Possible on case-sensitive file systems. A file with same name and
            // different case has already been processed. Ignore this duplicate.
            issueWarning(file.getName().getPathDecoded());
            continue;
        } else {
            existingFiles.add(containerFile.getName().toLowerCase());
            if (containerFile.getTimestamp() != file.getContent().getLastModifiedTime()) {
                return true;
            }
        }
    }

    // Check for deleted files
    List<String> containerFiles = new ArrayList<String>(_files.keySet());
    containerFiles.removeAll(existingFiles);
    if (containerFiles.size() > 0) {
        return true;
    } else {
        return false;
    }

}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

public void attach() {

    selectedDir = cb.getVfsUrl();/*from   www  .j av  a 2s  .c o  m*/
    try {

        final VFSFileExplorerPortlet app = instance;
        final User user = (User) app.getUser();
        final FileSystemManager fFileSystemManager = fileSystemManager;
        final FileSystemOptions fOpts = opts;

        final Table table = new Table() {

            private static final long serialVersionUID = 1L;

            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                if (TABLE_PROP_FILE_NAME.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        return getDisplayPath(property.getValue().toString());
                    }
                }
                if (TABLE_PROP_FILE_DATE.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss");
                        return sdf.format((Date) property.getValue());
                    }
                }
                return super.formatPropertyValue(rowId, colId, property);
            }

        };
        table.setSizeFull();
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null);
        if (app != null) {
            app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onValueChanged(TableChangedEvent event) {
                    try {
                        selectedDir = event.getNewDirectory();
                        fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        table.addListener(new Table.ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {

                Set<?> value = (Set<?>) event.getProperty().getValue();
                if (null == value || value.size() == 0) {
                    markedRows = null;
                } else {
                    markedRows = value;
                }
            }
        });

        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);

        Button btDownload = new Button("Download File(s)");
        btDownload.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    String[] files = new String[markedRows.size()];
                    int fileCount = 0;

                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        fileCount++;
                    }

                    File dlFile = null;
                    if (fileCount == 1) {
                        try {
                            String fileName = files[0];
                            dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                            logger.log(Level.INFO,
                                    "vfs2portlet: download file " + fileName + " by " + user.getScreenName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        byte[] buf = new byte[1024];

                        try {
                            dlFile = File.createTempFile("Files", ".zip");
                            ZipOutputStream out = new ZipOutputStream(
                                    new FileOutputStream(dlFile.getAbsolutePath()));
                            for (int i = 0; i < files.length; i++) {
                                String fileName = files[i];
                                logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by "
                                        + user.getScreenName());
                                File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                                FileInputStream in = new FileInputStream(f);
                                out.putNextEntry(new ZipEntry(f.getName()));
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.closeEntry();
                                in.close();
                            }
                            out.close();
                        } catch (IOException e) {
                        }

                    }

                    if (dlFile != null) {
                        try {
                            DownloadResource downloadResource = new DownloadResource(dlFile, getApplication());
                            getApplication().getMainWindow().open(downloadResource, "_new");
                        } catch (FileNotFoundException e) {
                            getWindow().showNotification("File not found !",
                                    Window.Notification.TYPE_ERROR_MESSAGE);
                            e.printStackTrace();
                        }

                    }

                    if (dlFile != null) {
                        dlFile.delete();
                    }
                }

            }
        });

        Button btDelete = new Button("Delete File(s)");
        btDelete.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        logger.log(Level.INFO, "Delete File " + fileToDelete);
                        try {
                            FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts);
                            logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by "
                                    + user.getScreenName());
                            boolean b = delFile.delete();
                            if (b)
                                logger.log(Level.INFO, "delete ok");
                            else
                                logger.log(Level.INFO, "delete failed");
                        } catch (FileSystemException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Button selAll = new Button("Select All", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(table.getItemIds());
            }
        });

        Button selNone = new Button("Select None", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(null);
            }
        });

        final UploadReceiver receiver = new UploadReceiver();
        upload = new Upload(null, receiver);
        upload.setImmediate(true);
        upload.setButtonCaption("File Upload");

        upload.addListener((new Upload.SucceededListener() {

            private static final long serialVersionUID = 1L;

            public void uploadSucceeded(SucceededEvent event) {

                try {
                    String fileName = receiver.getFileName();
                    ByteArrayOutputStream bos = receiver.getUploadedFile();
                    byte[] buf = bos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    app.getMainWindow().showNotification("Upload " + fileName + " successful ! ",
                            Notification.TYPE_TRAY_NOTIFICATION);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }));

        upload.addListener(new Upload.FailedListener() {
            private static final long serialVersionUID = 1L;

            public void uploadFailed(FailedEvent event) {
                System.out.println("Upload failed ! ");
            }
        });

        multiFileUpload = new MultiFileUpload() {

            private static final long serialVersionUID = 1L;

            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    byte[] buf = FileUtils.readFileToByteArray(file);
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (FileSystemException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            protected FileBuffer createReceiver() {
                FileBuffer receiver = super.createReceiver();
                /*
                 * Make receiver not to delete files after they have been
                 * handled by #handleFile().
                 */
                receiver.setDeleteFiles(false);
                return receiver;
            }
        };
        multiFileUpload.setUploadButtonCaption("Upload File(s)");

        HorizontalLayout filterGrp = new HorizontalLayout();
        filterGrp.setSpacing(true);
        final TextField tfFilter = new TextField();
        Button btFileFilter = new Button("Filter", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                String filterVal = (String) tfFilter.getValue();
                try {
                    if (filterVal == null || filterVal.length() == 0) {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } else {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button btResetFileFilter = new Button("Reset", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                try {
                    tfFilter.setValue("");
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (ReadOnlyException e) {
                    e.printStackTrace();
                } catch (ConversionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        filterGrp.addComponent(tfFilter);
        filterGrp.addComponent(btFileFilter);
        filterGrp.addComponent(btResetFileFilter);

        addComponent(filterGrp);

        addComponent(table);

        HorizontalLayout btGrp = new HorizontalLayout();

        btGrp.setSpacing(true);
        btGrp.addComponent(selAll);
        btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(selNone);
        btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(btDownload);
        btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER);

        List<Role> roles = null;
        boolean matchUserRole = false;
        try {

            if (user != null) {
                roles = user.getRoles();

            }
        } catch (SystemException e) {
            e.printStackTrace();
        }

        if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) {
            btGrp.addComponent(btDelete);
            btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
        } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) {
            matchUserRole = isUserInRole(roles, cb.getDeleteRoles());
            if (matchUserRole) {
                btGrp.addComponent(btDelete);
                btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
            }

        }
        if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) {
            btGrp.addComponent(upload);
            btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
            btGrp.addComponent(multiFileUpload);
            btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
        } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) {

            matchUserRole = isUserInRole(roles, cb.getUploadRoles());
            if (matchUserRole) {
                btGrp.addComponent(upload);
                btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
                btGrp.addComponent(multiFileUpload);
                btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
            }
        }
        addComponent(btGrp);

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

}