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.jahia.services.content.impl.vfs.VFSNodeImpl.java

public VFSNodeImpl(FileObject fileObject, VFSSessionImpl session) {
    this.fileObject = fileObject;
    this.session = session;
    this.properties = new HashMap<String, VFSPropertyImpl>();
    try {//from   w ww .ja  v a  2  s  .  co  m
        if (fileObject.exists() && (fileObject.getContent() != null)) {
            long lastModifiedTime = fileObject.getContent().getLastModifiedTime();
            if (lastModifiedTime > 0) {
                ValueFactory valueFactory = session.getValueFactory();
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(lastModifiedTime);
                properties.put(Constants.JCR_CREATED,
                        new VFSPropertyImpl(
                                new Name("created", org.apache.jackrabbit.spi.Name.NS_JCR_PREFIX,
                                        org.apache.jackrabbit.spi.Name.NS_JCR_URI),
                                this, session, valueFactory.createValue(calendar)));
                properties.put(Constants.JCR_LASTMODIFIED,
                        new VFSPropertyImpl(
                                new Name("lastModified", org.apache.jackrabbit.spi.Name.NS_JCR_PREFIX,
                                        org.apache.jackrabbit.spi.Name.NS_JCR_URI),
                                this, session, valueFactory.createValue(calendar)));
            }
        }
    } catch (FileSystemException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (UnsupportedRepositoryOperationException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (RepositoryException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionUploadFile(CommandRequest request) throws IOException {
    if (uploadFileAllowed || getUserStatus().isRootUser()) {
        FileObject currentDir = getCurrentDir();
        if (currentDir != null && currentDir.isWriteable()) {
            File file = (File) request.getFilesByParamName().get("file");
            if (file != null) {
                String fileName = file.getName();
                FileObject fileObject = currentDir.resolveFile(fileName);
                if (!fileObject.exists()) {
                    fileObject.createFile();
                    OutputStream os = fileObject.getContent().getOutputStream(true);
                    InputStream is = new BufferedInputStream(new FileInputStream(file));
                    IOUtils.copy(is, os);
                    is.close();//w w  w.ja  v a 2 s  .  com
                    os.close();
                    currentFilePath = fileObject.getName().getPath();
                    return getCommonResponse(request);
                } else {
                    //TODO: Deal with errors
                }
            }
        }
    }
    //TODO: Deal with permission error
    return getCommonResponse(request);
}

From source file:org.jboss.dashboard.ui.formatters.FileNavigationFileListFormatter.java

protected void renderFiles(List sortedChildren) throws FileSystemException {
    if (!sortedChildren.isEmpty()) {
        renderFragment("outputStart");
        for (int i = 0; i < sortedChildren.size(); i++) {
            FileObject fileObject = (FileObject) sortedChildren.get(i);
            FileContent content = fileObject.getContent();
            setAttribute("fileObject", fileObject);
            setAttribute("name", fileObject.getName().getBaseName());
            setAttribute("fileSize", content.getSize());
            String path = fileObject.getName().getPath();
            setAttribute("path", path);
            setAttribute("current", path.equals(getFileNavigationHandler().getCurrentFilePath()));
            String contentType = content.getContentInfo().getContentType();
            String extension = fileObject.getName().getExtension();
            if (contentType == null) {
                contentType = extension;
            }//from  www.  j a va  2  s.  c  o m
            setAttribute("contentType", contentType);
            setAttribute("imageURL",
                    getFileNavigationHandler().getFilesystemManager().getThumbnailPath(extension));
            renderFragment("output");
        }
        renderFragment("outputEnd");
    }

}

From source file:org.jboss.dashboard.ui.formatters.FileNavigationFilePreviewFormatter.java

public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException {
    try {/*from ww  w. j  a  va 2s.c  o  m*/
        FileObject currentFile = getFileNavigationHandler().getCurrentFile();
        if (currentFile != null) {
            String contentType = currentFile.getContent().getContentInfo().getContentType();
            if (contentType != null && contentType.startsWith("image")) {
                String imageUrl = getImageUrl(currentFile);
                setAttribute("imageUrl", imageUrl);
                renderFragment("outputAsImage");
            } else {
                String extension = currentFile.getName().getExtension();
                String imageUrl = getFileNavigationHandler().getFilesystemManager().getLargeIconPath(extension);
                setAttribute("imageUrl", imageUrl);
                setAttribute("url", getFileNavigationHandler().getFilesystemManager().getURI(currentFile));
                setAttribute("fileName", currentFile.getName().getBaseName());
                renderFragment("outputAsFile");
            }
        }
    } catch (FileSystemException e) {
        log.error("Error: ", e);
    }
}

From source file:org.jbpm.form.builder.services.impl.fs.FSMenuService.java

protected String readURL(URL url) throws FileNotFoundException, IOException {
    if (url.toExternalForm().startsWith("vfs")) {
        FileObject from = VFS.getManager().resolveFile(url.toExternalForm());
        return IOUtils.toString(from.getContent().getInputStream());
    } else {//w w  w.  jav a2 s.c  o  m
        return FileUtils.readFileToString(FileUtils.toFile(url));
    }
}

From source file:org.jclouds.vfs.provider.blobstore.test.BlobStoreProviderTestCase.java

private void writeFile(FileObject base, String name, String value) throws FileSystemException, IOException {
    FileObject file = base.resolveFile(name);
    FileContent content = file.getContent();
    CharStreams.write(value, CharStreams
            .newWriterSupplier(Utils.newOutputStreamSupplier(content.getOutputStream()), Charsets.UTF_8));
    content.close();//from www .jav a 2  s  . c o m
}

From source file:org.jclouds.vfs.tools.blobstore.BlobStoreShell.java

private void ls(FileSystemManager mg, FileObject wd, final String[] cmd) throws FileSystemException {
    int pos = 1;//w w  w . j a  v a2s  . c o m
    final boolean recursive;
    if (cmd.length > pos && cmd[pos].equals("-R")) {
        recursive = true;
        pos++;
    } else {
        recursive = false;
    }

    final FileObject file;
    if (cmd.length > pos) {
        file = mg.resolveFile(wd, cmd[pos]);
    } else {
        file = wd;
    }

    if (file.getType() == FileType.FOLDER) {
        // List the contents
        System.out.println("Contents of " + file.getName().getFriendlyURI());
        listChildren(file, recursive, "");
    } else {
        // Stat the file
        System.out.println(file.getName());
        final FileContent content = file.getContent();
        System.out.println("Size: " + content.getSize() + " bytes.");
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
        System.out.println("Last modified: " + lastMod);
    }
}

From source file:org.jclouds.vfs.tools.blobstore.BlobStoreShell.java

/**
 * Does a 'touch' command.//  w  w w . j a  v  a2 s.  c om
 */
private void touch(final String[] cmd) throws Exception {
    if (cmd.length < 2) {
        throw new Exception("USAGE: touch <path>");
    }
    final FileObject file = remoteMgr.resolveFile(remoteCwd, cmd[1]);
    if (!file.exists()) {
        file.createFile();
    }
    file.getContent().setLastModifiedTime(System.currentTimeMillis());
}

From source file:org.josso.tooling.gshell.install.commands.InstallWebGatewayCommand.java

protected void installConfig() throws Exception {

    if (copyConfigFiles) {
        // Generate a key for rememberme auth
        SecretKeySpec key = CipherUtil.generateAESKey();
        byte[] keyBytes = key.getEncoded();
        String keyStr = CipherUtil.encodeBase64(keyBytes);

        FileObject authProperties = tmpDir.resolveFile("josso-auth.properties");

        authProperties.createFile();/*from  w w  w . j av a  2s  . c  o m*/
        OutputStream os = authProperties.getContent().getOutputStream(true);
        java.util.Properties authProps = new java.util.Properties();

        authProps.setProperty("josso.rememberme.authscheme.key", keyStr);
        authProps.store(os, "JOSSO 'Remember Me' authentication schemem properties.");

        printer.printActionOkStatus("Generating", "'Remember Me' AES key",
                "Created " + authProperties.getName().getFriendlyURI());

        getInstaller().installConfiguration(
                createArtifact(tmpDir.getURL().toString(), JOSSOScope.GATEWAY, "josso-auth.properties"),
                isReplaceConfig());
        try {
            authProperties.delete();
        } catch (java.io.IOException e) {
            /* */ }

        String persistenceFileName = "josso-gateway-" + persistence + "-stores.xml";
        printer.printActionOkStatus("Using", "'" + persistence + "' default configuration",
                "Installing " + persistenceFileName + " as " + "josso-gateway-stores.xml");

        // Install all configuration files :
        FileObject[] libs = confDir.getChildren();
        for (int i = 0; i < confDir.getChildren().length; i++) {
            FileObject cfgFile = libs[i];

            if (!cfgFile.getType().getName().equals(FileType.FILE.getName())) {
                // ignore folders
                continue;
            }

            String fileName = cfgFile.getName().getBaseName();
            if (fileName.equals(persistenceFileName)) {
                getInstaller().installConfiguration(
                        createArtifact(confDir.getURL().toString(), JOSSOScope.GATEWAY, fileName),
                        "josso-gateway-stores.xml", isReplaceConfig());
            }

            getInstaller().installConfiguration(
                    createArtifact(confDir.getURL().toString(), JOSSOScope.GATEWAY, fileName),
                    isReplaceConfig());
        }
    } else {
        //TODO backup configuration files, if they exist
        io.out.println("Backup and remove existing configuration files");
        getInstaller().backupGatewayConfigurations(true);
    }

}

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

protected Document readContentAsDom(FileObject file, boolean nameSpaceAware) throws Exception {
    InputStream is = null;/*from  ww  w .  j av  a 2s  .c om*/

    try {
        is = file.getContent().getInputStream();

        DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(nameSpaceAware);
        parserFactory.setIgnoringElementContentWhitespace(false);
        parserFactory.setIgnoringComments(false);

        DocumentBuilder builder = parserFactory.newDocumentBuilder();

        boolean dtdNotFound = false;
        Document doc = null;
        try {
            doc = builder.parse(is);
        } catch (FileNotFoundException e) {
            dtdNotFound = true;
        }

        // if dtd doesn't exist parse the document again without trying to load dtd
        if (dtdNotFound) {
            is = file.getContent().getInputStream();
            // disable dtd loading
            parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            builder = parserFactory.newDocumentBuilder();
            doc = builder.parse(is);
        }

        DocumentType docType = doc.getDoctype();

        if (log.isDebugEnabled() && docType != null) {
            log.debug("docType.getPublicId()=" + docType.getPublicId());
            log.debug("docType.getSystemId()=" + docType.getSystemId());
        }

        return doc;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                /**/}
    }

}