001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.bean;
016    
017    import com.liferay.portal.kernel.util.HtmlUtil;
018    
019    import java.io.Serializable;
020    
021    import java.lang.reflect.InvocationHandler;
022    import java.lang.reflect.InvocationTargetException;
023    import java.lang.reflect.Method;
024    
025    /**
026     * Wraps a bean so that all strings returned from <code>@AutoEscape</code>
027     * annotated methods are automatically HTML escaped.
028     *
029     * @author Shuyang Zhou
030     * @see    AutoEscape
031     */
032    public class AutoEscapeBeanHandler implements InvocationHandler, Serializable {
033    
034            public AutoEscapeBeanHandler(Object bean) {
035                    _bean = (Serializable)bean;
036            }
037    
038            public Object getBean() {
039                    return _bean;
040            }
041    
042            @Override
043            public Object invoke(Object proxy, Method method, Object[] arguments)
044                    throws Throwable {
045    
046                    String methodName = method.getName();
047    
048                    if (methodName.startsWith("set")) {
049                            throw new IllegalAccessException(
050                                    "Setter methods cannot be called on an escaped bean");
051                    }
052    
053                    if (methodName.endsWith("isEscapedModel")) {
054                            return true;
055                    }
056                    else if (methodName.endsWith("toEscapedModel")) {
057                            return proxy;
058                    }
059    
060                    Object result = null;
061    
062                    try {
063                            result = method.invoke(_bean, arguments);
064                    }
065                    catch (InvocationTargetException ite) {
066                            throw ite.getTargetException();
067                    }
068    
069                    if (method.getAnnotation(AutoEscape.class) != null) {
070                            result = HtmlUtil.escape((String)result);
071                    }
072    
073                    return result;
074            }
075    
076            private final Serializable _bean;
077    
078    }