/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache license, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.internna.iwebmvc.tags;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.internna.iwebmvc.crypto.Cipherer;
import org.springframework.beans.BeanWrapperImpl;
import static org.internna.iwebmvc.utils.StringUtils.hasText;
import static org.internna.iwebmvc.utils.StringUtils.encodeToHtmlEntities;
import static org.internna.iwebmvc.utils.StringUtils.encodeToJSEscapeSequences;
/**
* Gets the value of a property of a bean and stores either it in a property or
* prints it in the JSP output directly.
*
* @author Jose Noheda
* @since 2.0
*/
public class Value extends SimpleTagSupport {
protected Log logger = LogFactory.getLog(getClass());
private String path;
private Object entity;
private String property;
private boolean encrypt = false;
private boolean javascript = false;
public void setPath(String path) {
this.path = path;
}
public void setEntity(Object entity) {
this.entity = entity;
}
public void setProperty(String property) {
this.property = property;
}
public void setEncrypt(boolean encrypt) {
this.encrypt = encrypt;
}
/**
* Encodes the result to JS unicode instead of HTML entities if printed to the JSP. Defaults to HTML
*
* @param javascript any
*/
public void setJavascript(boolean javascript) {
this.javascript = javascript;
}
/**
* Obtains the value of a (nested) property for an object and writes it to the page.
*/
@Override
public void doTag() throws JspException {
if (entity != null) {
try {
JspContext context = getJspContext();
Object val = new BeanWrapperImpl(entity).getPropertyValue(path);
if (logger.isDebugEnabled()) logger.debug("Obtained value [" + path + "] for bean [" + entity + "]: " + val);
if ((val != null) && encrypt) {
Cipherer cipher = (Cipherer) context.getAttribute(Cipherer.CIPHERER, 2);
val = cipher.encrypt(val.toString());
}
if (hasText(property)) context.setAttribute(property, val);
else if (val != null) context.getOut().print(javascript ? encodeToJSEscapeSequences(val.toString()): encodeToHtmlEntities(val.toString()));
} catch (Exception ex) {
if (logger.isDebugEnabled()) logger.debug("Could not obtain a value for [" + path + "] in bean [" + entity.getClass().getName() + "]: " + ex.getMessage());
}
}
}
}