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

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

Introduction

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

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:org.eobjects.datacleaner.actions.SaveAnalysisJobActionListener.java

@Override
public void actionPerformed(ActionEvent event) {
    final String actionCommand = event.getActionCommand();

    _window.setStatusLabelNotice();/*from ww  w .java  2 s. c  o m*/
    _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB);

    AnalysisJob analysisJob = null;
    try {
        _window.applyPropertyValues();
        analysisJob = _analysisJobBuilder.toAnalysisJob();
    } catch (Exception e) {
        if ("No Analyzers in job".equals(e.getMessage())) {
            // TODO: Have a better way to diagnose this issue
            int result = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "You job does not have any analyzer components in it, and is thus 'incomplete'. Do you want to save it anyway?",
                    "No analyzers in job", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (result == JOptionPane.YES_OPTION) {
                analysisJob = _analysisJobBuilder.toAnalysisJob(false);
            } else {
                return;
            }
        } else {
            String detail = _window.getStatusLabelText();
            if (LABEL_TEXT_SAVING_JOB.equals(detail)) {
                detail = e.getMessage();
            }
            WidgetUtils.showErrorMessage("Errors in job",
                    "Please fix the errors that exist in the job before saving it:\n\n" + detail, e);
            return;
        }
    }

    final FileObject existingFile = _window.getJobFile();

    final FileObject file;
    if (existingFile == null || ACTION_COMMAND_SAVE_AS.equals(actionCommand)) {
        // ask the user to select a file to save to ("Save as" scenario)
        final DCFileChooser fileChooser = new DCFileChooser(_userPreferences.getAnalysisJobDirectory());
        fileChooser.setFileFilter(FileFilters.ANALYSIS_XML);

        final int result = fileChooser.showSaveDialog(_window.toComponent());
        if (result != JFileChooser.APPROVE_OPTION) {
            return;
        }
        FileObject candidate = fileChooser.getSelectedFileObject();

        final boolean exists;
        try {
            final String baseName = candidate.getName().getBaseName();
            if (!baseName.endsWith(".xml")) {
                final FileObject parent = candidate.getParent();
                file = parent.resolveFile(baseName + FileFilters.ANALYSIS_XML.getExtension());
            } else {
                file = candidate;
            }
            exists = file.exists();
        } catch (FileSystemException e) {
            throw new IllegalStateException("Failed to prepare file for saving", e);
        }

        if (exists) {
            int overwrite = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "Are you sure you want to overwrite the file '" + file.getName() + "'?",
                    "Overwrite existing file?", JOptionPane.YES_NO_OPTION);
            if (overwrite != JOptionPane.YES_OPTION) {
                return;
            }
        }
    } else {
        // overwrite existing file ("Save" scenario).
        file = existingFile;
    }

    try {
        final FileObject parent = file.getParent();
        final File parentFile = VFSUtils.toFile(parent);
        if (parentFile != null) {
            _userPreferences.setAnalysisJobDirectory(parentFile);
        }
    } catch (FileSystemException e) {
        logger.warn("Failed to determine parent of {}: {}", file, e.getMessage());
    }

    final String author = System.getProperty("user.name");
    final String jobName = null;
    final String jobDescription = "Created with DataCleaner " + Version.getEdition() + " "
            + Version.getVersion();
    final String jobVersion = null;

    final JaxbJobWriter writer = new JaxbJobWriter(_configuration,
            new JaxbJobMetadataFactoryImpl(author, jobName, jobDescription, jobVersion));

    OutputStream outputStream = null;
    try {
        outputStream = file.getContent().getOutputStream();
        writer.write(analysisJob, outputStream);
    } catch (IOException e1) {
        throw new IllegalStateException(e1);
    } finally {
        FileHelper.safeClose(outputStream);
    }

    if (file instanceof DelegateFileObject) {
        // this "file" is probably a HTTP URL resource (often provided by DC
        // monitor)
        final DelegateFileObject delegateFileObject = (DelegateFileObject) file;
        final String scheme = file.getName().getScheme();

        if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
            final String uri = delegateFileObject.getName().getURI();
            final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();
            if (monitorConnection.matchesURI(uri) && monitorConnection.isAuthenticationEnabled()
                    && monitorConnection.getEncodedPassword() == null) {
                // password is not configured, ask for it.
                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(_window.getWindowContext(),
                        _userPreferences);
                dialog.openBlocking();
            }

            final PublishJobToMonitorActionListener publisher = new PublishJobToMonitorActionListener(
                    delegateFileObject, _window.getWindowContext(), _userPreferences);
            publisher.actionPerformed(event);
        } else {
            throw new UnsupportedOperationException("Unexpected delegate file object: " + delegateFileObject
                    + " (delegate: " + delegateFileObject.getDelegateFile() + ")");
        }
    } else {
        _userPreferences.addRecentJobFile(file);
    }

    _window.setJobFile(file);

    _window.setStatusLabelNotice();
    _window.setStatusLabelText("Saved job to file " + file.getName().getBaseName());
}

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  2s.c om*/
 * 
 * @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.guice.DCModule.java

private final Ref<UserPreferences> createUserPreferencesRef(final FileObject dataCleanerHome) {
    try {/*from  ww w.  j  a  va 2 s . com*/
        if ("true".equalsIgnoreCase(System.getProperty(SystemProperties.SANDBOX))) {
            return new ImmutableRef<UserPreferences>(new UserPreferencesImpl(null));
        }
        if (dataCleanerHome == null || !dataCleanerHome.exists()) {
            logger.info(
                    "DataCleaner home was not set or does not exist. Non-persistent user preferences will be applied.");
            return new ImmutableRef<UserPreferences>(new UserPreferencesImpl(null));
        }

        final FileObject userPreferencesFile = dataCleanerHome.resolveFile("userpreferences.dat");

        return new LazyRef<UserPreferences>() {
            @Override
            protected UserPreferences fetch() {
                return UserPreferencesImpl.load(userPreferencesFile, true);
            }
        };
    } catch (FileSystemException e) {
        throw new IllegalStateException("Not able to resolve files in DataCleaner home: " + dataCleanerHome, e);
    }
}

From source file:org.eobjects.datacleaner.Main.java

/**
 * Initializes logging, specifically by looking for log4j.xml or
 * log4j.properties file in DataCleaner's home directory.
 * //  ww  w. ja  va2s  .  c  om
 * @return true if a logging configuration file was found, or false
 *         otherwise
 */
protected static boolean initializeLogging() {
    try {

        // initial logging config, used before anything else
        {
            final URL url = Main.class.getResource("log4j-initial.xml");
            assert url != null;
            DOMConfigurator.configure(url);
        }

        if (ClassLoaderUtils.IS_WEB_START) {
            final URL url = Main.class.getResource("log4j-jnlp.xml");
            assert url != null;
            println("Using JNLP log configuration: " + url);
            DOMConfigurator.configure(url);
            return true;
        }

        final FileObject dataCleanerHome = DataCleanerHome.get();

        try {
            final FileObject xmlConfigurationFile = dataCleanerHome.resolveFile("log4j.xml");
            if (xmlConfigurationFile.exists() && xmlConfigurationFile.getType() == FileType.FILE) {
                println("Using custom log configuration: " + xmlConfigurationFile);
                DOMConfigurator.configure(xmlConfigurationFile.getURL());
                return true;
            }
        } catch (FileSystemException e) {
            // no xml logging found, ignore
        }

        try {
            final FileObject propertiesConfigurationFile = dataCleanerHome.resolveFile("log4j.properties");
            if (propertiesConfigurationFile.exists()
                    && propertiesConfigurationFile.getType() == FileType.FILE) {
                println("Using custom log configuration: " + propertiesConfigurationFile);
                PropertyConfigurator.configure(propertiesConfigurationFile.getURL());
                return true;
            }
        } catch (FileSystemException e) {
            // no xml logging found, ignore
        }

        // fall back to default log4j.xml file in classpath
        final URL url = Main.class.getResource("log4j-default.xml");
        assert url != null;
        println("Using default log configuration: " + url);
        DOMConfigurator.configure(url);
        return false;

    } catch (NoClassDefFoundError e) {
        // can happen if log4j is not on the classpath
        println("Failed to initialize logging, class not found: " + e.getMessage());
        return false;
    }
}

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  .  java2s.c o 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;
}

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

private static void 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;/*from  w  w  w  .ja  v  a 2 s.  c o  m*/
    }
    FileObject parentFile = file.getParent();
    if (!parentFile.exists()) {
        parentFile.createFolder();
    }

    final ResourceManager resourceManager = ResourceManager.get();
    final URL url = resourceManager.getUrl("datacleaner-home/" + filename);

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

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

public static UserPreferences load(final FileObject userPreferencesFile, final boolean loadDatabaseDrivers) {
    try {/*from   ww w. j a  v a2  s .c  o  m*/
        if (userPreferencesFile == null || !userPreferencesFile.exists()) {
            logger.info("User preferences file does not exist");
            return new UserPreferencesImpl(userPreferencesFile);
        }
    } catch (FileSystemException e1) {
        logger.debug("Could not determine if file exists: {}", userPreferencesFile);
    }

    ChangeAwareObjectInputStream inputStream = null;
    try {
        inputStream = new ChangeAwareObjectInputStream(userPreferencesFile.getContent().getInputStream());
        inputStream.addRenamedClass("org.eobjects.datacleaner.user.UserPreferences", UserPreferencesImpl.class);
        UserPreferencesImpl result = (UserPreferencesImpl) inputStream.readObject();

        if (loadDatabaseDrivers) {
            List<UserDatabaseDriver> installedDatabaseDrivers = result.getDatabaseDrivers();
            for (UserDatabaseDriver userDatabaseDriver : installedDatabaseDrivers) {
                try {
                    userDatabaseDriver.loadDriver();
                } catch (IllegalStateException e) {
                    logger.error("Could not load database driver", e);
                }
            }
        }

        result._userPreferencesFile = userPreferencesFile;
        result.refreshProxySettings();
        return result;
    } catch (InvalidClassException e) {
        logger.warn("User preferences file version does not match application version: {}", e.getMessage());
        return new UserPreferencesImpl(userPreferencesFile);
    } catch (Exception e) {
        logger.warn("Could not read user preferences file", e);
        return new UserPreferencesImpl(userPreferencesFile);
    } finally {
        FileHelper.safeClose(inputStream);
    }
}

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

@Override
public String createFile(String parentPath, String title, String type,
        SharedUserPortletParameters userParameters) {
    try {//from  w  ww.jav  a  2  s .  c  o m
        FileObject parent = cd(parentPath, userParameters);
        FileObject child = parent.resolveFile(title);
        if (!child.exists()) {
            if ("folder".equals(type)) {
                child.createFolder();
                log.info("folder " + title + " created");
            } else {
                child.createFile();
                log.info("file " + title + " created");
            }
            return child.getName().getPath();
        } else {
            log.info("file " + title + " already exists !");
        }
    } catch (FileSystemException e) {
        log.info("can't create file because of FileSystemException : " + e.getMessage(), e);
    }
    return null;
}

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

@Override
public boolean renameFile(String path, String title, SharedUserPortletParameters userParameters) {
    try {// w  ww . j  ava2 s  . c o m
        FileObject file = cd(path, userParameters);
        FileObject newFile = file.getParent().resolveFile(title);
        if (!newFile.exists()) {
            file.moveTo(newFile);
            return true;
        } else {
            log.info("file " + title + " already exists !");
        }
    } catch (FileSystemException e) {
        log.info("can't rename file because of FileSystemException : " + e.getMessage(), e);
    }
    return false;
}

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

@Override
public boolean putFile(String dir, String filename, InputStream inputStream,
        SharedUserPortletParameters userParameters, UploadActionType uploadOption) {

    boolean success = false;
    FileObject newFile = null;

    try {// w ww  .ja  v  a 2s  . c om
        FileObject folder = cd(dir, userParameters);
        newFile = folder.resolveFile(filename);
        if (newFile.exists()) {
            switch (uploadOption) {
            case ERROR:
                throw new EsupStockFileExistException();
            case OVERRIDE:
                newFile.delete();
                break;
            case RENAME_NEW:
                newFile = folder.resolveFile(this.getUniqueFilename(filename, "-new-"));
                break;
            case RENAME_OLD:
                newFile.moveTo(folder.resolveFile(this.getUniqueFilename(filename, "-old-")));
                break;
            }
        }
        newFile.createFile();

        OutputStream outstr = newFile.getContent().getOutputStream();

        FileCopyUtils.copy(inputStream, outstr);

        success = true;
    } catch (FileSystemException e) {
        log.info("can't upload file : " + e.getMessage(), e);
    } catch (IOException e) {
        log.warn("can't upload file : " + e.getMessage(), e);
    }

    if (!success && newFile != null) {
        // problem when uploading the file -> the file uploaded is corrupted
        // best is to delete it
        try {
            newFile.delete();
            log.debug("delete corrupted file after bad upload ok ...");
        } catch (Exception e) {
            log.debug("can't delete corrupted file after bad upload " + e.getMessage());
        }
    }

    return success;
}