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

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

Introduction

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

Prototype

FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

private JsTreeFile resourceAsJsTreeFile(FileObject resource, boolean folderDetails, boolean fileDetails,
        boolean showHiddenFiles) throws FileSystemException {
    String lid = resource.getName().getPath();
    String rootPath = this.root.getName().getPath();
    // lid must be a relative path from rootPath
    if (lid.startsWith(rootPath))
        lid = lid.substring(rootPath.length());
    if (lid.startsWith("/"))
        lid = lid.substring(1);// w  ww .j  a va  2 s  .c  o  m

    String title = "";
    String type = "drive";
    if (!"".equals(lid)) {
        type = resource.getType().getName();
        title = resource.getName().getBaseName();
    }
    JsTreeFile file = new JsTreeFile(title, lid, type);

    file.setHidden(this.isFileHidden(resource));

    if ("file".equals(type)) {
        String icon = resourceUtils.getIcon(title);
        file.setIcon(icon);
        file.setSize(resource.getContent().getSize());
        file.setOverSizeLimit(file.getSize() > resourceUtils.getSizeLimit(title));
    }

    try {
        if (folderDetails && ("folder".equals(type) || "drive".equals(type))) {
            if (resource.getChildren() != null) {
                long totalSize = 0;
                long fileCount = 0;
                long folderCount = 0;
                for (FileObject child : resource.getChildren()) {
                    if (showHiddenFiles || !this.isFileHidden(child)) {
                        if ("folder".equals(child.getType().getName())) {
                            ++folderCount;
                        } else if ("file".equals(child.getType().getName())) {
                            ++fileCount;
                            totalSize += child.getContent().getSize();
                        }
                    }
                }
                file.setTotalSize(totalSize);
                file.setFileCount(fileCount);
                file.setFolderCount(folderCount);
            }
        }

        final Calendar date = Calendar.getInstance();
        date.setTimeInMillis(resource.getContent().getLastModifiedTime());
        // In order to have a readable date
        file.setLastModifiedTime(new SimpleDateFormat(this.datePattern).format(date.getTime()));

        file.setReadable(resource.isReadable());
        file.setWriteable(resource.isWriteable());

    } catch (FileSystemException fse) {
        // we don't want that exception during retrieving details 
        // of the folder breaks  all this method ...
        log.error("Exception during retrieveing details on " + lid
                + " ... maybe broken symbolic links or whatever ...", fse);
    }

    return file;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public DownloadFile getFile(String dir, SharedUserPortletParameters userParameters) {
    try {/*from   w  ww  .  ja v  a 2 s  .c  o m*/
        FileObject file = cd(dir, userParameters);
        FileContent fc = file.getContent();
        int size = new Long(fc.getSize()).intValue();
        String baseName = fc.getFile().getName().getBaseName();
        // fc.getContentInfo().getContentType() use URLConnection.getFileNameMap, 
        // we prefer here to use our getMimeType : for Excel files and co 
        // String contentType = fc.getContentInfo().getContentType();
        String contentType = JsTreeFile.getMimeType(baseName.toLowerCase());
        InputStream inputStream = fc.getInputStream();
        DownloadFile dlFile = new DownloadFile(contentType, size, baseName, inputStream);
        return dlFile;
    } catch (FileSystemException e) {
        log.warn("can't download file : " + e.getMessage(), e);
    }
    return null;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public boolean putFile(String dir, String filename, InputStream inputStream,
        SharedUserPortletParameters userParameters, UploadActionType uploadOption) {

    boolean success = false;
    FileObject newFile = null;

    try {/*from  www.jav a2  s . c  o m*/
        FileObject folder = cd(dir, userParameters);
        newFile = folder.resolveFile(filename);
        if (newFile.exists()) {
            switch (uploadOption) {
            case ERROR:
                throw new EsupStockFileExistException();
            case OVERRIDE:
                newFile.delete();
                break;
            case RENAME_NEW:
                newFile = folder.resolveFile(this.getUniqueFilename(filename, "-new-"));
                break;
            case RENAME_OLD:
                newFile.moveTo(folder.resolveFile(this.getUniqueFilename(filename, "-old-")));
                break;
            }
        }
        newFile.createFile();

        OutputStream outstr = newFile.getContent().getOutputStream();

        FileCopyUtils.copy(inputStream, outstr);

        success = true;
    } catch (FileSystemException e) {
        log.info("can't upload file : " + e.getMessage(), e);
    } catch (IOException e) {
        log.warn("can't upload file : " + e.getMessage(), e);
    }

    if (!success && newFile != null) {
        // problem when uploading the file -> the file uploaded is corrupted
        // best is to delete it
        try {
            newFile.delete();
            log.debug("delete corrupted file after bad upload ok ...");
        } catch (Exception e) {
            log.debug("can't delete corrupted file after bad upload " + e.getMessage());
        }
    }

    return success;
}

From source file:org.freedesktop.AbstractFreedesktopEntity.java

public void load(FileObject file) throws IOException, ParseException {
    InputStream in = file.getContent().getInputStream();
    try {/*from  w w  w  . j  a v  a2 s .c o  m*/
        load(in);
    } finally {
        in.close();
        loaded = true;
    }
}

From source file:org.freedesktop.mime.DefaultAliasService.java

@Override
protected Collection<AliasEntry> scanBase(FileObject base) throws IOException {
    FileObject f = base.resolveFile("aliases");
    AliasBase aliasBase = new AliasBase();
    aliasBases.put(base, aliasBase);//  w w w .  j av a2  s.c  om
    InputStream fin = f.getContent().getInputStream();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!line.equals("") && !line.startsWith("#")) {
                int idx = line.indexOf(' ');
                if (idx == -1) {
                    throw new IOException(f + " contains invalid data '" + line + "'.");
                }
                String mimeType = line.substring(0, idx);
                String alias = line.substring(idx + 1);
                AliasEntry entry = new AliasEntry(mimeType, alias);
                aliasBase.byType.put(mimeType, entry);
                aliasBase.byAlias.put(alias, entry);
            }
        }
    } finally {
        fin.close();
    }
    return aliasBase.byType.values();
}

From source file:org.freedesktop.mime.DefaultGlobService.java

@Override
protected Collection<GlobEntry> scanBase(FileObject base) throws IOException {
    FileObject f = base.resolveFile("globs");
    GlobBase globBase = new GlobBase();
    globBases.put(base, globBase);/*from   ww  w  .j  ava 2  s.com*/
    InputStream fin = f.getContent().getInputStream();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!line.equals("") && !line.startsWith("#")) {
                int idx = line.indexOf(':');
                if (idx == -1) {
                    throw new IOException(f + " contains invalid data '" + line + "'.");
                }
                String mimeType = line.substring(0, idx);
                String pattern = line.substring(idx + 1);

                // A single mime type may have several patterns
                GlobEntry entry = globBase.byType.get(mimeType);
                if (entry == null) {
                    entry = new GlobEntry(mimeType);
                    globBase.byType.put(mimeType, entry);
                }
                entry.addPattern(pattern);

                // Provide a quick lookup table for simple patterns and
                // explicit names
                if (isSimplePattern(pattern) || !isExpression(pattern)) {
                    ArrayList<GlobEntry> entries = globBase.byPattern.get(pattern);
                    if (entries == null) {
                        entries = new ArrayList<GlobEntry>();
                        globBase.byPattern.put(pattern, entries);
                    }
                    if (!entries.contains(entry)) {
                        entries.add(entry);
                    }
                }
            }
        }
    } finally {
        fin.close();
    }
    return globBase.byType.values();
}

From source file:org.freedesktop.mime.DefaultMagicService.java

@Override
protected Collection<MagicEntry> scanBase(FileObject base) throws IOException {
    System.out.println(base);/* ww w  .  ja v a2  s.com*/
    FileObject f = base.resolveFile("magic");
    MagicBase aliasBase = new MagicBase();
    magicBases.put(base, aliasBase);
    InputStream fin = f.getContent().getInputStream();
    try {
        byte[] buf = new byte[65536];
        StringBuilder bui = new StringBuilder();

        int state = -1;

        // -1 outside of format
        // 0 file header
        // 1 in header (priority)
        // 2 in header (mime type)
        // 3 out of header, waiting for newline
        // 4 waiting for indent
        // 5 waiting for offset
        // 6 waiting for value length (hi)
        // 7 waiting for value length (lo)
        // 8 reading value
        // 9 read value, waiting for optional mask
        // 10 reading mask
        // 11 word-size
        // 12 range-length
        // 13 done

        MagicEntry entry = null;
        Pattern pattern = null;
        int valueLength = 0;
        int bufIdx = 0;
        while (true) {
            int read = fin.read(buf);
            if (read == -1) {
                break;
            }
            for (int i = 0; i < read; i++) {
                byte b = buf[i];
                // System.out.println((int)b + "[" + (char)b + "] = " +
                // state);

                if (state == -1) {
                    if (b == '\n') {
                        state = 0;
                        if (!bui.toString().equals("MIME-Magic\0")) {
                            throw new IOException("No MIME-Magic header");
                        }
                        bui.setLength(0);
                    } else {
                        bui.append((char) b);
                    }
                } else if (state == 0) {
                    if (b == '[') {
                        state = 1;
                    }
                } else if (state == 1) {
                    if (b == ':') {
                        entry = new MagicEntry();
                        entry.setPriority(Integer.parseInt(bui.toString()));
                        bui.setLength(0);
                        state = 2;
                    } else {
                        bui.append((char) b);
                    }
                } else if (state == 2) {
                    if (b == ']') {
                        entry.setMIMEType(bui.toString());
                        bui.setLength(0);
                        state = 3;
                        aliasBase.byType.put(entry.getInternalName(), entry);
                    } else {
                        bui.append((char) b);
                    }
                } else if (state == 3) {
                    if (b == '\n') {
                        state = 4;
                        pattern = new MagicEntry.Pattern();
                    }
                } else if (state == 4) {
                    if (b == '[') {
                        state = 1;
                    } else if (b == '>') {
                        state = 5;
                        if (bui.length() > 0) {
                            String str = bui.toString();
                            pattern.setIndent(Integer.parseInt(str));
                            bui.setLength(0);
                        }
                    } else {
                        bui.append((char) b);
                    }
                } else if (state == 5) {
                    if (b == '=') {
                        state = 6;
                        pattern.setOffset(Long.parseLong(bui.toString()));
                        bui.setLength(0);
                    } else {
                        bui.append((char) b);
                    }
                } else if (state == 6) {
                    valueLength = b << 8;
                    state = 7;
                } else if (state == 7) {
                    valueLength = valueLength | b;
                    state = 8;
                    pattern.setValueLength(valueLength);
                    bufIdx = 0;
                } else if (state == 8) {
                    pattern.getValue()[bufIdx++] = b;
                    if (bufIdx == valueLength) {
                        state = 9;
                    }
                } else if (state == 9) {
                    if (b == '&') {
                        bufIdx = 0;
                        state = 10;
                    } else if (b == '~') {
                        state = 11;
                    } else if (b == '+') {
                        state = 12;
                    } else if (b == '\n') {
                        state = 13;
                    }
                } else if (state == 10) {
                    pattern.getMask()[bufIdx++] = b;
                    if (bufIdx == valueLength) {
                        state = 9;
                    }
                } else if (state == 11) {
                    pattern.setWordSize(Integer.parseInt(String.valueOf((char) b)));
                    state = 9;
                } else if (state == 12) {
                    if (b == '\n') {
                        pattern.setRangeLength(Integer.parseInt(bui.toString()));
                        bui.setLength(0);
                        state = 13;
                    } else {
                        bui.append((char) b);
                    }
                }

                // Done
                if (state == 13) {
                    entry.add(pattern);
                    pattern = new MagicEntry.Pattern();
                    state = 4;
                }
            }
        }
    } finally {
        fin.close();
    }

    // Sort the patterns in the base
    for (MagicEntry e : aliasBase.byType.values()) {
        Collections.sort(e);
    }

    return aliasBase.byType.values();
}

From source file:org.freedesktop.mime.DefaultMIMEService.java

private MIMEEntry checkForTextOrBinary(FileObject file) throws FileSystemException, IOException {
    /*/*ww  w.  ja v a  2  s. c  om*/
     * If no magic rule matches the data (or if the content is not
     * available), use the default type of application/octet-stream for
     * binary data, or text/plain for textual data. If there was no glob
     * match the magic match as the result.
     */

    InputStream in = file.getContent().getInputStream();
    try {
        byte[] buf = new byte[(int) Math.min(32l, file.getContent().getSize())];
        DataInputStream din = new DataInputStream(in);
        din.readFully(buf);
        for (byte b : buf) {
            if (b < 32) {
                return getEntity("application/octet-stream");
            }
        }
    } finally {
        in.close();
    }

    return getEntity("text/plain");
}

From source file:org.freedesktop.mime.MagicEntry.java

public boolean match(FileObject file) throws IOException {
    RandomAccessContent s = file.getContent().getRandomAccessContent(RandomAccessMode.READ);
    try {//from ww w. j  a  v a 2s. c  o m
        for (Pattern p : this) {

            byte[] val = p.getValue();
            byte[] mask = p.getMask();

            // Read in portion of file
            ByteBuffer buf = ByteBuffer.allocate(p.getRangeLength() + val.length);
            s.seek(p.getOffset());
            byte[] bufArr = buf.array();
            s.readFully(bufArr);

            int valIdx = 0;
            for (int i = 0; i < bufArr.length; i++) {
                if ((bufArr[i] & mask[valIdx]) == (val[valIdx] & mask[valIdx])) {
                    valIdx++;
                    if (valIdx == val.length) {
                        return true;
                    }
                } else {
                    valIdx = 0;
                }
            }
        }
    } finally {
        s.close();
    }
    return false;
}

From source file:org.freedesktop.mime.MIMEEntry.java

void load(FileObject file) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);/*w  w w  . j a  v  a 2 s. com*/
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream in = file.getContent().getInputStream();
        try {
            Document document = builder.parse(in);
            build(document);
        } finally {
            in.close();
        }
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception e) {
        IOException ioe = new IOException("Failed to parse XML.");
        ioe.initCause(e);
        throw ioe;
    }

}