Example usage for org.apache.commons.vfs FileObject getContent

List of usage examples for org.apache.commons.vfs FileObject getContent

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject getContent.

Prototype

public FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

From source file:org.pentaho.s3.S3TestIntegration.java

@Test
public void doGetType() throws Exception {
    assertNotNull("FileSystemManager is null", fsManager);

    FileObject bucket = fsManager.resolveFile(buildS3URL("/mdamour_get_type_test"));
    // assertEquals(false, bucket.exists());
    bucket.createFolder();/*from   ww w .  j av a 2  s  . c  o  m*/
    assertEquals(true, bucket.exists());

    FileObject s3FileOut = fsManager.resolveFile(buildS3URL("/mdamour_get_type_test/child01"));
    s3FileOut.createFile();
    OutputStream out = s3FileOut.getContent().getOutputStream();
    out.write(HELLO_S3_STR.getBytes());
    out.close();
    assertEquals("Is not a folder type", FileType.FOLDER, bucket.getType());
    assertEquals("Is not a file type", FileType.FILE, s3FileOut.getType());

    fsManager.closeFileSystem(bucket.getFileSystem());
    assertEquals("Is not a folder type (after clearing cache)", FileType.FOLDER,
            fsManager.resolveFile(buildS3URL("/mdamour_get_type_test")).getType());
    assertEquals("Is not a file type (after clearing cache)", FileType.FILE,
            fsManager.resolveFile(buildS3URL("/mdamour_get_type_test/child01")).getType());

    bucket = fsManager.resolveFile(buildS3URL("/mdamour_get_type_test"));
    printFileObject(bucket, 0);

    bucket.delete(deleteFileSelector);
    assertEquals(false, bucket.exists());
}

From source file:org.richfaces.cdk.rd.utils.PluginUtils.java

public static Map<String, Components> processConfigs(FileObject[] configs, Digester digester)
        throws SAXException, IOException {
    Map<String, Components> collector = new HashMap<String, Components>();

    for (FileObject config : configs) {
        InputStream configInputStream = config.getContent().getInputStream();

        try {/*from  www  .j  av a  2 s . com*/
            Components components = (Components) digester.parse(configInputStream);
            collector.put(components.getNamespace(), components);
        } finally {
            configInputStream.close();
        }

    }

    return collector;
}

From source file:org.rzo.yajsw.script.GroovyScript.java

/**
 * Instantiates a new groovy script.//w  w w.j  ava 2  s  . co  m
 * 
 * @param script
 *            the script
 * @throws IOException
 * @throws CompilationFailedException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public GroovyScript(String script, String id, WrappedProcess process, String[] args)
        throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException {
    super(script, id, process, args);
    //System.out.println("groovy script "+new File(".").getCanonicalPath());
    ClassLoader parent = getClass().getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);
    setGroovyClasspath(loader);
    FileObject fileObject = VFSUtils.resolveFile(".", script);
    InputStream in = fileObject.getContent().getInputStream();
    Class groovyClass = loader.parseClass(in);
    in.close();

    // let's call some method on an instance
    _script = (GroovyObject) groovyClass.newInstance();
    binding = (Binding) _script.invokeMethod("getBinding", null);
    binding.setVariable("args", args);
    binding.setVariable("callCount", 0);
    binding.setVariable("context", context);
    if (process != null)
        _logger = process.getWrapperLogger();
    binding.setVariable("logger", _logger);
}

From source file:org.sakaiproject.assignment2.logic.impl.UploadGradesLogicImpl.java

public List<List<String>> getCSVContent(File file) {
    if (file == null) {
        throw new IllegalArgumentException("Null file passed to uploadGrades");
    }/* w w  w . java 2  s. com*/

    if (!file.getName().endsWith(".csv")) {
        throw new IllegalArgumentException("Uploaded file must be in .csv format");
    }

    List<List<String>> csvContent = new ArrayList<List<String>>();

    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject gradesFile = fsManager.toFileObject(file);
        FileContent gradesFileContent = gradesFile.getContent();
        csvContent = getCSVContent(gradesFileContent.getInputStream());
    } catch (FileSystemException fse) {
        throw new UploadException("There was an error parsing the data in the csv file", fse);
    }

    return csvContent;
}

From source file:org.sonatype.gshell.commands.text.CatCommand.java

public Object execute(final CommandContext context) throws Exception {
    assert context != null;
    IO io = context.getIo();/*from  w w  w .j av a  2  s .  c o  m*/

    //
    // TODO: Support multi-path cat, and the special '-' token (which is the default if no paths are given)
    //

    FileObject file = resolveFile(context, path);

    new FileObjectAssert(file).exists();
    ensureFileHasContent(file);

    org.apache.commons.vfs.FileContent content = file.getContent();
    FileContentInfo info = content.getContentInfo();
    log.debug("Content type: {}", info.getContentType());
    log.debug("Content encoding: {}", info.getContentEncoding());

    //
    // TODO: Only cat files which we think are text, or warn if its not, allow flag to force
    //

    log.debug("Displaying file: {}", file.getName());

    BufferedReader reader = new BufferedReader(new InputStreamReader(content.getInputStream()));
    try {
        cat(reader, io);
    } finally {
        Closer.close(reader);
    }

    FileObjects.close(file);

    return Result.SUCCESS;
}

From source file:org.sonatype.gshell.commands.text.GrepCommand.java

private void grep(final CommandContext context, final MatchActionProcessor processor, final FileObject file)
        throws Exception {
    assert context != null;
    assert processor != null;
    assert file != null;

    new FileObjectAssert(file).exists().isReadable();
    ensureFileHasContent(file);/*from  www.j ava 2 s  .c om*/

    BufferedInputStream input = new BufferedInputStream(file.getContent().getInputStream());
    try {
        processor.processMatches(input, context.getIo().streams.out);
    } finally {
        Closer.close(input);
    }
}

From source file:org.sonatype.gshell.commands.text.SortCommand.java

protected void sort(final CommandContext context, final FileObject file) throws Exception {
    assert context != null;
    assert file != null;

    new FileObjectAssert(file).exists().isReadable();
    ensureFileHasContent(file);/* w  w  w .j  a  va2 s  .c om*/

    BufferedInputStream input = new BufferedInputStream(file.getContent().getInputStream());
    try {
        sort(input, context.getIo().out);
    } finally {
        Closer.close(input);
    }
}

From source file:org.sonatype.gshell.commands.vfs.FileInfoCommand.java

public Object execute(final CommandContext context) throws Exception {
    assert context != null;
    IO io = context.getIo();/*  w w  w .j a v  a 2s .c  o m*/

    FileObject file = resolveFile(context, path);

    io.println("URL: {}", file.getURL());
    io.println("Name: {}", file.getName());
    io.println("BaseName: {}", file.getName().getBaseName());
    io.println("Extension: {}", file.getName().getExtension());
    io.println("Path: {}", file.getName().getPath());
    io.println("Scheme: {}", file.getName().getScheme());
    io.println("URI: {}", file.getName().getURI());
    io.println("Root URI: {}", file.getName().getRootURI());
    io.println("Parent: {}", file.getName().getParent());
    io.println("Type: {}", file.getType());
    io.println("Exists: {}", file.exists());
    io.println("Readable: {}", file.isReadable());
    io.println("Writeable: {}", file.isWriteable());
    io.println("Root path: {}", file.getFileSystem().getRoot().getName().getPath());

    if (file.exists()) {
        FileContent content = file.getContent();
        FileContentInfo contentInfo = content.getContentInfo();
        io.println("Content type: {}", contentInfo.getContentType());
        io.println("Content encoding: {}", contentInfo.getContentEncoding());

        try {
            // noinspection unchecked
            Map<String, Object> attrs = content.getAttributes();
            if (attrs != null && !attrs.isEmpty()) {
                io.println("Attributes:");
                for (Map.Entry<String, Object> entry : attrs.entrySet()) {
                    io.println("    {}='{}'", entry.getKey(), entry.getValue());
                }
            }
        } catch (FileSystemException e) {
            io.println("File attributes are NOT supported");
        }

        try {
            Certificate[] certs = content.getCertificates();
            if (certs != null && certs.length != 0) {
                io.println("Certificate:");
                for (Certificate cert : certs) {
                    io.println("    {}", cert);
                }
            }
        } catch (FileSystemException e) {
            io.println("File certificates are NOT supported");
        }

        if (file.getType().equals(FileType.FILE)) {
            io.println("Size: {} bytes", content.getSize());
        } else if (file.getType().hasChildren() && file.isReadable()) {
            FileObject[] children = file.getChildren();
            io.println("Directory with {} files", children.length);

            for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                io.println("#{}:{}", iterChildren, children[iterChildren].getName());
                if (iterChildren > 5) {
                    break;
                }
            }
        }

        io.println("Last modified: {}",
                DateFormat.getInstance().format(new Date(content.getLastModifiedTime())));
    } else {
        io.println("The file does not exist");
    }

    FileObjects.close(file);

    return Result.SUCCESS;
}

From source file:org.sonatype.gshell.commands.vfs.TouchCommand.java

public Object execute(final CommandContext context) throws Exception {
    assert context != null;

    FileObject file = resolveFile(context, path);

    try {//from  w ww.  jav  a  2 s  . c  o m
        if (!file.exists()) {
            file.createFile();
        }

        file.getContent().setLastModifiedTime(System.currentTimeMillis());
    } finally {
        FileObjects.close(file);
    }

    return Result.SUCCESS;
}

From source file:org.vivoweb.harvester.util.FileAide.java

/**
 * Get an inputstream from the first file under the given path with a matching fileName
 * @param path the path to search under//from ww w. ja  v a2  s.co  m
 * @param fileName the file name to match
 * @return an input stream to the matched file, null if none found
 * @throws IOException error resolving path
 */
public static InputStream getFirstFileNameChildInputStream(String path, String fileName) throws IOException {
    for (FileObject file : FileAide.getFileObject(path).findFiles(new AllFileSelector())) {
        if (file.getName().getBaseName().equals(fileName)) {
            return file.getContent().getInputStream();
        }
    }
    return null;
}