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.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
 *//* ww  w  .ja  v a  2  s. c  om*/
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.clever.Common.Storage.VirtualFileSystem.java

/**
 * This method copies a file or folder/*from   ww w  . ja  va 2s  . c  o  m*/
 * @param file_s
 * @param file_d
 * @throws FileSystemException 
 */
public void cp(FileObject file_s, FileObject file_d) throws FileSystemException {
    if (file_d.exists() && file_d.getType() == FileType.FOLDER) {
        file_d = file_d.resolveFile(file_s.getName().getBaseName());
    }
    file_d.copyFrom(file_s, Selectors.SELECT_ALL);
}

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

private void mergeTargetMetadataToStageMetaData(FileObject targetRepo, FileObject stagingRepo)
        throws IOException, XmlPullParserException {

    VfsFileSet fileset = new VfsFileSet();
    fileset.setSource(stagingRepo);//from  w w  w.  j  a va  2  s  .c  om
    String[] includes = { "**/" + MAVEN_METADATA };
    fileset.setIncludes(includes);

    VfsFileSetManager fileSetManager = new DefaultVfsFileSetManager();
    List<FileObject> targetMetaFileObjects = fileSetManager.list(fileset);

    // Merge all metadata files
    for (FileObject sourceMetaFileObject : targetMetaFileObjects) {

        String relativeMetaPath = VfsUtils.getRelativePath(stagingRepo, sourceMetaFileObject);

        FileObject targetMetaFile = targetRepo.resolveFile(relativeMetaPath);
        FileObject stagingTargetMetaFileObject = stagingRepo.resolveFile(relativeMetaPath + IN_PROCESS_MARKER);

        try {
            stagingTargetMetaFileObject.copyFrom(targetMetaFile, Selectors.SELECT_ALL);
        } catch (FileSystemException e) {
            // We don't have an equivalent on the targetRepositoryUrl side because we have something
            // new on the sourceRepositoryUrl side so just skip the metadata merging.
            continue;
        }

        try {
            File targetMetaData = new File(stagingTargetMetaFileObject.getName().getPath());
            File sourceMetaData = new File(sourceMetaFileObject.getName().getPath());
            MavenMetadataUtils mavenMetadataUtils = new MavenMetadataUtils();
            mavenMetadataUtils.merge(targetMetaData, sourceMetaData);
            targetMetaData.delete();
        } catch (XmlPullParserException e) {
            throw new IOException(
                    "Metadata file is corrupt " + sourceMetaFileObject + " Reason: " + e.getMessage());
        }

    }

}

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

private void copy(FileObject fromDir, FileObject toDir, List<FileObject> fromFiles, boolean overwrite)
        throws FileSystemException {
    for (FileObject fromFile : fromFiles) {
        String relPath = VfsUtils.getRelativePath(fromDir, fromFile);
        FileObject toFile = toDir.resolveFile(relPath);

        copyFile(fromFile, toFile, overwrite);
    }/*from  w w  w  .j ava 2  s. c o m*/
}

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

public DownloadFilesActionListener(final String[] urls, final FileObject targetDirectory,
        final String[] targetFilenames, final FileDownloadListener listener, final WindowContext windowContext,
        final WebServiceHttpClient httpClient) {
    if (urls == null) {
        throw new IllegalArgumentException("urls cannot be null");
    }/*from w  w  w.ja  v a2  s  .  co  m*/
    _urls = urls;
    _listener = listener;
    _files = new FileObject[_urls.length];

    final String[] finalFilenames = new String[_files.length];
    for (int i = 0; i < urls.length; i++) {
        final String filename = targetFilenames[i];
        try {
            _files[i] = targetDirectory.resolveFile(filename);
            // slight differences may exist between target filename and
            // actual filename. This trick will eradicate that.
            finalFilenames[i] = _files[i].getName().getBaseName();
        } catch (FileSystemException e) {
            // should never happen
            throw new IllegalStateException(e);
        }
    }

    final Action<Void> cancelCallback = new Action<Void>() {
        @Override
        public void run(Void arg0) throws Exception {
            cancelDownload();
        }
    };

    _downloadProgressWindow = new FileTransferProgressWindow(windowContext, cancelCallback, finalFilenames);
    _httpClient = httpClient;
}

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

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

    _window.setStatusLabelNotice();//from  w  w  w . j ava  2  s  . com
    _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.guice.DCModuleImpl.java

private final Ref<UserPreferences> createUserPreferencesRef(final FileObject dataCleanerHome) {
    try {//  w ww . j av 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(UserPreferencesImpl.DEFAULT_FILENAME);

        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.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;
    }/*w  w w  .ja v a2 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;
            }/*w ww .  j a v a2  s.c o  m*/
        }
    }
    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();/*from   w w w .  j a va  2  s.c o  m*/
    }

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