Skip to content
CustomPartialResponseWriter.java 2.72 KiB
Newer Older
package it.inaf.oats.ia2.tapschemamanager.webapp;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.ResponseWriter;

/**
 *
 * @author Sonia Zorba {@literal <zorba at oats.inaf.it>}
 */
public class CustomPartialResponseWriter extends PartialResponseWriter {

    private final Set<String> componentsToEncode;
    private final Map<String, JSUpdateHandler> customJSUpdates;

    public CustomPartialResponseWriter(ResponseWriter wrapped) {
        super(wrapped);
        componentsToEncode = new HashSet<String>();
        customJSUpdates = new HashMap<String, JSUpdateHandler>();
    }

    @Override
    public void endDocument() throws IOException {
        FacesContext fctx = FacesContext.getCurrentInstance();
        if (!customJSUpdates.isEmpty()) {
            startExtension(Collections.singletonMap("id", "jsupdates"));
            for (Map.Entry<String, JSUpdateHandler> entry : customJSUpdates.entrySet()) {
                String componentId = entry.getKey();
                startElement("jsupdate", null);
                writeAttribute("src", componentId, null);
                write(entry.getValue().getUpdate());
                endElement("jsupdate");
            }
            endExtension();
        if (!componentsToEncode.isEmpty()) {
            startExtension(Collections.singletonMap("id", "htmlupdates"));
            for (String componentId : componentsToEncode) {
                UIComponent component = fctx.getViewRoot().findComponent(componentId);
                startElement("htmlupdate", null);
                writeAttribute("src", componentId, null);
                component.encodeAll(fctx);
                endElement("htmlupdate");

    public void encodeComponent(String componentId) {
        componentsToEncode.add(componentId);
    }

    public void addCustomJSUpdate(String componentId, JSUpdateHandler updateHandler) {
        customJSUpdates.put(componentId, updateHandler);
    }

    public void addCustomJSUpdate(JSUpdateHandler updateHandler) {
        String sourceComponentId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("javax.faces.source");
        addCustomJSUpdate(sourceComponentId, updateHandler);
    }

    public static CustomPartialResponseWriter getCurrentInstance() {
        return (CustomPartialResponseWriter) FacesContext.getCurrentInstance().getPartialViewContext().getPartialResponseWriter();
    }