Rectangle 27 0

Essentially, you should be using an <ui:include> in combination with a custom ResourceHandler which is able to return the resource in flavor of an URL. So when having an OutputStream, you should really be writing it to a (temp) file so that you can get an URL out of it.

<ui:include src="/dynamic.xhtml" />

with

public class DynamicResourceHandler extends ResourceHandlerWrapper {

    private ResourceHandler wrapped;

    public DynamicResourceHandler(ResourceHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public ViewResource createViewResource(FacesContext context, String resourceName) {
        if (resourceName.equals("/dynamic.xhtml")) {
            try {
                File file = File.createTempFile("dynamic-", ".xhtml");

                try (Writer writer = new FileWriter(file)) {
                    writer
                        .append("<ui:composition")
                        .append(" xmlns:ui='http://java.sun.com/jsf/facelets'")
                        .append(" xmlns:h='http://java.sun.com/jsf/html'")
                        .append(">")
                        .append("<p>Hello from a dynamic include!</p>")
                        .append("<p>The below should render as a real input field:</p>")
                        .append("<p><h:inputText /></p>")
                        .append("</ui:composition>");
                }

                final URL url = file.toURI().toURL();
                return new ViewResource(){
                    @Override
                    public URL getURL() {
                        return url;
                    }
                };
            }
            catch (IOException e) {
                throw new FacesException(e);
            }
        }

        return super.createViewResource(context, resourceName);
    }

    @Override
    public ResourceHandler getWrapped() {
        return wrapped;
    }

}

which is registered in faces-config.xml as follows

<application>
    <resource-handler>com.example.DynamicResourceHandler</resource-handler>
</application>
ResourceResolver
ResourceHandler#createViewResource()

I was looking a way where we don't have to store the temp file on web server. Is there no alternative way which works directly with in memory data? Perhaps with custom jsf component/tag etc.

You can, you only need to create a custom URLStreamHandlerFactory and URLStreamHandler. Can't give examples from top of head, so no answer on that.

Question: Is it possible to access a backing bean object there and/or pass certain params to resource handler?

You can use CDI @Inject in resource handlers or programmatically evaluate EL by Application#evaluateExpressionGet(). Passing params is of course possible "the usual way" by manipulating the src accordingly like so src="/dynamic.xhtml?param=value", you only have to parse it yourself using e.g. String#split() on resourceName. Note that the format of path in src is completely free to your choice. E.g. src="dynamic:foo,bar,baz" etc in combination with a if (resourceName.startsWith("dynamic:")) check.

I tried with this and it works as expected. But i was unable to @Inject my bean there. Is there anything special we need here to inject a bean?

jsf 2 - Include dynamic content containing JSF tags/components from st...

jsf-2 facelets jsf-2.2 dynamic-content
Rectangle 27 0

My solution for JSF 2.2 and custom URLStream Handler

private ResourceHandler wrapped;

@Inject
UserSessionBean userBeean;

public DatabaseResourceHandlerWrapper(ResourceHandler wrapped) {
    this.wrapped = wrapped;
}

@Override
public Resource createResource(String resourceName, String libraryName) {
    return super.createResource(resourceName, libraryName); //To change body of generated methods, choose Tools | Templates.
}

@Override
public ViewResource createViewResource(FacesContext context, String resourceName) {
    if (resourceName.startsWith("/dynamic.xhtml?")) {
        try {
            String query = resourceName.substring("/dynamic.xhtml?".length());
            Map<String, String> params = splitQuery(query);
            //do some query to get content
            String content = "<ui:composition"
                    + " xmlns='http://www.w3.org/1999/xhtml' xmlns:ui='http://java.sun.com/jsf/facelets'"
                    + " xmlns:h='http://java.sun.com/jsf/html'> MY CONTENT"
                    + "</ui:composition>";

            final URL url = new URL(null, "string://helloworld", new MyCustomHandler(content));
            return new ViewResource() {
                @Override
                public URL getURL() {
                    return url;
                }
            };
        } catch (IOException e) {
            throw new FacesException(e);
        }
    }

    return super.createViewResource(context, resourceName);
}

public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
    Map<String, String> params = new LinkedHashMap<>();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        params.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
    }
    return params;
}

@Override
public ResourceHandler getWrapped() {
    return wrapped;
}

static class MyCustomHandler extends URLStreamHandler {

    private String content;

    public MyCustomHandler(String content) {
        this.content = content;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        return new UserURLConnection(u, content);
    }

    private static class UserURLConnection extends URLConnection {

        private String content;

        public UserURLConnection(URL url, String content) {
            super(url);
            this.content = content;
        }

        @Override
        public void connect() throws IOException {
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content.getBytes("UTF-8"));
        }
    }

}

jsf 2 - Include dynamic content containing JSF tags/components from st...

jsf-2 facelets jsf-2.2 dynamic-content