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.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Adds a file's detail information to the directory list
 *//* w  w w.  j  a  v  a2 s.  c o m*/
private void workerAddFileDetails(final FileObject file, final String connectionId) {
    long date = 0;
    try {
        date = file.getContent().getLastModifiedTime();
    } catch (Exception e) {
    }

    final String nameString = file.getName().getBaseName();
    final String dateString = dateFormat.format(new Date(date));
    final String sizeString;
    final String typeString;
    final Image iconImage;

    // If directory
    if (VFSUtil.isDirectory(file)) {
        typeString = getResourceString("filetype.Folder");
        sizeString = "";
        iconImage = iconCache.get(CFPluginImages.ICON_FOLDER);
    } else {
        long size = 0;
        try {
            size = file.getContent().getSize();
        } catch (Exception e) {
        }

        // It is a file, get size
        sizeString = getResourceString("filesize.KB", new Object[] { new Long((size + 512) / 1024) });

        int dot = nameString.lastIndexOf('.');
        if (dot != -1) {
            String extension = nameString.substring(dot);
            Program program = Program.findProgram(extension);

            // get icon based on extension
            if (program != null) {
                typeString = program.getName();
                iconImage = CFPluginImages.getIconFromProgram(program);
            } else {
                typeString = getResourceString("filetype.Unknown", new Object[] { extension.toUpperCase() });
                iconImage = iconCache.get(CFPluginImages.ICON_FILE);
            }
        } else {
            typeString = getResourceString("filetype.None");
            iconImage = iconCache.get(CFPluginImages.ICON_FILE);
        }
    }

    // Table values: Name, Size, Type, Date
    final String[] strings = new String[] { nameString, sizeString, typeString, dateString };

    display.syncExec(new Runnable() {
        public void run() {
            String attrs = VFSUtil.getFileAttributes(file);

            // guard against the shell being closed before this runs
            if (shell.isDisposed())
                return;
            TableItem tableItem = new TableItem(table, 0);
            tableItem.setText(strings);
            tableItem.setImage(iconImage);
            tableItem.setData(TABLEITEMDATA_FILE, file);
            tableItem.setData(TABLEITEMDATA_CONNECTIONID, connectionId);

            if (attrs.length() > 0)
                tableItem.setData("TIP_TEXT", attrs);
        }
    });
}

From source file:org.codehaus.cargo.module.JarArchiveTest.java

/**
 * Verifies that the method <code>expandToPath()</code> works.
 * //  www . ja v a 2s . c om
 * @throws Exception If an unexpected error occurs
 */
public void testExpandToPath() throws Exception {
    FileObject testJar = this.fsManager.resolveFile("ram:///test.jar");
    ZipOutputStream zos = new ZipOutputStream(testJar.getContent().getOutputStream());
    ZipEntry zipEntry = new ZipEntry("rootResource.txt");
    zos.putNextEntry(zipEntry);
    zos.write("Some content".getBytes("UTF-8"));
    zos.closeEntry();
    zos.close();

    DefaultJarArchive jarArchive = new DefaultJarArchive("ram:///test.jar");
    jarArchive.setFileHandler(new VFSFileHandler(this.fsManager));

    jarArchive.expandToPath("ram:///test");

    // Verify that the rootResource.txt file has been correctly expanded
    assertTrue(this.fsManager.resolveFile("ram:///test/rootResource.txt").exists());
}

From source file:org.codehaus.mojo.unix.core.FsFileCollector.java

private Callable packageFile(final FileObject from, final UnixFsObject.RegularFile to) {
    return new Callable() {
        public Object call() throws Exception {
            FileObject toFile = root.resolveFile(to.path.string);

            toFile.getParent().createFolder();
            toFile.copyFrom(from, Selectors.SELECT_SELF);
            toFile.getContent().setLastModifiedTime(to.lastModified.toDateTime().toDate().getTime());
            return Unit.unit();
        }//from   ww w . j a v a 2 s . c  om
    };
}

From source file:org.codehaus.mojo.unix.maven.sysvpkg.PkgUnixPackage.java

public FileObject fromFile(final FileObject fromFile, UnixFsObject.RegularFile file)
        throws FileSystemException {
    // If it is a file on the local file system, just point the entry in the prototype file to it
    if (fromFile.getFileSystem() instanceof LocalFileSystem) {
        return fromFile;
    }/*from   www  .j  av a2  s .  co m*/

    // Creates a file under the working directory that should match the destination path
    final FileObject tmpFile = workingDirectory.resolveFile(file.path.string);

    operations = operations.cons(new Callable() {
        public Object call() throws Exception {
            OutputStream outputStream = null;
            try {
                tmpFile.getParent().createFolder();
                tmpFile.copyFrom(fromFile, Selectors.SELECT_ALL);
                tmpFile.getContent().setLastModifiedTime(fromFile.getContent().getLastModifiedTime());
            } finally {
                IOUtil.close(outputStream);
            }

            return Unit.unit();
        }
    });

    return tmpFile;
}

From source file:org.docx4all.ui.menu.FileMenu.java

protected boolean save(WordprocessingMLPackage wmlPackage, String saveAsFilePath, String callerActionName) {
    boolean success = true;
    try {/*from   w w w  .  ja  v  a 2 s.c  o  m*/
        if (saveAsFilePath.endsWith(Constants.DOCX_STRING)) {
            SaveToVFSZipFile saver = new SaveToVFSZipFile(wmlPackage);
            saver.save(saveAsFilePath);
        } else if (saveAsFilePath.endsWith(Constants.FLAT_OPC_STRING)) {

            FlatOpcXmlCreator xmlPackageCreator = new FlatOpcXmlCreator(wmlPackage);
            org.docx4j.xmlPackage.Package flatOPC = xmlPackageCreator.get();

            FileObject fo = VFSUtils.getFileSystemManager().resolveFile(saveAsFilePath);
            OutputStream fos = fo.getContent().getOutputStream();

            Marshaller m = Context.jcXmlPackage.createMarshaller();
            try {
                NamespacePrefixMapperUtils.setProperty(m, NamespacePrefixMapperUtils.getPrefixMapper());

                m.setProperty("jaxb.formatted.output", true);
            } catch (javax.xml.bind.PropertyException cnfe) {
                log.error(cnfe.getMessage(), cnfe);
            }
            m.marshal(flatOPC, fos);
            try {
                //just in case
                fos.close();
            } catch (IOException exc) {
                ;//ignore
            }

        } else if (saveAsFilePath.endsWith(Constants.HTML_STRING)) {
            FileObject fo = VFSUtils.getFileSystemManager().resolveFile(saveAsFilePath);
            OutputStream fos = fo.getContent().getOutputStream();
            javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(fos);
            //wmlPackage.html(result);
            AbstractHtmlExporter exporter = new HtmlExporterNG2();

            // .. the HtmlSettings object
            HtmlSettings htmlSettings = new HtmlSettings();
            htmlSettings.setImageDirPath(saveAsFilePath + "_files");
            htmlSettings.setImageTargetUri(
                    saveAsFilePath.substring(saveAsFilePath.lastIndexOf("/") + 1) + "_files");

            exporter.html(wmlPackage, result, htmlSettings);

            try {
                //just in case
                fos.close();
            } catch (IOException exc) {
                ;//ignore
            }
        } else {
            throw new Docx4JException("Invalid filepath = " + VFSUtils.getFriendlyName(saveAsFilePath));
        }
    } catch (Exception exc) {
        exc.printStackTrace();

        success = false;
        WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
        ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());

        String title = rm.getString(callerActionName + ".Action.text");
        String message = rm.getString(callerActionName + ".Action.errorMessage") + "\n"
                + VFSUtils.getFriendlyName(saveAsFilePath);
        wmlEditor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);
    }

    return success;
}

From source file:org.docx4all.xml.ElementMLFactory.java

public final static DocumentML createDocumentML(FileObject f, boolean applyFilter) throws IOException {
    if (f == null || !(Constants.DOCX_STRING.equalsIgnoreCase(f.getName().getExtension())
            || Constants.FLAT_OPC_STRING.equalsIgnoreCase(f.getName().getExtension()))) {
        throw new IllegalArgumentException("Not a .docx (or .xml) file.");
    }//from  w w  w .  j av a  2s  .c o  m

    DocumentML docML = null;
    try {
        WordprocessingMLPackage wordMLPackage;
        if (Constants.DOCX_STRING.equalsIgnoreCase(f.getName().getExtension())) {
            // .docx
            LoadFromVFSZipFile loader = new LoadFromVFSZipFile(true);
            //LoadFromVFSZipFile.setCustomXmlDataStorageClass(new org.docx4j.model.datastorage.Dom4jCustomXmlDataStorage());
            wordMLPackage = (WordprocessingMLPackage) loader.getPackageFromFileObject(f);
        } else {
            // .xml

            // First get the Flat OPC package from the File Object
            InputStream is = f.getContent().getInputStream();

            Unmarshaller u = Context.jcXmlPackage.createUnmarshaller();
            u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());

            javax.xml.bind.JAXBElement j = (javax.xml.bind.JAXBElement) u.unmarshal(is);
            org.docx4j.xmlPackage.Package flatOpc = (org.docx4j.xmlPackage.Package) j.getValue();
            System.out.println("unmarshalled ");

            // Now convert it to a docx4j WordML Package            
            FlatOpcXmlImporter importer = new FlatOpcXmlImporter(flatOpc);
            wordMLPackage = (WordprocessingMLPackage) importer.get();
        }

        if (applyFilter) {
            wordMLPackage = XmlUtil.applyFilter(wordMLPackage);
        }
        docML = new DocumentML(wordMLPackage);
    } catch (Docx4JException exc) {
        throw new IOException(exc);
    } catch (Exception exc) {
        throw new IOException(exc);
    }

    return docML;
}

From source file:org.docx4j.extras.vfs.SaveToVFSZipFile.java

/**
 * Save the contained Package as a Zip file in the file system 
 * //from   ww  w . j  a va  2s.c o m
 * @param docxFile A destination FileObject
 * @return true if successful;
 *         false, otherwise.
 * @throws Docx4JException if there is an error
 */
public boolean save(FileObject docxFile) throws Docx4JException {
    log.info("Saving to" + docxFile);

    boolean success = false;

    try {
        OutputStream docxOut = docxFile.getContent().getOutputStream();
        success = _saveToZipFile.save(docxOut);
    } catch (FileSystemException exc) {
        exc.printStackTrace();
        throw new Docx4JException("Failed to save package", exc);
    }

    try {
        docxFile.close();
    } catch (FileSystemException exc) {
        ;//ignore
    }

    return success;
}

From source file:org.eclim.plugin.core.command.archive.ArchiveReadCommand.java

/**
 * {@inheritDoc}// ww  w.jav a  2 s  . c  om
 */
public String execute(CommandLine commandLine) throws Exception {
    InputStream in = null;
    OutputStream out = null;
    FileSystemManager fsManager = null;
    try {
        String file = commandLine.getValue(Options.FILE_OPTION);

        fsManager = VFS.getManager();
        FileObject fileObject = fsManager.resolveFile(file);
        FileObject tempFile = fsManager
                .resolveFile(SystemUtils.JAVA_IO_TMPDIR + "/eclim/" + fileObject.getName().getPath());

        // the vfs file cache isn't very intelligent, so clear it.
        fsManager.getFilesCache().clear(fileObject.getFileSystem());
        fsManager.getFilesCache().clear(tempFile.getFileSystem());

        // NOTE: FileObject.getName().getPath() does not include the drive
        // information.
        String path = tempFile.getName().getURI().substring(URI_PREFIX.length());
        // account for windows uri which has an extra '/' in front of the drive
        // letter (file:///C:/blah/blah/blah).
        if (WIN_PATH.matcher(path).matches()) {
            path = path.substring(1);
        }

        //if(!tempFile.exists()){
        tempFile.createFile();

        in = fileObject.getContent().getInputStream();
        out = tempFile.getContent().getOutputStream();
        IOUtils.copy(in, out);

        new File(path).deleteOnExit();
        //}

        return path;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

/**
 * Attempts to locate the IClassFile for the supplied file path from the
 * specified project's classpath./* w w w . jav  a  2s. c o  m*/
 *
 * @param project The project to find the class file in.
 * @param path Absolute path or url (jar:, zip:) to a .java source file.
 * @return The IClassFile.
 */
public static IClassFile findClassFile(IJavaProject project, String path) throws Exception {
    if (path.startsWith("/") || path.toLowerCase().startsWith("jar:")
            || path.toLowerCase().startsWith("zip:")) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(path);
        if (file.exists()) {
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(file.getContent().getInputStream()));
                String pack = null;
                String line = null;
                while ((line = in.readLine()) != null) {
                    Matcher matcher = PACKAGE_LINE.matcher(line);
                    if (matcher.matches()) {
                        pack = matcher.group(1);
                        break;
                    }
                }
                if (pack != null) {
                    String name = pack + '.' + FileUtils.getFileName(file.getName().getPath());
                    IType type = project.findType(name);
                    if (type != null) {
                        return type.getClassFile();
                    }
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
    return null;
}

From source file:org.eclim.util.file.FileOffsets.java

/**
 * Reads the supplied file and compiles a list of offsets.
 *
 * @param filename The file to compile a list of offsets for.
 * @return The FileOffsets instance./* w  ww. j a v a2s . c o  m*/
 */
public static FileOffsets compile(String filename) {
    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(filename);

        // disable caching (the cache seems to become invalid at some point
        // causing vfs errors).
        //fsManager.getFilesCache().clear(file.getFileSystem());

        if (!file.exists()) {
            throw new IllegalArgumentException(Services.getMessage("file.not.found", filename));
        }
        return compile(file.getContent().getInputStream());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}