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

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

Introduction

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

Prototype

FileObject resolveFile(String path) throws FileSystemException;

Source Link

Document

Finds a file, relative to this file.

Usage

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

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

    _window.setStatusLabelNotice();//w  w w  . ja v a 2  s  .c  om
    _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 2  s  .com
 * 
 * @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  w w w  .ja v a  2  s. co  m
        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.
 * /*from  www. ja  v a  2  s .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 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   ww  w .ja  v a 2s  . 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.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public String createFile(String parentPath, String title, String type,
        SharedUserPortletParameters userParameters) {
    try {// w w  w  .j a v a2  s  . co  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 moveCopyFilesIntoDirectory(String dir, List<String> filesToCopy, boolean copy,
        SharedUserPortletParameters userParameters) {
    try {//  ww w .j av a 2 s . com
        FileObject folder = cd(dir, userParameters);
        for (String fileToCopyPath : filesToCopy) {
            FileObject fileToCopy = cd(fileToCopyPath, userParameters);
            FileObject newFile = folder.resolveFile(fileToCopy.getName().getBaseName());
            if (copy) {
                newFile.copyFrom(fileToCopy, Selectors.SELECT_ALL);
            } else {
                fileToCopy.moveTo(newFile);
            }

        }
        return true;
    } catch (FileSystemException e) {
        log.warn("can't move/copy 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;/*from   w  ww .jav  a 2  s . c om*/

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

From source file:org.freedesktop.cursors.CursorTheme.java

public CursorTheme(FileObject base) throws IOException, ParseException {
    super(CURSOR_THEME, base);
    themeFile = base.resolveFile("index.theme");
    if (!themeFile.exists()) {
        throw new FileNotFoundException("index.theme not found");
    }//from w ww .  j  av a 2  s.  c o  m
}

From source file:org.freedesktop.cursors.DefaultCursorService.java

protected Collection<CursorTheme> scanBase(FileObject base) throws IOException {
    List<CursorTheme> themes = new ArrayList<CursorTheme>();
    for (FileObject dir : listDirs(base)) {
        FileObject cursorTheme = dir.resolveFile("cursor.theme");
        FileObject cursorsDir = dir.resolveFile("cursors");
        if (cursorTheme.exists() || cursorsDir.exists()) {
            try {
                themes.add(new CursorTheme(dir));
            } catch (FileNotFoundException fnfe) {
                // Skip
                Log.debug("Skipping " + dir + " because index.theme is missing.");
            } catch (IOException ioe) {
                Log.warn("Invalid theme directory " + dir.getName().getPath() + "." + ioe.getMessage());
            } catch (ParseException ioe) {
                Log.warn("Invalid theme definition in " + dir.getName().getPath() + ". " + ioe.getMessage());
            }/*from   w  w  w  .  j a v  a2 s .  c om*/
        } else {
            // Skip
            Log.debug("Skipping " + dir + " because it is an icon theme.");
        }
    }
    return themes;
}