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.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  va2  s .c om*/
    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.DataCleanerHome.java

private static boolean isUsable(FileObject candidate) throws FileSystemException {
    if (candidate != null) {
        if (candidate.exists() && candidate.getType() == FileType.FOLDER) {
            FileObject conf = candidate.resolveFile("conf.xml");
            if (conf.exists() && conf.getType() == FileType.FILE) {
                return true;
            }//  www.jav a 2  s  .c  om
        }
    }
    return false;
}

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();//  w w  w.java 2s. c  om
    }

    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.datacleaner.user.UserPreferencesImpl.java

/**
 * Loads a user preferences file and initializes a
 * {@link UserPreferencesImpl} object using it.
 * // ww  w.ja v a 2  s  .  c  o m
 * @param userPreferencesFile
 * @param loadDatabaseDrivers
 * @return
 */
public static UserPreferences load(final FileObject userPreferencesFile, final boolean loadDatabaseDrivers) {
    try {
        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.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.datacleaner.windows.AnalysisJobBuilderWindowImpl.java

private boolean isJobUnsaved(FileObject lastSavedJobFile, AnalysisJobBuilder analysisJobBuilder) {
    if (lastSavedJobFile == null) {
        if (analysisJobBuilder.getComponentCount() == 0) {
            // user didn't actually do anything yet
            return false;
        }//from  ww  w. j  av  a 2s .  c o  m
        return true;
    }
    try {
        if (!lastSavedJobFile.exists()) {
            return true;
        }
    } catch (FileSystemException e) {
        logger.warn("Error while determining if the job file already exists", e);
    }

    InputStream lastSavedOutputStream = null;
    ByteArrayOutputStream currentOutputStream = null;
    try {
        File jobFile = new File(getJobFile().getURL().getFile());
        if (jobFile.length() == 0) {
            return true;
        }

        String lastSavedJob = FileHelper.readFileAsString(jobFile);
        String lastSavedJobNoMetadata = lastSavedJob.replaceAll("\n", "")
                .replaceAll("<job-metadata>.*</job-metadata>", "");

        JaxbJobWriter writer = new JaxbJobWriter(_configuration);
        currentOutputStream = new ByteArrayOutputStream();
        writer.write(_analysisJobBuilder.toAnalysisJob(false), currentOutputStream);
        String currentJob = new String(currentOutputStream.toByteArray());
        String currentJobNoMetadata = currentJob.replaceAll("\n", "")
                .replaceAll("<job-metadata>.*</job-metadata>", "");

        return !currentJobNoMetadata.equals(lastSavedJobNoMetadata);
    } catch (FileSystemException e) {
        throw new IllegalStateException(e);
    } finally {
        FileHelper.safeClose(currentOutputStream);
        FileHelper.safeClose(lastSavedOutputStream);
    }
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * The method writes the context (from the input stream) to a temporary file
 * (same file URL, but with extension {@link #EXTENSION_TEMP}).
 *
 * @param _in   input stream defined the content of the file
 * @param _size length of the content (or negative meaning that the length
 *              is not known; then the content gets the length of readable
 *              bytes from the input stream)
 * @param _fileName name of the file/* w w  w.  ja  v a2s .  c  o  m*/
 * @return size of the created temporary file object
 * @throws EFapsException on error
 */
@Override
public long write(final InputStream _in, final long _size, final String _fileName) throws EFapsException {
    try {
        long size = _size;
        final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(),
                this.storeFileName + VFSStoreResource.EXTENSION_TEMP);
        if (!tmpFile.exists()) {
            tmpFile.createFile();
        }
        final FileContent content = tmpFile.getContent();
        OutputStream out = content.getOutputStream(false);
        if (getCompress().equals(Compress.GZIP)) {
            out = new GZIPOutputStream(out);
        } else if (getCompress().equals(Compress.ZIP)) {
            out = new ZipOutputStream(out);
        }

        // if size is unkown!
        if (_size < 0) {
            int length = 1;
            size = 0;
            while (length > 0) {
                length = _in.read(this.buffer);
                if (length > 0) {
                    out.write(this.buffer, 0, length);
                    size += length;
                }
            }
        } else {
            Long length = _size;
            while (length > 0) {
                final int readLength = length.intValue() < this.buffer.length ? length.intValue()
                        : this.buffer.length;
                _in.read(this.buffer, 0, readLength);
                out.write(this.buffer, 0, readLength);
                length -= readLength;
            }
        }
        if (getCompress().equals(Compress.GZIP) || getCompress().equals(Compress.ZIP)) {
            out.close();
        }
        tmpFile.close();
        setFileInfo(_fileName, size);
        return size;
    } catch (final IOException e) {
        VFSStoreResource.LOG.error("write of content failed", e);
        throw new EFapsException(VFSStoreResource.class, "write.IOException", e);
    }

}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * Method that deletes the oldest backup and moves the others one up.
 *
 * @param _backup   file to backup//from  w ww  .j a  v a  2s. com
 * @param _number         number of backup
 * @throws FileSystemException on error
 */
private void backup(final FileObject _backup, final int _number) throws FileSystemException {
    if (_number < this.numberBackup) {
        final FileObject backFile = this.manager.resolveFile(this.manager.getBaseFile(),
                this.storeFileName + VFSStoreResource.EXTENSION_BACKUP + _number);
        if (backFile.exists()) {
            backup(backFile, _number + 1);
        }
        _backup.moveTo(backFile);
    } else {
        _backup.delete();
    }
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * The method is called from the transaction manager if the complete
 * transaction is completed.<br/>//from  w w  w .  j a  v  a2  s.co  m
 * A file in the virtual file system is committed with the algorithms:
 * <ol>
 * <li>any existing backup fill will be moved to an older backup file. The
 *     maximum number of backups can be defined by setting the property
 *     {@link #PROPERTY_NUMBER_BACKUP}. Default is one. To disable the
 *     property must be set to 0.</li>
 * <li>the current file is moved to the backup file (or deleted if property
 *     {@link #PROPERTY_NUMBER_BACKUP} is 0)</li>
 * <li>the new file is moved to the original name</li>
 * </ol>
 *
 * @param _xid      global transaction identifier (not used, because each
 *                  file with the file id gets a new VFS store resource
 *                  instance)
 * @param _onePhase <i>true</i> if it is a one phase commitment transaction
 *                  (not used)
 * @throws XAException if any exception occurs (catch on
 *         {@link java.lang.Throwable})
 */
@Override
public void commit(final Xid _xid, final boolean _onePhase) throws XAException {
    if (VFSStoreResource.LOG.isDebugEnabled()) {
        VFSStoreResource.LOG.debug("transaction commit");
    }
    if (getStoreEvent() == VFSStoreResource.StoreEvent.WRITE) {
        try {
            final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_TEMP);
            final FileObject currentFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_NORMAL);
            final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_BACKUP);
            if (bakFile.exists() && (this.numberBackup > 0)) {
                backup(bakFile, 0);
            }
            if (currentFile.exists()) {
                if (this.numberBackup > 0) {
                    currentFile.moveTo(bakFile);
                } else {
                    currentFile.delete();
                }
            }
            tmpFile.moveTo(currentFile);
            tmpFile.close();
            currentFile.close();
            bakFile.close();
        } catch (final FileSystemException e) {
            VFSStoreResource.LOG
                    .error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e);
            final XAException xa = new XAException(XAException.XA_RBCOMMFAIL);
            xa.initCause(e);
            throw xa;
        }
    } else if (getStoreEvent() == VFSStoreResource.StoreEvent.DELETE) {
        try {
            final FileObject curFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_NORMAL);
            final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_BACKUP);
            if (bakFile.exists()) {
                bakFile.delete();
            }
            if (curFile.exists()) {
                curFile.moveTo(bakFile);
            }
            bakFile.close();
            curFile.close();
        } catch (final FileSystemException e) {
            VFSStoreResource.LOG
                    .error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e);
            final XAException xa = new XAException(XAException.XA_RBCOMMFAIL);
            xa.initCause(e);
            throw xa;
        }
    }
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * If the file written in the virtual file system must be rolled back, only
 * the created temporary file (created from method {@link #write}) is
 * deleted./*from  w w w .  j  a  v a  2 s  . com*/
 *
 * @param _xid      global transaction identifier (not used, because each
 *                  file with the file id gets a new VFS store resource
 *                  instance)
 * @throws XAException if any exception occurs (catch on
 *         {@link java.lang.Throwable})
 */
@Override
public void rollback(final Xid _xid) throws XAException {
    if (VFSStoreResource.LOG.isDebugEnabled()) {
        VFSStoreResource.LOG.debug("rollback (xid = " + _xid + ")");
    }
    try {
        final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(),
                this.storeFileName + VFSStoreResource.EXTENSION_TEMP);
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
    } catch (final FileSystemException e) {
        VFSStoreResource.LOG.error("transaction rollback fails for " + _xid, e);
        final XAException xa = new XAException(XAException.XA_RBCOMMFAIL);
        xa.initCause(e);
        throw xa;
    }
}

From source file:org.eobjects.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  w  w  .  j  av  a  2 s  .  com*/
            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);
                }
            }
        }

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

    return _files;
}