Example usage for org.apache.commons.vfs2 VFS getManager

List of usage examples for org.apache.commons.vfs2 VFS getManager

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 VFS getManager.

Prototype

public static synchronized FileSystemManager getManager() throws FileSystemException 

Source Link

Document

Returns the default FileSystemManager instance.

Usage

From source file:org.mycore.datamodel.ifs2.MCRStore.java

protected void init(final MCRStoreConfig config) {
    setStoreConfig(config);/*from  www . java  2  s .  co m*/

    idLength = 0;

    final StringTokenizer st = new StringTokenizer(getStoreConfig().getSlotLayout(), "-");
    slotLength = new int[st.countTokens() - 1];

    int i = 0;
    while (st.countTokens() > 1) {
        slotLength[i] = Integer.parseInt(st.nextToken());
        idLength += slotLength[i++];
    }
    idLength += Integer.parseInt(st.nextToken());

    try {
        baseDirectory = VFS.getManager().resolveFile(getStoreConfig().getBaseDir());

        if (!baseDirectory.exists()) {
            baseDirectory.createFolder();
        } else {
            if (!baseDirectory.isReadable()) {
                final String msg = "Store directory " + getStoreConfig().getBaseDir() + " is not readable";
                throw new MCRConfigurationException(msg);
            }

            if (baseDirectory.getType() != FileType.FOLDER) {
                final String msg = "Store " + getStoreConfig().getBaseDir() + " is a file, not a directory";
                throw new MCRConfigurationException(msg);
            }
        }
    } catch (final FileSystemException e) {
        e.printStackTrace();
    }
}

From source file:org.mycore.datamodel.ifs2.MCRStoredNode.java

/**
 * Creates a new stored node//ww w .ja  va 2s.  c o m
 * 
 * @param parent
 *            the parent directory
 * @param name
 *            the name of the node
 * @param type
 *            the node type, dir or file
 */
protected MCRStoredNode(MCRDirectory parent, String name, String type) throws IOException {
    super(parent, VFS.getManager().resolveFile(parent.fo, name));
    data = new Element(type);
    data.setAttribute(NAME_ATT, name);
    parent.data.addContent(data);
}

From source file:org.mycore.datamodel.ifs2.MCRStoredNode.java

/**
 * Renames this node./*  w  w  w .j  a  v  a2s.  com*/
 * 
 * @param name
 *            the new file name
 */
public void renameTo(String name) throws IOException {
    FileObject fNew = VFS.getManager().resolveFile(fo.getParent(), name);
    fo.moveTo(fNew);
    fo = fNew;
    fo.getContent().setLastModifiedTime(System.currentTimeMillis());
    data.setAttribute(NAME_ATT, name);
    getRoot().saveAdditionalData();
}

From source file:org.nanoko.coffee.mill.mojos.others.WatchMojo.java

private void setupMonitor(MavenProject project) throws FileSystemException {
    File baseDir = project.getBasedir();
    getLog().info("Set up file monitor on " + baseDir);
    FileSystemManager fsManager = VFS.getManager();
    FileObject dir = fsManager.resolveFile(baseDir.getAbsolutePath());

    DefaultFileMonitor fm = new DefaultFileMonitor(this);
    fm.setRecursive(true);//ww  w.  jav a  2s . c  o m
    fm.addFile(dir);
    fm.start();
}

From source file:org.nuxeo.launcher.gui.NuxeoLauncherGUI.java

/**
 * @param aLauncher Launcher being used in background
 *//* w  w  w  . j  av a2s .  c o m*/
public NuxeoLauncherGUI(NuxeoLauncher aLauncher) {
    launcher = aLauncher;
    // Set OS-specific decorations
    if (SystemUtils.IS_OS_MAC) {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
        System.setProperty("com.apple.mrj.application.live-resize", "true");
        System.setProperty("com.apple.macos.smallTabs", "true");
    }
    initFrame();
    dumpedConfigMonitor = new DefaultFileMonitor(new FileListener() {
        @Override
        public void fileDeleted(FileChangeEvent event) {
            // Ignore
        }

        @Override
        public void fileCreated(FileChangeEvent event) {
            updateNuxeoFrame();
        }

        @Override
        public void fileChanged(FileChangeEvent event) {
            updateNuxeoFrame();
        }

        synchronized private void updateNuxeoFrame() {
            waitForFrameLoaded();
            log.debug("Configuration changed. Reloading frame...");
            launcher.init();
            updateServerStatus();
            try {
                Properties props = new Properties();
                props.load(new FileReader(getConfigurationGenerator().getDumpedConfig()));
                nuxeoFrame.updateLogsTab(props.getProperty("log.id"));
            } catch (IOException e) {
                log.error(e);
            }
        }
    });
    try {
        dumpedConfigMonitor.setRecursive(false);
        FileObject dumpedConfig = VFS.getManager()
                .resolveFile(getConfigurationGenerator().getDumpedConfig().getPath());
        dumpedConfigMonitor.addFile(dumpedConfig);
        dumpedConfigMonitor.start();
    } catch (FileSystemException e) {
        throw new RuntimeException("Couldn't find " + getConfigurationGenerator().getNuxeoConf(), e);
    }
}

From source file:org.obiba.opal.fs.DecoratedFileObjectTest.java

@Before
public void setUp() throws IOException {

    java.io.File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();//from w ww.  ja  v a  2s .c  om
    root = VFS.getManager().resolveFile(tempDir.getAbsolutePath());
}

From source file:org.onehippo.forge.content.exim.core.util.ContentFileObjectUtils.java

/**
 * Create a temporary file by {@code prefix} and {@code suffix} and returns it as a {@link FileObject}.
 * @param prefix temporary file prefix//from   w w w  . j  av  a 2 s.  c om
 * @param suffix temporary file suffix
 * @return a temporary file by {@code prefix} and {@code suffix} and returns it as a {@link FileObject}
 * @throws IOException if IOException occurs
 */
public static FileObject createTempFile(String prefix, String suffix) throws IOException {
    File file = File.createTempFile(prefix, suffix);
    return VFS.getManager().toFileObject(file);
}

From source file:org.onehippo.forge.content.exim.core.util.ContentFileObjectUtils.java

/**
 * Creates a {@link FileObject} from the give local {@link File} object ({@code file}).
 * @param file a local {@link File} object
 * @return a {@link FileObject} from the give local {@link File} object ({@code file})
 * @throws IOException if any IOException occurs
 *///from w ww  .  j  a  va2 s.c  o m
public static FileObject toFileObject(File file) throws IOException {
    return VFS.getManager().toFileObject(file);
}

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 www .j ava 2  s .  c  om*/
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.ContentEximImportService.java

@Path("/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("multipart/mixed")
@POST// w  w  w .  ja  v a2 s .  c  om
public Response importContentFromZip(@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,
        @Multipart(value = "package", required = true) Attachment packageAttachment)
        throws JsonProcessingException {

    List<Attachment> attachments = new ArrayList<>();

    Logger procLogger = log;

    Result result = new Result();

    File tempLogFile = null;
    PrintStream tempLogOut = null;
    File tempZipFile = 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);
        }

        tempZipFile = File.createTempFile(TEMP_PREFIX, ".zip");
        procLogger.info("ContentEximService#importContentFromZip begins with {}", tempZipFile.getPath());

        if (packageAttachment == null) {
            result.addError("No zip attachment.");
            return Response.serverError().entity(toJsonString(result)).build();
        }

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

        transferAttachmentToFile(packageAttachment, tempZipFile);

        FileObject baseFolder = VFS.getManager().resolveFile("zip:" + tempZipFile.toURI());

        session = createSession();

        DocumentManager documentManager = new WorkflowDocumentManagerImpl(session);

        final DefaultBinaryImportTask binaryImportTask = new DefaultBinaryImportTask(documentManager);
        binaryImportTask.setLogger(procLogger);

        final WorkflowDocumentVariantImportTask documentImportTask = new WorkflowDocumentVariantImportTask(
                documentManager);
        documentImportTask.setLogger(procLogger);

        FileObject[] jsonFiles = binaryImportTask.findFilesByNamePattern(baseFolder, "^.+\\.json$", 1, 20);

        int batchCount = 0;

        try {
            binaryImportTask.start();
            batchCount = importBinaries(procLogger, processStatus, jsonFiles, params, baseFolder,
                    binaryImportTask, result, batchCount);
        } finally {
            binaryImportTask.stop();
        }

        try {
            documentImportTask.start();
            batchCount = importDocuments(procLogger, processStatus, jsonFiles, params, baseFolder,
                    documentImportTask, result, batchCount);
        } finally {
            documentImportTask.stop();
        }

        batchCount = cleanMirrorDocbaseValues(procLogger, processStatus, session, params, result, batchCount);
        batchCount = cleanAllDocbaseFieldValues(procLogger, processStatus, session, params, result, batchCount);

        if (processStatus != null) {
            processStatus.setProgress(1.0);
        }

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

        attachments.add(
                new Attachment("logs", MediaType.TEXT_PLAIN, FileUtils.readFileToString(tempLogFile, "UTF-8")));
        attachments.add(new Attachment("summary", MediaType.APPLICATION_JSON, toJsonString(result)));

    } catch (Exception e) {
        procLogger.error("Failed to import content.", e);
        result.addError(e.toString());
        return Response.serverError().entity(toJsonString(result)).build();
    } finally {
        procLogger.info("ContentEximService#importContentFromZip 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 (tempZipFile != null) {
            try {
                tempZipFile.delete();
            } catch (Exception e) {
                procLogger.error("Failed to delete temporary zip file.", 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);
            }
        }
    }

    return Response.ok(new MultipartBody(attachments, true)).build();
}