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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.ResponseWriter;
import javax.faces.event.AjaxBehaviorEvent;

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

    private static class JavascriptCustomUpdate {

        private final String componentId;
        private final String value;

        JavascriptCustomUpdate(String componentId, String value) {
            this.componentId = componentId;
            this.value = value;
        }
    }

    private final List<JavascriptCustomUpdate> customUpdates;

    public CustomPartialResponseWriter(ResponseWriter wrapped) {
        super(wrapped);
        customUpdates = new ArrayList<JavascriptCustomUpdate>();
    }

    public void addCustomUpdate(String componentId, String value) {
        customUpdates.add(new JavascriptCustomUpdate(componentId, value));
    }

    public void addCustomUpdate(AjaxBehaviorEvent event, String value) {
        this.addCustomUpdate(event.getComponent().getClientId(), value);
    }

    @Override
    public void endDocument() throws IOException {

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        if (!customUpdates.isEmpty()) {
            startExtension(Collections.singletonMap("id", "jsupdates"));
            for (JavascriptCustomUpdate update : customUpdates) {
                write(String.format("<jsupdate src=\"%s\">%s</jsupdate>", update.componentId, update.value));
            }
            endExtension();
        }

        super.endDocument();
    }
}