Skip to content
CustomPartialResponseWriter.java 2.87 KiB
Newer Older
/* 
 * _____________________________________________________________________________
 * 
 * INAF - OATS National Institute for Astrophysics - Astronomical Observatory of
 * Trieste INAF - IA2 Italian Center for Astronomical Archives
 * _____________________________________________________________________________
 * 
 * Copyright (C) 2016 Istituto Nazionale di Astrofisica
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License Version 3 as published by the
 * Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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 Map<String, JSUpdateHandler> customJSUpdates;

    public CustomPartialResponseWriter(ResponseWriter wrapped) {
        super(wrapped);
        customJSUpdates = new ConcurrentHashMap<>();
    }

    @Override
    public void endDocument() throws IOException {
        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();

    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();
    }