001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Andre Justo
018 */
019package org.nuxeo.ecm.platform.ui.web.component.message;
020
021import com.sun.faces.renderkit.html_basic.MessageRenderer;
022
023import javax.faces.component.UIComponent;
024import javax.faces.context.FacesContext;
025import javax.faces.context.ResponseWriter;
026import javax.faces.context.ResponseWriterWrapper;
027import javax.faces.render.FacesRenderer;
028import java.io.IOException;
029
030/**
031 * Custom MessageRenderer that allows the use of HTML in <h:message>
032 *
033 * @since 7.3
034 */
035@FacesRenderer(componentFamily="javax.faces.Message", rendererType="javax.faces.Message")
036public class EscapableMessageRenderer extends MessageRenderer {
037
038    @Override
039    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
040        final ResponseWriter originalResponseWriter = context.getResponseWriter();
041
042        try {
043            context.setResponseWriter(new ResponseWriterWrapper() {
044
045                @Override
046                public ResponseWriter getWrapped() {
047                    return originalResponseWriter;
048                }
049
050                @Override
051                public void writeText(Object text, UIComponent component, String property) throws IOException {
052                    String string = String.valueOf(text);
053                    String escape = (String) component.getAttributes().get("escape");
054                    if (escape != null && !Boolean.valueOf(escape)) {
055                        super.write(string);
056                    } else {
057                        super.writeText(string, component, property);
058                    }
059                }
060            });
061
062            super.encodeEnd(context, component); // Now, render it!
063        } finally {
064            context.setResponseWriter(originalResponseWriter); // Restore original writer.
065        }
066    }
067}