Minor code improvements's in the struts core module

- Use Java 7 features like diamond operater and multi catch
- Improve some logging message and don't check LOG.isXxx if not necessary
- Fix some typos
- Imrove some loops and use for each instead of iterator
- Use BooleanUtils.toBoolean(string) instead of "true".isEquals to be more robust
This commit is contained in:
Johannes Geppert
2015-06-08 19:27:05 +02:00
parent 27bfb22df7
commit e47a1127f8
131 changed files with 914 additions and 1391 deletions
@@ -21,6 +21,7 @@
package org.apache.struts2;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -69,8 +70,8 @@ public class RequestUtils {
servletPath = requestUri.substring(requestUri.indexOf(servletPath));
}
}
if (null != servletPath && !"".equals(servletPath)) {
if (StringUtils.isNotEmpty(servletPath)) {
return servletPath;
}
@@ -92,14 +93,13 @@ public class RequestUtils {
*/
public static String getUri(HttpServletRequest request) {
// handle http dispatcher includes.
String uri = (String) request
.getAttribute("javax.servlet.include.servlet_path");
String uri = (String) request.getAttribute("javax.servlet.include.servlet_path");
if (uri != null) {
return uri;
}
uri = getServletPath(request);
if (uri != null && !"".equals(uri)) {
if (StringUtils.isNotEmpty(uri)) {
return uri;
}
@@ -28,8 +28,8 @@ import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsException;
import org.apache.struts2.StrutsStatics;
@@ -47,7 +47,6 @@ import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
@@ -164,16 +163,13 @@ public class ActionComponent extends ContextBean {
try {
writer.flush();
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("error while trying to flush writer ", e);
}
}
}
executeAction();
if ((getVar() != null) && (proxy != null)) {
getStack().setValue("#attr['" + getVar() + "']",
proxy.getAction());
getStack().setValue("#attr['" + getVar() + "']", proxy.getAction());
}
} finally {
popComponentStack();
@@ -219,14 +215,14 @@ public class ActionComponent extends ContextBean {
parentParams = new ActionContext(getStack().getContext()).getParameters();
}
Map<String,String[]> newParams = (parentParams != null)
? new HashMap<String,String[]>(parentParams)
: new HashMap<String,String[]>();
Map<String, String[]> newParams = (parentParams != null)
? new HashMap<String, String[]>(parentParams)
: new HashMap<String, String[]>();
if (parameters != null) {
Map<String,String[]> params = new HashMap<String,String[]>();
for (Iterator i = parameters.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
Map<String, String[]> params = new HashMap<>();
for (Object o : parameters.entrySet()) {
Map.Entry entry = (Map.Entry) o;
String key = (String) entry.getKey();
Object val = entry.getValue();
if (val.getClass().isArray() && String.class == val.getClass().getComponentType()) {
@@ -82,7 +82,7 @@ public class ActionMessage extends UIBean {
addParameter("escape", escape);
}
@StrutsTagAttribute(description=" Whether to escape HTML", type="Boolean", defaultValue="true")
@StrutsTagAttribute(description = "Whether to escape HTML", type = "Boolean", defaultValue = "true")
public void setEscape(boolean escape) {
this.escape = escape;
}
@@ -23,19 +23,19 @@ package org.apache.struts2.components;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* <!-- START SNIPPET: javadoc -->
@@ -48,7 +48,7 @@ import java.util.LinkedHashMap;
* <p/>
* <pre>
* <!-- START SNIPPET: example1 -->
* &lt;s:a id="link1" theme="ajax" href="/DoIt.action"&gt;
* &lt;s:a id="link1" href="/do-it.action"&gt;
* &lt;img border="none" src="&lt;%=request.getContextPath()%&gt;/images/delete.gif"/&gt;
* &lt;s:param name="id" value="1"/&gt;
* &lt;/s:a&gt;
@@ -58,7 +58,7 @@ import java.util.LinkedHashMap;
@StrutsTag(
name = "a",
tldTagClass = "org.apache.struts2.views.jsp.ui.AnchorTag",
description = "Render a HTML href element that when clicked can optionally call a URL via remote XMLHttpRequest and updates its targets",
description = "Render a HTML href element",
allowDynamicAttributes = true)
public class Anchor extends ClosingUIBean {
private static final Logger LOG = LogManager.getLogger(Anchor.class);
@@ -21,20 +21,19 @@
package org.apache.struts2.components;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.components.Param.UnnamedParametric;
import org.apache.struts2.util.AppendIteratorFilter;
import org.apache.struts2.util.MakeIterator;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* <!-- START SNIPPET: javadoc -->
@@ -141,9 +140,7 @@ public class AppendIterator extends ContextBean implements UnnamedParametric {
Object iteratorEntryObj = paramEntries.next();
if (! MakeIterator.isIterable(iteratorEntryObj)) {
if (LOG.isWarnEnabled()) {
LOG.warn("param with value resolved as "+iteratorEntryObj+" cannot be make as iterator, it will be ignored and hence will not appear in the merged iterator");
}
LOG.warn("param with value resolved as {} cannot be make as iterator, it will be ignored and hence will not appear in the merged iterator", iteratorEntryObj);
continue;
}
appendIteratorFilter.setSource(MakeIterator.convert(iteratorEntryObj));
@@ -21,18 +21,16 @@
package org.apache.struts2.components;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.util.MakeIterator;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import org.apache.struts2.util.MakeIterator;
import com.opensymphony.xwork2.util.ValueStack;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* <!-- START SNIPPET: javadoc -->
@@ -158,7 +156,7 @@ public class ComboBox extends TextField {
"Example: people or people.{name}");
}
@StrutsTagAttribute(description="Iteratable source to populate from. " +
@StrutsTagAttribute(description = "Iterable source to populate from. " +
"If this is missing, the select widget is simply not displayed.", required=true)
public void setList(String list) {
this.list = list;
@@ -179,12 +177,12 @@ public class ComboBox extends TextField {
this.headerValue = headerValue;
}
@StrutsTagAttribute(description="Set the key used to retrive the option key.")
@StrutsTagAttribute(description = "Set the key used to retrieve the option key.")
public void setListKey(String listKey) {
this.listKey = listKey;
}
@StrutsTagAttribute(description="Set the value used to retrive the option value.")
@StrutsTagAttribute(description = "Set the value used to retrieve the option value.")
public void setListValue(String listValue) {
this.listValue = listValue;
}
@@ -25,9 +25,10 @@ import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.AnnotationUtils;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
@@ -44,11 +45,7 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -67,7 +64,7 @@ public class Component {
/**
* Caches information about common tag's attributes to reduce scanning for annotation @StrutsTagAttribute
*/
protected static ConcurrentMap<Class<?>, Collection<String>> standardAttributesMap = new ConcurrentHashMap<Class<?>, Collection<String>>();
protected static ConcurrentMap<Class<?>, Collection<String>> standardAttributesMap = new ConcurrentHashMap<>();
protected boolean devMode = false;
protected ValueStack stack;
@@ -83,7 +80,7 @@ public class Component {
*/
public Component(ValueStack stack) {
this.stack = stack;
this.parameters = new LinkedHashMap<String, Object>();
this.parameters = new LinkedHashMap<>();
getComponentStack().push(this);
}
@@ -101,7 +98,7 @@ public class Component {
@Inject(value = StrutsConstants.STRUTS_DEVMODE, required = false)
public void setDevMode(String devMode) {
this.devMode = Boolean.parseBoolean(devMode);
this.devMode = BooleanUtils.toBoolean(devMode);
}
@Inject
@@ -111,7 +108,7 @@ public class Component {
@Inject(StrutsConstants.STRUTS_EL_THROW_EXCEPTION)
public void setThrowExceptionsOnELFailure(String throwException) {
this.throwExceptionOnELFailure = "true".equals(throwException);
this.throwExceptionOnELFailure = BooleanUtils.toBoolean(throwException);
}
@Inject
@@ -133,7 +130,7 @@ public class Component {
public Stack<Component> getComponentStack() {
Stack<Component> componentStack = (Stack<Component>) stack.getContext().get(COMPONENT_STACK);
if (componentStack == null) {
componentStack = new Stack<Component>();
componentStack = new Stack<>();
stack.getContext().put(COMPONENT_STACK, componentStack);
}
return componentStack;
@@ -230,7 +227,7 @@ public class Component {
* Evaluates the OGNL stack to find a String value.
* <p/>
* If the given expression is <tt>null</tt/> a error is logged and a <code>RuntimeException</code> is thrown
* constructed with a messaged based on the given field and errorMsg paramter.
* constructed with a messaged based on the given field and errorMsg parameter.
*
* @param expr OGNL expression.
* @param field field name used when throwing <code>RuntimeException</code>.
@@ -499,7 +496,7 @@ public class Component {
* If the provided value is <tt>null</tt> any existing parameter with
* the given key name is removed.
* @param key the key of the new parameter to add.
* @param value the value assoicated with the key.
* @param value the value associated with the key.
*/
public void addParameter(String key, Object value) {
if (key != null) {
@@ -539,7 +536,7 @@ public class Component {
Collection<String> standardAttributes = standardAttributesMap.get(clz);
if (standardAttributes == null) {
Collection<Method> methods = AnnotationUtils.getAnnotatedMethods(clz, StrutsTagAttribute.class);
standardAttributes = new HashSet<String>(methods.size());
standardAttributes = new HashSet<>(methods.size());
for(Method m : methods) {
standardAttributes.add(StringUtils.uncapitalize(m.getName().substring(3)));
}
@@ -56,7 +56,7 @@ public class ComponentUrlProvider implements UrlProvider {
/**
*
* @param component The component used to delagete some calls to
* @param component The component used to delegate some calls to
* @param parameters parameters passed from <param...>
*/
public ComponentUrlProvider(Component component, Map parameters) {
@@ -21,9 +21,9 @@
package org.apache.struts2.components;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
/**
* Base class for control and data tags
@@ -36,7 +36,7 @@ public abstract class ContextBean extends Component {
}
protected void putInContext(Object value) {
if (var != null && var.length() > 0) {
if (StringUtils.isNotBlank(var)) {
stack.getContext().put(var, value);
}
}
@@ -24,8 +24,8 @@ package org.apache.struts2.components;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -35,7 +35,6 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
@@ -200,10 +199,7 @@ public class Date extends ContextBean {
}
private TextProvider findProviderInStack() {
for (Iterator iterator = getStack().getRoot().iterator(); iterator
.hasNext();) {
Object o = iterator.next();
for (Object o : getStack().getRoot()) {
if (o instanceof TextProvider) {
return (TextProvider) o;
}
@@ -234,31 +230,31 @@ public class Date extends ContextBean {
int years = days / 365;
if (years > 0) {
args.add(Long.valueOf(years));
args.add(Long.valueOf(day));
args.add(years);
args.add(day);
args.add(sb);
args.add(null);
sb.append(tp.getText(DATETAG_PROPERTY_YEARS, DATETAG_DEFAULT_YEARS, args));
} else if (day > 0) {
args.add(Long.valueOf(day));
args.add(Long.valueOf(hour));
args.add(day);
args.add(hour);
args.add(sb);
args.add(null);
sb.append(tp.getText(DATETAG_PROPERTY_DAYS, DATETAG_DEFAULT_DAYS, args));
} else if (hour > 0) {
args.add(Long.valueOf(hour));
args.add(Long.valueOf(min));
args.add(hour);
args.add(min);
args.add(sb);
args.add(null);
sb.append(tp.getText(DATETAG_PROPERTY_HOURS, DATETAG_DEFAULT_HOURS, args));
} else if (min > 0) {
args.add(Long.valueOf(min));
args.add(Long.valueOf(sec));
args.add(min);
args.add(sec);
args.add(sb);
args.add(null);
sb.append(tp.getText(DATETAG_PROPERTY_MINUTES, DATETAG_DEFAULT_MINUTES, args));
} else {
args.add(Long.valueOf(sec));
args.add(sec);
args.add(sb);
args.add(null);
sb.append(tp.getText(DATETAG_PROPERTY_SECONDS, DATETAG_DEFAULT_SECONDS, args));
@@ -21,12 +21,11 @@
package org.apache.struts2.components;
import java.io.Writer;
import java.util.Map;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.views.annotations.StrutsTag;
import com.opensymphony.xwork2.util.ValueStack;
import java.io.Writer;
import java.util.Map;
/**
* <!-- START SNIPPET: javadoc -->
@@ -70,6 +69,6 @@ public class Else extends Component {
context.remove(If.ANSWER);
return !((ifResult == null) || (ifResult.booleanValue()));
return !((ifResult == null) || (ifResult));
}
}
@@ -21,12 +21,11 @@
package org.apache.struts2.components;
import java.io.Writer;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import java.io.Writer;
/**
* <!-- START SNIPPET: javadoc -->
@@ -75,27 +74,27 @@ public class ElseIf extends Component {
public boolean start(Writer writer) {
Boolean ifResult = (Boolean) stack.getContext().get(If.ANSWER);
if ((ifResult == null) || (ifResult.booleanValue())) {
if ((ifResult == null) || (ifResult)) {
return false;
}
//make the comparision
//make the comparison
answer = (Boolean) findValue(test, Boolean.class);
if (answer == null) {
answer = Boolean.FALSE;
}
if (answer.booleanValue()) {
if (answer) {
stack.getContext().put(If.ANSWER, answer);
}
return answer.booleanValue();
return answer;
}
public boolean end(Writer writer, String body) {
if (answer == null) {
answer = Boolean.FALSE;
}
if (answer.booleanValue()) {
if (answer) {
stack.getContext().put(If.ANSWER, answer);
}
return super.end(writer, "");
@@ -91,7 +91,7 @@ import java.util.List;
"or partial depending on param tag nested)if they exists")
public class FieldError extends UIBean implements UnnamedParametric {
private List<String> errorFieldNames = new ArrayList<String>();
private List<String> errorFieldNames = new ArrayList<>();
private boolean escape = true;
public FieldError(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
@@ -21,15 +21,14 @@
package org.apache.struts2.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <!-- START SNIPPET: javadoc -->
@@ -75,17 +74,13 @@ public class File extends UIBean {
String encType = (String) form.getParameters().get("enctype");
if (!"multipart/form-data".equals(encType)) {
// uh oh, this isn't good! Let's warn the developer
if (LOG.isWarnEnabled()) {
LOG.warn("Struts has detected a file upload UI tag (s:file) being used without a form set to enctype 'multipart/form-data'. This is probably an error!");
}
LOG.warn("Struts has detected a file upload UI tag (s:file) being used without a form set to enctype 'multipart/form-data'. This is probably an error!");
}
String method = (String) form.getParameters().get("method");
if (!"post".equalsIgnoreCase(method)) {
// uh oh, this isn't good! Let's warn the developer
if (LOG.isWarnEnabled()) {
LOG.warn("Struts has detected a file upload UI tag (s:file) being used without a form set to method 'POST'. This is probably an error!");
}
LOG.warn("Struts has detected a file upload UI tag (s:file) being used without a form set to method 'POST'. This is probably an error!");
}
}
@@ -29,12 +29,7 @@ import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptorUtil;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.validator.ActionValidatorManager;
import com.opensymphony.xwork2.validator.FieldValidator;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.ValidationInterceptor;
import com.opensymphony.xwork2.validator.Validator;
import com.opensymphony.xwork2.validator.ValidatorContext;
import com.opensymphony.xwork2.validator.*;
import com.opensymphony.xwork2.validator.validators.VisitorFieldValidator;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
@@ -278,7 +273,7 @@ public class Form extends ClosingUIBean {
String actionName = mapping.getName();
List<Validator> actionValidators = actionValidatorManager.getValidators(actionClass, actionName);
List<Validator> validators = new ArrayList<Validator>();
List<Validator> validators = new ArrayList<>();
findFieldValidators(name, actionClass, actionName, actionValidators, validators, "");
@@ -286,7 +281,7 @@ public class Form extends ClosingUIBean {
}
private void findFieldValidators(String name, Class actionClass, String actionName,
List<Validator> validatorList, List<Validator> retultValidators, String prefix) {
List<Validator> validatorList, List<Validator> resultValidators, String prefix) {
for (Validator validator : validatorList) {
if (validator instanceof FieldValidator) {
@@ -301,14 +296,14 @@ public class Form extends ClosingUIBean {
List<Validator> visitorValidators = actionValidatorManager.getValidators(clazz, actionName);
String vPrefix = prefix + (vfValidator.isAppendPrefix() ? vfValidator.getFieldName() + "." : "");
findFieldValidators(name, clazz, actionName, visitorValidators, retultValidators, vPrefix);
findFieldValidators(name, clazz, actionName, visitorValidators, resultValidators, vPrefix);
} else if ((prefix + fieldValidator.getFieldName()).equals(name)) {
if (StringUtils.isNotBlank(prefix)) {
//fixing field name for js side
FieldVisitorValidatorWrapper wrap = new FieldVisitorValidatorWrapper(fieldValidator, prefix);
retultValidators.add(wrap);
resultValidators.add(wrap);
} else {
retultValidators.add(fieldValidator);
resultValidators.add(fieldValidator);
}
}
}
@@ -21,24 +21,23 @@
package org.apache.struts2.components;
import java.io.Writer;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import org.apache.struts2.StrutsException;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.TextProviderFactory;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.TextProviderFactory;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsException;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import java.io.Writer;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* <!-- START SNIPPET: javadoc -->
@@ -129,8 +128,7 @@ public class I18n extends Component {
pushed = true;
}
} catch (Exception e) {
String msg = "Could not find the bundle " + name;
throw new StrutsException(msg, e);
throw new StrutsException("Could not find the bundle " + name, e);
}
return result;
@@ -21,17 +21,15 @@
package org.apache.struts2.components;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.util.FastByteArrayOutputStream;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
@@ -40,17 +38,9 @@ import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.util.FastByteArrayOutputStream;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
/**
* <!-- START SNIPPET: javadoc -->
@@ -135,24 +125,20 @@ public class Include extends Component {
String concat = "";
// Set parameters
Iterator iter = parameters.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
for (Object next : parameters.entrySet()) {
Map.Entry entry = (Map.Entry) next;
Object name = entry.getKey();
List values = (List) entry.getValue();
for (int i = 0; i < values.size(); i++) {
for (Object value : values) {
urlBuf.append(concat);
urlBuf.append(name);
urlBuf.append('=');
try {
urlBuf.append(URLEncoder.encode(values.get(i).toString(), "UTF-8"));
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("unable to url-encode "+values.get(i).toString()+", it will be ignored");
}
urlBuf.append(URLEncoder.encode(value.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
LOG.warn("Unable to url-encode {}, it will be ignored", value);
}
concat = "&";
@@ -165,10 +151,8 @@ public class Include extends Component {
// Include
try {
include(result, writer, req, res, defaultEncoding);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Exception thrown during include of " + result, e);
}
} catch (ServletException | IOException e) {
LOG.warn("Exception thrown during include of {}", result, e);
}
return super.end(writer, body);
@@ -199,7 +183,7 @@ public class Include extends Component {
// .. is illegal in an absolute path according to the Servlet Spec and will cause
// known problems on Orion application servers.
if (returnValue.indexOf("..") != -1) {
if (returnValue.contains("..")) {
Stack stack = new Stack();
StringTokenizer pathParts = new StringTokenizer(returnValue.replace('\\', '/'), "/");
@@ -21,18 +21,17 @@
package org.apache.struts2.components;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* <!-- START SNIPPET: javadoc -->
@@ -40,7 +39,7 @@ import org.apache.logging.log4j.LogManager;
* Create a input transfer select component which is basically an text input
* and &lt;select ...&gt; tag with buttons in the middle of them allowing text
* to be added to the transfer select. Will auto-select all its
* elements upon its containing form submision.
* elements upon its containing form submission.
*
* <!-- END SNIPPET: javadoc -->
*
@@ -113,11 +112,11 @@ public class InputTransferSelect extends ListUIBean {
public void evaluateExtraParams() {
super.evaluateExtraParams();
if (size == null || size.trim().length() <= 0) {
if (StringUtils.isBlank(size)) {
addParameter("size", "5");
}
if (multiple == null || multiple.trim().length() <= 0) {
if (StringUtils.isBlank(multiple)) {
addParameter("multiple", Boolean.TRUE);
}
@@ -140,12 +139,12 @@ public class InputTransferSelect extends ListUIBean {
// buttonCssClass
if (buttonCssClass != null && buttonCssClass.trim().length() > 0) {
if (StringUtils.isNotBlank(buttonCssClass)) {
addParameter("buttonCssClass", buttonCssClass);
}
// buttonCssStyle
if (buttonCssStyle != null && buttonCssStyle.trim().length() > 0) {
if (StringUtils.isNotBlank(buttonCssStyle)) {
addParameter("buttonCssStyle", buttonCssStyle);
}
@@ -174,11 +173,11 @@ public class InputTransferSelect extends ListUIBean {
// inform the form component our select tag infos, so they know how to select
// its elements upon onsubmit
// its elements upon onSubmit
Form formAncestor = (Form) findAncestor(Form.class);
if (formAncestor != null) {
// inform ancestor form that we are having a customOnsubmit (see form-close.ftl [simple theme])
// inform ancestor form that we are having a customOnSubmit (see form-close.ftl [simple theme])
enableAncestorFormCustomOnsubmit();
@@ -22,8 +22,8 @@
package org.apache.struts2.components;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.util.MakeIterator;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -276,7 +276,7 @@ public class IteratorComponent extends ContextBean {
if (iterator == null) {
//classic for loop from 'begin' to 'end'
iterator = new CounterIterator(begin, end, step, null);
} else if (iterator != null) {
} else {
//only arrays and lists are supported
if (iteratorTarget.getClass().isArray()) {
Object[] values = (Object[]) iteratorTarget;
@@ -304,8 +304,6 @@ public class IteratorComponent extends ContextBean {
String var = getVar();
if ((var != null) && (currentValue != null)) {
//pageContext.setAttribute(id, currentValue);
//pageContext.setAttribute(id, currentValue, PageContext.REQUEST_SCOPE);
putInContext(currentValue);
}
@@ -22,6 +22,7 @@
package org.apache.struts2.components;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.util.ContainUtil;
import org.apache.struts2.util.MakeIterator;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -96,11 +97,11 @@ public abstract class ListUIBean extends UIBean {
}
if (value instanceof Collection) {
addParameter("listSize", Integer.valueOf(((Collection) value).size()));
addParameter("listSize", ((Collection) value).size());
} else if (value instanceof Map) {
addParameter("listSize", Integer.valueOf(((Map) value).size()));
addParameter("listSize", ((Map) value).size());
} else if (value != null && value.getClass().isArray()) {
addParameter("listSize", Integer.valueOf(Array.getLength(value)));
addParameter("listSize", Array.getLength(value));
}
if (listKey != null) {
@@ -127,15 +128,15 @@ public abstract class ListUIBean extends UIBean {
addParameter("listLabelKey", listLabelKey);
}
if (listCssClass != null && listCssClass.trim().length() > 0) {
if (StringUtils.isNotBlank(listCssClass)) {
addParameter("listCssClass", listCssClass);
}
if (listCssStyle != null && listCssStyle.trim().length() > 0) {
if (StringUtils.isNotBlank(listCssStyle)) {
addParameter("listCssStyle", listCssStyle);
}
if (listTitle != null && listTitle.trim().length() > 0) {
if (StringUtils.isNotBlank(listTitle)) {
addParameter("listTitle", listTitle);
}
}
@@ -154,12 +155,12 @@ public abstract class ListUIBean extends UIBean {
this.list = list;
}
@StrutsTagAttribute(description = " Property of list objects to get field value from")
@StrutsTagAttribute(description = "Property of list objects to get field value from")
public void setListKey(String listKey) {
this.listKey = listKey;
}
@StrutsTagAttribute(description = " Property of list objects to get field value label from")
@StrutsTagAttribute(description = "Property of list objects to get field value label from")
public void setListValueKey(String listValueKey) {
this.listValueKey = listValueKey;
}
@@ -21,20 +21,18 @@
package org.apache.struts2.components;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.components.Param.UnnamedParametric;
import org.apache.struts2.util.MakeIterator;
import org.apache.struts2.util.MergeIteratorFilter;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* <!-- START SNIPPET: javadoc -->
@@ -152,12 +150,9 @@ public class MergeIterator extends ContextBean implements UnnamedParametric {
public boolean end(Writer writer, String body) {
for (Iterator parametersIterator = _parameters.iterator(); parametersIterator.hasNext(); ) {
Object iteratorEntryObj = parametersIterator.next();
for (Object iteratorEntryObj : _parameters) {
if (! MakeIterator.isIterable(iteratorEntryObj)) {
if (LOG.isWarnEnabled()) {
LOG.warn("param with value resolved as "+iteratorEntryObj+" cannot be make as iterator, it will be ignored and hence will not appear in the merged iterator");
}
LOG.warn("param with value resolved as {} cannot be make as iterator, it will be ignored and hence will not appear in the merged iterator", iteratorEntryObj);
continue;
}
mergeIteratorFilter.setSource(MakeIterator.convert(iteratorEntryObj));
@@ -22,8 +22,9 @@
package org.apache.struts2.components;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -150,35 +151,29 @@ public class OptionTransferSelect extends DoubleListUIBean {
doubleValue = findValue(doubleList);
addParameter("doubleList", doubleValue);
}
if (size == null || size.trim().length() <= 0) {
if (StringUtils.isBlank(size)) {
addParameter("size", "15");
}
if (doubleSize == null || doubleSize.trim().length() <= 0) {
if (StringUtils.isBlank(doubleSize)) {
addParameter("doubleSize", "15");
}
if (multiple == null || multiple.trim().length() <= 0) {
if (StringUtils.isBlank(multiple)) {
addParameter("multiple", Boolean.TRUE);
}
if (doubleMultiple == null || doubleMultiple.trim().length() <= 0) {
if (StringUtils.isBlank(doubleMultiple)) {
addParameter("doubleMultiple", Boolean.TRUE);
}
// buttonCssClass
if (buttonCssClass != null && buttonCssClass.trim().length() > 0) {
if (StringUtils.isNotBlank(buttonCssClass)) {
addParameter("buttonCssClass", buttonCssClass);
}
// buttonCssStyle
if (buttonCssStyle != null && buttonCssStyle.trim().length() > 0) {
if (StringUtils.isNotBlank(buttonCssStyle)) {
addParameter("buttonCssStyle", buttonCssStyle);
}
// allowSelectAll
addParameter("allowSelectAll",
allowSelectAll != null ? findValue(allowSelectAll, Boolean.class) : Boolean.TRUE);
@@ -22,6 +22,7 @@
package org.apache.struts2.components;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.StrutsException;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -126,7 +127,7 @@ public class Param extends Component {
Object value = findValue(this.value);
if (suppressEmptyParameters) {
if (value != null && !value.toString().isEmpty()) {
if (value != null && StringUtils.isNotBlank(value.toString())) {
component.addParameter(name, value);
}
} else {
@@ -22,9 +22,9 @@
package org.apache.struts2.components;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -165,9 +165,7 @@ public class Property extends Component {
writer.write(prepare(defaultValue));
}
} catch (IOException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Could not print out value '" + value + "'", e);
}
LOG.info("Could not print out value '{}'", value, e);
}
return result;
@@ -26,9 +26,9 @@ import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
@@ -201,7 +201,7 @@ public class ServletUrlRenderer implements UrlRenderer {
// Warn user that the specified namespace/action combo
// was not found in the configuration.
if (namespace != null && LOG.isWarnEnabled()) {
LOG.warn("No configuration found for the specified action: '" + actionName + "' in namespace: '" + namespace + "'. Form action defaulting to 'action' attribute's literal value.");
LOG.warn("No configuration found for the specified action: '{}' in namespace: '{}'. Form action defaulting to 'action' attribute's literal value.", actionName, namespace);
}
String result = urlHelper.buildUrl(action, formComponent.request, formComponent.response, null, scheme, formComponent.includeContext, true);
@@ -264,17 +264,11 @@ public class ServletUrlRenderer implements UrlRenderer {
includeGetParameters(urlComponent);
includeExtraParameters(urlComponent);
} else if (includeParams != null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unknown value for includeParams parameter to URL tag: " + includeParams);
}
LOG.warn("Unknown value for includeParams parameter to URL tag: {}", includeParams);
}
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to put request parameters (" + urlComponent.getHttpServletRequest().getQueryString() + ") into parameter map.", e);
}
LOG.warn("Unable to put request parameters ({}) into parameter map.", urlComponent.getHttpServletRequest().getQueryString(), e);
}
}
private void includeExtraParameters(UrlProvider urlComponent) {
@@ -324,13 +318,13 @@ public class ServletUrlRenderer implements UrlRenderer {
*/
protected void mergeRequestParameters(String value, Map<String, Object> parameters, Map<String, Object> contextParameters) {
Map<String, Object> mergedParams = new LinkedHashMap<String, Object>(contextParameters);
Map<String, Object> mergedParams = new LinkedHashMap<>(contextParameters);
// Merge contextParameters (from current request) with parameters specified in value attribute
// eg. value="someAction.action?id=someId&venue=someVenue"
// where the parameters specified in value attribute takes priority.
if (value != null && value.trim().length() > 0 && value.indexOf("?") > 0) {
if (StringUtils.contains(value, "?")) {
String queryString = value.substring(value.indexOf("?") + 1);
mergedParams = urlHelper.parseQueryString(queryString, false);
@@ -22,9 +22,9 @@
package org.apache.struts2.components;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.util.TextProviderHelper;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -130,7 +130,7 @@ public class Text extends ContextBean implements Param.UnnamedParametric {
super(stack);
}
@StrutsTagAttribute(description=" Name of resource property to fetch", required=true)
@StrutsTagAttribute(description = "Name of resource property to fetch", required = true)
public void setName(String name) {
this.name = name;
}
@@ -21,13 +21,12 @@
package org.apache.struts2.components;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <!-- START SNIPPET: javadoc -->
@@ -42,8 +41,6 @@ import com.opensymphony.xwork2.util.ValueStack;
* <!-- END SNIPPET: example -->
* </pre>
*
* @see TabbedPanel
*
*/
@StrutsTag(
name="textarea",
@@ -24,8 +24,9 @@ package org.apache.struts2.components;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.StrutsException;
import org.apache.struts2.components.template.Template;
@@ -504,7 +505,7 @@ public abstract class UIBean extends Component {
protected String tooltipIconPath;
// dynamic attributes
protected Map<String,Object> dynamicAttributes = new HashMap<String,Object>();
protected Map<String, Object> dynamicAttributes = new HashMap<>();
protected String defaultTemplateDir;
protected String defaultUITheme;
@@ -576,9 +577,7 @@ public abstract class UIBean extends Component {
throw new ConfigurationException("Unable to find a TemplateEngine for template " + template);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Rendering template " + template);
}
LOG.debug("Rendering template {}", template);
final TemplateRenderingContext context = new TemplateRenderingContext(template, writer, getStack(), getParameters(), this);
engine.renderTemplate(context);
@@ -593,17 +592,17 @@ public abstract class UIBean extends Component {
// If templateDir is not explicitly given,
// try to find attribute which states the dir set to use
if ((templateDir == null) || (templateDir.equals(""))) {
if (StringUtils.isBlank(templateDir)) {
templateDir = stack.findString("#attr.templateDir");
}
// Default template set
if ((templateDir == null) || (templateDir.equals(""))) {
if (StringUtils.isBlank(templateDir)) {
templateDir = defaultTemplateDir;
}
// Defaults to 'template'
if ((templateDir == null) || (templateDir.equals(""))) {
if (StringUtils.isBlank(templateDir)) {
templateDir = "template";
}
@@ -617,7 +616,7 @@ public abstract class UIBean extends Component {
theme = findString(this.theme);
}
if ( theme == null || theme.equals("") ) {
if (StringUtils.isBlank(theme)) {
Form form = (Form) findAncestor(Form.class);
if (form != null) {
theme = form.getTheme();
@@ -626,12 +625,12 @@ public abstract class UIBean extends Component {
// If theme set is not explicitly given,
// try to find attribute which states the theme set to use
if ((theme == null) || (theme.equals(""))) {
if (StringUtils.isBlank(theme)) {
theme = stack.findString("#attr.theme");
}
// Default theme set
if ((theme == null) || (theme.equals(""))) {
if (StringUtils.isBlank(theme)) {
theme = defaultUITheme;
}
@@ -662,7 +661,6 @@ public abstract class UIBean extends Component {
// lookup the label from a TextProvider (default value is the key)
providedLabel = TextProviderHelper.getText(key, key, stack);
}
}
if (this.name != null) {
@@ -841,7 +839,7 @@ public abstract class UIBean extends Component {
if (form != null) { // inform the containing form that we need tooltip javascript included
form.addParameter("hasTooltip", Boolean.TRUE);
// tooltipConfig defined in component itseilf will take precedence
// tooltipConfig defined in component itself will take precedence
// over those defined in the containing form
Map overallTooltipConfigMap = getTooltipConfig(form);
overallTooltipConfigMap.putAll(tooltipConfigMap); // override parent form's tooltip config
@@ -852,9 +850,7 @@ public abstract class UIBean extends Component {
}
}
else {
if (LOG.isWarnEnabled()) {
LOG.warn("No ancestor Form found, javascript based tooltip will not work, however standard HTML tooltip using alt and title attribute will still work ");
}
LOG.warn("No ancestor Form found, javascript based tooltip will not work, however standard HTML tooltip using alt and title attribute will still work");
}
//TODO: this is to keep backward compatibility, remove once when tooltipConfig is dropped
@@ -886,8 +882,6 @@ public abstract class UIBean extends Component {
if (this.tooltipCssClass != null)
this.addParameter("tooltipCssClass", findString(this.tooltipCssClass));
}
}
evaluateExtraParams();
@@ -947,14 +941,14 @@ public abstract class UIBean extends Component {
protected Map getTooltipConfig(UIBean component) {
Object tooltipConfigObj = component.getParameters().get("tooltipConfig");
Map<String, String> tooltipConfig = new LinkedHashMap<String, String>();
Map<String, String> tooltipConfig = new LinkedHashMap<>();
if (tooltipConfigObj instanceof Map) {
// we get this if its configured using
// 1] UI component's tooltipConfig attribute OR
// 2] <param name="tooltip" value="" /> param tag value attribute
tooltipConfig = new LinkedHashMap<String, String>((Map)tooltipConfigObj);
tooltipConfig = new LinkedHashMap<>((Map) tooltipConfigObj);
} else if (tooltipConfigObj instanceof String) {
// we get this if its configured using
@@ -970,9 +964,7 @@ public abstract class UIBean extends Component {
value = configEntry[1].trim();
tooltipConfig.put(key, value);
} else {
if (LOG.isWarnEnabled()) {
LOG.warn("component " + component + " tooltip config param " + key + " has no value defined, skipped");
}
LOG.warn("component {} tooltip config param {} has no value defined, skipped", component, key);
}
}
}
@@ -23,8 +23,6 @@ package org.apache.struts2.components;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
@@ -110,7 +108,7 @@ import java.io.Writer;
*/
@StrutsTag(name="url", tldTagClass="org.apache.struts2.views.jsp.URLTag", description="This tag is used to create a URL")
public class URL extends ContextBean {
private static final Logger LOG = LogManager.getLogger(URL.class);
private UrlProvider urlProvider;
private UrlRenderer urlRenderer;
@@ -21,18 +21,17 @@
package org.apache.struts2.components;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* <!-- START SNIPPET: javadoc -->
@@ -109,15 +108,13 @@ public class UpDownSelect extends Select {
// override Select's default
if (size == null || size.trim().length() <= 0) {
if (StringUtils.isBlank(size)) {
addParameter("size", "5");
}
if (multiple == null || multiple.trim().length() <= 0) {
if (StringUtils.isBlank(multiple)) {
addParameter("multiple", Boolean.TRUE);
}
if (allowMoveUp != null) {
addParameter("allowMoveUp", findValue(allowMoveUp, Boolean.class));
}
@@ -138,13 +135,12 @@ public class UpDownSelect extends Select {
addParameter("selectAllLabel", findString(selectAllLabel));
}
// inform our form ancestor about this UpDownSelect so the form knows how to
// auto select all options upon it submission
Form ancestorForm = (Form) findAncestor(Form.class);
if (ancestorForm != null) {
// inform form ancestor that we are using a custom onsubmit
// inform form ancestor that we are using a custom onSubmit
enableAncestorFormCustomOnsubmit();
Map m = (Map) ancestorForm.getParameters().get("updownselectIds");
@@ -22,6 +22,7 @@
package org.apache.struts2.components;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import java.io.Writer;
/**
@@ -33,14 +34,14 @@ public interface UrlRenderer {
/**
* Preprocessing step
* @param urlComponent
* @param provider
*/
void beforeRenderUrl(UrlProvider provider);
/**
* Render a URL.
* @param writer A writer that the implementation can use to write the result to.
* @param urlComponent The {@link UrlProvider} component that "owns" this renderer.
* @param provider The {@link UrlProvider} component that "owns" this renderer.
*/
void renderUrl(Writer writer, UrlProvider provider);
@@ -22,17 +22,12 @@
package org.apache.struts2.components.template;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.io.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
@@ -49,7 +44,7 @@ public abstract class BaseTemplateEngine implements TemplateEngine {
*/
public static final String DEFAULT_THEME_PROPERTIES_FILE_NAME = "theme.properties";
private final Map<String, Properties> themeProps = new ConcurrentHashMap<String, Properties>();
private final Map<String, Properties> themeProps = new ConcurrentHashMap<>();
public Map getThemeProps(Template template) {
Properties props = themeProps.get(template.getTheme());
@@ -109,7 +104,7 @@ public abstract class BaseTemplateEngine implements TemplateEngine {
try {
props.load(is);
} catch (IOException e) {
LOG.error("Could not load " + propName, e);
LOG.error("Could not load property with name: {}", propName, e);
} finally {
tryCloseStream(is);
}
@@ -119,9 +114,7 @@ public abstract class BaseTemplateEngine implements TemplateEngine {
try {
is.close();
} catch (IOException io) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to close input stream", io);
}
}
}
@@ -137,9 +130,7 @@ public abstract class BaseTemplateEngine implements TemplateEngine {
try {
return createFileInputStream(propFile);
} catch (FileNotFoundException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to find file in filesystem [" + propFile.getAbsolutePath() + "]");
}
LOG.warn("Unable to find file in filesystem [{}]", propFile.getAbsolutePath());
return null;
}
}
@@ -21,30 +21,26 @@
package org.apache.struts2.components.template;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.SimpleHash;
import freemarker.core.ParseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
/**
* Freemarker based template engine.
@@ -110,11 +106,11 @@ public class FreemarkerTemplateEngine extends BaseTemplateEngine {
if (template == null) {
if (LOG.isErrorEnabled()) {
LOG.error("Could not load the FreeMarker template named '" + templateContext.getTemplate().getName() +"':");
LOG.error("Could not load the FreeMarker template named '{}':", templateContext.getTemplate().getName());
for (Template t : templates) {
LOG.error("Attempted: " + getFinalTemplateName(t));
LOG.error("Attempted: {}", getFinalTemplateName(t));
}
LOG.error("The TemplateLoader provided by the FreeMarker Configuration was a: "+config.getTemplateLoader().getClass().getName());
LOG.error("The TemplateLoader provided by the FreeMarker Configuration was a: {}", config.getTemplateLoader().getClass().getName());
}
if (exception != null) {
throw exception;
@@ -123,9 +119,7 @@ public class FreemarkerTemplateEngine extends BaseTemplateEngine {
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Rendering template " + templateName);
}
LOG.debug("Rendering template: {}", templateName);
ActionInvocation ai = ActionContext.getContext().getActionInvocation();
@@ -164,6 +158,4 @@ public class FreemarkerTemplateEngine extends BaseTemplateEngine {
protected String getSuffix() {
return "ftl";
}
}
}
@@ -21,21 +21,18 @@
package org.apache.struts2.components.template;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.components.Include;
import org.apache.struts2.components.UIBean;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.util.List;
/**
* JSP based template engine.
@@ -53,9 +50,7 @@ public class JspTemplateEngine extends BaseTemplateEngine {
public void renderTemplate(TemplateRenderingContext templateContext) throws Exception {
Template template = templateContext.getTemplate();
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to render template " + template + ", repeating through parents until we succeed");
}
LOG.debug("Trying to render template [{}], repeating through parents until we succeed", template);
UIBean tag = templateContext.getTag();
ValueStack stack = templateContext.getStack();
stack.push(tag);
@@ -77,7 +72,7 @@ public class JspTemplateEngine extends BaseTemplateEngine {
}
if (!success) {
LOG.error("Could not render JSP template " + templateContext.getTemplate());
LOG.error("Could not render JSP template {}", templateContext.getTemplate());
if (exception != null) {
throw exception;
@@ -83,7 +83,7 @@ public class Template implements Cloneable {
* @return a string in the format <code>/dir/theme/name</code>.
*/
public String toString() {
return "/" + dir + "/" + theme + "/" + name;
return new StringBuilder().append("/").append(dir).append("/").append(theme).append("/").append(name).toString();
}
protected Object clone() throws CloneNotSupportedException {
@@ -24,6 +24,7 @@ package org.apache.struts2.components.template;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.StrutsConstants;
import java.util.Collections;
@@ -36,11 +37,13 @@ import java.util.Set;
*/
public class TemplateEngineManager {
/** The default template extenstion is <code>ftl</code>. */
/**
* The default template extension is <code>ftl</code>.
*/
public static final String DEFAULT_TEMPLATE_TYPE = "ftl";
Map<String,EngineFactory> templateEngines = new HashMap<String,EngineFactory>();
Map<String, EngineFactory> templateEngines = new HashMap<>();
Container container;
String defaultTemplateType;
@@ -52,13 +55,12 @@ public class TemplateEngineManager {
@Inject
public void setContainer(Container container) {
this.container = container;
Map<String,EngineFactory> map = new HashMap<String,EngineFactory>();
Map<String, EngineFactory> map = new HashMap<>();
Set<String> prefixes = container.getInstanceNames(TemplateEngine.class);
for (String prefix : prefixes) {
map.put(prefix, new LazyEngineFactory(prefix));
}
this.templateEngines = Collections.unmodifiableMap(map);
}
/**
@@ -89,9 +91,9 @@ public class TemplateEngineManager {
public TemplateEngine getTemplateEngine(Template template, String templateTypeOverride) {
String templateType = DEFAULT_TEMPLATE_TYPE;
String templateName = template.toString();
if (templateName.indexOf(".") > 0) {
templateType = templateName.substring(templateName.indexOf(".") + 1);
} else if (templateTypeOverride !=null && templateTypeOverride.length() > 0) {
if (StringUtils.contains(templateName, ".")) {
templateType = StringUtils.substring(templateName, StringUtils.indexOf(templateName, ".") + 1);
} else if (StringUtils.isNotBlank(templateTypeOverride)) {
templateType = templateTypeOverride;
} else {
String type = defaultTemplateType;
@@ -104,7 +106,7 @@ public class TemplateEngineManager {
/** Abstracts loading of the template engine */
interface EngineFactory {
public TemplateEngine create();
TemplateEngine create();
}
/**
@@ -21,23 +21,21 @@
package org.apache.struts2.components.template;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.velocity.VelocityManager;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
/**
* Velocity based template engine.
@@ -84,7 +82,7 @@ public class VelocityTemplateEngine extends BaseTemplateEngine {
}
if (template == null) {
LOG.error("Could not load template " + templateContext.getTemplate());
LOG.error("Could not load template {}", templateContext.getTemplate());
if (exception != null) {
throw exception;
} else {
@@ -92,9 +90,7 @@ public class VelocityTemplateEngine extends BaseTemplateEngine {
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Rendering template " + templateName);
}
LOG.debug("Rendering template {}", templateName);
Context context = velocityManager.createContext(templateContext.getStack(), req, res);
@@ -4,15 +4,11 @@ import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.config.BeanSelectionProvider;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.inject.Context;
import com.opensymphony.xwork2.inject.Factory;
import com.opensymphony.xwork2.inject.Scope;
import com.opensymphony.xwork2.inject.*;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Properties;
@@ -87,8 +83,6 @@ public abstract class AbstractBeanSelectionProvider implements BeanSelectionProv
}
}
static class ObjectFactoryDelegateFactory implements Factory {
String name;
@@ -107,6 +101,5 @@ public abstract class AbstractBeanSelectionProvider implements BeanSelectionProv
throw new ConfigurationException("Unable to load bean "+type.getName()+" ("+name+")");
}
}
}
}
@@ -22,8 +22,8 @@
package org.apache.struts2.config;
import com.opensymphony.xwork2.util.location.Location;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import java.util.ArrayList;
@@ -56,7 +56,7 @@ public class DefaultSettings implements Settings {
*/
public DefaultSettings() {
ArrayList<Settings> list = new ArrayList<Settings>();
ArrayList<Settings> list = new ArrayList<>();
// stuts.properties, default.properties
try {
@@ -77,7 +77,7 @@ public class DefaultSettings implements Settings {
try {
list.add(new PropertiesSettings(name));
} catch (Exception e) {
LOG.error("DefaultSettings: Could not find " + name + ".properties. Skipping.");
LOG.error("DefaultSettings: Could not find {}.properties. Skipping.", name);
}
}
@@ -69,7 +69,7 @@ class DelegatingSettings implements Settings {
public Iterator list() {
boolean workedAtAll = false;
Set<Object> settingList = new HashSet<Object>();
Set<Object> settingList = new HashSet<>();
UnsupportedOperationException e = null;
for (Settings delegate : delegates) {
@@ -83,7 +83,6 @@ class DelegatingSettings implements Settings {
workedAtAll = true;
} catch (UnsupportedOperationException ex) {
e = ex;
// Try next delegate
}
}
@@ -25,8 +25,8 @@ import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import com.opensymphony.xwork2.util.location.Location;
import com.opensymphony.xwork2.util.location.LocationImpl;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsException;
import java.io.IOException;
@@ -56,9 +56,7 @@ class PropertiesSettings implements Settings {
URL settingsUrl = ClassLoaderUtil.getResource(name + ".properties", getClass());
if (settingsUrl == null) {
if (LOG.isDebugEnabled()) {
LOG.debug(name + ".properties missing");
}
LOG.debug("{}.properties missing", name);
settings = new LocatableProperties();
return;
}
@@ -71,15 +69,13 @@ class PropertiesSettings implements Settings {
in = settingsUrl.openStream();
settings.load(in);
} catch (IOException e) {
throw new StrutsException("Could not load " + name + ".properties:" + e, e);
throw new StrutsException("Could not load " + name + ".properties: " + e, e);
} finally {
if(in != null) {
try {
in.close();
} catch(IOException io) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to close input stream", io);
}
}
}
}
@@ -21,18 +21,6 @@
package org.apache.struts2.config;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider;
@@ -40,8 +28,15 @@ import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.inject.Context;
import com.opensymphony.xwork2.inject.Factory;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
/**
* Override Xwork class so we can use an arbitrary config file
@@ -128,7 +123,7 @@ public class StrutsXmlConfigurationProvider extends XmlConfigurationProvider {
}
}
if (url != null) {
List<URL> list = new ArrayList<URL>();
List<URL> list = new ArrayList<>();
list.add(url);
return list.iterator();
} else {
@@ -139,9 +134,7 @@ public class StrutsXmlConfigurationProvider extends XmlConfigurationProvider {
protected URL findInFileSystem(String fileName) throws IOException {
URL url = null;
File file = new File(fileName);
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to load file " + file);
}
LOG.debug("Trying to load file: {}", file);
// Trying relative path to original file
if (!file.exists()) {
@@ -86,10 +86,10 @@ public class ActionContextCleanUp implements Filter {
try {
Integer count = (Integer)request.getAttribute(COUNTER);
if (count == null) {
count = Integer.valueOf(1);
count = 1;
}
else {
count = Integer.valueOf(count.intValue()+1);
count = count.intValue() + 1;
}
request.setAttribute(COUNTER, count);
@@ -97,9 +97,9 @@ public class ActionContextCleanUp implements Filter {
chain.doFilter(request, response);
} finally {
int counterVal = ((Integer)request.getAttribute(COUNTER)).intValue();
int counterVal = ((Integer) request.getAttribute(COUNTER));
counterVal -= 1;
request.setAttribute(COUNTER, Integer.valueOf(counterVal));
request.setAttribute(COUNTER, counterVal);
cleanUp(request);
}
}
@@ -117,9 +117,7 @@ public class ActionContextCleanUp implements Filter {
// should we clean up yet?
Integer count = (Integer) req.getAttribute(COUNTER);
if (count != null && count > 0 ) {
if (LOG.isDebugEnabled()) {
LOG.debug("skipping cleanup counter="+count);
}
LOG.debug("Skipping cleanup counter: ", count);
return;
}
@@ -23,11 +23,7 @@ package org.apache.struts2.dispatcher;
import javax.servlet.ServletContext;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
@@ -74,7 +70,7 @@ public class ApplicationMap extends AbstractMap implements Serializable {
*/
public Set entrySet() {
if (entries == null) {
entries = new HashSet<Object>();
entries = new HashSet<>();
// Add servlet context attributes
Enumeration enumeration = context.getAttributeNames();
@@ -12,7 +12,7 @@ import com.opensymphony.xwork2.inject.Container;
*/
class ContainerHolder {
private static ThreadLocal<Container> instance = new ThreadLocal<Container>();
private static ThreadLocal<Container> instance = new ThreadLocal<>();
public static void store(Container instance) {
ContainerHolder.instance.set(instance);
@@ -3,9 +3,10 @@ package org.apache.struts2.dispatcher;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.location.Location;
import com.opensymphony.xwork2.util.location.LocationUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import freemarker.template.Template;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.StrutsException;
import org.apache.struts2.views.freemarker.FreemarkerManager;
@@ -39,7 +40,7 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
@Inject(StrutsConstants.STRUTS_DEVMODE)
public void setDevMode(String devMode) {
this.devMode = "true".equalsIgnoreCase(devMode);
this.devMode = BooleanUtils.toBoolean(devMode);
}
public void init(ServletContext ctx) {
@@ -65,9 +66,7 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
// WW-1977: Only put errors in the request when code is a 500 error
if (code == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
// WW-4103: Only logs error when application error occurred, not Struts error
if (LOG.isErrorEnabled()) {
LOG.error("Exception occurred during processing request: {}", e, e.getMessage());
}
LOG.error("Exception occurred during processing request: {}", e, e.getMessage());
// send a http error response to use the servlet defined error handler
// make the exception available to the web.xml defined error page
request.setAttribute("javax.servlet.error.exception", e);
@@ -86,7 +85,7 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
protected void handleErrorInDevMode(HttpServletResponse response, int code, Exception e) {
LOG.debug("Exception occurred during processing request: {}", e, e.getMessage());
try {
List<Throwable> chain = new ArrayList<Throwable>();
List<Throwable> chain = new ArrayList<>();
Throwable cur = e;
chain.add(cur);
while ((cur = cur.getCause()) != null) {
@@ -101,9 +100,7 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
response.getWriter().close();
} catch (Exception exp) {
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Cannot show problem report!", exp);
}
LOG.debug("Cannot show problem report!", exp);
response.sendError(code, "Unable to show problem report:\n" + exp + "\n\n" + LocationUtils.getLocation(exp));
} catch (IOException ex) {
// we're already sending an error, not much else we can do if more stuff breaks
@@ -112,7 +109,7 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
}
protected HashMap<String, Object> createReportData(Exception e, List<Throwable> chain) {
HashMap<String,Object> data = new HashMap<String,Object>();
HashMap<String, Object> data = new HashMap<>();
data.put("exception", e);
data.put("unknown", Location.UNKNOWN);
data.put("chain", chain);
@@ -22,8 +22,9 @@ package org.apache.struts2.dispatcher;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.dispatcher.ng.HostConfig;
@@ -35,11 +36,7 @@ import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.*;
/**
* <b>Default implementation to server static content</b>
@@ -97,33 +94,33 @@ public class DefaultStaticContentLoader implements StaticContentLoader {
/**
* Modify state of StrutsConstants.STRUTS_SERVE_STATIC_CONTENT setting.
*
* @param val
* @param serveStaticContent
* New setting
*/
@Inject(StrutsConstants.STRUTS_SERVE_STATIC_CONTENT)
public void setServeStaticContent(String val) {
serveStatic = "true".equals(val);
public void setServeStaticContent(String serveStaticContent) {
this.serveStatic = BooleanUtils.toBoolean(serveStaticContent);
}
/**
* Modify state of StrutsConstants.STRUTS_SERVE_STATIC_BROWSER_CACHE
* setting.
*
* @param val
* @param serveStaticBrowserCache
* New setting
*/
@Inject(StrutsConstants.STRUTS_SERVE_STATIC_BROWSER_CACHE)
public void setServeStaticBrowserCache(String val) {
serveStaticBrowserCache = "true".equals(val);
public void setServeStaticBrowserCache(String serveStaticBrowserCache) {
this.serveStaticBrowserCache = BooleanUtils.toBoolean(serveStaticBrowserCache);
}
/**
* Modify state of StrutsConstants.STRUTS_I18N_ENCODING setting.
* @param val New setting
* @param encoding New setting
*/
@Inject(StrutsConstants.STRUTS_I18N_ENCODING)
public void setEncoding(String val) {
encoding = val;
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/*
@@ -155,7 +152,7 @@ public class DefaultStaticContentLoader implements StaticContentLoader {
if (packages == null) {
return Collections.emptyList();
}
List<String> pathPrefixes = new ArrayList<String>();
List<String> pathPrefixes = new ArrayList<>();
StringTokenizer st = new StringTokenizer(packages, ", \n\t");
while (st.hasMoreTokens()) {
@@ -213,9 +210,7 @@ public class DefaultStaticContentLoader implements StaticContentLoader {
try {
ifModifiedSince = request.getDateHeader("If-Modified-Since");
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Invalid If-Modified-Since header value: '{}', ignoring", request.getHeader("If-Modified-Since"));
}
LOG.warn("Invalid If-Modified-Since header value: '{}', ignoring", request.getHeader("If-Modified-Since"));
}
long lastModifiedMillis = lastModifiedCal.getTimeInMillis();
long now = cal.getTimeInMillis();
@@ -38,9 +38,11 @@ import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.util.location.LocatableProperties;
import com.opensymphony.xwork2.util.location.Location;
import com.opensymphony.xwork2.util.location.LocationUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.opensymphony.xwork2.util.profiling.UtilTimerStack;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.StrutsException;
@@ -82,13 +84,12 @@ public class Dispatcher {
/**
* Provide a thread local instance.
*/
private static ThreadLocal<Dispatcher> instance = new ThreadLocal<Dispatcher>();
private static ThreadLocal<Dispatcher> instance = new ThreadLocal<>();
/**
* Store list of DispatcherListeners.
*/
private static List<DispatcherListener> dispatcherListeners =
new CopyOnWriteArrayList<DispatcherListener>();
private static List<DispatcherListener> dispatcherListeners = new CopyOnWriteArrayList<>();
/**
* Store ConfigurationManager instance, set on init.
@@ -220,7 +221,7 @@ public class Dispatcher {
*/
@Inject(value=StrutsConstants.STRUTS_DISABLE_REQUEST_ATTRIBUTE_VALUE_STACK_LOOKUP, required=false)
public void setDisableRequestAttributeValueStackLookup(String disableRequestAttributeValueStackLookup) {
this.disableRequestAttributeValueStackLookup = "true".equalsIgnoreCase(disableRequestAttributeValueStackLookup);
this.disableRequestAttributeValueStackLookup = BooleanUtils.toBoolean(disableRequestAttributeValueStackLookup);
}
/**
@@ -278,9 +279,7 @@ public class Dispatcher {
// clean up ObjectFactory
ObjectFactory objectFactory = getContainer().getInstance(ObjectFactory.class);
if (objectFactory == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Object Factory is null, something is seriously wrong, no clean up will be performed");
}
}
if (objectFactory instanceof ObjectFactoryDestroyable) {
try {
@@ -288,7 +287,7 @@ public class Dispatcher {
}
catch(Exception e) {
// catch any exception that may occurred during destroy() and log it
LOG.error("exception occurred while destroying ObjectFactory [{}]", e, objectFactory.toString());
LOG.error("Exception occurred while destroying ObjectFactory [{}]", objectFactory.toString(), e);
}
}
@@ -303,7 +302,7 @@ public class Dispatcher {
}
// clean up all interceptors by calling their destroy() method
Set<Interceptor> interceptors = new HashSet<Interceptor>();
Set<Interceptor> interceptors = new HashSet<>();
Collection<PackageConfig> packageConfigs = configurationManager.getConfiguration().getPackageConfigs().values();
for (PackageConfig packageConfig : packageConfigs) {
for (Object config : packageConfig.getAllInterceptorConfigs().values()) {
@@ -441,11 +440,8 @@ public class Dispatcher {
private void init_CheckWebLogicWorkaround(Container container) {
// test whether param-access workaround needs to be enabled
if (servletContext != null && servletContext.getServerInfo() != null
&& servletContext.getServerInfo().contains("WebLogic")) {
if (LOG.isInfoEnabled()) {
LOG.info("WebLogic server detected. Enabling Struts parameter access work-around.");
}
if (servletContext != null && StringUtils.contains(servletContext.getServerInfo(), "WebLogic")) {
LOG.info("WebLogic server detected. Enabling Struts parameter access work-around.");
paramsWorkaroundEnabled = true;
} else {
paramsWorkaroundEnabled = "true".equals(container.getInstance(String.class,
@@ -484,8 +480,7 @@ public class Dispatcher {
errorHandler.init(servletContext);
} catch (Exception ex) {
if (LOG.isErrorEnabled())
LOG.error("Dispatcher initialization failed", ex);
LOG.error("Dispatcher initialization failed", ex);
throw new StrutsException(ex);
}
}
@@ -591,7 +586,7 @@ public class Dispatcher {
uri = uri + "?" + request.getQueryString();
}
if (devMode) {
LOG.error("Could not find action or result\n{}", uri, e);
LOG.error("Could not find action or result: {}", uri, e);
} else if (LOG.isWarnEnabled()) {
LOG.warn("Could not find action or result: {}", uri, e);
}
@@ -675,7 +670,7 @@ public class Dispatcher {
Map applicationMap,
HttpServletRequest request,
HttpServletResponse response) {
HashMap<String,Object> extraContext = new HashMap<String,Object>();
HashMap<String, Object> extraContext = new HashMap<>();
extraContext.put(ActionContext.PARAMETERS, new HashMap(parameterMap));
extraContext.put(ActionContext.SESSION, sessionMap);
extraContext.put(ActionContext.APPLICATION, applicationMap);
@@ -715,9 +710,7 @@ public class Dispatcher {
if (saveDir.equals("")) {
File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
if (LOG.isInfoEnabled()) {
LOG.info("Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir");
}
if (tempdir != null) {
saveDir = tempdir.toString();
@@ -737,17 +730,13 @@ public class Dispatcher {
if (devMode) {
LOG.error(logMessage);
} else {
if (LOG.isWarnEnabled()) {
LOG.warn(logMessage);
}
LOG.warn(logMessage);
}
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("saveDir=" + saveDir);
}
LOG.debug("saveDir={}", saveDir);
return saveDir;
}
@@ -794,7 +783,7 @@ public class Dispatcher {
request.setCharacterEncoding(encoding);
}
} catch (Exception e) {
LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);
LOG.error("Error setting character encoding to '{}' - ignoring.", encoding, e);
}
}
@@ -170,7 +170,7 @@ public class FilterDispatcher implements StrutsStatics, Filter {
/**
* Maintains per-request override of devMode configuration.
*/
private static ThreadLocal<Boolean> devModeOverride = new InheritableThreadLocal<Boolean>();
private static ThreadLocal<Boolean> devModeOverride = new InheritableThreadLocal<>();
/**
* Initializes the filter by creating a default dispatcher
@@ -226,7 +226,7 @@ public class FilterDispatcher implements StrutsStatics, Filter {
*/
public void destroy() {
if (dispatcher == null) {
log.warn("something is seriously wrong, Dispatcher is not initialized (null) ");
log.warn("something is seriously wrong, Dispatcher is not initialized (null)");
} else {
try {
dispatcher.cleanup();
@@ -243,10 +243,8 @@ public class FilterDispatcher implements StrutsStatics, Filter {
*
* @param devMode the override value
*/
public static void overrideDevMode(
boolean devMode)
{
devModeOverride.set(Boolean.valueOf(devMode));
public static void overrideDevMode(boolean devMode) {
devModeOverride.set(devMode);
}
/**
@@ -265,7 +263,7 @@ public class FilterDispatcher implements StrutsStatics, Filter {
* @return Initialized Dispatcher
*/
protected Dispatcher createDispatcher(FilterConfig filterConfig) {
Map<String, String> params = new HashMap<String, String>();
Map<String, String> params = new HashMap<>();
for (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
String value = filterConfig.getInitParameter(name);
@@ -26,8 +26,8 @@ import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletResponse;
@@ -83,7 +83,7 @@ public class HttpHeaderResult implements Result {
private static final Logger LOG = LogManager.getLogger(HttpHeaderResult.class);
/**
* This result type doesn't have a default param, null is ok to reduce noice in logs
* This result type doesn't have a default param, null is ok to reduce noise in logs
*/
public static final String DEFAULT_PARAM = null;
@@ -95,7 +95,7 @@ public class HttpHeaderResult implements Result {
public HttpHeaderResult() {
super();
headers = new HashMap<String, String>();
headers = new HashMap<>();
}
public HttpHeaderResult(int status) {
@@ -195,9 +195,7 @@ public class HttpHeaderResult implements Result {
try {
errorCode = Integer.parseInt(parse ? TextParseUtil.translateVariables(error, stack) : error);
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Cannot parse errorCode [{}] value as Integer!", error, e);
}
LOG.error("Cannot parse errorCode [{}] value as Integer!", error, e);
}
if (errorCode != -1) {
if (errorMessage != null) {
@@ -22,8 +22,8 @@
package org.apache.struts2.dispatcher;
import com.opensymphony.xwork2.ActionInvocation;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
@@ -132,9 +132,7 @@ public class PlainTextResult extends StrutsResultSupport {
} else {
reader = new InputStreamReader(resourceAsStream);
}
if (resourceAsStream != null) {
sendStream(writer, reader);
}
sendStream(writer, reader);
} finally {
if (reader != null)
reader.close();
@@ -152,9 +150,7 @@ public class PlainTextResult extends StrutsResultSupport {
protected void logWrongStream(String finalLocation, InputStream resourceAsStream) {
if (resourceAsStream == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Resource at location [" + finalLocation + "] cannot be obtained (return null) from ServletContext !!! ");
}
LOG.warn("Resource at location [{}] cannot be obtained (return null) from ServletContext !!!", finalLocation);
}
}
@@ -191,13 +187,10 @@ public class PlainTextResult extends StrutsResultSupport {
if (Charset.isSupported(charSet)) {
charset = Charset.forName(charSet);
} else {
if (LOG.isWarnEnabled()) {
LOG.warn("charset [" + charSet + "] is not recognized ");
}
LOG.warn("charset [{}] is not recognized", charset);
charset = null;
}
}
return charset;
}
}
@@ -39,7 +39,6 @@ public class RequestMap extends AbstractMap implements Serializable {
private Set<Object> entries;
private HttpServletRequest request;
/**
* Saves the request to use as the backing for getting and setting values
*
@@ -70,7 +69,7 @@ public class RequestMap extends AbstractMap implements Serializable {
*/
public Set entrySet() {
if (entries == null) {
entries = new HashSet<Object>();
entries = new HashSet<>();
Enumeration enumeration = request.getAttributeNames();
@@ -23,10 +23,10 @@ package org.apache.struts2.dispatcher;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.views.util.UrlHelper;
@@ -122,9 +122,7 @@ public class ServletDispatcherResult extends StrutsResultSupport {
* HTTP request.
*/
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Forwarding to location " + finalLocation);
}
LOG.debug("Forwarding to location: {}", finalLocation);
PageContext pageContext = ServletActionContext.getPageContext();
@@ -25,10 +25,10 @@ import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.opensymphony.xwork2.util.reflection.ReflectionException;
import com.opensymphony.xwork2.util.reflection.ReflectionExceptionHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
@@ -106,7 +106,7 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec
protected ActionMapper actionMapper;
protected int statusCode = SC_FOUND;
protected boolean suppressEmptyParameters = false;
protected Map<String, Object> requestParameters = new LinkedHashMap<String, Object>();
protected Map<String, Object> requestParameters = new LinkedHashMap<>();
protected String anchor;
private UrlHelper urlHelper;
@@ -221,10 +221,8 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec
}
finalLocation = response.encodeRedirectURL(tmpLocation.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("Redirecting to finalLocation " + finalLocation);
}
LOG.debug("Redirecting to finalLocation: {}", finalLocation);
sendRedirect(response, finalLocation);
}
@@ -21,17 +21,10 @@
package org.apache.struts2.dispatcher;
import org.apache.struts2.components.Submit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
@@ -110,9 +103,9 @@ public class SessionMap<K, V> extends AbstractMap<K, V> implements Serializable
synchronized (session.getId().intern()) {
if (entries == null) {
entries = new HashSet<Map.Entry<K, V>>();
entries = new HashSet<>();
Enumeration<? extends Object> enumeration = session.getAttributeNames();
Enumeration<?> enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
final String key = enumeration.nextElement().toString();
@@ -21,15 +21,14 @@
package org.apache.struts2.dispatcher;
import java.io.InputStream;
import java.io.OutputStream;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.ActionInvocation;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.opensymphony.xwork2.util.ValueStack;
import java.io.InputStream;
import java.io.OutputStream;
/**
* <!-- START SNIPPET: description -->
@@ -259,9 +258,7 @@ public class StreamResult extends StrutsResultSupport {
}
}
catch(NumberFormatException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("failed to recongnize "+_contentLength+" as a number, contentLength header will not be set", e);
}
LOG.warn("failed to recognize {} as a number, contentLength header will not be set", _contentLength, e);
}
}
@@ -279,24 +276,18 @@ public class StreamResult extends StrutsResultSupport {
// Get the outputstream
oOutput = oResponse.getOutputStream();
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming result [" + inputName + "] type=[" + contentType + "] length=[" + contentLength +
"] content-disposition=[" + contentDisposition + "] charset=[" + contentCharSet + "]");
}
LOG.debug("Streaming result [{}] type=[{}] length=[{}] content-disposition=[{}] charset=[{}]",
inputName, contentType, contentLength, contentDisposition, contentCharSet);
// Copy input to output
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming to output buffer +++ START +++");
}
byte[] oBuff = new byte[bufferSize];
int iSize;
while (-1 != (iSize = inputStream.read(oBuff))) {
oOutput.write(oBuff, 0, iSize);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming to output buffer +++ END +++");
}
// Flush
oOutput.flush();
}
@@ -334,7 +325,7 @@ public class StreamResult extends StrutsResultSupport {
Integer bufferSize = (Integer) stack.findValue("bufferSize", Integer.class);
if (bufferSize != null) {
setBufferSize(bufferSize.intValue());
setBufferSize(bufferSize);
}
if (contentCharSet != null ) {
@@ -21,19 +21,18 @@
package org.apache.struts2.dispatcher;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.TextParseUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.TextParseUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/**
* <!-- START SNIPPET: javadoc -->
@@ -227,7 +226,7 @@ public abstract class StrutsResultSupport implements Result, StrutsStatics {
excludeEmptyElements,
new EncodingParsedValueEvaluator());
} else {
Collection<String> collection = new ArrayList<String>(1);
Collection<String> collection = new ArrayList<>(1);
collection.add(param);
return collection;
}
@@ -246,9 +245,7 @@ public abstract class StrutsResultSupport implements Result, StrutsStatics {
return URLEncoder.encode(parsedValue, DEFAULT_URL_ENCODING);
}
catch(UnsupportedEncodingException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("error while trying to encode ["+parsedValue+"]", e);
}
LOG.warn("error while trying to encode [{}]", parsedValue, e);
}
}
}
@@ -25,8 +25,8 @@ import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.views.JspSupportServlet;
@@ -159,7 +159,7 @@ public class VelocityResult extends StrutsResultSupport {
// to do it all the time (WW-829). Since Velocity support is being deprecated, we'll oblige :)
writer.flush();
} catch (Exception e) {
LOG.error("Unable to render Velocity Template, '{}'", finalLocation, e);
LOG.error("Unable to render velocity template: '{}'", finalLocation, e);
throw e;
} finally {
if (usedJspFactory) {
@@ -24,6 +24,7 @@ package org.apache.struts2.dispatcher.mapper;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
@@ -49,18 +50,16 @@ public class CompositeActionMapper implements ActionMapper {
private static final Logger LOG = LogManager.getLogger(CompositeActionMapper.class);
protected List<ActionMapper> actionMappers = new LinkedList<ActionMapper>();
protected List<ActionMapper> actionMappers = new LinkedList<>();
@Inject
public CompositeActionMapper(Container container,
@Inject(value = StrutsConstants.STRUTS_MAPPER_COMPOSITE) String list) {
if (list != null) {
String[] arr = list.split(",");
for (String name : arr) {
Object obj = container.getInstance(ActionMapper.class, name);
if (obj != null) {
actionMappers.add((ActionMapper) obj);
}
String[] arr = StringUtils.split(StringUtils.trimToEmpty(list), ",");
for (String name : arr) {
Object obj = container.getInstance(ActionMapper.class, name);
if (obj != null) {
actionMappers.add((ActionMapper) obj);
}
}
}
@@ -69,21 +68,15 @@ public class CompositeActionMapper implements ActionMapper {
for (ActionMapper actionMapper : actionMappers) {
ActionMapping actionMapping = actionMapper.getMapping(request, configManager);
if (LOG.isDebugEnabled()) {
LOG.debug("Using ActionMapper "+actionMapper);
}
LOG.debug("Using ActionMapper: {}", actionMapper);
if (actionMapping == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("ActionMapper "+actionMapper+" failed to return an ActionMapping (null)");
}
LOG.debug("ActionMapper {} failed to return an ActionMapping (null)", actionMapper);
}
else {
return actionMapping;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("exhausted from ActionMapper that could return an ActionMapping");
}
LOG.debug("exhausted from ActionMapper that could return an ActionMapping");
return null;
}
@@ -91,21 +84,15 @@ public class CompositeActionMapper implements ActionMapper {
for (ActionMapper actionMapper : actionMappers) {
ActionMapping actionMapping = actionMapper.getMappingFromActionName(actionName);
if (LOG.isDebugEnabled()) {
LOG.debug("Using ActionMapper "+actionMapper);
}
LOG.debug("Using ActionMapper: {}", actionMapper);
if (actionMapping == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("ActionMapper "+actionMapper+" failed to return an ActionMapping (null)");
}
LOG.debug("ActionMapper {} failed to return an ActionMapping (null)", actionMapper);
}
else {
return actionMapping;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("exhausted from ActionMapper that could return an ActionMapping");
}
LOG.debug("exhausted from ActionMapper that could return an ActionMapping");
return null;
}
@@ -113,21 +100,15 @@ public class CompositeActionMapper implements ActionMapper {
for (ActionMapper actionMapper : actionMappers) {
String uri = actionMapper.getUriFromActionMapping(mapping);
if (LOG.isDebugEnabled()) {
LOG.debug("Using ActionMapper "+actionMapper);
}
LOG.debug("Using ActionMapper: {}", actionMapper);
if (uri == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("ActionMapper "+actionMapper+" failed to return an ActionMapping (null)");
}
LOG.debug("ActionMapper {} failed to return an ActionMapping (null)", actionMapper);
}
else {
return uri;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("exhausted from ActionMapper that could return a uri");
}
LOG.debug("exhausted from ActionMapper that could return an ActionMapping");
return null;
}
}
@@ -27,21 +27,17 @@ import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.util.PrefixTrie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.regex.Pattern;
/**
@@ -185,18 +181,18 @@ public class DefaultActionMapper implements ActionMapper {
}
@Inject(StrutsConstants.STRUTS_ENABLE_DYNAMIC_METHOD_INVOCATION)
public void setAllowDynamicMethodCalls(String allow) {
allowDynamicMethodCalls = "true".equalsIgnoreCase(allow);
public void setAllowDynamicMethodCalls(String enableDynamicMethodCalls) {
this.allowDynamicMethodCalls = BooleanUtils.toBoolean(enableDynamicMethodCalls);
}
@Inject(StrutsConstants.STRUTS_ENABLE_SLASHES_IN_ACTION_NAMES)
public void setSlashesInActionNames(String allow) {
allowSlashesInActionNames = "true".equals(allow);
public void setSlashesInActionNames(String enableSlashesInActionNames) {
this.allowSlashesInActionNames = BooleanUtils.toBoolean(enableSlashesInActionNames);
}
@Inject(StrutsConstants.STRUTS_ALWAYS_SELECT_FULL_NAMESPACE)
public void setAlwaysSelectFullNamespace(String val) {
this.alwaysSelectFullNamespace = "true".equals(val);
public void setAlwaysSelectFullNamespace(String alwaysSelectFullNamespace) {
this.alwaysSelectFullNamespace = BooleanUtils.toBoolean(alwaysSelectFullNamespace);
}
@Inject(value = StrutsConstants.STRUTS_ALLOWED_ACTION_NAMES, required = false)
@@ -206,12 +202,12 @@ public class DefaultActionMapper implements ActionMapper {
@Inject(value = StrutsConstants.STRUTS_MAPPER_ACTION_PREFIX_ENABLED)
public void setAllowActionPrefix(String allowActionPrefix) {
this.allowActionPrefix = "true".equalsIgnoreCase(allowActionPrefix);
this.allowActionPrefix = BooleanUtils.toBoolean(allowActionPrefix);
}
@Inject(value = StrutsConstants.STRUTS_MAPPER_ACTION_PREFIX_CROSSNAMESPACES)
public void setAllowActionCrossNamespaceAccess(String allowActionCrossNamespaceAccess) {
this.allowActionCrossNamespaceAccess = "true".equalsIgnoreCase(allowActionCrossNamespaceAccess);
this.allowActionCrossNamespaceAccess = BooleanUtils.toBoolean(allowActionCrossNamespaceAccess);
}
@Inject
@@ -221,8 +217,8 @@ public class DefaultActionMapper implements ActionMapper {
@Inject(StrutsConstants.STRUTS_ACTION_EXTENSION)
public void setExtensions(String extensions) {
if (extensions != null && !"".equals(extensions)) {
List<String> list = new ArrayList<String>();
if (StringUtils.isNotEmpty(extensions)) {
List<String> list = new ArrayList<>();
String[] tokens = extensions.split(",");
Collections.addAll(list, tokens);
if (extensions.endsWith(",")) {
@@ -292,7 +288,7 @@ public class DefaultActionMapper implements ActionMapper {
*/
public void handleSpecialParameters(HttpServletRequest request, ActionMapping mapping) {
// handle special parameter prefixes.
Set<String> uniqueParameters = new HashSet<String>();
Set<String> uniqueParameters = new HashSet<>();
Map parameterMap = request.getParameterMap();
for (Object o : parameterMap.keySet()) {
String key = (String) o;
@@ -3,8 +3,9 @@ package org.apache.struts2.dispatcher.mapper;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.StrutsConstants;
@@ -44,7 +45,7 @@ public class PrefixBasedActionMapper extends DefaultActionMapper implements Acti
private static final Logger LOG = LogManager.getLogger(PrefixBasedActionMapper.class);
protected Container container;
protected Map<String, ActionMapper> actionMappers = new HashMap<String, ActionMapper>();
protected Map<String, ActionMapper> actionMappers = new HashMap<>();
@Inject
public void setContainer(Container container) {
@@ -53,19 +54,17 @@ public class PrefixBasedActionMapper extends DefaultActionMapper implements Acti
@Inject(StrutsConstants.PREFIX_BASED_MAPPER_CONFIGURATION)
public void setPrefixBasedActionMappers(String list) {
if (list != null) {
String[] mappers = list.split(",");
for (String mapper : mappers) {
String[] thisMapper = mapper.split(":");
if ((thisMapper != null) && (thisMapper.length == 2)) {
String mapperPrefix = thisMapper[0].trim();
String mapperName = thisMapper[1].trim();
Object obj = container.getInstance(ActionMapper.class, mapperName);
if (obj != null) {
actionMappers.put(mapperPrefix, (ActionMapper) obj);
} else {
LOG.debug("invalid PrefixBasedActionMapper config entry: [{}]", mapper);
}
String[] mappers = StringUtils.split(StringUtils.trimToEmpty(list), ",");
for (String mapper : mappers) {
String[] thisMapper = mapper.split(":");
if (thisMapper.length == 2) {
String mapperPrefix = thisMapper[0].trim();
String mapperName = thisMapper[1].trim();
Object obj = container.getInstance(ActionMapper.class, mapperName);
if (obj != null) {
actionMappers.put(mapperPrefix, (ActionMapper) obj);
} else {
LOG.debug("invalid PrefixBasedActionMapper config entry: [{}]", mapper);
}
}
}
@@ -104,9 +103,7 @@ public class PrefixBasedActionMapper extends DefaultActionMapper implements Acti
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("No ActionMapper found");
}
LOG.debug("No ActionMapper found");
return null;
}
@@ -124,9 +121,7 @@ public class PrefixBasedActionMapper extends DefaultActionMapper implements Acti
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("ActionMapper failed to return a uri");
}
LOG.debug("ActionMapper failed to return a uri");
return null;
}
@@ -23,6 +23,7 @@ package org.apache.struts2.dispatcher.mapper;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
@@ -62,18 +63,16 @@ public class Restful2ActionMapper extends DefaultActionMapper {
}
String actionName = mapping.getName();
String id = null;
// Only try something if the action name is specified
if (actionName != null && actionName.length() > 0) {
if (StringUtils.isNotBlank(actionName)) {
int lastSlashPos = actionName.lastIndexOf('/');
if (lastSlashPos > -1) {
id = actionName.substring(lastSlashPos+1);
}
// If a method hasn't been explicitly named, try to guess using ReST-style patterns
if (mapping.getMethod() == null) {
@@ -124,7 +123,7 @@ public class Restful2ActionMapper extends DefaultActionMapper {
int actionSlashPos = actionName.lastIndexOf('/', lastSlashPos - 1);
if (actionSlashPos > 0 && actionSlashPos < lastSlashPos) {
String params = actionName.substring(0, actionSlashPos);
HashMap<String,String> parameters = new HashMap<String,String>();
HashMap<String, String> parameters = new HashMap<>();
try {
StringTokenizer st = new StringTokenizer(params, "/");
boolean isNameTok = true;
@@ -152,9 +151,7 @@ public class Restful2ActionMapper extends DefaultActionMapper {
mapping.getParams().putAll(parameters);
}
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to determine parameters from the url", e);
}
}
mapping.setName(actionName.substring(actionSlashPos+1));
}
@@ -52,7 +52,7 @@ public class RestfulActionMapper implements ActionMapper {
}
String actionName = uri.substring(1, nextSlash);
Map<String, Object> parameters = new HashMap<String, Object>();
Map<String, Object> parameters = new HashMap<>();
try {
StringTokenizer st = new StringTokenizer(uri.substring(nextSlash), "/");
boolean isNameTok = true;
@@ -80,9 +80,7 @@ public class RestfulActionMapper implements ActionMapper {
}
}
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Cannot determine url parameters", e);
}
}
return new ActionMapping(actionName, "", "", parameters);
@@ -24,8 +24,6 @@ package org.apache.struts2.dispatcher.multipart;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
@@ -33,6 +31,8 @@ import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import javax.servlet.http.HttpServletRequest;
@@ -40,14 +40,7 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
* Multipart form data request adapter for Jakarta Commons Fileupload package.
@@ -57,13 +50,13 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
static final Logger LOG = LogManager.getLogger(JakartaMultiPartRequest.class);
// maps parameter name -> List of FileItem objects
protected Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>();
protected Map<String, List<FileItem>> files = new HashMap<>();
// maps parameter name -> List of param values
protected Map<String, List<String>> params = new HashMap<String, List<String>>();
protected Map<String, List<String>> params = new HashMap<>();
// any errors while processing this request
protected List<String> errors = new ArrayList<String>();
protected List<String> errors = new ArrayList<>();
protected long maxSize;
private Locale defaultLocale = Locale.ENGLISH;
@@ -91,17 +84,13 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
setLocale(request);
processUpload(request, saveDir);
} catch (FileUploadBase.SizeLimitExceededException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Request exceeded size limit!", e);
}
LOG.warn("Request exceeded size limit!", e);
String errorMessage = buildErrorMessage(e, new Object[]{e.getPermittedSize(), e.getActualSize()});
if (!errors.contains(errorMessage)) {
errors.add(errorMessage);
}
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to parse request", e);
}
LOG.warn("Unable to parse request", e);
String errorMessage = buildErrorMessage(e, new Object[]{});
if (!errors.contains(errorMessage)) {
errors.add(errorMessage);
@@ -145,7 +134,7 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
if (files.get(item.getFieldName()) != null) {
values = files.get(item.getFieldName());
} else {
values = new ArrayList<FileItem>();
values = new ArrayList<>();
}
values.add(item);
@@ -159,7 +148,7 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
if (params.get(item.getFieldName()) != null) {
values = params.get(item.getFieldName());
} else {
values = new ArrayList<String>();
values = new ArrayList<>();
}
// note: see http://jira.opensymphony.com/browse/WW-633
@@ -214,7 +203,7 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
return null;
}
List<String> contentTypes = new ArrayList<String>(items.size());
List<String> contentTypes = new ArrayList<>(items.size());
for (FileItem fileItem : items) {
contentTypes.add(fileItem.getContentType());
}
@@ -232,16 +221,14 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
return null;
}
List<File> fileList = new ArrayList<File>(items.size());
List<File> fileList = new ArrayList<>(items.size());
for (FileItem fileItem : items) {
File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
if (fileItem.isInMemory() && storeLocation != null && !storeLocation.exists()) {
try {
storeLocation.createNewFile();
} catch (IOException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Cannot write uploaded empty file to disk: " + storeLocation.getAbsolutePath(), e);
}
LOG.error("Cannot write uploaded empty file to disk: {}", storeLocation.getAbsolutePath(), e);
}
}
fileList.add(storeLocation);
@@ -260,7 +247,7 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
return null;
}
List<String> fileNames = new ArrayList<String>(items.size());
List<String> fileNames = new ArrayList<>(items.size());
for (FileItem fileItem : items) {
fileNames.add(getCanonicalName(fileItem.getName()));
}
@@ -278,7 +265,7 @@ public class JakartaMultiPartRequest implements MultiPartRequest {
return null;
}
List<String> fileNames = new ArrayList<String>(items.size());
List<String> fileNames = new ArrayList<>(items.size());
for (FileItem fileItem : items) {
fileNames.add(((DiskFileItem) fileItem).getStoreLocation().getName());
}
@@ -3,31 +3,19 @@ package org.apache.struts2.dispatcher.multipart;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.io.*;
import java.util.*;
/**
* Multi-part form data request adapter for Jakarta Commons FileUpload package that
@@ -50,22 +38,22 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
/**
* Map between file fields and file data.
*/
private Map<String, List<FileInfo>> fileInfos = new HashMap<String, List<FileInfo>>();
private Map<String, List<FileInfo>> fileInfos = new HashMap<>();
/**
* Map between non-file fields and values.
*/
private Map<String, List<String>> parameters = new HashMap<String, List<String>>();
private Map<String, List<String>> parameters = new HashMap<>();
/**
* Internal list of raised errors to be passed to the the Struts2 framework.
*/
private List<String> errors = new ArrayList<String>();
private List<String> errors = new ArrayList<>();
/**
* Internal list of non-critical messages to be passed to the Struts2 framework.
*/
private List<String> messages = new ArrayList<String>();
private List<String> messages = new ArrayList<>();
/**
* Specifies the maximum size of the entire request.
@@ -121,8 +109,9 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
for (FileInfo fileInfo : fileInfos.get(fieldName)) {
File file = fileInfo.getFile();
LOG.debug("Deleting file '{}'.", file.getName());
if (!file.delete())
if (!file.delete()) {
LOG.warn("There was a problem attempting to delete file '{}'.", file.getName());
}
}
}
}
@@ -132,12 +121,14 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
public String[] getContentType(String fieldName) {
List<FileInfo> infos = fileInfos.get(fieldName);
if (infos == null)
if (infos == null) {
return null;
}
List<String> types = new ArrayList<String>(infos.size());
for (FileInfo fileInfo : infos)
List<String> types = new ArrayList<>(infos.size());
for (FileInfo fileInfo : infos) {
types.add(fileInfo.getContentType());
}
return types.toArray(new String[types.size()]);
}
@@ -163,12 +154,14 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
public File[] getFile(String fieldName) {
List<FileInfo> infos = fileInfos.get(fieldName);
if (infos == null)
if (infos == null) {
return null;
}
List<File> files = new ArrayList<File>(infos.size());
for (FileInfo fileInfo : infos)
List<File> files = new ArrayList<>(infos.size());
for (FileInfo fileInfo : infos) {
files.add(fileInfo.getFile());
}
return files.toArray(new File[files.size()]);
}
@@ -178,12 +171,14 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
public String[] getFileNames(String fieldName) {
List<FileInfo> infos = fileInfos.get(fieldName);
if (infos == null)
if (infos == null) {
return null;
}
List<String> names = new ArrayList<String>(infos.size());
for (FileInfo fileInfo : infos)
List<String> names = new ArrayList<>(infos.size());
for (FileInfo fileInfo : infos) {
names.add(getCanonicalName(fileInfo.getOriginalName()));
}
return names.toArray(new String[names.size()]);
}
@@ -200,12 +195,14 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
public String[] getFilesystemName(String fieldName) {
List<FileInfo> infos = fileInfos.get(fieldName);
if (infos == null)
if (infos == null) {
return null;
}
List<String> names = new ArrayList<String>(infos.size());
for (FileInfo fileInfo : infos)
List<String> names = new ArrayList<>(infos.size());
for (FileInfo fileInfo : infos) {
names.add(fileInfo.getFile().getName());
}
return names.toArray(new String[names.size()]);
}
@@ -215,8 +212,9 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
public String getParameter(String name) {
List<String> values = parameters.get(name);
if (values != null && values.size() > 0)
if (values != null && values.size() > 0) {
return values.get(0);
}
return null;
}
@@ -232,24 +230,25 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
public String[] getParameterValues(String name) {
List<String> values = parameters.get(name);
if (values != null && values.size() > 0)
if (values != null && values.size() > 0) {
return values.toArray(new String[values.size()]);
}
return null;
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#parse(javax.servlet.http.HttpServletRequest, java.lang.String)
*/
public void parse(HttpServletRequest request, String saveDir)
throws IOException {
public void parse(HttpServletRequest request, String saveDir) throws IOException {
try {
setLocale(request);
processUpload(request, saveDir);
} catch (Exception e) {
e.printStackTrace();
LOG.warn("Error occurred during parsing of multi part request", e);
String errorMessage = buildErrorMessage(e, new Object[]{});
if (!errors.contains(errorMessage))
if (!errors.contains(errorMessage)) {
errors.add(errorMessage);
}
}
}
@@ -260,8 +259,9 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
* @param request
*/
protected void setLocale(HttpServletRequest request) {
if (defaultLocale == null)
if (defaultLocale == null) {
defaultLocale = request.getLocale();
}
}
/**
@@ -271,8 +271,7 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
* @param saveDir
* @throws Exception
*/
private void processUpload(HttpServletRequest request, String saveDir)
throws Exception {
private void processUpload(HttpServletRequest request, String saveDir) throws Exception {
// Sanity check that the request is a multi-part/form-data request.
if (ServletFileUpload.isMultipartContent(request)) {
@@ -313,7 +312,7 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
processFileItemStreamAsFileField(itemStream, saveDir);
}
} catch (IOException e) {
e.printStackTrace();
LOG.warn("Error occurred during process upload", e);
}
}
}
@@ -329,8 +328,9 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
// if maxSize is specified as -1, there is no sanity check and it's
// safe to return true for any request, delegating the failure
// checks later in the upload process.
if (maxSize == -1 || request == null)
if (maxSize == -1 || request == null) {
return true;
}
return request.getContentLength() < maxSize;
}
@@ -343,8 +343,10 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
private long getRequestSize(HttpServletRequest request) {
long requestSize = 0;
if (request != null)
if (request != null) {
requestSize = request.getContentLength();
}
return requestSize;
}
@@ -358,8 +360,9 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
String exceptionMessage = "Skipped file " + fileName + "; request size limit exceeded.";
FileSizeLimitExceededException exception = new FileUploadBase.FileSizeLimitExceededException(exceptionMessage, getRequestSize(request), maxSize);
String message = buildErrorMessage(exception, new Object[]{fileName, getRequestSize(request), maxSize});
if (!errors.contains(message))
if (!errors.contains(message)) {
errors.add(message);
}
}
/**
@@ -370,10 +373,10 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
private void processFileItemStreamAsFormField(FileItemStream itemStream) {
String fieldName = itemStream.getFieldName();
try {
List<String> values = null;
List<String> values;
String fieldValue = Streams.asString(itemStream.openStream());
if (!parameters.containsKey(fieldName)) {
values = new ArrayList<String>();
values = new ArrayList<>();
parameters.put(fieldName, values);
} else {
values = parameters.get(fieldName);
@@ -396,8 +399,9 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
// Create the temporary upload file.
file = createTemporaryFile(itemStream.getName(), location);
if (streamFileToDisk(itemStream, file))
if (streamFileToDisk(itemStream, file)) {
createFileInfoFromItemStream(itemStream, file);
}
} catch (IOException e) {
if (file != null) {
try {
@@ -417,8 +421,7 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
* @return
* @throws IOException
*/
private File createTemporaryFile(String fileName, String location)
throws IOException {
private File createTemporaryFile(String fileName, String location) throws IOException {
String name = fileName
.substring(fileName.lastIndexOf('/') + 1)
.substring(fileName.lastIndexOf('\\') + 1);
@@ -452,22 +455,23 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
output = new BufferedOutputStream(new FileOutputStream(file), bufferSize);
byte[] buffer = new byte[bufferSize];
LOG.debug("Streaming file using buffer size {}.", bufferSize);
for (int length = 0; ((length = input.read(buffer)) > 0); )
for (int length = 0; ((length = input.read(buffer)) > 0); ) {
output.write(buffer, 0, length);
}
result = true;
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
LOG.warn("Error occurred during closing of OutputStream.", e);
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
LOG.warn("Error occurred during closing of InputStream.", e);
}
}
}
@@ -490,7 +494,7 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
FileInfo fileInfo = new FileInfo(file, itemStream.getContentType(), fileName);
// append or create new entry.
if (!fileInfos.containsKey(fieldName)) {
List<FileInfo> infos = new ArrayList<FileInfo>();
List<FileInfo> infos = new ArrayList<>();
infos.add(fileInfo);
fileInfos.put(fieldName, infos);
} else {
@@ -524,8 +528,7 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
private String buildErrorMessage(Throwable e, Object[] args) {
String errorKey = "struts.message.upload.error." + e.getClass().getSimpleName();
if (LOG.isDebugEnabled())
LOG.debug("Preparing error message for key: [{}]", errorKey);
LOG.debug("Preparing error message for key: [{}]", errorKey);
return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args);
}
@@ -538,8 +541,7 @@ public class JakartaStreamMultiPartRequest implements MultiPartRequest {
*/
private String buildMessage(Throwable e, Object[] args) {
String messageKey = "struts.message.upload.message." + e.getClass().getSimpleName();
if (LOG.isDebugEnabled())
LOG.debug("Preparing message for key: [{}]", messageKey);
LOG.debug("Preparing message for key: [{}]", messageKey);
return LocalizedTextUtil.findText(this.getClass(), messageKey, defaultLocale, e.getMessage(), args);
}
@@ -108,7 +108,7 @@ public interface MultiPartRequest {
* Returns a list of error messages that may have occurred while processing the request.
* If there are no errors, an empty list is returned. If the underlying implementation
* (ie: pell, cos, jakarta, etc) cannot support providing these errors, an empty list is
* also returned. This list of errors is repoted back to the
* also returned. This list of errors is reported back to the
* {@link MultiPartRequestWrapper}'s errors field.
*
* @return a list of Strings that represent various errors during parsing
@@ -21,23 +21,16 @@
package org.apache.struts2.dispatcher.multipart;
import com.opensymphony.xwork2.DefaultLocaleProvider;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import java.util.*;
/**
@@ -76,7 +69,7 @@ public class MultiPartRequestWrapper extends StrutsRequestWrapper {
String saveDir, LocaleProvider provider,
boolean disableRequestAttributeValueStackLookup) {
super(request, disableRequestAttributeValueStackLookup);
errors = new ArrayList<String>();
errors = new ArrayList<>();
multi = multiPartRequest;
defaultLocale = provider.getLocale();
setLocale(request);
@@ -86,9 +79,7 @@ public class MultiPartRequestWrapper extends StrutsRequestWrapper {
addError(error);
}
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(e.getMessage(), e);
}
LOG.warn(e.getMessage(), e);
addError(buildErrorMessage(e, new Object[] {e.getMessage()}));
}
}
@@ -105,9 +96,7 @@ public class MultiPartRequestWrapper extends StrutsRequestWrapper {
protected String buildErrorMessage(Throwable e, Object[] args) {
String errorKey = "struts.messages.upload.error." + e.getClass().getSimpleName();
if (LOG.isDebugEnabled()) {
LOG.debug("Preparing error message for key: [{}]", errorKey);
}
LOG.debug("Preparing error message for key: [{}]", errorKey);
return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args);
}
@@ -194,7 +183,7 @@ public class MultiPartRequestWrapper extends StrutsRequestWrapper {
* @see javax.servlet.http.HttpServletRequest#getParameterMap()
*/
public Map getParameterMap() {
Map<String, String[]> map = new HashMap<String, String[]>();
Map<String, String[]> map = new HashMap<>();
Enumeration enumeration = getParameterNames();
while (enumeration.hasMoreElements()) {
@@ -23,17 +23,11 @@ package org.apache.struts2.dispatcher.ng;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.StaticContentLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.regex.Pattern;
/**
@@ -103,7 +97,7 @@ public class InitOperations {
* Create a {@link Dispatcher}
*/
private Dispatcher createDispatcher( HostConfig filterConfig ) {
Map<String, String> params = new HashMap<String, String>();
Map<String, String> params = new HashMap<>();
for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) {
String name = (String) e.next();
String value = filterConfig.getInitParameter(name);
@@ -131,7 +125,7 @@ public class InitOperations {
private List<Pattern> buildExcludedPatternsList( String patterns ) {
if (null != patterns && patterns.trim().length() != 0) {
List<Pattern> list = new ArrayList<Pattern>();
List<Pattern> list = new ArrayList<>();
String[] tokens = patterns.split(",");
for ( String token : tokens ) {
list.add(Pattern.compile(token.trim()));
@@ -23,8 +23,8 @@ package org.apache.struts2.dispatcher.ng;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.Dispatcher;
@@ -50,7 +50,6 @@ public class PrepareOperations {
private Dispatcher dispatcher;
private static final String STRUTS_ACTION_MAPPING_KEY = "struts.actionMapping";
public static final String CLEANUP_RECURSION_COUNTER = "__cleanup_recursion_counter";
private Logger log = LogManager.getLogger(PrepareOperations.class);
@Deprecated
public PrepareOperations(ServletContext servletContext, Dispatcher dispatcher) {
@@ -75,7 +74,7 @@ public class PrepareOperations {
ActionContext oldContext = ActionContext.getContext();
if (oldContext != null) {
// detected existing context, so we are probably in a forward
ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));
ctx = new ActionContext(new HashMap<>(oldContext.getContextMap()));
} else {
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
stack.getContext().putAll(dispatcher.createContextMap(request, response, null));
@@ -95,9 +94,7 @@ public class PrepareOperations {
counterVal -= 1;
request.setAttribute(CLEANUP_RECURSION_COUNTER, counterVal);
if (counterVal > 0 ) {
if (log.isDebugEnabled()) {
log.debug("skipping cleanup counter="+counterVal);
}
LOG.debug("skipping cleanup counter={}", counterVal);
return;
}
}
@@ -27,12 +27,7 @@ import org.apache.struts2.dispatcher.ng.ExecuteOperations;
import org.apache.struts2.dispatcher.ng.InitOperations;
import org.apache.struts2.dispatcher.ng.PrepareOperations;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@@ -80,8 +75,8 @@ public class StrutsExecuteFilter implements StrutsStatics, Filter {
ActionMapping mapping = prepare.findActionMapping(request, response);
//if recusrion counter is > 1, it means we are in a "forward", in that case a mapping will still be
//in the request, if we handle it, it will lead to an infinte loop, see WW-3077
//if recursion counter is > 1, it means we are in a "forward", in that case a mapping will still be
//in the request, if we handle it, it will lead to an infinite loop, see WW-3077
Integer recursionCounter = (Integer) request.getAttribute(PrepareOperations.CLEANUP_RECURSION_COUNTER);
if (mapping == null || recursionCounter > 1) {
@@ -5,8 +5,8 @@ import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.DefaultActionProxyFactory;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import java.util.HashMap;
@@ -35,7 +35,7 @@ public class PrefixBasedActionProxyFactory extends DefaultActionProxyFactory {
private static final Logger LOG = LogManager.getLogger(PrefixBasedActionProxyFactory.class);
private Map<String, ActionProxyFactory> actionProxyFactories = new HashMap<String, ActionProxyFactory>();
private Map<String, ActionProxyFactory> actionProxyFactories = new HashMap<>();
private ActionProxyFactory defaultFactory;
@Inject
@@ -54,7 +54,7 @@ public class PrefixBasedActionProxyFactory extends DefaultActionProxyFactory {
String[] factories = list.split(",");
for (String factory : factories) {
String[] thisFactory = factory.split(":");
if ((thisFactory != null) && (thisFactory.length == 2)) {
if (thisFactory.length == 2) {
String factoryPrefix = thisFactory[0].trim();
String factoryName = thisFactory[1].trim();
ActionProxyFactory obj = container.getInstance(ActionProxyFactory.class, factoryName);
@@ -53,7 +53,7 @@ public class StrutsObjectFactory extends ObjectFactory {
throws ConfigurationException {
String className = interceptorConfig.getClassName();
Map<String, String> params = new HashMap<String, String>();
Map<String, String> params = new HashMap<>();
Map typeParams = interceptorConfig.getParams();
if (typeParams != null && !typeParams.isEmpty())
params.putAll(typeParams);
@@ -21,16 +21,15 @@
package org.apache.struts2.interceptor;
import com.opensymphony.xwork2.interceptor.ParametersInterceptor;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
import java.util.Collections;
import java.util.TreeMap;
import com.opensymphony.xwork2.interceptor.ParametersInterceptor;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/**
* <!-- START SNIPPET: description -->
* This interceptor sets all parameters from the action mapping, for this request, on the value stack. It operates
@@ -75,8 +74,7 @@ public class ActionMappingParametersInteceptor extends ParametersInterceptor {
/**
* @param ac The action context
* @return the parameters from the action mapping in the context. If none found, returns
* an empty map.
* @return the parameters from the action mapping in the context. If none found, returns an empty map.
*/
@Override
protected Map<String, Object> retrieveParameters(ActionContext ac) {
@@ -100,7 +98,7 @@ public class ActionMappingParametersInteceptor extends ParametersInterceptor {
@Override
protected void addParametersToContext(ActionContext ac, Map newParams) {
Map previousParams = ac.getParameters();
Map combinedParams = null;
Map combinedParams;
if (previousParams != null) {
combinedParams = new TreeMap(previousParams);
} else {
@@ -22,14 +22,14 @@
package org.apache.struts2.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* <!-- START SNIPPET: description -->
@@ -59,7 +59,7 @@ public class CheckboxInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation ai) throws Exception {
Map<String, Object> parameters = ai.getInvocationContext().getParameters();
Map<String, String[]> newParams = new HashMap<String, String[]>();
Map<String, String[]> newParams = new HashMap<>();
Set<Map.Entry<String, Object>> entries = parameters.entrySet();
for (Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); iterator.hasNext();) {
@@ -21,13 +21,13 @@
package org.apache.struts2.interceptor;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Map;
/**
* <!-- START SNIPPET: description -->
@@ -83,10 +83,8 @@ public class ClearSessionInterceptor extends AbstractInterceptor {
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Clearing HttpSession");
}
LOG.debug("Clearing HttpSession");
ActionContext ac = invocation.getInvocationContext();
Map session = ac.getSession();
@@ -29,8 +29,8 @@ import com.opensymphony.xwork2.security.AcceptedPatternsChecker;
import com.opensymphony.xwork2.security.ExcludedPatternsChecker;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.Cookie;
@@ -195,8 +195,9 @@ public class CookieInterceptor extends AbstractInterceptor {
* @param cookiesName
*/
public void setCookiesName(String cookiesName) {
if (cookiesName != null)
if (cookiesName != null) {
this.cookiesNameSet = TextParseUtil.commaDelimitedStringToSet(cookiesName);
}
}
/**
@@ -207,8 +208,9 @@ public class CookieInterceptor extends AbstractInterceptor {
* @param cookiesValue
*/
public void setCookiesValue(String cookiesValue) {
if (cookiesValue != null)
if (cookiesValue != null) {
this.cookiesValueSet = TextParseUtil.commaDelimitedStringToSet(cookiesValue);
}
}
/**
@@ -222,12 +224,10 @@ public class CookieInterceptor extends AbstractInterceptor {
}
public String intercept(ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("start interception");
}
LOG.debug("start interception");
// contains selected cookies
final Map<String, String> cookiesMap = new LinkedHashMap<String, String>();
final Map<String, String> cookiesMap = new LinkedHashMap<>();
Cookie[] cookies = ServletActionContext.getRequest().getCookies();
if (cookies != null) {
@@ -239,9 +239,7 @@ public class CookieInterceptor extends AbstractInterceptor {
if (isAcceptableName(name) && isAcceptableValue(value)) {
if (cookiesNameSet.contains("*")) {
if (LOG.isDebugEnabled()) {
LOG.debug("contains cookie name [*] in configured cookies name set, cookie with name [" + name + "] with value [" + value + "] will be injected");
}
LOG.debug("Contains cookie name [*] in configured cookies name set, cookie with name [{}] with value [{}] will be injected", name, value);
populateCookieValueIntoStack(name, value, cookiesMap, stack);
} else if (cookiesNameSet.contains(cookie.getName())) {
populateCookieValueIntoStack(name, value, cookiesMap, stack);
@@ -346,9 +344,7 @@ public class CookieInterceptor extends AbstractInterceptor {
// if cookiesValues is specified, the cookie's value must match before we
// inject them into Struts' action
if (cookiesValueSet.contains(cookieValue)) {
if (LOG.isDebugEnabled()) {
LOG.debug("both configured cookie name and value matched, cookie [{}] with value [{}] will be injected", cookieName, cookieValue);
}
LOG.debug("both configured cookie name and value matched, cookie [{}] with value [{}] will be injected", cookieName, cookieValue);
cookiesMap.put(cookieName, cookieValue);
stack.setValue(cookieName, cookieValue);
@@ -23,8 +23,8 @@ package org.apache.struts2.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
@@ -92,9 +92,7 @@ public class CreateSessionInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
if (httpSession == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating new HttpSession and new SessionMap in ServletActionContext");
}
LOG.debug("Creating new HttpSession and new SessionMap in ServletActionContext");
ServletActionContext.getRequest().getSession(true);
ServletActionContext.getContext().setSession(new SessionMap<String, Object>(ServletActionContext.getRequest()));
}
@@ -1,18 +1,14 @@
package org.apache.struts2.interceptor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
public class DateTextFieldInterceptor implements Interceptor {
@@ -31,9 +27,9 @@ public class DateTextFieldInterceptor implements Interceptor {
private String description;
private Integer length;
private String dateType;
private DateWord(String n, Integer l, String t) {
description = n;
DateWord(String n, Integer l, String t) {
description = n;
length = l;
dateType = t;
}
@@ -68,7 +64,7 @@ public class DateTextFieldInterceptor implements Interceptor {
public String intercept(ActionInvocation ai) throws Exception {
Map<String, Object> parameters = ai.getInvocationContext().getParameters();
Set<Entry<String, Object>> entries = parameters.entrySet();
Map<String, Map<String, String>> dates = new HashMap<String, Map<String,String>>();
Map<String, Map<String, String>> dates = new HashMap<>();
DateWord[] dateWords = DateWord.getAll();
@@ -88,8 +84,8 @@ public class DateTextFieldInterceptor implements Interceptor {
iterator.remove();
Map<String, String> map = dates.get(name);
if (map == null) {
map = new HashMap<String, String>();
dates.put(name, map);
map = new HashMap<>();
dates.put(name, map);
}
map.put(dateWord.getDateType(), values[0]);
}
@@ -100,7 +96,7 @@ public class DateTextFieldInterceptor implements Interceptor {
}
// Create all the date objects
Map<String, Date> newParams = new HashMap<String, Date>();
Map<String, Date> newParams = new HashMap<>();
Set<Entry<String, Map<String, String>>> dateEntries = dates.entrySet();
for (Entry<String, Map<String, String>> dateEntry : dateEntries) {
Set<Entry<String, String>> dateFormatEntries = dateEntry.getValue().entrySet();
@@ -116,8 +112,7 @@ public class DateTextFieldInterceptor implements Interceptor {
Date value = formatter.parse(dateValue);
newParams.put(dateEntry.getKey(), value);
} catch (ParseException e) {
LOG.warn("Cannot parse the parameter '" + dateEntry.getKey()
+ "' with format '" + dateFormat + "' and with value '" + dateValue + "'");
LOG.warn("Cannot parse the parameter '{}' with format '{}' and with value '{}'", dateEntry.getKey(), dateFormat, dateValue);
}
}
parameters.putAll(newParams);
@@ -5,8 +5,9 @@ import com.opensymphony.xwork2.XWorkConstants;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import java.lang.reflect.Field;
@@ -47,7 +48,7 @@ public class DeprecationInterceptor extends AbstractInterceptor {
* @throws Exception
*/
private String validate() throws Exception {
Set<String> constants = new HashSet<String>();
Set<String> constants = new HashSet<>();
readConstants(constants, StrutsConstants.class);
readConstants(constants, XWorkConstants.class);
@@ -55,7 +56,7 @@ public class DeprecationInterceptor extends AbstractInterceptor {
Set<String> applicationConstants = container.getInstanceNames(String.class);
String message = null;
if (!constants.containsAll(applicationConstants)) {
Set<String> deprecated = new HashSet<String>(applicationConstants);
Set<String> deprecated = new HashSet<>(applicationConstants);
deprecated.removeAll(constants);
message = prepareMessage(deprecated);
}
@@ -94,7 +95,7 @@ public class DeprecationInterceptor extends AbstractInterceptor {
@Inject(StrutsConstants.STRUTS_DEVMODE)
public void setDevMode(String state) {
this.devMode = "true".equals(state);
this.devMode = BooleanUtils.toBoolean(state);
}
@Inject
@@ -21,26 +21,21 @@
package org.apache.struts2.interceptor;
import java.util.Collections;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.struts2.util.TokenHelper;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.util.TokenHelper;
import org.apache.struts2.views.freemarker.FreemarkerResult;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
@@ -264,12 +259,9 @@ public class ExecuteAndWaitInterceptor extends MethodFilterInterceptor {
Map results = proxy.getConfig().getResults();
if (!results.containsKey(WAIT)) {
if (LOG.isWarnEnabled()) {
LOG.warn("ExecuteAndWait interceptor has detected that no result named 'wait' is available. " +
"Defaulting to a plain built-in wait page. It is highly recommend you " +
"provide an action-specific or global result named '" + WAIT +
"'.");
}
"provide an action-specific or global result named '{}'.", WAIT);
// no wait result? hmm -- let's try to do dynamically put it in for you!
//we used to add a fake "wait" result here, since the configuration is unmodifiable, that is no longer
@@ -314,7 +306,7 @@ public class ExecuteAndWaitInterceptor extends MethodFilterInterceptor {
* Performs the initial delay.
* <p/>
* When this interceptor is executed for the first time this methods handles any provided initial delay.
* An initial delay is a time in miliseconds we let the server wait before we continue.
* An initial delay is a time in milliseconds we let the server wait before we continue.
* <br/> During the wait this interceptor will wake every 100 millis to check if the background
* process is done premature, thus if the job for some reason doesn't take to long the wait
* page is not shown to the user.
@@ -328,16 +320,12 @@ public class ExecuteAndWaitInterceptor extends MethodFilterInterceptor {
}
int steps = delay / delaySleepInterval;
if (LOG.isDebugEnabled()) {
LOG.debug("Delaying for " + delay + " millis. (using " + steps + " steps)");
}
LOG.debug("Delaying for {} millis. (using {} steps)", delay, steps);
int step;
for (step = 0; step < steps && !bp.isDone(); step++) {
Thread.sleep(delaySleepInterval);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Sleeping ended after " + step + " steps and the background process is " + (bp.isDone() ? " done" : " not done"));
}
LOG.debug("Sleeping ended after {} steps and the background process is {}", step, (bp.isDone() ? " done" : " not done"));
}
/**
@@ -21,19 +21,13 @@
package org.apache.struts2.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.TextProviderFactory;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.TextParseUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.util.ContentTypeMatcher;
@@ -41,14 +35,7 @@ import org.apache.struts2.util.ContentTypeMatcher;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
* <!-- START SNIPPET: description -->
@@ -288,9 +275,9 @@ public class FileUploadInterceptor extends AbstractInterceptor {
// get a File object for the uploaded File
File[] files = multiWrapper.getFiles(inputName);
if (files != null && files.length > 0) {
List<File> acceptedFiles = new ArrayList<File>(files.length);
List<String> acceptedContentTypes = new ArrayList<String>(files.length);
List<String> acceptedFileNames = new ArrayList<String>(files.length);
List<File> acceptedFiles = new ArrayList<>(files.length);
List<String> acceptedContentTypes = new ArrayList<>(files.length);
List<String> acceptedFileNames = new ArrayList<>(files.length);
String contentTypeName = inputName + "ContentType";
String fileNameName = inputName + "FileName";
@@ -21,19 +21,18 @@
package org.apache.struts2.interceptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.struts2.dispatcher.ServletRedirectResult;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.dispatcher.ServletRedirectResult;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* <!-- START SNIPPET: description -->
@@ -189,18 +188,14 @@ public class MessageStoreInterceptor extends AbstractInterceptor {
}
public String intercept(ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("entering MessageStoreInterceptor ...");
}
LOG.debug("entering MessageStoreInterceptor ...");
before(invocation);
String result = invocation.invoke();
after(invocation, result);
if (LOG.isDebugEnabled()) {
LOG.debug("exit executing MessageStoreInterceptor");
}
LOG.debug("exit executing MessageStoreInterceptor");
return result;
}
@@ -224,17 +219,13 @@ public class MessageStoreInterceptor extends AbstractInterceptor {
Map session = (Map) invocation.getInvocationContext().get(ActionContext.SESSION);
if (session == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Session is not open, no errors / messages could be retrieve for action ["+action+"]");
}
LOG.debug("Session is not open, no errors / messages could be retrieve for action [{}]", action);
return;
}
ValidationAware validationAwareAction = (ValidationAware) action;
if (LOG.isDebugEnabled()) {
LOG.debug("retrieve error / message from session to populate into action ["+action+"]");
}
LOG.debug("Retrieve error / message from session to populate into action [{}]", action);
Collection actionErrors = (Collection) session.get(actionErrorsSessionKey);
Collection actionMessages = (Collection) session.get(actionMessagesSessionKey);
@@ -283,23 +274,18 @@ public class MessageStoreInterceptor extends AbstractInterceptor {
Map session = (Map) invocation.getInvocationContext().get(ActionContext.SESSION);
if (session == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not store action ["+action+"] error/messages into session, because session hasn't been opened yet.");
}
LOG.debug("Could not store action [{}] error/messages into session, because session hasn't been opened yet.", action);
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("store action ["+action+"] error/messages into session ");
}
LOG.debug("Store action [{}] error/messages into session.", action);
ValidationAware validationAwareAction = (ValidationAware) action;
session.put(actionErrorsSessionKey, validationAwareAction.getActionErrors());
session.put(actionMessagesSessionKey, validationAwareAction.getActionMessages());
session.put(fieldErrorsSessionKey, validationAwareAction.getFieldErrors());
}
else if(LOG.isDebugEnabled()) {
LOG.debug("Action ["+action+"] is not ValidationAware, no message / error that are storeable");
} else {
LOG.debug("Action [{}] is not ValidationAware, no message / error that are storeable", action);
}
}
}
@@ -48,7 +48,7 @@ public class MultiselectInterceptor extends AbstractInterceptor {
*/
public String intercept(ActionInvocation actionInvocation) throws Exception {
Map<String, Object> parameters = actionInvocation.getInvocationContext().getParameters();
Map<String, Object> newParams = new HashMap<String, Object>();
Map<String, Object> newParams = new HashMap<>();
Set<String> keys = parameters.keySet();
for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
@@ -25,7 +25,7 @@ import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.profiling.UtilTimerStack;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.struts2.StrutsConstants;
/**
@@ -87,7 +87,7 @@ public class ProfilingActivationInterceptor extends AbstractInterceptor {
@Inject(StrutsConstants.STRUTS_DEVMODE)
public void setDevMode(String mode) {
this.devMode = "true".equals(mode);
this.devMode = BooleanUtils.toBoolean(mode);
}
@Override
@@ -96,13 +96,11 @@ public class ProfilingActivationInterceptor extends AbstractInterceptor {
Object val = invocation.getInvocationContext().getParameters().get(profilingKey);
if (val != null) {
String sval = (val instanceof String ? (String)val : ((String[])val)[0]);
boolean enable = "yes".equalsIgnoreCase(sval) || "true".equalsIgnoreCase(sval);
boolean enable = BooleanUtils.toBoolean(sval);
UtilTimerStack.setActive(enable);
invocation.getInvocationContext().getParameters().remove(profilingKey);
}
}
return invocation.invoke();
}
}
@@ -23,8 +23,8 @@ package org.apache.struts2.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
@@ -172,9 +172,7 @@ public class RolesInterceptor extends AbstractInterceptor {
* @return The result code
* @throws Exception
*/
protected String handleRejection(ActionInvocation invocation,
HttpServletResponse response)
throws Exception {
protected String handleRejection(ActionInvocation invocation, HttpServletResponse response) throws Exception {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
@@ -21,22 +21,23 @@
package org.apache.struts2.interceptor;
import java.io.Serializable;
import java.util.IdentityHashMap;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.SessionMap;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.SessionMap;
import java.io.Serializable;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* <!-- START SNIPPET: description -->
@@ -182,8 +183,8 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
* @param value True if it should be created
*/
public void setAutoCreateSession(String value) {
if (value != null && value.length() > 0) {
this.autoCreateSession = Boolean.valueOf(value).booleanValue();
if (StringUtils.isNotBlank(value)) {
this.autoCreateSession = BooleanUtils.toBoolean(value);
}
}
@@ -219,7 +220,7 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
private static final Object NULL = new NULLClass();
private static final Object nullConvert(Object o) {
private static Object nullConvert(Object o) {
if (o == null) {
return NULL;
}
@@ -233,10 +234,10 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
private static Map locks = new IdentityHashMap();
static final void lock(Object o, ActionInvocation invocation) throws Exception {
static void lock(Object o, ActionInvocation invocation) throws Exception {
synchronized (o) {
int count = 3;
Object previous = null;
Object previous;
while ((previous = locks.get(o)) != null) {
if (previous == invocation) {
return;
@@ -249,12 +250,11 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
}
o.wait(10000);
}
;
locks.put(o, invocation);
}
}
static final void unlock(Object o) {
static void unlock(Object o) {
synchronized (o) {
locks.remove(o);
o.notify();
@@ -285,19 +285,13 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
Map app = ActionContext.getContext().getApplication();
final ValueStack stack = ActionContext.getContext().getValueStack();
if (LOG.isDebugEnabled()) {
LOG.debug("scope interceptor before");
}
LOG.debug("scope interceptor before");
if (application != null)
for (int i = 0; i < application.length; i++) {
String string = application[i];
for (String string : application) {
Object attribute = app.get(key + string);
if (attribute != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("application scoped variable set " + string + " = " + String.valueOf(attribute));
}
LOG.debug("Application scoped variable set {} = {}", string, String.valueOf(attribute));
stack.setValue(string, nullConvert(attribute));
}
}
@@ -316,13 +310,10 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
}
if (session != null && (!"start".equals(type))) {
for (int i = 0; i < session.length; i++) {
String string = session[i];
for (String string : session) {
Object attribute = ses.get(key + string);
if (attribute != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("session scoped variable set " + string + " = " + String.valueOf(attribute));
}
LOG.debug("Session scoped variable set {} = {}", string, String.valueOf(attribute));
stack.setValue(string, nullConvert(attribute));
}
}
@@ -342,12 +333,9 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
final ValueStack stack = ActionContext.getContext().getValueStack();
if (application != null)
for (int i = 0; i < application.length; i++) {
String string = application[i];
for (String string : application) {
Object value = stack.findValue(string);
if (LOG.isDebugEnabled()) {
LOG.debug("application scoped variable saved " + string + " = " + String.valueOf(value));
}
LOG.debug("Application scoped variable saved {} = {}", string, String.valueOf(value));
//if( value != null)
app.put(key + string, nullConvert(value));
@@ -359,16 +347,12 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
if (ses != null) {
if (session != null) {
for (int i = 0; i < session.length; i++) {
String string = session[i];
for (String string : session) {
if (ends) {
ses.remove(key + string);
} else {
Object value = stack.findValue(string);
if (LOG.isDebugEnabled()) {
LOG.debug("session scoped variable saved " + string + " = " + String.valueOf(value));
}
LOG.debug("Session scoped variable saved {} = {}", string, String.valueOf(value));
// Null value should be scoped too
//if( value != null)
@@ -380,9 +364,7 @@ public class ScopeInterceptor extends AbstractInterceptor implements PreResultLi
} else {
LOG.debug("No HttpSession created... Cannot save session scoped variables.");
}
if (LOG.isDebugEnabled()) {
LOG.debug("scope interceptor after (before result)");
}
LOG.debug("scope interceptor after (before result)");
}
/**
@@ -136,9 +136,7 @@ public class TokenInterceptor extends MethodFilterInterceptor {
*/
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Intercepting invocation to check for valid transaction token.");
}
log.debug("Intercepting invocation to check for valid transaction token.");
return handleToken(invocation);
}
@@ -21,6 +21,22 @@
package org.apache.struts2.interceptor.debugging;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.views.freemarker.FreemarkerResult;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
@@ -29,30 +45,7 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.views.freemarker.FreemarkerResult;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
import java.util.*;
/**
* <!-- START SNIPPET: description -->
@@ -99,7 +92,7 @@ public class DebuggingInterceptor extends AbstractInterceptor {
"com.opensymphony.xwork2.", "xwork."};
private String[] _ignoreKeys = new String[]{"application", "session",
"parameters", "request"};
private HashSet<String> ignoreKeys = new HashSet<String>(Arrays.asList(_ignoreKeys));
private HashSet<String> ignoreKeys = new HashSet<>(Arrays.asList(_ignoreKeys));
private final static String XML_MODE = "xml";
private final static String CONSOLE_MODE = "console";
@@ -145,7 +138,7 @@ public class DebuggingInterceptor extends AbstractInterceptor {
boolean actionOnly = false;
boolean cont = true;
Boolean devModeOverride = FilterDispatcher.getDevModeOverride();
boolean devMode = devModeOverride != null ? devModeOverride.booleanValue() : this.devMode;
boolean devMode = devModeOverride != null ? devModeOverride : this.devMode;
if (devMode) {
final ActionContext ctx = ActionContext.getContext();
String type = getParameter(DEBUG_PARAM);
@@ -266,7 +259,6 @@ public class DebuggingInterceptor extends AbstractInterceptor {
}
}
/**
* Gets a single string from the request parameters
*
@@ -281,7 +273,6 @@ public class DebuggingInterceptor extends AbstractInterceptor {
return null;
}
/**
* Prints the current context to the response in XML format.
*/
@@ -299,7 +290,6 @@ public class DebuggingInterceptor extends AbstractInterceptor {
}
}
/**
* Prints the current request to the existing writer.
*
@@ -308,8 +298,7 @@ public class DebuggingInterceptor extends AbstractInterceptor {
protected void printContext(PrettyPrintWriter writer) {
ActionContext ctx = ActionContext.getContext();
writer.startNode(DEBUG_PARAM);
serializeIt(ctx.getParameters(), "parameters", writer,
new ArrayList<Object>());
serializeIt(ctx.getParameters(), "parameters", writer, new ArrayList<>());
writer.startNode("context");
String key;
Map ctxMap = ctx.getContextMap();
@@ -324,24 +313,23 @@ public class DebuggingInterceptor extends AbstractInterceptor {
}
}
if (print) {
serializeIt(ctxMap.get(key), key, writer, new ArrayList<Object>());
serializeIt(ctxMap.get(key), key, writer, new ArrayList<>());
}
}
writer.endNode();
Map requestMap = (Map) ctx.get("request");
serializeIt(requestMap, "request", writer, filterValueStack(requestMap));
serializeIt(ctx.getSession(), "session", writer, new ArrayList<Object>());
serializeIt(ctx.getSession(), "session", writer, new ArrayList<>());
ValueStack stack = (ValueStack) ctx.get(ActionContext.VALUE_STACK);
serializeIt(stack.getRoot(), "valueStack", writer, new ArrayList<Object>());
serializeIt(stack.getRoot(), "valueStack", writer, new ArrayList<>());
writer.endNode();
}
/**
* Recursive function to serialize objects to XML. Currently it will
* serialize Collections, maps, Arrays, and JavaBeans. It maintains a stack
* of objects serialized already in the current functioncall. This is used
* of objects serialized already in the current function call. This is used
* to avoid looping (stack overflow) of circular linked objects. Struts and
* XWork objects are ignored.
*
@@ -356,10 +344,7 @@ public class DebuggingInterceptor extends AbstractInterceptor {
writer.flush();
// Check stack for this object
if ((bean != null) && (stack.contains(bean))) {
if (LOG.isInfoEnabled()) {
LOG.info("Circular reference detected, not serializing object: "
+ name);
}
LOG.info("Circular reference detected, not serializing object: {}", name);
return;
} else if (bean != null) {
// Push object onto stack.
@@ -428,7 +413,6 @@ public class DebuggingInterceptor extends AbstractInterceptor {
stack.remove(bean);
}
/**
* @param enableXmlWithConsole the enableXmlWithConsole to set
*/
@@ -436,17 +420,14 @@ public class DebuggingInterceptor extends AbstractInterceptor {
this.enableXmlWithConsole = enableXmlWithConsole;
}
private List<Object> filterValueStack(Map requestMap) {
List<Object> filter = new ArrayList<Object>();
Object valueStack = requestMap.get("struts.valueStack");
List<Object> filter = new ArrayList<>();
Object valueStack = requestMap.get("struts.valueStack");
if(valueStack != null) {
filter.add(valueStack);
}
return filter;
}
}
@@ -21,17 +21,16 @@
package org.apache.struts2.interceptor.debugging;
import com.opensymphony.xwork2.util.reflection.ReflectionException;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
import java.beans.IntrospectionException;
import java.io.Writer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.opensymphony.xwork2.util.reflection.ReflectionException;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
/**
* Writes an object as a table, where each field can be expanded if it is an Object/Collection/Array
*
@@ -51,9 +50,8 @@ class ObjectToHTMLWriter {
prettyWriter.addAttribute("class", "debugTable");
if (root instanceof Map) {
for (Iterator iterator = ((Map) root).entrySet().iterator(); iterator
.hasNext();) {
Map.Entry property = (Map.Entry) iterator.next();
for (Object next : ((Map) root).entrySet()) {
Map.Entry property = (Map.Entry) next;
String key = property.getKey().toString();
Object value = property.getValue();
writeProperty(key, value, expr);
@@ -66,8 +64,8 @@ class ObjectToHTMLWriter {
}
} else if (root instanceof Set) {
Set set = (Set) root;
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
writeProperty("", iterator.next(), expr);
for (Object next : set) {
writeProperty("", next, expr);
}
} else if (root.getClass().isArray()) {
Object[] objects = (Object[]) root;
@@ -81,8 +79,9 @@ class ObjectToHTMLWriter {
String name = property.getKey();
Object value = property.getValue();
if ("class".equals(name))
if ("class".equals(name)) {
continue;
}
writeProperty(name, value, expr);
}
@@ -104,9 +103,8 @@ class ObjectToHTMLWriter {
prettyWriter.startNode("td");
if (value != null) {
//if is is an empty collection or array, don't write a link
if (value != null &&
(isEmptyCollection(value) || isEmptyMap(value) || (value.getClass()
.isArray() && ((Object[]) value).length == 0))) {
if (isEmptyCollection(value) || isEmptyMap(value) || (value.getClass()
.isArray() && ((Object[]) value).length == 0)) {
prettyWriter.addAttribute("class", "emptyCollection");
prettyWriter.setValue("empty");
} else {
@@ -28,7 +28,7 @@ import java.util.Stack;
public class PrettyPrintWriter {
private final PrintWriter writer;
private final Stack<String> elementStack = new Stack<String>();
private final Stack<String> elementStack = new Stack<>();
private final char[] lineIndenter;
private boolean tagInProgress;
@@ -153,7 +153,7 @@ public class PrettyPrintWriter {
} else {
finishTag();
writer.write(CLOSE);
writer.write((String)elementStack.pop());
writer.write(elementStack.pop());
writer.write('>');
}
readyForNewLine = true;
@@ -21,17 +21,17 @@
package org.apache.struts2.interceptor.validation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.AnnotationUtils;
import com.opensymphony.xwork2.validator.ValidationInterceptor;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.struts2.StrutsConstants;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
/**
* Extends the xwork validation interceptor to also check for a @SkipValidation
* annotation, and if found, don't validate this action method
@@ -45,7 +45,7 @@ public class AnnotationValidationInterceptor extends ValidationInterceptor {
@Inject(StrutsConstants.STRUTS_DEVMODE)
public void setDevMode(String devMode) {
this.devMode = "true".equalsIgnoreCase(devMode);
this.devMode = BooleanUtils.toBoolean(devMode);
}
protected String doIntercept(ActionInvocation invocation) throws Exception {
@@ -79,13 +79,14 @@ public class AnnotationValidationInterceptor extends ValidationInterceptor {
// FIXME: This is copied from DefaultActionInvocation but should be exposed through the interface
protected Method getActionMethod(Class actionClass, String methodName) throws NoSuchMethodException {
Method method = null;
Class[] classes = new Class[0];
try {
method = actionClass.getMethod(methodName, new Class[0]);
method = actionClass.getMethod(methodName, classes);
} catch (NoSuchMethodException e) {
// hmm -- OK, try doXxx instead
try {
String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
method = actionClass.getMethod(altMethodName, new Class[0]);
method = actionClass.getMethod(altMethodName, classes);
} catch (NoSuchMethodException e1) {
// throw the original one
if (devMode) {
@@ -23,14 +23,13 @@ package org.apache.struts2.util;
import javax.servlet.jsp.JspWriter;
import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.CoderResult;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.LinkedList;
/**
@@ -136,7 +135,7 @@ public class FastByteArrayOutputStream extends OutputStream {
private void writeToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("/tmp/" + getClass().getName() + System.currentTimeMillis() + ".log");
fileOutputStream = new FileOutputStream(File.createTempFile(getClass().getName() + System.currentTimeMillis(), ".log"));
writeTo(fileOutputStream);
} catch (IOException e) {
// Ignore
@@ -219,7 +218,7 @@ public class FastByteArrayOutputStream extends OutputStream {
protected void addBuffer() {
if (buffers == null) {
buffers = new LinkedList<byte[]>();
buffers = new LinkedList<>();
}
buffers.addLast(buffer);
buffer = new byte[blockSize];
@@ -21,15 +21,15 @@
package org.apache.struts2.util;
import com.opensymphony.xwork2.Action;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import com.opensymphony.xwork2.Action;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/**
* A bean that generates an iterator filled with a given object depending on the count,
@@ -93,9 +93,7 @@ public class IteratorGenerator implements Iterator, Action {
values.add(convertedObj);
}
catch(Exception e) { // make sure things, goes on, we just ignore the bad ones
if (LOG.isWarnEnabled()) {
LOG.warn("unable to convert ["+token+"], skipping this token, it will not appear in the generated iterator", e);
}
LOG.warn("Unable to convert [{}], skipping this token, it will not appear in the generated iterator", token, e);
}
}
else {
@@ -49,7 +49,7 @@ public class RegexPatternMatcher implements PatternMatcher<RegexPatternMatcherEx
private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
public RegexPatternMatcherExpression compilePattern(String data) {
Map<Integer, String> params = new HashMap<Integer, String>();
Map<Integer, String> params = new HashMap<>();
Matcher matcher = PATTERN.matcher(data);
int count = 0;
@@ -21,14 +21,11 @@
package org.apache.struts2.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.opensymphony.xwork2.Action;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
/**
@@ -38,6 +35,7 @@ import org.apache.logging.log4j.LogManager;
* @see org.apache.struts2.views.jsp.iterator.SortIteratorTag
*/
public class SortIteratorFilter extends IteratorFilterSupport implements Iterator, Action {
private static final Logger LOG = LogManager.getLogger(IteratorGenerator.class);
Comparator comparator;
Iterator iterator;
@@ -67,8 +65,7 @@ public class SortIteratorFilter extends IteratorFilterSupport implements Iterato
} else {
try {
if (!MakeIterator.isIterable(source)) {
LogManager.getLogger(SortIteratorFilter.class.getName()).warn("Cannot create SortIterator for source " + source);
LOG.warn("Cannot create SortIterator for source: {}", source);
return ERROR;
}
@@ -86,8 +83,7 @@ public class SortIteratorFilter extends IteratorFilterSupport implements Iterato
return SUCCESS;
} catch (Exception e) {
LogManager.getLogger(SortIteratorFilter.class.getName()).warn("Error creating sort iterator.", e);
LOG.warn("Error creating sort iterator.", e);
return ERROR;
}
}
@@ -21,21 +21,19 @@
package org.apache.struts2.util;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.inject.Container;
import org.apache.struts2.dispatcher.Dispatcher;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.DispatcherErrorHandler;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* Generic test setup methods to be used with any unit testing framework.
@@ -52,7 +50,7 @@ public class StrutsTestCaseHelper {
public static Dispatcher initDispatcher(ServletContext ctx, Map<String,String> params) {
if (params == null) {
params = new HashMap<String,String>();
params = new HashMap<>();
}
Dispatcher du = new DispatcherWrapper(ctx, params);
du.init();
@@ -27,8 +27,8 @@ import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.views.jsp.ui.OgnlTool;
import org.apache.struts2.views.util.UrlHelper;
@@ -42,12 +42,7 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* Struts base utility class, for use in Velocity and Freemarker templates
@@ -58,7 +53,7 @@ public class StrutsUtil {
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map<String, Class> classes = new Hashtable<String, Class>();
protected Map<String, Class> classes = new Hashtable<>();
protected OgnlTool ognl;
protected ValueStack stack;
@@ -117,9 +112,7 @@ public class StrutsUtil {
return responseWrapper.getData();
}
catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cannot include {}", e, aName.toString());
}
LOG.debug("Cannot include {}", aName.toString(), e);
throw e;
}
}
@@ -23,8 +23,8 @@ package org.apache.struts2.util;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Collections;
import java.util.List;
@@ -79,7 +79,7 @@ public class TextProviderHelper {
}
if (msg == null) {
// evaluate the defaultMesage as an OGNL expression
// evaluate the defaultMessage as an OGNL expression
if (searchStack)
msg = stack.findString(defaultMessage);
@@ -90,14 +90,14 @@ public class TextProviderHelper {
if (LOG.isWarnEnabled()) {
if (tp != null) {
LOG.warn("The first TextProvider in the ValueStack ("+tp.getClass().getName()+") could not locate the message resource with key '"+key+"'");
LOG.warn("The first TextProvider in the ValueStack ({}) could not locate the message resource with key '{}'", tp.getClass().getName(), key);
} else {
LOG.warn("Could not locate the message resource '"+key+"' as there is no TextProvider in the ValueStack.");
LOG.warn("Could not locate the message resource '{}' as there is no TextProvider in the ValueStack.", key);
}
if (defaultMessage.equals(msg)) {
LOG.warn("The default value expression '"+defaultMessage+"' was evaluated and did not match a property. The literal value '"+defaultMessage+"' will be used.");
LOG.warn("The default value expression '{}' was evaluated and did not match a property. The literal value '{}' will be used.", defaultMessage, defaultMessage);
} else {
LOG.warn("The default value expression '"+defaultMessage+"' evaluated to '"+msg+"'");
LOG.warn("The default value expression '{}' evaluated to '{}'", defaultMessage, msg);
}
}
}
@@ -23,8 +23,8 @@ package org.apache.struts2.util;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.math.BigInteger;
import java.security.SecureRandom;
@@ -91,11 +91,9 @@ public class TokenHelper {
session.put(buildTokenSessionAttributeName(tokenName), token);
} catch ( IllegalStateException e ) {
// WW-1182 explain to user what the problem is
String msg = "Error creating HttpSession due response is commited to client. You can use the CreateSessionInterceptor or create the HttpSession from your action before the result is rendered to the client: " + e.getMessage();
if (LOG.isErrorEnabled()) {
LOG.error(msg, e);
}
throw new IllegalArgumentException(msg);
String msg = "Error creating HttpSession due response is committed to client. You can use the CreateSessionInterceptor or create the HttpSession from your action before the result is rendered to the client: " + e.getMessage();
LOG.error(msg, e);
throw new IllegalArgumentException(msg);
}
}
@@ -135,15 +133,11 @@ public class TokenHelper {
String token;
if ((tokens == null) || (tokens.length < 1)) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not find token mapped to token name " + tokenName);
}
LOG.warn("Could not find token mapped to token name: {}", tokenName);
return null;
}
token = tokens[0];
return token;
}
@@ -156,10 +150,7 @@ public class TokenHelper {
Map params = ActionContext.getContext().getParameters();
if (!params.containsKey(TOKEN_NAME_FIELD)) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not find token name in params.");
}
return null;
}
@@ -167,15 +158,11 @@ public class TokenHelper {
String tokenName;
if ((tokenNames == null) || (tokenNames.length < 1)) {
if (LOG.isWarnEnabled()) {
LOG.warn("Got a null or empty token name.");
}
return null;
}
tokenName = tokenNames[0];
return tokenName;
}
@@ -189,18 +176,14 @@ public class TokenHelper {
String tokenName = getTokenName();
if (tokenName == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("no token name found -> Invalid token ");
}
LOG.debug("No token name found -> Invalid token ");
return false;
}
String token = getToken(tokenName);
if (token == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("no token found for token name "+tokenName+" -> Invalid token ");
}
LOG.debug("No token found for token name {} -> Invalid token ", tokenName);
return false;
}
@@ -27,24 +27,16 @@ import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.cache.*;
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.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateModel;
import freemarker.template.*;
import freemarker.template.utility.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.views.JspSupportServlet;
import org.apache.struts2.views.TagLibrary;
@@ -60,13 +52,7 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
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;
import java.util.*;
/**
@@ -210,14 +196,14 @@ public class FreemarkerManager {
@Inject
public void setContainer(Container container) {
Map<String,TagLibraryModelProvider> map = new HashMap<String,TagLibraryModelProvider>();
Map<String, TagLibraryModelProvider> map = new HashMap<>();
Set<String> prefixes = container.getInstanceNames(TagLibraryModelProvider.class);
for (String prefix : prefixes) {
map.put(prefix, container.getInstance(TagLibraryModelProvider.class, prefix));
}
this.tagLibraries = Collections.unmodifiableMap(map);
Map<String, TagLibrary> oldMap = new HashMap<String, TagLibrary>();
Map<String, TagLibrary> oldMap = new HashMap<>();
Set<String> oldPrefixes = container.getInstanceNames(TagLibrary.class);
for (String prefix : oldPrefixes) {
oldMap.put(prefix, container.getInstance(TagLibrary.class, prefix));
@@ -268,9 +254,7 @@ public class FreemarkerManager {
try {
init(servletContext);
} catch (TemplateException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Cannot load freemarker configuration: ",e);
}
LOG.error("Cannot load freemarker configuration: ", e);
}
// store this configuration in the servlet context
servletContext.setAttribute(CONFIG_SERVLET_CONTEXT_KEY, config);
@@ -287,9 +271,7 @@ public class FreemarkerManager {
// Process object_wrapper init-param out of order:
wrapper = createObjectWrapper(servletContext);
if (LOG.isDebugEnabled()) {
LOG.debug("Using object wrapper of class " + wrapper.getClass().getName());
}
LOG.debug("Using object wrapper of class {}", wrapper.getClass().getName());
config.setObjectWrapper(wrapper);
// Process TemplatePath init-param out of order:
@@ -480,21 +462,15 @@ public class FreemarkerManager {
}
}
} catch (IOException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Error while loading freemarker settings from /freemarker.properties", e);
}
LOG.error("Error while loading freemarker settings from /freemarker.properties", e);
} catch (TemplateException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Error while loading freemarker settings from /freemarker.properties", e);
}
LOG.error("Error while loading freemarker settings from /freemarker.properties", e);
} finally {
if (in != null) {
try {
in.close();
} catch(IOException io) {
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to close input stream", io);
}
LOG.warn("Unable to close input stream", io);
}
}
}

Some files were not shown because too many files have changed in this diff Show More