Example usage for org.apache.commons.vfs2 FileSystemManager resolveFile

List of usage examples for org.apache.commons.vfs2 FileSystemManager resolveFile

Introduction

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

Prototype

FileObject resolveFile(URL url) throws FileSystemException;

Source Link

Document

Resolves a URL into a FileObject .

Usage

From source file:org.eobjects.datacleaner.user.DataCleanerHome.java

private static FileObject findDataCleanerHome() throws FileSystemException {
    final FileSystemManager manager = VFSUtils.getFileSystemManager();

    FileObject candidate = null;/*from   w  w  w.  jav a  2  s  . c o  m*/

    final String env = System.getenv("DATACLEANER_HOME");
    if (!StringUtils.isNullOrEmpty(env)) {
        candidate = manager.resolveFile(env);
        logger.info("Resolved env. variable DATACLEANER_HOME ({}) to: {}", env, candidate);
    }

    if (isUsable(candidate)) {
        return candidate;
    }

    if (ClassLoaderUtils.IS_WEB_START) {
        // in web start, the default folder will be in user.home
        final String userHomePath = System.getProperty("user.home");
        if (userHomePath == null) {
            throw new IllegalStateException("Could not determine user home directory: " + candidate);
        }

        final String path = userHomePath + File.separatorChar + ".datacleaner" + File.separatorChar
                + Version.getVersion();
        candidate = manager.resolveFile(path);
        logger.info("Running in WebStart mode. Attempting to build DATACLEANER_HOME in user.home: {} -> {}",
                path, candidate);
    } else {
        // in normal mode, the default folder will be in the working
        // directory
        candidate = manager.resolveFile(".");
        logger.info("Running in standard mode. Attempting to build DATACLEANER_HOME in '.' -> {}", candidate);
    }

    if ("true".equalsIgnoreCase(System.getProperty(SystemProperties.SANDBOX))) {
        logger.info("Running in sandbox mode ({}), setting {} as DATACLEANER_HOME", SystemProperties.SANDBOX,
                candidate);
        if (!candidate.exists()) {
            candidate.createFolder();
        }
        return candidate;
    }

    if (!isUsable(candidate)) {
        if (!candidate.exists()) {
            logger.debug("DATACLEANER_HOME directory does not exist, creating: {}", candidate);
            candidate.createFolder();
        }

        if (candidate.isWriteable()) {
            logger.debug("Copying default configuration and examples to DATACLEANER_HOME directory: {}",
                    candidate);
            copyIfNonExisting(candidate, manager, "conf.xml");
            copyIfNonExisting(candidate, manager, "examples/countrycodes.csv");
            copyIfNonExisting(candidate, manager, "examples/employees.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/duplicate_customer_detection.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/customer_data_cleansing.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/write_order_information.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/customer_data_completeness.analysis.xml");
        }
    }

    return candidate;
}

From source file:org.fuin.vfs2.filter.BaseFilterTest.java

/**
 * Returns a ZIP file object./*from ww  w .  ja va 2s .c  o m*/
 * 
 * @param file
 *            File to resolve.
 * 
 * @return File object.
 * 
 * @throws FileSystemException
 *             Error resolving the file.
 */
protected static FileObject getZipFileObject(final File file) throws FileSystemException {
    final FileSystemManager fsManager = VFS.getManager();
    return fsManager.resolveFile("zip:" + file.toURI());
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * Extracts the archive file {@code archiveFile} to {@code targetFolder}; both shall previously exist.
 *
 * @param archiveFile//from w  w  w . j a v  a2  s . c om
 * @param targetFolder
 * @throws IOException
 */
public static void extractTo(Resource archiveFile, Resource targetFolder) throws IOException {
    FileSystemManager manager = VFS.getManager();
    String sourceURI = resolveArchiveURI(archiveFile);

    FileObject source = manager.resolveFile(sourceURI);
    if (manager.canCreateFileSystem(source)) {
        source = manager.createFileSystem(source);
    }
    FileObject target = manager
            .createVirtualFileSystem(manager.resolveFile(targetFolder.dir().getAbsolutePath()));

    FileSelector selector = new AllFileSelector() {
        @Override
        public boolean includeFile(FileSelectInfo fileInfo) {
            LOGGER.fine("Uncompressing " + fileInfo.getFile().getName().getFriendlyURI());
            return true;
        }
    };
    target.copyFrom(source, selector);
    source.close();
    target.close();
    manager.closeFileSystem(source.getFileSystem());
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * Compress {@code sourceFolder} to the archive file {@code archiveFile}; both shall previously exist.
 * //from   ww  w. j av  a2  s. c om
 * @param sourceFolder
 * @param archiveFile
 * @throws IOException
 */
public static void compressTo(Resource sourceFolder, Resource archiveFile) throws IOException {
    // See https://commons.apache.org/proper/commons-vfs/filesystems.html
    // for the supported filesystems

    FileSystemManager manager = VFS.getManager();

    FileObject sourceDir = manager
            .createVirtualFileSystem(manager.resolveFile(sourceFolder.dir().getAbsolutePath()));

    try {
        if ("zip".equalsIgnoreCase(FileUtils.getExtension(archiveFile.path()))) {
            // apache VFS does not support ZIP as writable FileSystem

            OutputStream fos = archiveFile.out();

            // Create access to zip.
            ZipOutputStream zos = new ZipOutputStream(fos);

            // add entry/-ies.
            for (FileObject sourceFile : sourceDir.getChildren()) {
                writeEntry(zos, sourceFile, null);
            }

            // Close streams
            zos.flush();
            zos.close();
            fos.close();
        } else {
            // Create access to archive.
            FileObject zipFile = manager.resolveFile(resolveArchiveURI(archiveFile));
            zipFile.createFile();
            ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream());

            // add entry/-ies.
            for (FileObject sourceFile : sourceDir.getChildren()) {
                writeEntry(zos, sourceFile, null);
            }

            // Close streams
            zos.flush();
            zos.close();
            zipFile.close();
            manager.closeFileSystem(zipFile.getFileSystem());
        }
    } finally {
        manager.closeFileSystem(sourceDir.getFileSystem());
    }
}

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

/**
 * This function creates a temporary directory, which has a unique file name.
 *
 * @param prefix/*ww  w  .j  a  v  a 2 s.c  o  m*/
 *          This prefix will be used for the temporary directory.
 * @param parentDir
 *          The parent directory. In it the new directory will be created.
 * @return The new unique directory.
 */
public static FileObject createTempDirectory(final String prefix, final FileObject parentDir,
        final FileSystemManager fsManager) throws FileSystemException {
    while (true) {
        final String dirParent = parentDir.getURL().toExternalForm();
        final String dirName = prefix + String.valueOf(System.currentTimeMillis());

        final FileObject newDir = fsManager.resolveFile(dirParent + "/" + dirName); //$NON-NLS-1$
        if (newDir.exists()) {
            continue;
        }

        KalypsoCommonsDebug.DEBUG.printf("Creating folder %s ...%n", newDir.getName().getPath()); //$NON-NLS-1$
        newDir.createFolder();
        return newDir;
    }
}

From source file:org.kalypso.project.database.client.core.base.worker.CreateRemoteProjectWorker.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *///from w ww .  j ava2 s .co  m
@Override
public IStatus execute(final IProgressMonitor monitor) throws CoreException {

    final IProject project = m_handler.getProject();
    final String zipName = String.format("%s.zip", project.getName()); //$NON-NLS-1$

    final File urlTempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$
    final File src = new File(urlTempDir, zipName); //$NON-NLS-1$

    try {
        final ProjectExportWorker worker = new ProjectExportWorker(project, src, false);
        final IStatus status = worker.execute(monitor);

        if (!status.isOK())
            throw new CoreException(
                    new Status(IStatus.ERROR, KalypsoProjectDatabaseClient.PLUGIN_ID, Messages.getString(
                            "org.kalypso.project.database.client.core.project.create.CreateRemoteProjectWorker.2"))); //$NON-NLS-1$

        final FileSystemManager manager = VFSUtilities.getManager();
        final FileObject source = manager.resolveFile(src.getAbsolutePath());

        final String urlDestination = ProjectModelUrlResolver
                .getUrlAsFtp(new ProjectModelUrlResolver.IResolverInterface() {
                    @Override
                    public String getPath() {
                        return System.getProperty(IProjectDataBaseClientConstant.SERVER_INCOMING_PATH);
                    }

                }, zipName); //$NON-NLS-1$

        // change caching strategy of destination file to avoid deadlocks!
        final FileObject destination = new OnCallRefreshFileObject(manager.resolveFile(urlDestination));

        VFSUtilities.copy(source, destination);

        final IProjectDatabase service = KalypsoProjectDatabaseClient.getService();

        // always commit - download of projects assert nature!
        final KalypsoProjectBean bean = new KalypsoProjectBean();
        bean.setName(project.getName());
        bean.setDescription(project.getName());
        bean.setUnixName(project.getName()); // TODO generate unixName
        bean.setProjectVersion(0);
        bean.setProjectType(m_commitType);
        bean.setModuleIdentifier(m_commitType);

        service.createProject(bean, new URL(urlDestination));

        final WorkspaceJob updateDescription = new WorkspaceJob("") //$NON-NLS-1$
        {
            int updateCount = 0;

            @Override
            public IStatus runInWorkspace(final IProgressMonitor m) throws CoreException {
                try {
                    // FIXME *grummel* why .project file is always locked and project.setDescription() fails?
                    final IProjectDescription description = project.getDescription();
                    description.setNatureIds(
                            ArrayUtils.add(description.getNatureIds(), RemoteProjectNature.NATURE_ID));
                    project.setDescription(description, m);

                    final RemoteProjectNature remote = (RemoteProjectNature) project
                            .getNature(RemoteProjectNature.NATURE_ID);
                    final IRemoteProjectPreferences preferences = remote.getRemotePreferences(project, null);
                    preferences.setVersion(0);
                    preferences.setIsOnServer(true);
                    preferences.setModified(false);
                } catch (final Exception e) {
                    updateCount += 1;
                    if (updateCount < 5)
                        this.schedule(250);
                    else
                        throw new CoreException(new Status(IStatus.ERROR,
                                KalypsoProjectDatabaseClient.PLUGIN_ID,
                                Messages.getString(
                                        "org.kalypso.project.database.client.core.project.create.CreateRemoteProjectWorker.0"), //$NON-NLS-1$
                                e));

                    return Status.CANCEL_STATUS;
                }

                return Status.OK_STATUS;
            }
        };

        updateDescription.schedule(250);

        // bad @hack if the client has committed a large file, it can happen, that the client looses the http connection.
        // file.close() reestablish this http-connection
        destination.close();
    } catch (final Exception e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e));
    } finally {
        src.delete();
    }

    return Status.OK_STATUS;
}

From source file:org.kalypso.project.database.client.core.base.worker.UpdateProjectWorker.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *///from  w  ww.j a v  a2s  . co  m
@Override
public IStatus execute(final IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(
            Messages.getString("org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.0"), //$NON-NLS-1$
            4);

    // remove local project lock
    final IRemoteProjectPreferences preferences = m_handler.getRemotePreferences();
    final String ticket = preferences.getEditTicket();
    preferences.setEditTicket(""); //$NON-NLS-1$

    final File urlTempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$
    final File src = new File(urlTempDir, "update.zip"); //$NON-NLS-1$

    monitor.worked(1);

    try {
        monitor.subTask(Messages
                .getString("org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.4")); //$NON-NLS-1$
        final ProjectExportWorker worker = new ProjectExportWorker(m_handler.getProject(), src, false);
        final IStatus status = worker.execute(monitor);
        monitor.worked(1);

        if (!status.isOK())
            throw new CoreException(
                    new Status(IStatus.ERROR, KalypsoProjectDatabaseClient.PLUGIN_ID, Messages.getString(
                            "org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.5"))); //$NON-NLS-1$

        final FileSystemManager manager = VFSUtilities.getManager();
        final FileObject source = manager.resolveFile(src.getAbsolutePath());

        final String fileName = String.format("%s.zip", m_handler.getName()); //$NON-NLS-1$

        final String urlDestination = ProjectModelUrlResolver
                .getUrlAsFtp(new ProjectModelUrlResolver.IResolverInterface() {
                    @Override
                    public String getPath() {
                        return System.getProperty(IProjectDataBaseClientConstant.SERVER_INCOMING_PATH);
                    }

                }, fileName); //$NON-NLS-1$

        monitor.subTask(Messages
                .getString("org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.7")); //$NON-NLS-1$

        final FileObject destination = manager.resolveFile(urlDestination);
        VFSUtilities.copy(source, destination);

        final IProjectDatabase service = KalypsoProjectDatabaseClient.getService();
        final KalypsoProjectBean bean = service.udpateProject(m_handler.getBean(), new URL(urlDestination));
        preferences.setVersion(bean.getProjectVersion());

        destination.close();
        destination.delete();
    } catch (final Exception e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e));
    } finally {
        try {
            // add local project lock
            preferences.setEditTicket(ticket);
        } catch (final Throwable t) {
            t.printStackTrace();
        }
        src.delete();

        monitor.done();
    }

    return Status.OK_STATUS;
}

From source file:org.kalypso.project.database.server.ProjectDatabase.java

/**
 * @see org.kalypso.project.database.sei.IProjectDatabase#createProject(java.lang.String)
 *///  www  .  j a  v  a 2 s  . com
@Override
public KalypsoProjectBean createProject(final KalypsoProjectBean bean, final URL incoming) throws IOException {
    synchronized (this) {
        final FileSystemManager manager = VFSUtilities.getManager();
        final FileObject src = manager.resolveFile(incoming.toExternalForm());

        try {
            if (!src.exists())
                throw new FileNotFoundException(
                        String.format("Incoming file not exists: %s", incoming.toExternalForm())); //$NON-NLS-1$

            /* destination of incoming file */
            final String urlDestination = ProjectDatabaseHelper.resolveDestinationUrl(bean);

            final FileObject destination = manager.resolveFile(urlDestination);
            VFSUtilities.copy(src, destination);

            /* store project bean in database */
            bean.setCreationDate(Calendar.getInstance().getTime());

            final Session session = FACTORY.getCurrentSession();
            final Transaction tx = session.beginTransaction();
            session.save(bean);

            tx.commit();

            final IConfigurationElement confElementTrigger = KalypsoProjectDatabaseExtensions
                    .getProjectDatabaseTriggers(bean.getProjectType());
            if (confElementTrigger != null)
                TriggerHelper.handleBean(bean, confElementTrigger);

            return bean;
        } catch (final Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

}

From source file:org.kalypso.project.database.server.ProjectDatabaseHelper.java

protected static Boolean removeBean(final Session session, final KalypsoProjectBean bean) {
    try {//  w w  w  .  j  av a 2s . c om
        final FileSystemManager manager = VFSUtilities.getManager();

        /* remove file from server */
        // destination webdav url of bean
        final String urlBean = ProjectDatabaseHelper.resolveDestinationUrl(bean);
        final FileObject fileBean = manager.resolveFile(urlBean);
        if (fileBean.exists()) {
            fileBean.delete();
        }

        final FileObject parentFolder = fileBean.getParent();
        if (parentFolder.exists()) {
            parentFolder.delete();
        }

        /* delete database entry */
        final Transaction tx = session.beginTransaction();
        session.delete(bean);
        tx.commit();

        return true;
    } catch (final FileSystemException e) {
        KalypsoProjectDatabase.getDefault().getLog().log(StatusUtilities.statusFromThrowable(e));
    }

    return false;

}

From source file:org.kalypso.project.database.server.trigger.TriggerHelper.java

public static void handleBean(final KalypsoProjectBean bean, final IConfigurationElement element)
        throws Exception {
    /* resolve trigger extension class */
    final String pluginid = element.getContributor().getName();
    final Bundle bundle = Platform.getBundle(pluginid);
    final Class<?> triggerClass = bundle.loadClass(element.getAttribute("class")); //$NON-NLS-1$
    final Constructor<?> constructor = triggerClass.getConstructor();

    final IProjectDatabaseTrigger trigger = (IProjectDatabaseTrigger) constructor.newInstance();

    final FileSystemManager manager = VFSUtilities.getManager();

    /* resolve global dir */
    final String urlGlobalPath = System.getProperty(IProjectDataBaseServerConstant.SERVER_GLOBAL_DATA_PATH);
    final FileObject folderGlobal = manager.resolveFile(urlGlobalPath);
    if (!folderGlobal.exists()) {
        folderGlobal.createFolder();/*from w ww . ja va2 s.com*/
    }

    /* global "global" dir */
    final FileObject destinationCommonFolder = folderGlobal.resolveFile(COMMON_FOLDER);
    if (!destinationCommonFolder.exists()) {
        destinationCommonFolder.createFolder();
    }

    /* global project dir */
    final FileObject destinationProjectFolder = folderGlobal.resolveFile(bean.getUnixName());
    if (!destinationProjectFolder.exists()) {
        destinationProjectFolder.createFolder();
    }

    trigger.handleCommonData(bean, destinationCommonFolder);
    trigger.handleProjectData(bean, destinationProjectFolder);
}