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:pt.webdetails.cpf.repository.vfs.VfsRepositoryAccess.java

public InputStream getResourceInputStream(String file) throws FileNotFoundException {
    try {//www  .jav  a2  s  . com
        FileObject fo = repo.resolveFile(file);
        if (fo.exists()) {
            return fo.getContent().getInputStream();
        }
    } catch (Exception e) {
        log.error("Cannot getResourceInputStream for: " + file, e);
    }
    throw new FileNotFoundException("Cannot get input stream for: " + file);
}

From source file:pt.webdetails.cpf.repository.vfs.VfsRepositoryAccess.java

public SaveFileStatus publishFile(String solution, String path, String fileName, byte[] data,
        boolean overwrite) {
    try {//from  w w w. j ava2s  .  c  o m
        if (data != null) {
            String file = getRelativePath(path, solution, fileName);
            if (resourceExists(file)) {
                if (canWrite(file) && overwrite) {
                    FileObject fileObject = resolveFile(repo, file);
                    fileObject.getContent().getOutputStream().write(data);
                    fileObject.getContent().close();
                    return SaveFileStatus.OK;
                } else {
                    return SaveFileStatus.FAIL;
                }
            } else {
                FileObject f = resolveFile(repo, file);
                f.getContent().getOutputStream().write(data);
                f.getContent().close();
                return SaveFileStatus.OK;
            }

        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Cannot publish file! solution: " + solution + " path: " + path + " file: " + fileName, e);
    }
    return SaveFileStatus.FAIL;
}

From source file:r.base.Files.java

/**
 * Utility function to extract information about files on the user's file systems.
 *
 * @param context  current call Context/*from   www  . j  av  a  2  s .  c om*/
 * @param paths the list of files for which to return information
 * @return list column-oriented table of file information
 * @throws FileSystemException
 */
@Primitive("file.info")
public static ListVector fileInfo(@Current Context context, StringVector paths) throws FileSystemException {

    DoubleVector.Builder size = new DoubleVector.Builder();
    LogicalVector.Builder isdir = new LogicalVector.Builder();
    IntVector.Builder mode = (IntVector.Builder) new IntVector.Builder().setAttribute(Symbols.CLASS,
            new StringVector("octmode"));
    DoubleVector.Builder mtime = new DoubleVector.Builder();
    StringVector.Builder exe = new StringVector.Builder();

    for (String path : paths) {
        FileObject file = context.resolveFile(path);
        if (file.exists()) {
            if (file.getType() == FileType.FILE) {
                size.add((int) file.getContent().getSize());
            } else {
                size.add(0);
            }
            isdir.add(file.getType() == FileType.FOLDER);
            mode.add(mode(file));
            try {
                mtime.add(file.getContent().getLastModifiedTime());
            } catch (Exception e) {
                mtime.add(0);
            }
            exe.add(file.getName().getBaseName().endsWith(".exe") ? "yes" : "no");
        } else {
            size.add(IntVector.NA);
            isdir.add(IntVector.NA);
            mode.add(IntVector.NA);
            mtime.add(DoubleVector.NA);
            exe.add(StringVector.NA);
        }
    }

    return ListVector.newNamedBuilder().add("size", size).add("isdir", isdir).add("mode", mode)
            .add("mtime", mtime).add("ctime", mtime).add("atime", mtime).add("exe", exe).build();
}

From source file:r.base.Files.java

/**
 * Helper function to extract a zip entry to the given folder.
 *//*from   w  w  w.  j  av  a2 s .c  o  m*/
private static void unzipExtract(ZipInputStream zin, ZipEntry entry, FileObject exdir, boolean junkpaths,
        boolean overwrite) throws IOException {
    if (junkpaths) {
        throw new EvalException("unzip(junpaths=false) not yet implemented");
    }

    FileObject exfile = exdir.resolveFile(entry.getName());
    if (exfile.exists() && !overwrite) {
        throw new EvalException("file to be extracted '%s' already exists", exfile.getName().getURI());
    }
    OutputStream out = exfile.getContent().getOutputStream();
    try {

        byte buffer[] = new byte[64 * 1024];
        int bytesRead;
        while ((bytesRead = zin.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } finally {
        out.close();
    }
}

From source file:rsc.backend.modules.ips.IPS.java

public void connectionConnect() {
    try {/*  ww w .  j  a  v  a 2s  . c  o  m*/
        Connection c = host.getConnection();
        FileObject fo = c.getFileSystem().resolveFile(snortConf);
        if (!fo.isWriteable() && fo.isReadable()) {
            JOptionPane.showMessageDialog(null, "cant write to snort.conf - your changes might be lost",
                    "snort configuration", JOptionPane.INFORMATION_MESSAGE);
        }
        if (!fo.isReadable()) {
            JOptionPane.showMessageDialog(null, "cant read snort.conf", "snort configuration error",
                    JOptionPane.ERROR_MESSAGE);
        }
        conf = SnortFactoryParser.createInstance(fo.getContent().getInputStream());//new Snortconf(fo.getContent().getInputStream());
        fireChangeEvent();
    } catch (ConfigurationException ex) {
        IPS.log(Level.SEVERE, "cant configure ips-configuration", ex);
    } catch (FileSystemException ex) {
        IPS.log(Level.SEVERE, "cant read ips-configuration", ex);
    } catch (Exception ex) {
        Logger.getLogger(IPS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:uk.ac.liv.shaman.vfsme.CommonVFSMediaAdaptor.java

@Override
public Object parse(INode parent) throws Exception {
    String html = null;/* w  w w  .  j ava  2 s . c  om*/
    try {

        String pre = getExtension();

        // Case for archive files
        if (pre != null)

            html = toHTML(pre);
        else {
            // case for files embedded in archives
            String s = getURI().toString();
            int pos = s.lastIndexOf('/');
            if (pos != -1) {
                s = s.substring(pos);
                pos = s.lastIndexOf('.');
                if (pos != -1)
                    s = s.substring(s.lastIndexOf('.'));
                else
                    s = null;
            } else
                s = null;

            FileSystemManager m = VFS.getManager();
            FileObject fo = m.resolveFile(getURI().toString());
            // Workaround for loopy: loopy breaks when reading at the end of the input stram;
            // we stop at the lenght of the file to avoid an arrayindexoutofbound
            File f = Fab4utils.copyToTemp(fo.getContent().getInputStream(), "vfstemp", s,
                    fo.getContent().getSize());
            return Fab4utils.parseHelper(f, getURI(), getDocument(), parent);

            //            FileInputStream is = new FileInputStream(f);
            //            String mime = null;
            //            String mime2 = null;
            //            byte[] bufferData = new byte[Math.max(1024, FileGuess.minBytes)];
            //            int a;
            //            MessageDigest md = null;
            //            try {
            //               md = MessageDigest.getInstance("MD5");
            //            } catch (NoSuchAlgorithmException e1) {
            //            }
            //
            //            while ((a = is.read(bufferData)) != -1) {
            //               if (mime2 == null && a >= FileGuess.minBytes) {
            //                  mime2 = FileGuess
            //                        .guess(bufferData, getURI().toString());
            //                  if (mime2 == null)
            //                     mime2 = "";
            //               }
            //               if (md != null)
            //                  md.update(bufferData, 0, a);
            //            }
            //            is.close();
            //            is = new FileInputStream(f);
            //            InputUni iu = InputUni.getInstance(is, getURI(), getGlobal()
            //                  .getCache());
            //            mime = iu.getContentType();
            //            byte[] digest = md.digest(); // 128 bit or 16 bytes
            //            MediaLoader.MD5Cache.put(getURI(), digest);
            //            MediaLoader.FileCache.put(getURI(), f);
            //            if (mime == null
            //                  || mime.equalsIgnoreCase("application/octet-stream")
            //                  || mime.equals("text/html")) {
            //               mime = mime2;
            //               iu.setContentType(mime);
            //            }
            //
            //            String genre = getGlobal().getGenre(mime, getURI().toString());
            //            System.out.println(genre + " " + mime);
            //            Layer dsl = getDocument().getLayers();
            //            Layer baseLayer = dsl.getInstance(Layer.BASE);
            //            MediaAdaptor helper = (MediaAdaptor) Behavior.getInstance(
            //                  "helper", genre, null, baseLayer);
            //            helper.setInput(iu);
            //            float zoom = 1;
            //            try {
            //               zoom = Float.parseFloat(Multivalent.getInstance()
            //                     .getPreference(genre + "-zoom", "1"));
            //            } catch (NumberFormatException nfe) {
            //            }
            //            helper.setZoom(zoom);
            //            dsl.getInstance(genre);
            //            // getDocument().setMediaAdaptor(helper);
            //
            //            Node root = null;
            //            try {
            //
            //               root = (Node) helper.parse(parent);
            //            } catch (Exception e) {
            //               new LeafUnicode("ERROR " + e, null, parent);
            //
            //               e.printStackTrace();
            //            } finally {
            //               try {
            //                  helper.close();
            //               } catch (IOException ioe) {
            //               }
            //            }
            //            // getDocument().removeAttr(Document.ATTR_LOADING);
            //            return root;
        }
    } catch (Exception e) {
        e.printStackTrace();
        html = e.toString();
    }
    return parseHelper(html, "HTML", getLayer(), parent);
}

From source file:uk.ac.liv.shaman.vfsme.CommonVFSMediaAdaptor.java

private void processChild(FileObject f, FileSystemManager m, StringBuilder sb)
        throws FileSystemException, UnsupportedEncodingException {
    if (f.getType() == FileType.FOLDER || f.getType() == FileType.IMAGINARY) {
        sb.append("<tr>");
        sb.append("<td><b>").append(f.getName()).append("</b></td>");
        sb.append(//from   w w  w  .ja  v a2 s  .  c  o m
                "<td align='right'><span Behavior='ElideSpan'>0</span> --<td align='right'><span Behavior='ElideSpan'>0</span> --");
        FileObject[] children = f.getChildren();

        for (FileObject subfile : children)
            processChild(subfile, m, sb);
    } else {
        sb.append("<tr>");
        FileName fname = f.getName();
        sb.append("<td><a href='").append(fname.getURI().replaceAll(" ", "%20")).append("'>").append(fname)
                .append("</a>");
        DateFormat outdfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long size = 0;
        Date last = new Date();
        try {
            size = f.getContent().getSize();
            last = new Date(f.getContent().getLastModifiedTime());
        } catch (Exception e) {
            // TODO: handle exception
        }
        sb.append("<td align='right'>").append(Long.toString(size)).append("<td align='right'>")
                .append(outdfm.format(last));

    }
}

From source file:unitTests.dataspaces.VFSFactoryTest.java

@Test
public void testLocalFileProvider() throws Exception {
    FileObject fo = null;
    try {//  w  w w.  ja  va 2s . c  om
        fo = manager.resolveFile(testFile.getCanonicalPath());
        assertTrue(fo.exists());

        final InputStream ios = fo.getContent().getInputStream();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(ios));
        assertEquals("test", reader.readLine());
    } finally {
        if (fo != null)
            fo.close();
    }
}

From source file:us.paulevans.basicxslt.Utils.java

/**
 * Returns the contents of the input XML file as an InputStream.  Uses
 * Apache Jakarta commons-VFS to resolve the location.
 * @param aURI//from   w w w . jav a  2s  . c  om
 * @return
 */
public static final byte[] getXMLContents(FileSystemManager aFSMgr, String aURI) throws IOException {

    FileObject file;
    FileContent content;

    file = aFSMgr.resolveFile(aURI);
    content = file.getContent();
    return IOUtils.toByteArray(content.getInputStream());
}

From source file:us.paulevans.basicxslt.Utils.java

/**
 * Returns the contents of the input XSL file as a Source object.  Uses
 * Apache Jakarta commons-VFS to resolve the location.
 * @param aURI/*from w  w  w  .j  a  va 2 s  .  c  o m*/
 * @return
 */
public static final Source getXSLSource(FileSystemManager aFSMgr, String aURI) {

    FileObject file;
    FileContent content;

    try {
        file = aFSMgr.resolveFile(aURI);
        content = file.getContent();
        return new StreamSource(content.getInputStream(), file.getURL().toURI().toString());
    } catch (Throwable any) {
        throw new RuntimeException(any);
    }
}