001/*
002 * (C) Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
003 *
004 * The contents of this file are subject to the terms of either the GNU
005 * General Public License Version 2 only ("GPL") or the Common Development
006 * and Distribution License("CDDL") (collectively, the "License").  You
007 * may not use this file except in compliance with the License.  You can
008 * obtain a copy of the License at
009 * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
010 * or packager/legal/LICENSE.txt.  See the License for the specific
011 * language governing permissions and limitations under the License.
012 *
013 * When distributing the software, include this License Header Notice in each
014 * file and include the License file at packager/legal/LICENSE.txt.
015 *
016 * GPL Classpath Exception:
017 * Oracle designates this particular file as subject to the "Classpath"
018 * exception as provided by Oracle in the GPL Version 2 section of the License
019 * file that accompanied this code.
020 *
021 * Modifications:
022 * If applicable, add the following below the License Header, with the fields
023 * enclosed by brackets [] replaced by your own identifying information:
024 * "Portions Copyright [year] [name of copyright owner]"
025 *
026 * Contributor(s):
027 * If you wish your version of this file to be governed by only the CDDL or
028 * only the GPL Version 2, indicate your decision by adding "[Contributor]
029 * elects to include this software in this distribution under the [CDDL or GPL
030 * Version 2] license."  If you don't indicate a single choice of license, a
031 * recipient has the option to distribute your version of this file under
032 * either the CDDL, the GPL Version 2 or to extend the choice of license to
033 * its licensees as provided above.  However, if you add GPL Version 2 code
034 * and therefore, elected the GPL Version 2 license, then the option applies
035 * only if the new code is made subject to such option by the copyright
036 * holder.
037 *
038 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
039 */
040
041package org.nuxeo.ecm.web.resources.jsf;
042
043import java.io.IOException;
044import java.util.Map;
045import java.util.logging.Level;
046import java.util.logging.Logger;
047
048import javax.faces.application.FacesMessage;
049import javax.faces.application.ProjectStage;
050import javax.faces.component.UIComponent;
051import javax.faces.context.FacesContext;
052import javax.faces.context.ResponseWriter;
053import javax.faces.event.AbortProcessingException;
054import javax.faces.event.ComponentSystemEvent;
055import javax.faces.event.ComponentSystemEventListener;
056import javax.faces.event.ListenerFor;
057import javax.faces.event.PostAddToViewEvent;
058import javax.faces.render.Renderer;
059
060import org.nuxeo.ecm.platform.ui.web.util.ComponentUtils;
061
062import com.sun.faces.util.FacesLogger;
063
064/**
065 * Override of the default JSF class to override #encodeChildren
066 *
067 * @since 7.4
068 */
069@ListenerFor(systemEventClass = PostAddToViewEvent.class)
070public abstract class ScriptStyleBaseRenderer extends Renderer implements ComponentSystemEventListener {
071
072    private static final String COMP_KEY = ScriptStyleBaseRenderer.class.getName() + "_COMPOSITE_COMPONENT";
073
074    // Log instance for this class
075    protected static final Logger logger = FacesLogger.RENDERKIT.getLogger();
076
077    /*
078     * Indicates that the component associated with this Renderer has already been added to the facet in the view.
079     */
080
081    /*
082     * When this method is called, we know that there is a component with a script renderer somewhere in the view. We
083     * need to make it so that when an element with a name given by the value of the optional "target" component
084     * attribute is encountered, this component can be called upon to render itself. This method will add the component
085     * (associated with this Renderer) to a facet in the view only if a "target" component attribute is set.
086     */
087    public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
088        UIComponent component = event.getComponent();
089        if (ComponentUtils.isRelocated(component)) {
090            return;
091        }
092        String target = verifyTarget((String) component.getAttributes().get("target"));
093        if (target != null) {
094            ComponentUtils.relocate(component, target, COMP_KEY);
095        }
096    }
097
098    @Override
099    public final void decode(FacesContext context, UIComponent component) {
100        // no-op
101    }
102
103    @Override
104    public final boolean getRendersChildren() {
105        return true;
106    }
107
108    /**
109     * If overridden, this method (i.e. super.encodeEnd) should be called <em>last</em> within the overridding
110     * implementation.
111     */
112    @Override
113    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
114
115        // Remove the key to prevent issues with state saving...
116        String ccID = (String) component.getAttributes().get(COMP_KEY);
117        if (ccID != null) {
118            // the first pop maps to the component we're rendering.
119            // the second pop maps to the composite component that was pushed
120            // in this renderer's encodeBegin implementation.
121            // re-push the current component to reset the original context
122            component.popComponentFromEL(context);
123            component.popComponentFromEL(context);
124            component.pushComponentToEL(context, component);
125        }
126    }
127
128    /**
129     * If overridden, this method (i.e. super.encodeBegin) should be called <em>first</em> within the overridding
130     * implementation.
131     */
132    @Override
133    public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
134
135        String ccID = (String) component.getAttributes().get(COMP_KEY);
136        if (null != ccID) {
137            UIComponent cc = context.getViewRoot().findComponent(':' + ccID);
138            UIComponent curCC = UIComponent.getCurrentCompositeComponent(context);
139            if (cc != curCC) {
140                // the first pop maps to the component we're rendering.
141                // push the composite component to the 'stack' and then re-push
142                // the component we're rendering so the current component is
143                // correct.
144                component.popComponentFromEL(context);
145                component.pushComponentToEL(context, cc);
146                component.pushComponentToEL(context, component);
147            }
148        }
149
150    }
151
152    @Override
153    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
154        encodeChildren(context, component, false);
155    }
156
157    public final void encodeChildren(FacesContext context, UIComponent component, boolean warnOnChildren)
158            throws IOException {
159        int childCount = component.getChildCount();
160        boolean renderChildren = (0 < childCount);
161
162        if (warnOnChildren) {
163            Map<String, Object> attributes = component.getAttributes();
164            boolean hasName = attributes.get("name") != null;
165            boolean hasSrc = attributes.get("src") != null;
166            // If we have no "name" attribute...
167            if (!hasName && !hasSrc) {
168                // and no child content...
169                if (0 == childCount) {
170                    // this is user error, so put up a message if desired
171                    if (context.isProjectStage(ProjectStage.Development)) {
172                        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
173                                "outputScript with no library, no name, and no body content",
174                                "Is body content intended?");
175                        context.addMessage(component.getClientId(context), message);
176                    }
177                    // We have no children, but don't bother with the method
178                    // invocation anyway.
179                    renderChildren = false;
180                }
181            } else if (0 < childCount) {
182                // If we have a "name" and also have child content, ignore
183                // the child content and log a message.
184                if (logger.isLoggable(Level.INFO)) {
185                    logger.info("outputScript with \"name\" attribute and nested content.  Ignoring nested content.");
186                }
187                renderChildren = false;
188            }
189        }
190        if (renderChildren) {
191            ResponseWriter writer = context.getResponseWriter();
192            startElement(writer, component);
193            super.encodeChildren(context, component);
194            endElement(writer);
195        }
196
197    }
198
199    // ------------------------------------------------------- Protected Methods
200
201    /**
202     * <p>
203     * Allow the subclass to customize the start element content
204     * </p>
205     */
206    protected abstract void startElement(ResponseWriter writer, UIComponent component) throws IOException;
207
208    /**
209     * <p>
210     * Allow the subclass to customize the start element content
211     * </p>
212     */
213    protected abstract void endElement(ResponseWriter writer) throws IOException;
214
215    /**
216     * <p>
217     * Allow a subclass to control what's a valid value for "target".
218     */
219    protected String verifyTarget(String toVerify) {
220        return ComponentUtils.verifyTarget(toVerify, toVerify);
221    }
222
223}