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.kalypso.ui.wizards.results.ReevaluateResultOperation.java

@Override
public IStatus execute(final IProgressMonitor monitor) {
    monitor.beginTask(Messages.getString("ReevaluateResultOperation.1"), m_selectedResults.length); //$NON-NLS-1$

    final IStatusCollector stati = new StatusCollector(Kalypso1d2dProjectPlugin.PLUGIN_ID);
    try {//w  ww.ja  va 2 s.  c o  m
        m_vfsManager = VFSUtilities.getNewManager();
    } catch (FileSystemException e) {
        final IStatus status = new Status(IStatus.ERROR, Kalypso1d2dProjectPlugin.PLUGIN_ID,
                Messages.getString("ReevaluateResultOperation.9")); //$NON-NLS-1$
        m_geoLog.log(status);
        return status;
    }

    try {
        FileObject actResFolder = m_vfsManager.resolveFile(m_scenarioFolder
                .getFolder(m_selectedResults[0].getFullPath()).getLocationURI().toURL().toExternalForm());
        m_fileObjSWANResult = actResFolder.resolveFile(ResultMeta1d2dHelper
                .resolvePathFromResultDataByMetaName(((IStepResultMeta) m_selectedResults[0]),
                        ResultMeta1d2dHelper.SWAN_RAW_DATA_META_NAME)
                .toOSString());
    } catch (final Exception e) {
        final IStatus status = new Status(IStatus.WARNING, Kalypso1d2dProjectPlugin.PLUGIN_ID,
                Messages.getString("ReevaluateResultOperation.8")); //$NON-NLS-1$
        m_geoLog.log(status);
        stati.add(status);
    }

    for (final IResultMeta resultMeta : m_selectedResults) {
        if (resultMeta instanceof IStepResultMeta) {
            final IStatus status = processStepResult((IStepResultMeta) resultMeta,
                    new SubProgressMonitor(monitor, 1));
            stati.add(status);
        }
    }

    if (m_vfsManager != null)
        m_vfsManager.close();

    return stati.asMultiStatusOrOK(Messages.getString("ReevaluateResultOperation.0")); //$NON-NLS-1$
}

From source file:org.obiba.opal.shell.commands.AbstractOpalRuntimeDependentCommand.java

public FileObject getFile(FileObject folder, String fileName) throws FileSystemException {
    return folder.resolveFile(fileName);
}

From source file:org.obiba.opal.shell.commands.ImportCommand.java

private void archive(FileObject file) throws IOException {
    if (!options.isArchive()) {
        return;//w w w.  ja v a2s  . c  o m
    }

    String archivePath = options.getArchive();
    try {
        FileObject archiveDir = getFile(archivePath);
        if (archiveDir == null) {
            throw new IOException("Cannot archive file " + file.getName().getPath()
                    + ". Archive directory is null: " + archivePath);
        }
        archiveDir.createFolder();
        FileObject archiveFile = archiveDir.resolveFile(file.getName().getBaseName());
        file.moveTo(archiveFile);
    } catch (FileSystemException ex) {
        throw new IOException("Failed to archive file " + file.getName().getPath() + " to " + archivePath);
    }
}

From source file:org.obiba.opal.shell.commands.ReportCommand.java

private FileObject getReportOutput(ReportTemplate reportTemplate, Date reportDate) throws FileSystemException {
    String reportTemplateName = reportTemplate.getName();
    String reportFormat = reportTemplate.getFormat();
    String reportFileName = getReportFileName(reportTemplateName, reportFormat, reportDate);

    FileObject reportDir = getFile("/reports/" + reportTemplate.getProject() + "/" + reportTemplateName);
    reportDir.createFolder();//  w  ww.  ja  v  a 2 s .  co m

    return reportDir.resolveFile(reportFileName);
}

From source file:org.obiba.opal.shell.test.support.OpalFileSystemMockBuilder.java

public OpalFileSystemMockBuilder resolveFile(String parentPath, String relativePath)
        throws FileSystemException {
    FileObject file = createMock(FileObject.class);
    FileObject parent = fileMap.get(parentPath);
    expect(parent.resolveFile(relativePath)).andReturn(file).anyTimes();

    fileMap.put(parentPath + "/" + relativePath, file);

    return this;
}

From source file:org.obiba.opal.web.FilesResource.java

private Response doUploadFile(String folderPath, FileObject folder, FileItem uploadedFile, UriInfo uriInfo)
        throws FileSystemException {
    String fileName = uploadedFile.getName();
    FileObject file = folder.resolveFile(fileName);
    boolean overwrite = file.exists();

    writeUploadedFileToFileSystem(uploadedFile, file);

    log.info("The following file was uploaded to Opal file system : {}", file.getURL());

    if (overwrite) {
        return Response.ok().build();
    }/*from   w  w  w  .  jav  a 2  s .  c  o  m*/
    URI fileUri = uriInfo.getBaseUriBuilder().path(FilesResource.class).path(folderPath).path(fileName).build();
    return Response.created(fileUri)//
            .header(AuthorizationInterceptor.ALT_PERMISSIONS, new OpalPermissions(fileUri, AclAction.FILES_ALL))//
            .build();
}

From source file:org.obiba.opal.web.FilesResource.java

@POST
@Path("/{path:.*}")
@Consumes("text/plain")
public Response createFolder(@PathParam("path") String path, String folderName, @Context UriInfo uriInfo)
        throws FileSystemException {
    if (folderName == null || folderName.trim().isEmpty())
        return Response.status(Status.BAD_REQUEST).build();

    String folderPath = getPathOfFileToWrite(path);
    FileObject folder = resolveFileInFileSystem(folderPath);
    Response folderResponse = validateFolder(folder, path);
    if (folderResponse != null)
        return folderResponse;

    FileObject file = folder.resolveFile(folderName);
    Response fileResponse = validateFile(file);
    if (fileResponse != null)
        return fileResponse;

    try {/*from   w ww . j  a  v  a  2  s .  c  om*/
        file.createFolder();
        Opal.FileDto dto = getBaseFolderBuilder(file).build();
        URI folderUri = uriInfo.getBaseUriBuilder().path(FilesResource.class).path(folderPath).path(folderName)
                .build();
        return Response.created(folderUri)//
                .header(AuthorizationInterceptor.ALT_PERMISSIONS,
                        new OpalPermissions(folderUri, AclAction.FILES_ALL))//
                .entity(dto).build();
    } catch (FileSystemException couldNotCreateTheFolder) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity("cannotCreateFolderUnexpectedError")
                .build();
    }
}

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

/**
 * Return true if a stop signal file is found under the base folder.
 * @param baseFolder the base folder where zip content files are created temporarily.
 * @return true if a stop signal file is found under the base folder
 *//*w ww . j  a  va2s  .  com*/
protected boolean isStopRequested(FileObject baseFolder) {
    try {
        FileObject stopSignalFile = baseFolder.resolveFile(STOP_REQUEST_FILE_REL_PATH);
        return stopSignalFile.exists();
    } catch (Exception e) {
        log.error("Failed to check stop request file.", e);
    }

    return false;
}

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

@Path("/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@POST//from   w  ww  .ja  v a2 s. com
public Response exportContentToZip(@Context SecurityContext securityContext,
        @Context HttpServletRequest request,
        @Multipart(value = "batchSize", required = false) String batchSizeParam,
        @Multipart(value = "throttle", required = false) String throttleParam,
        @Multipart(value = "publishOnImport", required = false) String publishOnImportParam,
        @Multipart(value = "dataUrlSizeThreshold", required = false) String dataUrlSizeThresholdParam,
        @Multipart(value = "docbasePropNames", required = false) String docbasePropNamesParam,
        @Multipart(value = "documentTags", required = false) String documentTagsParam,
        @Multipart(value = "binaryTags", required = false) String binaryTagsParam,
        @Multipart(value = "paramsJson", required = false) String paramsJsonParam,
        @Multipart(value = "params", required = false) Attachment paramsAttachment) {

    Logger procLogger = log;

    File tempLogFile = null;
    PrintStream tempLogOut = null;
    File baseFolder = null;
    Session session = null;
    ExecutionParams params = new ExecutionParams();
    ProcessStatus processStatus = null;

    try {
        tempLogFile = File.createTempFile(TEMP_PREFIX, ".log");
        tempLogOut = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempLogFile)));
        procLogger = createTeeLogger(log, tempLogOut);

        if (getProcessMonitor() != null) {
            processStatus = getProcessMonitor().startProcess();
            fillProcessStatusByRequestInfo(processStatus, securityContext, request);
            processStatus.setLogFile(tempLogFile);
        }

        baseFolder = Files.createTempDirectory(TEMP_PREFIX).toFile();
        procLogger.info("ContentEximService#exportContentToZip begins at {}.", baseFolder);

        if (paramsAttachment != null) {
            final String json = attachmentToString(paramsAttachment, "UTF-8");
            if (StringUtils.isNotBlank(json)) {
                params = getObjectMapper().readValue(json, ExecutionParams.class);
            }
        } else {
            if (StringUtils.isNotBlank(paramsJsonParam)) {
                params = getObjectMapper().readValue(paramsJsonParam, ExecutionParams.class);
            }
        }
        overrideExecutionParamsByParameters(params, batchSizeParam, throttleParam, publishOnImportParam,
                dataUrlSizeThresholdParam, docbasePropNamesParam, documentTagsParam, binaryTagsParam);

        if (processStatus != null) {
            processStatus.setExecutionParams(params);
        }

        session = createSession();
        Result result = ResultItemSetCollector.collectItemsFromExecutionParams(session, params);
        session.refresh(false);

        FileObject baseFolderObject = VFS.getManager().resolveFile(baseFolder.toURI());
        FileObject attachmentsFolderObject = baseFolderObject.resolveFile(BINARY_ATTACHMENT_REL_PATH);

        DocumentManager documentManager = new WorkflowDocumentManagerImpl(session);

        final WorkflowDocumentVariantExportTask documentExportTask = new WorkflowDocumentVariantExportTask(
                documentManager);
        documentExportTask.setLogger(log);
        documentExportTask.setBinaryValueFileFolder(attachmentsFolderObject);
        documentExportTask.setDataUrlSizeThreashold(params.getDataUrlSizeThreshold());

        final DefaultBinaryExportTask binaryExportTask = new DefaultBinaryExportTask(documentManager);
        binaryExportTask.setLogger(log);
        binaryExportTask.setBinaryValueFileFolder(attachmentsFolderObject);
        binaryExportTask.setDataUrlSizeThreashold(params.getDataUrlSizeThreshold());

        int batchCount = 0;

        Set<String> referredNodePaths = new LinkedHashSet<>();

        try {
            documentExportTask.start();
            batchCount = exportDocuments(procLogger, processStatus, params, documentExportTask, result,
                    batchCount, baseFolderObject, referredNodePaths);
        } finally {
            documentExportTask.stop();
        }

        if (!referredNodePaths.isEmpty()) {
            ResultItemSetCollector.fillResultItemsForNodePaths(session, referredNodePaths, true, null, result);
            session.refresh(false);
        }

        try {
            binaryExportTask.start();
            batchCount = exportBinaries(procLogger, processStatus, params, binaryExportTask, result, batchCount,
                    baseFolderObject);
        } finally {
            binaryExportTask.stop();
        }

        session.logout();
        session = null;

        procLogger.info("ContentEximService#exportContentToZip ends.");

        tempLogOut.close();
        tempLogOut = null;
        procLogger = log;

        final String tempLogOutString = FileUtils.readFileToString(tempLogFile, "UTF-8");
        final File zipBaseFolder = baseFolder;

        final StreamingOutput entity = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                ZipArchiveOutputStream zipOutput = null;
                try {
                    zipOutput = new ZipArchiveOutputStream(output);
                    ZipCompressUtils.addEntryToZip(EXIM_EXECUTION_LOG_REL_PATH, tempLogOutString, "UTF-8",
                            zipOutput);
                    ZipCompressUtils.addEntryToZip(EXIM_SUMMARY_BINARIES_LOG_REL_PATH,
                            binaryExportTask.getSummary(), "UTF-8", zipOutput);
                    ZipCompressUtils.addEntryToZip(EXIM_SUMMARY_DOCUMENTS_LOG_REL_PATH,
                            documentExportTask.getSummary(), "UTF-8", zipOutput);
                    ZipCompressUtils.addFileEntriesInFolderToZip(zipBaseFolder, "", zipOutput);
                } finally {
                    zipOutput.finish();
                    IOUtils.closeQuietly(zipOutput);
                    FileUtils.deleteDirectory(zipBaseFolder);
                }
            }
        };

        String fileName = "exim-export-" + DateFormatUtils.format(Calendar.getInstance(), "yyyyMMdd-HHmmss")
                + ".zip";
        return Response.ok().header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                .entity(entity).build();
    } catch (Exception e) {
        procLogger.error("Failed to export content.", e);
        if (baseFolder != null) {
            try {
                FileUtils.deleteDirectory(baseFolder);
            } catch (Exception ioe) {
                procLogger.error("Failed to delete the temporary folder at {}", baseFolder.getPath(), e);
            }
        }
        final String message = new StringBuilder().append(e.getMessage()).append("\r\n").toString();
        return Response.serverError().entity(message).build();
    } finally {
        procLogger.info("ContentEximService#exportContentToZip finally ends.");

        if (getProcessMonitor() != null) {
            try {
                getProcessMonitor().stopProcess(processStatus);
            } catch (Exception e) {
                procLogger.error("Failed to stop process.", e);
            }
        }

        if (session != null) {
            try {
                session.logout();
            } catch (Exception e) {
                procLogger.error("Failed to logout JCR session.", e);
            }
        }

        if (tempLogOut != null) {
            IOUtils.closeQuietly(tempLogOut);
        }

        if (tempLogFile != null) {
            try {
                tempLogFile.delete();
            } catch (Exception e) {
                log.error("Failed to delete temporary log file.", e);
            }
        }
    }
}

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;
        }//  ww  w  . j av a2s  . 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;
}