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

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

Introduction

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

Prototype

boolean delete() throws FileSystemException;

Source Link

Document

Deletes this file.

Usage

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

public static void releaseFail(FileSystemManager fsManager, FileObject fo) {
    try {/*  w  ww  .j a va  2  s.  c o  m*/
        String fullPath = fo.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos > -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject failObject = fsManager.resolveFile(fullPath + ".fail");
        if (failObject.exists()) {
            failObject.delete();
        }
    } catch (FileSystemException e) {
        log.error("Couldn't release the fail for the file : " + maskURLPassword(fo.getName().getURI()));
    }
}

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

private static boolean releaseLock(byte[] bLockValue, String sLockValue, FileObject lockObject,
        Boolean autoLockReleaseSameNode, Long autoLockReleaseInterval) {
    try {//w w w.  ja va  2 s  . com
        InputStream is = lockObject.getContent().getInputStream();
        byte[] val = new byte[bLockValue.length];
        // noinspection ResultOfMethodCallIgnored
        is.read(val);
        String strVal = new String(val);
        // Lock format random:hostname:hostip:time
        String[] arrVal = strVal.split(":");
        String[] arrValNew = sLockValue.split(STR_SPLITER);
        if (arrVal.length == 4 && arrValNew.length == 4) {
            if (!autoLockReleaseSameNode
                    || (arrVal[1].equals(arrValNew[1]) && arrVal[2].equals(arrValNew[2]))) {
                long lInterval = 0;
                try {
                    lInterval = Long.parseLong(arrValNew[3]) - Long.parseLong(arrVal[3]);
                } catch (NumberFormatException nfe) {
                }
                if (autoLockReleaseInterval == null || autoLockReleaseInterval <= lInterval) {
                    try {
                        lockObject.delete();
                    } catch (Exception e) {
                        log.warn("Unable to delete the lock file during auto release cycle.", e);
                    } finally {
                        lockObject.close();
                    }
                    return true;
                }
            }
        }
    } catch (FileSystemException e) {
        log.error("Couldn't verify the lock", e);
        return false;
    } catch (IOException e) {
        log.error("Couldn't verify the lock", e);
        return false;
    }
    return false;
}

From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java

/**
 * Take specified action to either move or delete the processed file, depending on the outcome
 * @param entry the PollTableEntry for the file that has been processed
 * @param fileObject the FileObject representing the file to be moved or deleted
 *///from www .j  a va 2s. c  o  m
private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject,
        FileSystemOptions fso) throws AxisFault {

    String moveToDirectoryURI = null;
    try {
        switch (entry.getLastPollState()) {
        case PollTableEntry.SUCCSESSFUL:
            if (entry.getActionAfterProcess() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterProcess();
                //Postfix the date given timestamp format
                String strSubfoldertimestamp = entry.getSubfolderTimestamp();
                if (strSubfoldertimestamp != null) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat(strSubfoldertimestamp);
                        String strDateformat = sdf.format(new Date());
                        int iIndex = moveToDirectoryURI.indexOf("?");
                        if (iIndex > -1) {
                            moveToDirectoryURI = moveToDirectoryURI.substring(0, iIndex) + strDateformat
                                    + moveToDirectoryURI.substring(iIndex, moveToDirectoryURI.length());
                        } else {
                            moveToDirectoryURI += strDateformat;
                        }
                    } catch (Exception e) {
                        log.warn("Error generating subfolder name with date", e);
                    }
                }
            }
            break;

        case PollTableEntry.FAILED:
            if (entry.getActionAfterFailure() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterFailure();
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (entry.getMoveTimestampFormat() != null) {
                prefix = entry.getMoveTimestampFormat().format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            if (entry.isForceCreateFolder() && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }
            FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + VFSUtils.maskURLPassword(dest.getName().getURI()));
            }
            try {
                fileObject.moveTo(dest);
            } catch (FileSystemException e) {
                handleException("Error moving file : " + VFSUtils.maskURLPassword(fileObject.toString())
                        + " to " + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
            } finally {
                try {
                    fileObject.close();
                } catch (FileSystemException ignore) {
                }
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting file :" + VFSUtils.maskURLPassword(fileObject.toString()));
                }
                fileObject.close();
                if (!fileObject.delete()) {
                    String msg = "Cannot delete file : " + VFSUtils.maskURLPassword(fileObject.toString());
                    log.error(msg);
                    throw new AxisFault(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + VFSUtils.maskURLPassword(fileObject.toString()), e);
            }
        }

    } catch (FileSystemException e) {
        handleException("Error resolving directory to move after processing : "
                + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
    }
}

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

private void deleteBackup(final FileObject backup) throws FileSystemException {
    // TODO: try to move this further up the application stack.
    backup.delete();
    log.info(LogMessage.DELETED_BACKUP, backup);
}

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

public void delete(VfsFileSet fileSet) throws FileSystemException {
    VfsDirectoryScanner scanner = createScanner(fileSet);
    List<FileObject> fos = scanner.scan();
    for (FileObject fo : fos) {
        // TODO check for return error
        fo.delete();
    }//ww  w  .ja v a 2  s .  c  o m

}

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

public void move(VfsFileSet fileSet) throws FileSystemException {
    VfsDirectoryScanner scanner = createScanner(fileSet);
    List<FileObject> fos = scanner.scan();

    // better to use FileObject.move()??
    copy(fileSet.getSource(), fileSet.getDestination(), fos, fileSet.isOverwrite());

    for (FileObject fo : fos) {
        fo.delete();
    }/*  w w  w .  java 2s  .c om*/

}

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 w  w  .  ja  v  a2 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);
                }
            }

            _httpClient.close();
        }

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

    return _files;
}

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 va 2  s .  c o m
 * @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/>// w  ww .jav  a  2  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  ww  w  . j a v a 2  s.c  o  m*/
 *
 * @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;
    }
}