Example usage for org.apache.commons.vfs2 FileContent getOutputStream

List of usage examples for org.apache.commons.vfs2 FileContent getOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileContent getOutputStream.

Prototype

OutputStream getOutputStream() throws FileSystemException;

Source Link

Document

Returns an output stream for writing the file's content.

Usage

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void copy(byte[] content, String targetPath) throws PublishException {

    String targetFullPath = targetFullPath(builder.getPath(), targetPath);
    logger.debug("Server file's path is {}", targetFullPath);

    FileObject root = null;/*from   www. ja va 2s  .co  m*/
    FileObject target = null;
    try {
        root = getRootFileObject();
        //target = getTargetFileObject(root, targetFullPath);
        //-------------- Windows? ??----------------------
        targetPath = targetPath.replace("\\", "/").replace("//", "/");
        if (targetPath.indexOf("/") == 0) {
            targetPath = targetPath.substring(1);
        }
        target = getTargetFileObject(root, targetPath);
        //--------------------------------------------------------------
        FileContent fileContent = target.getContent();
        OutputStream stream = fileContent.getOutputStream();
        stream.write(content);
        stream.flush();

        stream.close();
        fileContent.close();
        target.close();
        root.close();
    } catch (FileSystemException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } catch (IOException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } finally {
        try {
            if (root != null) {
                root.close();
            }
            if (target != null) {
                target.close();
            }
        } catch (Exception e) {
            logger.error("vfs close is error:{}", e.toString());
        }
    }
}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void copy(File sourceFile, String targetPath) throws PublishException {
    //TODO ??????
    if (!sourceFile.exists()) {
        logger.debug("Source file path's {} is not exists.", sourceFile.getPath());
        return;//from   ww w  . j a  va2 s . c o  m
    }

    String targetFullPath = targetFullPath(builder.getPath(), targetPath);
    logger.debug("Server file's path is {}", targetFullPath);
    logger.debug("Source file's path is {}  ", sourceFile.getPath());

    FileObject root = null;
    FileObject target = null;
    try {
        root = getRootFileObject();
        //target = getTargetFileObject(root, targetFullPath);
        //-------------- Windows? ??----------------------
        targetPath = targetPath.replace("\\", "/").replace("//", "/");
        if (targetPath.indexOf("/") == 0) {
            targetPath = targetPath.substring(1);
        }
        target = getTargetFileObject(root, targetPath);
        //--------------------------------------------------------------
        FileContent fileContent = target.getContent();

        OutputStream out = fileContent.getOutputStream();
        InputStream in = new FileInputStream(sourceFile);

        byte[] buffer = new byte[1024 * 8];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.flush();

        in.close();
        out.close();
        fileContent.close();
    } catch (FileSystemException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } catch (IOException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } finally {
        try {
            if (root != null) {
                root.close();
            }
            if (target != null) {
                target.close();
            }
        } catch (Exception e) {
            logger.error("vfs close is error:{}", e.toString());
        }
    }
}

From source file:erigo.filepump.FilePumpWorker.java

protected void writeToSFTP(String filename, int random_num) {

    String connectionStr = baseConnectionStr + "/" + filename;
    if (debug)/*  w  ww.ja  v a 2  s. c o  m*/
        System.err.println(connectionStr);

    try {
        // Create remote file object
        FileObject fo = manager.resolveFile(connectionStr, fileSystemOptions);
        FileContent fc = fo.getContent();
        OutputStream ostream = fc.getOutputStream();
        if (ostream == null) {
            throw new IOException("Error opening output stream to SFTP");
        }
        // Write content to file
        PrintWriter pw = new PrintWriter(ostream);
        pw.format("%06d\n", random_num);
        pw.close();
        // Cleanup
        if (fo != null)
            fo.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.datacleaner.util.VfsResource.java

@Override
public OutputStream write() throws ResourceException {
    try {/*from   ww w . ja  v  a  2 s. com*/
        final FileContent content = _fileObject.getContent();
        final OutputStream out = content.getOutputStream();
        return out;
    } catch (Exception e) {
        throw new ResourceException(this, e);
    }
}

From source file:org.eobjects.analyzer.util.VfsResource.java

@Override
public void write(Action<OutputStream> writeCallback) throws ResourceException {
    try {/*from  w w w .  j av  a2 s.  c  om*/
        FileContent content = _fileObject.getContent();
        OutputStream out = content.getOutputStream();
        try {
            writeCallback.run(out);
        } finally {
            FileHelper.safeClose(out);
        }
    } catch (Exception e) {
        throw new ResourceException(this, e);
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException {
    String resourceBundleName = module.getResourceBundleName();
    if (resourceBundleName == null) {
        resourceBundleName = "resources." + module.getId();
    }/*from   ww  w . ja va2 s  .  c om*/
    String rbBasePath = "/src/main/resources/resources/"
            + StringUtils.substringAfterLast(resourceBundleName, ".");
    Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties();
    if (i18nProperties != null) {
        List<File> newFiles = new ArrayList<File>();
        for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) {
            String lang = entry.getKey();
            Map<String, String[]> properties = entry.getValue();

            String[] values = properties.get(Constants.JCR_TITLE);
            String title = ArrayUtils.isEmpty(values) ? null : values[0];

            values = properties.get(Constants.JCR_DESCRIPTION);
            String description = ArrayUtils.isEmpty(values) ? null : values[0];

            String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION;
            InputStream is = null;
            InputStreamReader isr = null;
            OutputStream os = null;
            OutputStreamWriter osw = null;
            try {
                FileObject file = getFile(rbPath);
                FileContent content = file.getContent();
                Properties p = new SortedProperties();
                if (file.exists()) {
                    is = content.getInputStream();
                    isr = new InputStreamReader(is, Charsets.ISO_8859_1);
                    p.load(isr);
                    isr.close();
                    is.close();
                } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) {
                    continue;
                } else {
                    newFiles.add(new File(file.getName().getPath()));
                }
                if (!StringUtils.isEmpty(title)) {
                    p.setProperty(key, title);
                }
                if (!StringUtils.isEmpty(description)) {
                    p.setProperty(key + "_description", description);
                }
                os = content.getOutputStream();
                osw = new OutputStreamWriter(os, Charsets.ISO_8859_1);
                p.store(osw, rbPath);
                ResourceBundle.clearCache();
            } catch (FileSystemException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } catch (IOException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(osw);
            }
        }
        SourceControlManagement sourceControl = module.getSourceControl();
        if (sourceControl != null) {
            try {
                sourceControl.add(newFiles);
            } catch (IOException e) {
                logger.error("Failed to add files to source control", e);
                throw new RepositoryException("Failed to add new files to source control: " + newFiles, e);
            }
        }
    }
}

From source file:org.mycore.backend.filesystem.MCRCStoreVFS.java

@Override
protected String doStoreContent(MCRFileReader file, MCRContentInputStream source) throws Exception {
    StringBuilder storageId = new StringBuilder();

    String[] slots = buildSlotPath();
    // Recursively create directory name
    for (String slot : slots) {
        storageId.append(slot).append("/");
    }//  w w  w  .  ja va  2  s.c o  m

    String fileId = buildNextID(file);
    storageId.append(fileId);

    FileObject targetObject = fsManager.resolveFile(getBase(), storageId.toString());
    FileContent targetContent = targetObject.getContent();
    try (OutputStream out = targetContent.getOutputStream()) {
        IOUtils.copy(source, out);
    } finally {
        targetContent.close();
    }
    return storageId.toString();
}

From source file:org.pentaho.metaverse.impl.VfsLineageWriter.java

protected OutputStream createOutputStream(LineageHolder holder, String extension) {
    if (holder != null) {
        try {/*from   w w  w  .  jav a 2s  .  com*/
            IExecutionProfile profile = holder.getExecutionProfile();
            String timestampString = Long.toString(profile.getExecutionData().getStartTime().getTime());
            FileObject destFolder = getOutputDirectoryAsFile(holder);
            String name = Const.NVL(profile.getName(), "unknown");
            FileObject file = destFolder.resolveFile(timestampString + "_" + name + extension);
            FileContent content = file.getContent();
            return content.getOutputStream();
        } catch (Exception e) {
            log.error(Messages.getErrorString("ERROR.CantCreateOutputStream"), e);
            return null;
        }
    } else {
        return null;
    }
}

From source file:tain.kr.test.vfs.v01.TestVfs2FilehandleService.java

@Test
public void testAccessFile() throws Exception {

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(this.absoluteFilePath);
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    //   // ww  w . j  ava 2s  . co m
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());

    //  
    file.createFile();
    assertTrue(file.exists());

    FileContent fileContent = file.getContent();
    assertEquals(0, fileContent.getSize());

    //  
    String string = "test.";
    OutputStream os = fileContent.getOutputStream();

    try {
        os.write(string.getBytes());
        os.flush();
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }
    assertNotSame(0, fileContent.getSize());

    //  
    StringBuffer sb = new StringBuffer();
    FileObject writtenFile = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileContent writtenContents = writtenFile.getContent();
    InputStream is = writtenContents.getInputStream();

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }

    //  
    assertEquals(sb.toString(), string);
}