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

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

Introduction

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

Prototype

FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

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

private boolean backupIsOld(final FileObject backup) throws FileSystemException {
    final long lastModifiedTime = backup.getContent().getLastModifiedTime();
    final Instant instant = new Instant(lastModifiedTime);
    return currentTime.plus(durationToKeepBackups).isAfter(instant);
}

From source file:org.clever.Common.Storage.VirtualFileSystem.java

/**
 * This method lists contents of a file or folder
 * @param file/* ww w  .  ja v a 2  s  .com*/
 * @return
 * @throws FileSystemException 
 */
public String ls(FileObject file) throws FileSystemException {
    String str = "Contents of " + file.getName() + "\n";
    if (file.exists()) {
        if (file.getType().equals(FileType.FILE)) {
            str = str + "Size: " + file.getContent().getSize() + " bytes\n" + "Last modified: "
                    + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())) + "\n"
                    + "Readable: " + file.isReadable() + "\n" + "Writeable: " + file.isWriteable() + "\n";
            return str;
        } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
            FileObject[] children = file.getChildren();
            str = str = "Directory with " + children.length + " files \n" + "Readable: " + file.isReadable()
                    + "\n" + "Writeable: " + file.isWriteable() + "\n\n";
            //str=str+"Last modified: " +DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime()))+"\n" ;
            for (int i = 0; i < children.length; i++) {
                str = str + children[i].getName().getBaseName() + "\n";
            }
        }
    } else {
        str = str + "The file does not exist";
    }
    return str;
}

From source file:org.clever.Common.Storage.VirtualFileSystem.java

/**
 * Simply changed the last modification time of the given file
 * @param fo/*from  ww w  .  j ava2  s  . co m*/
 * @throws FileSystemException 
 */
public void ChangeLastModificationTime(FileObject fo) throws FileSystemException {
    long setTo = System.currentTimeMillis();
    System.err.println("set to: " + setTo);
    fo.getContent().setLastModifiedTime(setTo);
    System.err.println("after set: " + fo.getContent().getLastModifiedTime());
}

From source file:org.cloudifysource.esc.installer.filetransfer.VfsFileTransfer.java

@Override
public void copyFiles(final InstallationDetails details, final Set<String> excludedFiles,
        final List<File> additionalFiles, final long endTimeMillis)
        throws TimeoutException, InstallerException {

    logger.fine("Copying files to: " + host + " from local dir: " + localDir.getName().getPath() + " excluding "
            + excludedFiles.toString());

    try {/*from  w ww  .  j  a v a2  s  .co  m*/

        if (remoteDir.exists()) {
            FileType type = remoteDir.getType();
            if (!type.equals(FileType.FOLDER)) {
                throw new InstallerException("The remote location: " + remoteDir.getName().getFriendlyURI()
                        + " exists but is not a directory");
            }

            if (deleteRemoteDirectoryContents) {
                logger.info("Deleting contents of remote directory: " + remoteDir.getName().getFriendlyURI());
                remoteDir.delete(new FileDepthSelector(1, Integer.MAX_VALUE));
            }
            FileObject[] children = remoteDir.getChildren();
            if (children.length > 0) {

                throw new InstallerException(
                        "The remote directory: " + remoteDir.getName().getFriendlyURI() + " is not empty");
            }
        }

        remoteDir.copyFrom(localDir, new FileSelector() {

            @Override
            public boolean includeFile(final FileSelectInfo fileInfo) throws Exception {
                if (excludedFiles.contains(fileInfo.getFile().getName().getBaseName())) {
                    logger.fine(fileInfo.getFile().getName().getBaseName() + " excluded");
                    return false;

                }
                final FileObject remoteFile = fileSystemManager.resolveFile(remoteDir,
                        localDir.getName().getRelativeName(fileInfo.getFile().getName()));

                if (!remoteFile.exists()) {
                    logger.fine(fileInfo.getFile().getName().getBaseName() + " missing on server");
                    return true;
                }

                if (fileInfo.getFile().getType() == FileType.FILE) {
                    final long remoteSize = remoteFile.getContent().getSize();
                    final long localSize = fileInfo.getFile().getContent().getSize();
                    final boolean res = localSize != remoteSize;
                    if (res) {
                        logger.fine(fileInfo.getFile().getName().getBaseName() + " different on server");
                    }
                    return res;
                }
                return false;

            }

            @Override
            public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception {
                return true;
            }
        });

        for (final File file : additionalFiles) {
            logger.fine("copying file: " + file.getAbsolutePath() + " to remote directory");
            final FileObject fileObject = fileSystemManager.resolveFile("file:" + file.getAbsolutePath());
            final FileObject remoteFile = remoteDir.resolveFile(file.getName());
            remoteFile.copyFrom(fileObject, new AllFileSelector());
        }

        logger.fine("Copying files to: " + host + " completed.");
    } catch (final FileSystemException e) {
        throw new InstallerException("Failed to copy files to remote host " + host + ": " + e.getMessage(), e);

    }
    checkTimeout(endTimeMillis);

}

From source file:org.codehaus.mojo.vfs.internal.DefaultVfsFileSetManager.java

private void copyFile(FileObject fromFile, FileObject toFile, boolean overwrite) throws FileSystemException {
    if (overwrite || !toFile.exists()
            || fromFile.getContent().getLastModifiedTime() > toFile.getContent().getLastModifiedTime()) {
        toFile.copyFrom(fromFile, Selectors.SELECT_ALL);
    }//  ww  w .  ja  va  2  s .  c  o  m
}

From source file:org.datacleaner.actions.DownloadFilesActionListener.java

@Override
protected FileObject[] doInBackground() throws Exception {
    for (int i = 0; i < _urls.length; i++) {
        final String url = _urls[i];
        final FileObject file = _files[i];

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {/*from  w ww .  j av  a  2 s  .c o m*/
            byte[] buffer = new byte[1024];

            final HttpGet method = new HttpGet(url);

            if (!_cancelled) {
                final HttpResponse response = _httpClient.execute(method);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new InvalidHttpResponseException(url, response);
                }

                final HttpEntity responseEntity = response.getEntity();
                final long expectedSize = responseEntity.getContentLength();
                if (expectedSize > 0) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize);
                        }
                    });
                }

                inputStream = responseEntity.getContent();

                if (!file.exists()) {
                    file.createFile();
                }
                outputStream = file.getContent().getOutputStream();

                long bytes = 0;
                for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream
                        .read(buffer)) {
                    if (_cancelled) {
                        break;
                    }
                    outputStream.write(buffer, 0, numBytes);
                    bytes += numBytes;

                    final long totalBytes = bytes;
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes);
                        }
                    });
                }

                if (!_cancelled) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setFinished(file.getName().getBaseName());
                        }
                    });
                }
            }
        } catch (IOException e) {
            logger.debug("IOException occurred while downloading files", e);
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not close input stream: " + e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not flush & close output stream: " + e.getMessage(), e);
                }
            }

            _httpClient.close();
        }

        if (_cancelled) {
            logger.info("Deleting non-finished download-file '{}'", file);
            file.delete();
        }
    }

    return _files;
}

From source file:org.datacleaner.actions.OpenAnalysisJobActionListener.java

public ResultWindow openAnalysisResult(final FileObject fileObject, DCModule parentModule) {
    final AnalysisResult analysisResult;
    try {//from  w ww.  j  ava 2 s .c  om
        ChangeAwareObjectInputStream is = new ChangeAwareObjectInputStream(
                fileObject.getContent().getInputStream());
        try {
            is.addClassLoader(ExtensionPackage.getExtensionClassLoader());
            analysisResult = (AnalysisResult) is.readObject();
        } finally {
            FileHelper.safeClose(is);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    final File file = VFSUtils.toFile(fileObject);
    if (file != null) {
        _userPreferences.setAnalysisJobDirectory(file.getParentFile());
        _userPreferences.addRecentJobFile(fileObject);
    }

    final Injector injector = Guice.createInjector(new DCModuleImpl(parentModule, null) {
        public FileObject getJobFilename() {
            return fileObject;
        };

        @Override
        public AnalysisResult getAnalysisResult() {
            return analysisResult;
        }

        @Override
        public AnalysisJobBuilder getAnalysisJobBuilder(DataCleanerConfiguration configuration) {
            return null;
        }
    });

    ResultWindow resultWindow = injector.getInstance(ResultWindow.class);
    resultWindow.open();
    return resultWindow;
}

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

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

    _window.setStatusLabelNotice();/*from w ww. ja v a 2s.c om*/
    _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB);

    AnalysisJob analysisJob = null;
    try {
        _window.applyPropertyValues();
        analysisJob = _analysisJobBuilder.toAnalysisJob();
    } catch (Exception e) {
        if (e instanceof NoResultProducingComponentsException) {
            int result = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "You job does not have any result-producing components in it, and is thus 'incomplete'. Do you want to save it anyway?",
                    "No result producing components 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;
        }
        final 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 AnalysisJobMetadata existingMetadata = analysisJob.getMetadata();
    final String jobName = existingMetadata.getJobName();
    final String jobVersion = existingMetadata.getJobVersion();

    final String author;
    if (Strings.isNullOrEmpty(existingMetadata.getAuthor())) {
        author = System.getProperty("user.name");
    } else {
        author = existingMetadata.getAuthor();
    }

    final String jobDescription;
    if (Strings.isNullOrEmpty(existingMetadata.getJobDescription())) {
        jobDescription = "Created with DataCleaner " + Version.getEdition() + " " + Version.getVersion();
    } else {
        jobDescription = existingMetadata.getJobDescription();
    }

    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.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 ava2 s. co  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.cli.CliRunner.java

/**
 * Alternative constructor that will specifically specifies the output
 * writer. Should be used only for testing, since normally the CliArguments
 * should be used to decide which outputwriter to use
 * //from ww  w  .  jav a  2s. com
 * @param arguments
 * @param writer
 * @param outputStream
 */
protected CliRunner(CliArguments arguments, Writer writer, OutputStream outputStream) {
    _arguments = arguments;
    if (outputStream == null) {
        final String outputFilePath = arguments.getOutputFile();
        if (outputFilePath == null) {
            _outputStreamRef = null;
            _writerRef = new LazyRef<Writer>() {
                @Override
                protected Writer fetch() {
                    return new PrintWriter(System.out);
                }
            };
        } else {

            final FileObject outputFile;
            try {
                outputFile = VFSUtils.getFileSystemManager().resolveFile(outputFilePath);
            } catch (FileSystemException e) {
                throw new IllegalStateException(e);
            }

            _writerRef = new LazyRef<Writer>() {
                @Override
                protected Writer fetch() {
                    try {
                        OutputStream out = outputFile.getContent().getOutputStream();
                        return new OutputStreamWriter(out, FileHelper.DEFAULT_ENCODING);
                    } catch (Exception e) {
                        if (e instanceof RuntimeException) {
                            throw (RuntimeException) e;
                        }
                        throw new IllegalStateException(e);
                    }
                }
            };
            _outputStreamRef = new LazyRef<OutputStream>() {
                @Override
                protected OutputStream fetch() {
                    try {
                        return outputFile.getContent().getOutputStream();
                    } catch (FileSystemException e) {
                        throw new IllegalStateException(e);
                    }
                }
            };
        }
        _closeOut = true;
    } else {
        _writerRef = new ImmutableRef<Writer>(writer);
        _outputStreamRef = new ImmutableRef<OutputStream>(outputStream);
        _closeOut = false;
    }
}