Skip to content

Commit

Permalink
Merge pull request #735 from apache/WW-5336-deprecate-ognltool
Browse files Browse the repository at this point in the history
  • Loading branch information
kusalk authored Aug 22, 2023
2 parents c087f2e + 6e5a1a0 commit 555a3a3
Show file tree
Hide file tree
Showing 9 changed files with 200 additions and 149 deletions.
171 changes: 83 additions & 88 deletions core/src/main/java/org/apache/struts2/util/StrutsUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@
*/
package org.apache.struts2.util;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.ognl.OgnlUtil;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.ValueStack;
import ognl.OgnlException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsException;
import org.apache.struts2.views.jsp.ui.OgnlTool;
import org.apache.struts2.views.util.UrlHelper;

import javax.servlet.RequestDispatcher;
Expand All @@ -39,7 +41,16 @@
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.text.MessageFormat.format;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;

/**
* Struts base utility class, for use in Velocity and Freemarker templates
Expand All @@ -50,32 +61,30 @@ public class StrutsUtil {

protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map<String, Class> classes = new Hashtable<>();
protected OgnlTool ognl;
protected Map<String, Class<?>> classes = new HashMap<>();
protected OgnlUtil ognl;
protected ValueStack stack;

private UrlHelper urlHelper;
private ObjectFactory objectFactory;
private final UrlHelper urlHelper;
private final ObjectFactory objectFactory;

public StrutsUtil(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
this.stack = stack;
this.request = request;
this.response = response;
this.ognl = stack.getActionContext().getContainer().getInstance(OgnlTool.class);
this.ognl = stack.getActionContext().getContainer().getInstance(OgnlUtil.class);
this.urlHelper = stack.getActionContext().getContainer().getInstance(UrlHelper.class);
this.objectFactory = stack.getActionContext().getContainer().getInstance(ObjectFactory.class);
}

public Object bean(Object aName) throws Exception {
String name = aName.toString();
Class c = classes.get(name);

if (c == null) {
c = ClassLoaderUtil.loadClass(name, StrutsUtil.class);
classes.put(name, c);
public Object bean(Object name) throws Exception {
String className = name.toString();
Class<?> clazz = classes.get(className);
if (clazz == null) {
clazz = ClassLoaderUtil.loadClass(className, StrutsUtil.class);
classes.put(className, clazz);
}

return objectFactory.buildBean(c, stack.getContext());
return objectFactory.buildBean(clazz, stack.getContext());
}

public boolean isTrue(String expression) {
Expand All @@ -88,30 +97,20 @@ public Object findString(String name) {
}

public String include(Object aName) throws Exception {
try {
RequestDispatcher dispatcher = request.getRequestDispatcher(aName.toString());

if (dispatcher == null) {
throw new IllegalArgumentException("Cannot find included file " + aName);
}

ResponseWrapper responseWrapper = new ResponseWrapper(response);

dispatcher.include(request, responseWrapper);

return responseWrapper.getData();
}
catch (Exception e) {
LOG.debug("Cannot include {}", aName, e);
throw e;
RequestDispatcher dispatcher = request.getRequestDispatcher(aName.toString());
if (dispatcher == null) {
throw new IllegalArgumentException("Cannot find included file " + aName);
}
ResponseWrapper responseWrapper = new ResponseWrapper(response);
dispatcher.include(request, responseWrapper);
return responseWrapper.getData();
}

public String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.debug("Cannot encode URL [{}]", s, e);
LOG.debug(format("Cannot encode URL [{0}]", s), e);
return s;
}
}
Expand All @@ -124,6 +123,17 @@ public Object findValue(String expression, String className) throws ClassNotFoun
return stack.findValue(expression, Class.forName(className));
}

public Object findValue(String expr, Object context) {
try {
return ognl.getValue(expr, ActionContext.getContext().getContextMap(), context);
} catch (OgnlException e) {
if (e.getReason() instanceof SecurityException) {
LOG.error(format("Could not evaluate this expression due to security constraints: [{0}]", expr), e);
}
return null;
}
}

public String getText(String text) {
return (String) stack.findValue("getText('" + text.replace('\'', '"') + "')");
}
Expand All @@ -132,7 +142,7 @@ public String getText(String text) {
* @return the url ContextPath. An empty string if one does not exist.
*/
public String getContext() {
return (request == null)? "" : request.getContextPath();
return request == null ? "" : request.getContextPath();
}

public String translateVariables(String expression) {
Expand All @@ -156,71 +166,64 @@ public String translateVariables(String expression) {
* to use as the value of the ListEntry
* @return a List of ListEntry
*/
public List makeSelectList(String selectedList, String list, String listKey, String listValue) {
List selectList = new ArrayList();

Collection selectedItems = null;

Object i = stack.findValue(selectedList);

if (i != null) {
if (i.getClass().isArray()) {
selectedItems = Arrays.asList((Object[]) i);
} else if (i instanceof Collection) {
selectedItems = (Collection) i;
} else {
// treat it is a single item
selectedItems = new ArrayList();
selectedItems.add(i);
}
}
public List<ListEntry> makeSelectList(String selectedList, String list, String listKey, String listValue) {
List<ListEntry> selectList = new ArrayList<>();

Collection items = (Collection) stack.findValue(list);
if (items == null) {
return selectList;
}

if (items != null) {
for (Object element : items) {
Object key;

if ((listKey == null) || (listKey.length() == 0)) {
key = element;
} else {
key = ognl.findValue(listKey, element);
}

Object value = null;

if ((listValue == null) || (listValue.length() == 0)) {
value = element;
} else {
value = ognl.findValue(listValue, element);
}
Collection selectedItems = getSelectedItems(selectedList);
for (Object element : items) {
Object key = computeKey(listKey, element);
Object value = computeValue(listValue, element);
boolean isSelected = value != null && selectedItems.contains(value);
selectList.add(new ListEntry(key, value, isSelected));
}

boolean isSelected = false;
return selectList;
}

if ((value != null) && (selectedItems != null) && selectedItems.contains(value)) {
isSelected = true;
}
private Collection getSelectedItems(String selectedListName) {
Object i = stack.findValue(selectedListName);
if (i == null) {
return emptyList();
}
if (i.getClass().isArray()) {
return Arrays.asList((Object[]) i);
} else if (i instanceof Collection) {
return (Collection) i;
}
return singletonList(i);
}

selectList.add(new ListEntry(key, value, isSelected));
}
private Object computeKey(String listKey, Object element) {
if (listKey == null || listKey.isEmpty()) {
return element;
}
return findValue(listKey, element);
}

return selectList;
private Object computeValue(String listValue, Object element) {
if (listValue == null || listValue.isEmpty()) {
return element;
}
return findValue(listValue, element);
}

public int toInt(long aLong) {
return (int) aLong;
}

public long toLong(int anInt) {
return (long) anInt;
return anInt;
}

public long toLong(String aLong) {
if (aLong == null) {
if (aLong == null || aLong.isEmpty()) {
return 0;
}

return Long.parseLong(aLong);
}

Expand All @@ -233,14 +236,7 @@ public String toString(int anInt) {
}

public String toStringSafe(Object obj) {
try {
if (obj != null) {
return String.valueOf(obj);
}
return "";
} catch (Exception e) {
return "Exception thrown: " + e;
}
return obj == null ? "" : obj.toString();
}

static class ResponseWrapper extends HttpServletResponseWrapper {
Expand All @@ -257,7 +253,6 @@ static class ResponseWrapper extends HttpServletResponseWrapper {

public String getData() {
writer.flush();

return strout.toString();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,24 @@
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.ValueStack;
import freemarker.cache.*;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.core.HTMLOutputFormat;
import freemarker.core.OutputFormat;
import freemarker.core.TemplateClassResolver;
import freemarker.ext.jsp.TaglibFactory;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.ext.servlet.HttpRequestParametersHashModel;
import freemarker.ext.servlet.HttpSessionHashModel;
import freemarker.ext.servlet.ServletContextHashModel;
import freemarker.template.*;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateModel;
import freemarker.template.Version;
import freemarker.template.utility.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Expand All @@ -51,7 +59,13 @@
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
* <p>
Expand Down Expand Up @@ -176,27 +190,27 @@ public class FreemarkerManager {
public void setEncoding(String encoding) {
this.encoding = encoding;
}

@Inject(StrutsConstants.STRUTS_FREEMARKER_WRAPPER_ALT_MAP)
public void setWrapperAltMap(String val) {
altMapWrapper = "true".equals(val);
}

@Inject(StrutsConstants.STRUTS_FREEMARKER_BEANWRAPPER_CACHE)
public void setCacheBeanWrapper(String val) {
cacheBeanWrapper = "true".equals(val);
}

@Inject(StrutsConstants.STRUTS_FREEMARKER_MRU_MAX_STRONG_SIZE)
public void setMruMaxStrongSize(String size) {
mruMaxStrongSize = Integer.parseInt(size);
}

@Inject(value = StrutsConstants.STRUTS_FREEMARKER_TEMPLATES_CACHE_UPDATE_DELAY, required = false)
public void setTemplateUpdateDelay(String delay) {
templateUpdateDelay = delay;
}

@Inject
public void setContainer(Container container) {
Map<String, TagLibraryModelProvider> map = new HashMap<>();
Expand Down Expand Up @@ -281,8 +295,8 @@ public void init(ServletContext servletContext) throws TemplateException {
loadSettings(servletContext);
}

/**
* Sets the Freemarker Configuration's template loader with the FreemarkerThemeTemplateLoader
/**
* Sets the Freemarker Configuration's template loader with the FreemarkerThemeTemplateLoader
* at the top.
*
* @param templateLoader the template loader
Expand All @@ -293,7 +307,7 @@ protected void configureTemplateLoader(TemplateLoader templateLoader) {
themeTemplateLoader.init(templateLoader);
config.setTemplateLoader(themeTemplateLoader);
}

/**
* Create the instance of the freemarker Configuration object.
* <p>
Expand Down Expand Up @@ -543,7 +557,7 @@ public ScopesHashModel buildTemplateModel(ValueStack stack, Object action, Servl

protected void populateContext(ScopesHashModel model, ValueStack stack, Object action, HttpServletRequest request, HttpServletResponse response) {
// put the same objects into the context that the velocity result uses
Map standard = ContextUtil.getStandardContext(stack, request, response);
Map<String, Object> standard = ContextUtil.getStandardContext(stack, request, response);
model.putAll(standard);

// support for JSP exception pages, exposing the servlet or JSP exception
Expand Down
Loading

0 comments on commit 555a3a3

Please sign in to comment.