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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:org.obiba.opal.web.shell.reporting.ProjectReportTemplateResource.java

@GET
@Path("/reports")
public List<Opal.ReportDto> getReports() throws FileSystemException {
    getReportTemplate();/* w  ww  .j  a v a  2  s . c  o m*/
    FileObject reportFolder = getReportFolder();
    List<Opal.ReportDto> reports = Lists.newArrayList();
    if (reportFolder.exists()) {
        for (FileObject reportFile : reportFolder.getChildren()) {
            if (reportFile.getType() == FileType.FILE
                    && reportFile.getName().getBaseName().startsWith(name + "-") && reportFile.isReadable()) {
                reports.add(getReportDto(reportFile));
            }
        }
    }
    return reports;
}

From source file:org.obiba.opal.web.shell.reporting.ProjectReportTemplateResource.java

@GET
@Path("/reports/latest")
public Response getReport() throws FileSystemException {
    getReportTemplate();//from  ww  w  .j a  v  a2 s  . c  o m

    FileObject reportFolder = getReportFolder();
    if (!reportFolder.exists()) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    FileObject lastReportFile = null;
    File lastReport = null;
    for (FileObject reportFile : reportFolder.getChildren()) {
        if (reportFile.getType() == FileType.FILE && reportFile.getName().getBaseName().startsWith(name + "-")
                && reportFile.isReadable()) {
            File report = opalRuntime.getFileSystem().getLocalFile(reportFile);
            if (lastReport == null || report.lastModified() > lastReport.lastModified()) {
                lastReport = report;
                lastReportFile = reportFile;
            }
        }
    }

    return lastReportFile == null ? Response.status(Response.Status.NOT_FOUND).build()
            : Response.ok(getReportDto(lastReportFile)).build();
}

From source file:org.obiba.opal.web.shell.reporting.ProjectReportTemplateResource.java

private Opal.ReportDto getReportDto(FileObject reportFile) throws FileSystemException {
    String publicLink = "/report/public/" + opalRuntime.getFileSystem().getObfuscatedPath(reportFile)
            + "?project=" + getReportTemplate().getProject();

    return Opal.ReportDto.newBuilder()//
            .setName(reportFile.getName().getBaseName())//
            .setLink("/files" + reportFile.getName().getPath())//
            .setSize(reportFile.getContent().getSize())//
            .setLastModifiedTime(reportFile.getContent().getLastModifiedTime())//
            .setPublicLink(publicLink).build();
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.ContentEximExportService.java

private int exportBinaries(Logger procLogger, ProcessStatus processStatus, ExecutionParams params,
        DefaultBinaryExportTask exportTask, Result result, int batchCount, FileObject baseFolder)
        throws Exception {
    final String baseFolderUrlPrefix = baseFolder.getURL().toString() + "/";
    final AntPathMatcher pathMatcher = new AntPathMatcher();

    for (ResultItem item : result.getItems()) {
        if (isStopRequested(baseFolder)) {
            procLogger.info("Stop requested by file at {}/{}", baseFolder.getName().getPath(),
                    STOP_REQUEST_FILE_REL_PATH);
            break;
        }/*w  w w  .  j  a  va  2 s.c om*/

        ContentMigrationRecord record = null;

        try {
            String handlePath = item.getPath();

            if (!isBinaryPathIncluded(pathMatcher, params, handlePath)) {
                continue;
            }

            if (!HippoNodeUtils.isBinaryPath(handlePath)) {
                continue;
            }

            if (!exportTask.getDocumentManager().getSession().nodeExists(handlePath)) {
                continue;
            }

            Node handle = exportTask.getDocumentManager().getSession().getNode(handlePath);
            Node variant = HippoNodeUtils.getFirstVariantNode(handle);

            if (variant == null) {
                continue;
            }

            String variantPath = variant.getPath();
            record = exportTask.beginRecord(variant.getIdentifier(), variantPath);

            ContentNode contentNode = exportTask.exportBinarySetToContentNode(variant);
            record.setProcessed(true);

            ContentNodeUtils.replaceDocbasesByPaths(exportTask.getDocumentManager().getSession(), contentNode,
                    ContentNodeUtils.MIRROR_DOCBASES_XPATH);

            Set<String> docbasePropNames = params.getDocbasePropNames();
            if (CollectionUtils.isNotEmpty(docbasePropNames)) {
                for (String docbasePropName : docbasePropNames) {
                    ContentNodeUtils.replaceDocbasePropertiesByPaths(
                            exportTask.getDocumentManager().getSession(), contentNode,
                            "properties[@itemName='" + docbasePropName + "']");
                }
            }

            ContentNodeUtils.removeUrlPrefixInJcrDataValues(contentNode, baseFolderUrlPrefix);

            applyTagContentProperties(contentNode, params.getBinaryTags());

            String relPath = StringUtils
                    .removeStart(ContentPathUtils.removeIndexNotationInNodePath(variantPath), "/");
            FileObject file = baseFolder.resolveFile(relPath + ".json");
            record.setAttribute("file", file.getName().getPath());
            exportTask.writeContentNodeToJsonFile(contentNode, file);

            procLogger.debug("Exported document from {} to {}.", handlePath, file.getName().getPath());
            record.setSucceeded(true);
        } catch (Exception e) {
            procLogger.error("Failed to process record: {}", record, e);
            if (record != null) {
                record.setErrorMessage(e.toString());
            }
        } finally {
            if (record != null) {
                exportTask.endRecord();
                result.incrementTotalBinaryCount();
                if (record.isSucceeded()) {
                    result.incrementSucceededBinaryCount();
                } else {
                    result.incrementFailedBinaryCount();
                }
                if (processStatus != null) {
                    processStatus.setProgress(result.getProgress());
                }
            }
            ++batchCount;
            if (batchCount % params.getBatchSize() == 0) {
                exportTask.getDocumentManager().getSession().refresh(false);
                if (params.getThrottle() > 0) {
                    Thread.sleep(params.getThrottle());
                }
            }
        }
    }

    exportTask.getDocumentManager().getSession().refresh(false);

    return batchCount;
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.ContentEximExportService.java

private int exportDocuments(Logger procLogger, ProcessStatus processStatus, ExecutionParams params,
        WorkflowDocumentVariantExportTask exportTask, Result result, int batchCount, FileObject baseFolder,
        Set<String> referredBinaryPaths) throws Exception {
    final String baseFolderUrlPrefix = baseFolder.getURL().toString() + "/";
    final AntPathMatcher pathMatcher = new AntPathMatcher();

    for (ResultItem item : result.getItems()) {
        if (isStopRequested(baseFolder)) {
            procLogger.info("Stop requested by file at {}/{}", baseFolder.getName().getPath(),
                    STOP_REQUEST_FILE_REL_PATH);
            break;
        }/* www .  j av  a 2s.c om*/

        ContentMigrationRecord record = null;

        try {
            String handlePath = item.getPath();

            if (!isDocumentPathIncluded(pathMatcher, params, handlePath)) {
                continue;
            }

            if (!HippoNodeUtils.isDocumentPath(handlePath)) {
                continue;
            }

            if (!exportTask.getDocumentManager().getSession().nodeExists(handlePath)) {
                continue;
            }

            Node handle = exportTask.getDocumentManager().getSession().getNode(handlePath);
            Map<String, Node> variantsMap = HippoNodeUtils.getDocumentVariantsMap(handle);
            Node variant = variantsMap.get(HippoStdNodeType.PUBLISHED);
            if (variant == null) {
                variant = variantsMap.get(HippoStdNodeType.UNPUBLISHED);
            }

            if (variant == null) {
                continue;
            }

            String variantPath = variant.getPath();
            record = exportTask.beginRecord(variant.getIdentifier(), variantPath);

            Document document = new Document(variant.getIdentifier());
            ContentNode contentNode = exportTask.exportVariantToContentNode(document);
            record.setProcessed(true);

            ContentNodeUtils.replaceDocbasesByPaths(exportTask.getDocumentManager().getSession(), contentNode,
                    ContentNodeUtils.MIRROR_DOCBASES_XPATH, referredBinaryPaths);

            Set<String> docbasePropNames = params.getDocbasePropNames();
            if (CollectionUtils.isNotEmpty(docbasePropNames)) {
                for (String docbasePropName : docbasePropNames) {
                    ContentNodeUtils.replaceDocbasePropertiesByPaths(
                            exportTask.getDocumentManager().getSession(), contentNode,
                            "properties[@itemName='" + docbasePropName + "']");
                }
            }

            ContentNodeUtils.removeUrlPrefixInJcrDataValues(contentNode, baseFolderUrlPrefix);

            applyTagContentProperties(contentNode, params.getDocumentTags());

            String relPath = StringUtils
                    .removeStart(ContentPathUtils.removeIndexNotationInNodePath(variantPath), "/");
            FileObject file = baseFolder.resolveFile(relPath + ".json");
            record.setAttribute("file", file.getName().getPath());

            exportTask.writeContentNodeToJsonFile(contentNode, file);
            procLogger.debug("Exported document from {} to {}.", handlePath, file.getName().getPath());
            record.setSucceeded(true);
        } catch (Exception e) {
            procLogger.error("Failed to process record: {}", record, e);
            if (record != null) {
                record.setErrorMessage(e.toString());
            }
        } finally {
            if (record != null) {
                exportTask.endRecord();
                result.incrementTotalDocumentCount();
                if (record.isSucceeded()) {
                    result.incrementSucceededDocumentCount();
                } else {
                    result.incrementFailedDocumentCount();
                }
                if (processStatus != null) {
                    processStatus.setProgress(result.getProgress());
                }
            }
            ++batchCount;
            if (batchCount % params.getBatchSize() == 0) {
                exportTask.getDocumentManager().getSession().refresh(false);
                if (params.getThrottle() > 0) {
                    Thread.sleep(params.getThrottle());
                }
            }
        }
    }

    exportTask.getDocumentManager().getSession().refresh(false);

    return batchCount;
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.ContentEximImportService.java

private int importBinaries(Logger procLogger, ProcessStatus processStatus, FileObject[] jsonFiles,
        ExecutionParams params, FileObject baseFolder, DefaultBinaryImportTask importTask, Result result,
        int batchCount) throws Exception {
    final String baseFolderUrlPrefix = baseFolder.getURL().toString();
    final AntPathMatcher pathMatcher = new AntPathMatcher();

    for (FileObject file : jsonFiles) {
        if (isStopRequested(baseFolder)) {
            procLogger.info("Stop requested by file at {}/{}", baseFolder.getName().getPath(),
                    STOP_REQUEST_FILE_REL_PATH);
            break;
        }//from   ww  w. j  a v a2s .c o m

        ContentNode contentNode = importTask.readContentNodeFromJsonFile(file);

        String primaryTypeName = contentNode.getPrimaryType();
        String path = contentNode.getProperty("jcr:path").getValue();

        if (!isBinaryPathIncluded(pathMatcher, params, path)) {
            continue;
        }

        if (!HippoNodeUtils.isBinaryPath(path)) {
            continue;
        }

        ContentMigrationRecord record = null;

        try {
            ContentNodeUtils.prependUrlPrefixInJcrDataValues(contentNode, BINARY_ATTACHMENT_REL_PATH,
                    baseFolderUrlPrefix);

            record = importTask.beginRecord("", path);
            record.setAttribute("file", file.getName().getPath());
            record.setProcessed(true);

            String[] folderPathAndName = ContentPathUtils.splitToFolderPathAndName(path);
            String folderPath = folderPathAndName[0];
            String name = folderPathAndName[1];

            String folderPrimaryType;
            String[] folderTypes;
            String[] galleryTypes;

            if (HippoNodeUtils.isGalleryPath(path)) {
                folderPrimaryType = params.getGalleryFolderPrimaryType();
                folderTypes = params.getGalleryFolderFolderTypes();
                galleryTypes = params.getGalleryFolderGalleryTypes();
            } else {
                folderPrimaryType = params.getAssetFolderPrimaryType();
                folderTypes = params.getAssetFolderFolderTypes();
                galleryTypes = params.getAssetFolderGalleryTypes();
            }

            folderPath = importTask.createOrUpdateBinaryFolder(folderPath, folderPrimaryType, folderTypes,
                    galleryTypes);

            applyTagContentProperties(contentNode, params.getBinaryTags());

            String updatedPath = importTask.createOrUpdateBinaryFromContentNode(contentNode, primaryTypeName,
                    folderPath, name);

            HippoBinaryNodeUtils.extractTextFromBinariesAndSaveHippoTextsUnderHandlePath(
                    importTask.getDocumentManager().getSession(), updatedPath);

            record.setSucceeded(true);
        } catch (Exception e) {
            procLogger.error("Failed to process record: {}", record, e);
            if (record != null) {
                record.setErrorMessage(e.toString());
            }
        } finally {
            if (record != null) {
                importTask.endRecord();
                result.addItem(recordToResultItem(record));
                result.incrementTotalBinaryCount();
                if (record.isSucceeded()) {
                    result.incrementSucceededBinaryCount();
                } else {
                    result.incrementFailedBinaryCount();
                }
                if (processStatus != null) {
                    // the remaining 5% for cleaning paths to convert those to uuids.
                    processStatus.setProgress(0.95 * ((double) batchCount) / ((double) jsonFiles.length));
                }
            }
            ++batchCount;
            if (batchCount % params.getBatchSize() == 0) {
                importTask.getDocumentManager().getSession().save();
                importTask.getDocumentManager().getSession().refresh(false);
                if (params.getThrottle() > 0) {
                    Thread.sleep(params.getThrottle());
                }
            }
        }
    }

    importTask.getDocumentManager().getSession().save();
    importTask.getDocumentManager().getSession().refresh(false);

    return batchCount;
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.ContentEximImportService.java

private int importDocuments(Logger procLogger, ProcessStatus processStatus, FileObject[] jsonFiles,
        ExecutionParams params, FileObject baseFolder, WorkflowDocumentVariantImportTask importTask,
        Result result, int batchCount) throws Exception {
    final String baseFolderUrlPrefix = baseFolder.getURL().toString();
    final AntPathMatcher pathMatcher = new AntPathMatcher();

    for (FileObject file : jsonFiles) {
        if (isStopRequested(baseFolder)) {
            procLogger.info("Stop requested by file at {}/{}", baseFolder.getName().getPath(),
                    STOP_REQUEST_FILE_REL_PATH);
            break;
        }/*  w w w  .ja  va2s  . c o m*/

        ContentNode contentNode = importTask.readContentNodeFromJsonFile(file);

        String primaryTypeName = contentNode.getPrimaryType();
        String path = contentNode.getProperty("jcr:path").getValue();

        if (!isDocumentPathIncluded(pathMatcher, params, path)) {
            continue;
        }

        if (!HippoNodeUtils.isDocumentPath(path)) {
            continue;
        }

        ContentMigrationRecord record = null;

        try {
            ContentNodeUtils.prependUrlPrefixInJcrDataValues(contentNode, BINARY_ATTACHMENT_REL_PATH,
                    baseFolderUrlPrefix);

            record = importTask.beginRecord("", path);
            record.setAttribute("file", file.getName().getPath());
            record.setProcessed(true);

            String locale = (contentNode.hasProperty("hippotranslation:locale"))
                    ? contentNode.getProperty("hippotranslation:locale").getValue()
                    : null;
            String localizedName = contentNode.getProperty("jcr:localizedName").getValue();

            applyTagContentProperties(contentNode, params.getDocumentTags());

            String updatedPath = importTask.createOrUpdateDocumentFromVariantContentNode(contentNode,
                    primaryTypeName, path, locale, localizedName);

            boolean isToPublish = ExecutionParams.PUBLISH_ON_IMPORT_ALL.equals(params.getPublishOnImport());

            if (!isToPublish && ExecutionParams.PUBLISH_ON_IMPORT_LIVE.equals(params.getPublishOnImport())) {
                isToPublish = ContentNodeUtils.containsStringValueInProperty(contentNode,
                        HippoNodeType.HIPPO_AVAILABILITY, "live");
            }

            if (isToPublish) {
                importTask.getDocumentManager().depublishDocument(updatedPath);
                importTask.getDocumentManager().publishDocument(updatedPath);
            }

            record.setSucceeded(true);
        } catch (Exception e) {
            procLogger.error("Failed to process record: {}", record, e);
            if (record != null) {
                record.setErrorMessage(e.toString());
            }
        } finally {
            if (record != null) {
                importTask.endRecord();
                result.addItem(recordToResultItem(record));
                result.incrementTotalDocumentCount();
                if (record.isSucceeded()) {
                    result.incrementSucceededDocumentCount();
                } else {
                    result.incrementFailedDocumentCount();
                }
                if (processStatus != null) {
                    // the remaining 5% for cleaning paths to convert those to uuids.
                    processStatus.setProgress(0.95 * ((double) batchCount) / ((double) jsonFiles.length));
                }
            }
            ++batchCount;
            if (batchCount % params.getBatchSize() == 0) {
                importTask.getDocumentManager().getSession().save();
                importTask.getDocumentManager().getSession().refresh(false);
                if (params.getThrottle() > 0) {
                    Thread.sleep(params.getThrottle());
                }
            }
        }
    }

    importTask.getDocumentManager().getSession().save();
    importTask.getDocumentManager().getSession().refresh(false);

    return batchCount;
}

From source file:org.ow2.proactive.scheduler.smartproxy.SmartProxyImpl.java

@Override
protected void downloadTaskOutputFiles(AwaitedJob awaitedjob, String jobId, String t_name, String localFolder)
        throws Exception {
    AwaitedTask atask = awaitedjob.getAwaitedTask(t_name);
    if (atask == null) {
        throw new IllegalArgumentException(
                "The task " + t_name + " does not belong to job " + jobId + " or has already been removed");
    }/*ww  w  .j a  va2s. c  om*/
    if (atask.isTransferring()) {
        log.warn("The task " + t_name + " of job " + jobId + " is already transferring its output");
        return;
    }
    String pull_URL = awaitedjob.getPullURL();

    if (awaitedjob.isIsolateTaskOutputs()) {
        pull_URL = pull_URL.replace(SchedulerConstants.TASKID_DIR_DEFAULT_NAME,
                SchedulerConstants.TASKID_DIR_DEFAULT_NAME + "/" + atask.getTaskId());
    }

    FileObject remotePullFolderFO;
    FileObject localfolderFO;

    try {
        remotePullFolderFO = jobTracker.resolveFile(pull_URL);

        localfolderFO = jobTracker.resolveFile(localFolder);
    } catch (FileSystemException e) {
        log.error("Could not retrieve data for job " + jobId, e);
        throw new IllegalStateException("Could not retrieve data for job " + jobId, e);
    }

    String sourceUrl = remotePullFolderFO.getURL().toString();
    String destUrl = localfolderFO.getURL().toString();

    org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector fileSelector = new org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector();

    List<OutputSelector> ouputFileSelectors = atask.getOutputSelectors();
    for (OutputSelector os : ouputFileSelectors) {
        org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector fs = os.getOutputFiles();
        if (!fs.getIncludes().isEmpty()) {
            fileSelector.addIncludes(fs.getIncludes());
        }

        if (!fs.getExcludes().isEmpty()) {
            fileSelector.addExcludes(fs.getExcludes());
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Looking at files in " + sourceUrl + " with " + fileSelector.getIncludes() + "-"
                + fileSelector.getExcludes());
        boolean goon = true;
        int cpt = 0;
        FileObject[] fos = null;
        while (goon) {
            fos = remotePullFolderFO.findFiles(fileSelector);
            goon = cpt < 50 && (fos == null || fos.length == 0);
            cpt++;
            if (goon) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

        if (fos != null && fos.length > 0) {
            for (FileObject fo : fos) {
                log.debug("Found " + fo.getName());
            }
        } else {
            log.warn("Couldn't find " + fileSelector.getIncludes() + "-" + fileSelector.getExcludes() + " in "
                    + sourceUrl);
        }
    }
    if (awaitedjob.isAutomaticTransfer()) {
        DataTransferProcessor dtp = new DataTransferProcessor(remotePullFolderFO, localfolderFO, jobId, t_name,
                fileSelector);
        jobTracker.setTaskTransferring(jobId, t_name, true);
        threadPool.submit((Runnable) dtp);
    } else {
        log.debug("Copying files from " + sourceUrl + " to " + destUrl);

        try {
            localfolderFO.copyFrom(remotePullFolderFO, fileSelector);
        } catch (FileSystemException e) {
            log.error(e);
            throw e;
        } finally {
            jobTracker.setTaskTransferring(jobId, t_name, false);
            jobTracker.removeAwaitedTask(jobId, t_name);
        }

        log.debug("Finished copying files from " + sourceUrl + " to " + destUrl);
        // ok we can remove the task
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.FileSystem.java

public static ListFile list(FileObject fo, List<String> includes, List<String> excludes)
        throws FileSystemException {
    fo.refresh();//ww w.  java 2s .  c om
    ListFile answer = new ListFile();
    List<String> dirList = Lists.newArrayList();
    List<String> fileList = Lists.newArrayList();
    List<String> fullList = Lists.newArrayList();
    List<FileObject> foundFileObjects = new LinkedList<>();
    if (isNullOrEmpty(includes) && isNullOrEmpty(excludes)) {
        fo.findFiles(Selectors.SELECT_CHILDREN, false, foundFileObjects);
    } else {
        FileSelector selector = new org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector(
                includes, excludes);
        fo.findFiles(selector, false, foundFileObjects);
    }

    for (FileObject child : foundFileObjects) {
        FileType type = child.getType();
        FileName childName = child.getName();
        switch (type) {
        case FOLDER:
            if (!child.equals(fo)) {
                // exclude root directory from the list
                String relativePath = fo.getName().getRelativeName(childName);
                dirList.add(relativePath);
                fullList.add(relativePath);
            }
            break;
        case FILE:
            String relativePath = fo.getName().getRelativeName(childName);
            fileList.add(relativePath);
            fullList.add(relativePath);
            break;
        default:
            throw new RuntimeException("Unknown : " + type);
        }
    }
    Collections.sort(dirList);
    Collections.sort(fileList);
    Collections.sort(fullList);
    answer.setDirectoryListing(dirList);
    answer.setFileListing(fileList);
    answer.setFullListing(fullList);
    return answer;
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.FileSystem.java

private static String baseName(FileObject fo) throws FileSystemException {
    return fo.getName().getBaseName();
}