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

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

Introduction

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

Prototype

void createFolder() throws FileSystemException;

Source Link

Document

Creates this folder, if it does not exist.

Usage

From source file:org.apache.zeppelin.notebook.repo.VFSNotebookRepo.java

@Override
public void save(Note note) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();//  w  w w  .  ja v a 2 s . com
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(note);

    FileObject rootDir = getRootDir();

    FileObject noteDir = rootDir.resolveFile(note.id(), NameScope.CHILD);

    if (!noteDir.exists()) {
        noteDir.createFolder();
    }
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }

    FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
    // false means not appending. creates file if not exists
    OutputStream out = noteJson.getContent().getOutputStream(false);
    out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
    out.close();
}

From source file:org.celeria.minecraft.backup.ConfigurationModule.java

@CheckedProvides(FileProvider.class)
@BackupFolder//from   www . jav  a 2s  .  c  om
@Singleton
public FileObject provideBackupFolder(final Configuration configuration,
        final FileProvider<FileSystemManager> fileSystemProvider) throws FileSystemException {
    final String folderName = getProperty(configuration, BACKUP_FOLDER);
    final FileSystemManager fileSystemManager = fileSystemProvider.get();
    final FileObject folder = fileSystemManager.resolveFile(folderName);
    folder.createFolder();
    return folder;
}

From source file:org.celeria.minecraft.backup.TemporaryFolderProvider.java

private FileObject getChildFolder(final FileSystemManager fileSystem, final FileObject baseFolder,
        final String baseName) throws FileSystemException {
    for (int counter = 0; counter < TEMPORARY_FOLDER_ATTEMPTS; ++counter) {
        final FileObject temporaryFolder = fileSystem.resolveFile(baseFolder, baseName + counter);
        if (!temporaryFolder.exists()) {
            temporaryFolder.createFolder();
            return temporaryFolder;
        }//from  w w  w .  ja va  2  s.c  om
    }
    throw new FileSystemException("Failed to create directory within " + TEMPORARY_FOLDER_ATTEMPTS
            + " attempts (tried " + baseName + "0 to " + baseName + (TEMPORARY_FOLDER_ATTEMPTS - 1) + ')');
}

From source file:org.datacleaner.bootstrap.Bootstrap.java

/**
 * Looks up a file, either based on a user requested filename (typically a
 * CLI parameter, may be a URL) or by a relative filename defined in the
 * system-/*from   w  w  w .j  a v a  2  s.  c  o  m*/
 * 
 * @param userRequestedFilename
 *            the user requested filename, may be null
 * @param localFilename
 *            the relative filename defined by the system
 * @param userPreferences
 * @return
 * @throws FileSystemException
 */
private FileObject resolveFile(final String userRequestedFilename, final String localFilename,
        UserPreferences userPreferences) throws FileSystemException {
    final File dataCleanerHome = DataCleanerHome.getAsFile();
    if (userRequestedFilename == null) {
        File file = new File(dataCleanerHome, localFilename);
        return VFSUtils.toFileObject(file);
    } else {
        String lowerCaseFilename = userRequestedFilename.toLowerCase();
        if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) {
            if (!GraphicsEnvironment.isHeadless()) {
                // download to a RAM file.
                final FileObject targetDirectory = VFSUtils.getFileSystemManager()
                        .resolveFile("ram:///datacleaner/temp");
                if (!targetDirectory.exists()) {
                    targetDirectory.createFolder();
                }

                final URI uri;
                try {
                    uri = new URI(userRequestedFilename);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e);
                }

                final WindowContext windowContext = new SimpleWindowContext();

                MonitorConnection monitorConnection = null;

                // check if URI points to DC monitor. If so, make sure
                // credentials are entered.
                if (userPreferences != null && userPreferences.getMonitorConnection() != null) {
                    monitorConnection = userPreferences.getMonitorConnection();
                    if (monitorConnection.matchesURI(uri)) {
                        if (monitorConnection.isAuthenticationEnabled()) {
                            if (monitorConnection.getEncodedPassword() == null) {
                                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(
                                        windowContext, userPreferences);
                                dialog.openBlocking();
                            }
                            monitorConnection = userPreferences.getMonitorConnection();
                        }
                    }
                }

                try (MonitorHttpClient httpClient = getHttpClient(monitorConnection)) {

                    final String[] urls = new String[] { userRequestedFilename };
                    final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls);

                    final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames,
                            windowContext, httpClient, monitorConnection);

                    assert files.length == 1;

                    final FileObject ramFile = files[0];

                    if (logger.isInfoEnabled()) {
                        final InputStream in = ramFile.getContent().getInputStream();
                        try {
                            final String str = FileHelper
                                    .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8");
                            logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str);
                        } finally {
                            FileHelper.safeClose(in);
                        }
                    }

                    final String scheme = uri.getScheme();
                    final int defaultPort;
                    if ("http".equals(scheme)) {
                        defaultPort = 80;
                    } else {
                        defaultPort = 443;
                    }

                    final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(),
                            defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery());

                    AbstractFileSystem fileSystem = (AbstractFileSystem) VFSUtils.getBaseFileSystem();
                    return new DelegateFileObject(fileName, fileSystem, ramFile);
                } finally {
                    userPreferences.setMonitorConnection(monitorConnection);
                }

            }
        }

        return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename);
    }
}

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

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

    if (ClassLoaderUtils.IS_WEB_START) {
        // in web start, the default folder will be in user.home
        final String path = getUserHomeCandidatePath();
        candidate = manager.resolveFile(path);
        logger.info("Running in WebStart mode. Attempting to build DATACLEANER_HOME in user.home: {} -> {}",
                path, candidate);//from   ww w .  ja  v a2  s . com
    } else {
        // in normal mode try to use specified directory first
        logger.info("Running in standard mode.");
        if (isWriteable(candidate)) {
            logger.info("Attempting to build DATACLEANER_HOME in {}", candidate);
        } else {
            // Workaround: isWritable is not reliable for a non-existent
            // directory. Trying to create it, if it does not exist.
            if ((candidate != null) && (!candidate.exists())) {
                logger.info("Folder {} does not exist. Trying to create it.", candidate);
                try {
                    candidate.createFolder();
                    logger.info("Folder {} created successfully. Attempting to build DATACLEANER_HOME here.",
                            candidate);
                } catch (FileSystemException e) {
                    logger.info("Unable to create folder {}. No write permission in that location.", candidate);
                    candidate = initializeDataCleanerHomeFallback();
                }
            } else {
                candidate = initializeDataCleanerHomeFallback();
            }
        }

    }

    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)) {
        DataCleanerHomeUpgrader upgrader = new DataCleanerHomeUpgrader();
        boolean upgraded = upgrader.upgrade(candidate);

        if (!upgraded) {
            logger.debug("Copying default configuration and examples to DATACLEANER_HOME directory: {}",
                    candidate);
            copyIfNonExisting(candidate, manager, "conf.xml");

            final List<String> allFilePaths = DemoConfiguration.getAllFilePaths();
            for (String filePath : allFilePaths) {
                copyIfNonExisting(candidate, manager, filePath);
            }
        }
    }
    return candidate;
}

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

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

    FileObject candidate;

    // Fallback to user home directory
    final String path = getUserHomeCandidatePath();
    candidate = manager.resolveFile(path);
    logger.info("Attempting to build DATACLEANER_HOME in user.home: {} -> {}", path, candidate);
    if (!isWriteable(candidate)) {
        // Workaround: isWritable is not reliable for a non-existent
        // directory. Trying to create it, if it does not exist.
        if ((candidate != null) && (!candidate.exists())) {
            logger.info("Folder {} does not exist. Trying to create it.", candidate);
            try {
                candidate.createFolder();
                logger.info("Folder {} created successfully. Attempting to build DATACLEANER_HOME here.",
                        candidate);//w  w  w .jav a 2 s. c om
            } catch (FileSystemException e) {
                logger.info("Unable to create folder {}. No write permission in that location.", candidate);
                throw new IllegalStateException("User home directory (" + candidate
                        + ") is not writable. DataCleaner requires write access to its home directory.");
            }
        }
    }
    return candidate;
}

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

private static FileObject copyIfNonExisting(FileObject candidate, FileSystemManager manager, String filename)
        throws FileSystemException {
    FileObject file = candidate.resolveFile(filename);
    if (file.exists()) {
        logger.info("File already exists in DATACLEANER_HOME: " + filename);
        return file;
    }/*  ww  w . ja v a  2  s  . com*/
    FileObject parentFile = file.getParent();
    if (!parentFile.exists()) {
        parentFile.createFolder();
    }

    final ResourceManager resourceManager = ResourceManager.get();
    final URL url = resourceManager.getUrl("datacleaner-home/" + filename);
    if (url == null) {
        return null;
    }

    InputStream in = null;
    OutputStream out = null;
    try {
        in = url.openStream();
        out = file.getContent().getOutputStream();

        FileHelper.copy(in, out);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        FileHelper.safeClose(in, out);
    }

    return file;
}

From source file:org.datacleaner.user.upgrade.DataCleanerHomeUpgrader.java

private static FileObject overwriteFileWithDefaults(FileObject targetDirectory, String targetFilename)
        throws FileSystemException {
    FileObject file = targetDirectory.resolveFile(targetFilename);
    FileObject parentFile = file.getParent();
    if (!parentFile.exists()) {
        parentFile.createFolder();
    }//from   w  w  w  .  j a va2s. com

    final ResourceManager resourceManager = ResourceManager.get();
    final URL url = resourceManager.getUrl("datacleaner-home/" + targetFilename);
    if (url == null) {
        return null;
    }

    InputStream in = null;
    OutputStream out = null;
    try {
        in = url.openStream();
        out = file.getContent().getOutputStream();

        FileHelper.copy(in, out);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        FileHelper.safeClose(in, out);
    }

    return file;
}

From source file:org.eobjects.datacleaner.bootstrap.Bootstrap.java

/**
 * Looks up a file, either based on a user requested filename (typically a
 * CLI parameter, may be a URL) or by a relative filename defined in the
 * system-//from  w  w  w  .  j  a v a 2  s . c o m
 * 
 * @param userRequestedFilename
 *            the user requested filename, may be null
 * @param localFilename
 *            the relative filename defined by the system
 * @param userPreferences
 * @return
 * @throws FileSystemException
 */
private FileObject resolveFile(final String userRequestedFilename, final String localFilename,
        UserPreferences userPreferences) throws FileSystemException {
    final FileObject dataCleanerHome = DataCleanerHome.get();
    if (userRequestedFilename == null) {
        return dataCleanerHome.resolveFile(localFilename);
    } else {
        String lowerCaseFilename = userRequestedFilename.toLowerCase();
        if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) {
            if (!GraphicsEnvironment.isHeadless()) {
                // download to a RAM file.
                final FileObject targetDirectory = VFSUtils.getFileSystemManager()
                        .resolveFile("ram:///datacleaner/temp");
                if (!targetDirectory.exists()) {
                    targetDirectory.createFolder();
                }

                final URI uri;
                try {
                    uri = new URI(userRequestedFilename);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e);
                }

                final WindowContext windowContext = new SimpleWindowContext();

                @SuppressWarnings("resource")
                MonitorHttpClient httpClient = new SimpleWebServiceHttpClient();
                MonitorConnection monitorConnection = null;

                // check if URI points to DC monitor. If so, make sure
                // credentials are entered.
                if (userPreferences != null && userPreferences.getMonitorConnection() != null) {
                    monitorConnection = userPreferences.getMonitorConnection();
                    if (monitorConnection.matchesURI(uri)) {
                        if (monitorConnection.isAuthenticationEnabled()) {
                            if (monitorConnection.getEncodedPassword() == null) {
                                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(
                                        windowContext, userPreferences);
                                dialog.openBlocking();
                            }
                            monitorConnection = userPreferences.getMonitorConnection();
                            httpClient = monitorConnection.getHttpClient();
                        }
                    }
                }

                try {

                    final String[] urls = new String[] { userRequestedFilename };
                    final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls);

                    final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames,
                            windowContext, httpClient, monitorConnection);

                    assert files.length == 1;

                    final FileObject ramFile = files[0];

                    if (logger.isInfoEnabled()) {
                        final InputStream in = ramFile.getContent().getInputStream();
                        try {
                            final String str = FileHelper
                                    .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8");
                            logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str);
                        } finally {
                            FileHelper.safeClose(in);
                        }
                    }

                    final String scheme = uri.getScheme();
                    final int defaultPort;
                    if ("http".equals(scheme)) {
                        defaultPort = 80;
                    } else {
                        defaultPort = 443;
                    }

                    final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(),
                            defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery());

                    AbstractFileSystem fileSystem = (AbstractFileSystem) dataCleanerHome.getFileSystem();
                    return new DelegateFileObject(fileName, fileSystem, ramFile);
                } finally {
                    httpClient.close();

                    userPreferences.setMonitorConnection(monitorConnection);
                }

            }
        }

        return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename);
    }
}

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

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

    FileObject candidate = null;

    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);
    }//from   ww  w  .  j a v  a 2 s.co m

    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;
}