diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ActionChainResult.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ActionChainResult.java index 694dbfef7..859ccfd27 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ActionChainResult.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ActionChainResult.java @@ -186,7 +186,7 @@ public class ActionChainResult implements Result { LinkedList chainHistory = (LinkedList) ActionContext.getContext().get(CHAIN_HISTORY); // Add if not exists if (chainHistory == null) { - chainHistory = new LinkedList(); + chainHistory = new LinkedList<>(); ActionContext.getContext().put(CHAIN_HISTORY, chainHistory); } @@ -211,8 +211,7 @@ public class ActionChainResult implements Result { if (isInChainHistory(finalNamespace, finalActionName, finalMethodName)) { addToHistory(finalNamespace, finalActionName, finalMethodName); - throw new XWorkException("Infinite recursion detected: " - + ActionChainResult.getChainHistory().toString()); + throw new XWorkException("Infinite recursion detected: " + ActionChainResult.getChainHistory().toString()); } if (ActionChainResult.getChainHistory().isEmpty() && invocation != null && invocation.getProxy() != null) { @@ -220,14 +219,12 @@ public class ActionChainResult implements Result { } addToHistory(finalNamespace, finalActionName, finalMethodName); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.VALUE_STACK, ActionContext.getContext().getValueStack()); extraContext.put(ActionContext.PARAMETERS, ActionContext.getContext().getParameters()); extraContext.put(CHAIN_HISTORY, ActionChainResult.getChainHistory()); - if (LOG.isDebugEnabled()) { - LOG.debug("Chaining to action " + finalActionName); - } + LOG.debug("Chaining to action {}", finalActionName); proxy = actionProxyFactory.createActionProxy(finalNamespace, finalActionName, finalMethodName, extraContext); proxy.execute(); @@ -261,7 +258,7 @@ public class ActionChainResult implements Result { return false; } else { // Actions to skip - Set skipActionsList = new HashSet(); + Set skipActionsList = new HashSet<>(); if (skipActions != null && skipActions.length() > 0) { ValueStack stack = ActionContext.getContext().getValueStack(); String finalSkipActions = TextParseUtil.translateVariables(this.skipActions, stack); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ActionContext.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ActionContext.java index a78761db6..60ff183d4 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ActionContext.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ActionContext.java @@ -41,7 +41,7 @@ import java.util.Map; */ public class ActionContext implements Serializable { - static ThreadLocal actionContext = new ThreadLocal(); + static ThreadLocal actionContext = new ThreadLocal<>(); /** * Constant for the name of the action being executed. @@ -197,7 +197,7 @@ public class ActionContext implements Serializable { Map errors = (Map) get(CONVERSION_ERRORS); if (errors == null) { - errors = new HashMap(); + errors = new HashMap<>(); setConversionErrors(errors); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ActionSupport.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ActionSupport.java index 940dbfad7..fd8675b5f 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ActionSupport.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ActionSupport.java @@ -83,9 +83,7 @@ public class ActionSupport implements Action, Validateable, ValidationAware, Tex if (ctx != null) { return ctx.getLocale(); } else { - if (LOG.isDebugEnabled()) { LOG.debug("Action context not initialized"); - } return null; } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/CompositeTextProvider.java b/xwork-core/src/main/java/com/opensymphony/xwork2/CompositeTextProvider.java index af1898656..39276102b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/CompositeTextProvider.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/CompositeTextProvider.java @@ -19,7 +19,7 @@ public class CompositeTextProvider implements TextProvider { private static final Logger LOG = LogManager.getLogger(CompositeTextProvider.class); - private List textProviders = new ArrayList(); + private List textProviders = new ArrayList<>(); /** * Instantiates a {@link CompositeTextProvider} with some predefined textProviders. @@ -60,7 +60,7 @@ public class CompositeTextProvider implements TextProvider { * It will consult each {@link TextProvider}s and return the first valid message for this * key * - * @param key The key to lookup in ressource bundles. + * @param key The key to lookup in resource bundles. * @return The i18n text for the requested key. * @see {@link com.opensymphony.xwork2.TextProvider#getText(String)} */ @@ -83,7 +83,7 @@ public class CompositeTextProvider implements TextProvider { /** * It will consult each {@link TextProvider}s and return the first valid message for this - * key, before returining defaultValue + * key, before returning defaultValue * if every else fails. * * @param key @@ -97,8 +97,6 @@ public class CompositeTextProvider implements TextProvider { { add(obj); } - - }); } @@ -131,7 +129,7 @@ public class CompositeTextProvider implements TextProvider { /** * It will consult each {@link TextProvider}s and return the first valid message for this - * key, before returining defaultValue + * key, before returning defaultValue * * @param key * @param defaultValue @@ -155,7 +153,7 @@ public class CompositeTextProvider implements TextProvider { /** * It will consult each {@link TextProvider}s and return the first valid message for this - * key, before returining defaultValue. + * key, before returning defaultValue. * * @param key * @param defaultValue @@ -179,7 +177,7 @@ public class CompositeTextProvider implements TextProvider { /** * It will consult each {@link TextProvider}s and return the first valid message for this - * key, before returining defaultValue + * key, before returning defaultValue * * @param key * @param defaultValue @@ -203,7 +201,7 @@ public class CompositeTextProvider implements TextProvider { /** * It will consult each {@link TextProvider}s and return the first valid message for this - * key, before returining defaultValue + * key, before returning defaultValue * * @param key * @param defaultValue @@ -234,7 +232,7 @@ public class CompositeTextProvider implements TextProvider { * @see {@link TextProvider#getTexts(String)} */ public ResourceBundle getTexts(String bundleName) { - // if there's one text provider that gives us a non-null resource bunlde for this bundleName, we are ok, else try the next + // if there's one text provider that gives us a non-null resource bundle for this bundleName, we are ok, else try the next // text provider for (TextProvider textProvider : textProviders) { ResourceBundle bundle = textProvider.getTexts(bundleName); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultActionInvocation.java b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultActionInvocation.java index 1f7cfc47d..82c0eec45 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultActionInvocation.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultActionInvocation.java @@ -156,9 +156,9 @@ public class DefaultActionInvocation implements ActionInvocation { } public void setResultCode(String resultCode) { - if (isExecuted()) + if (isExecuted()) { throw new IllegalStateException("Result has already been executed."); - + } this.resultCode = resultCode; } @@ -176,7 +176,7 @@ public class DefaultActionInvocation implements ActionInvocation { */ public void addPreResultListener(PreResultListener listener) { if (preResultListeners == null) { - preResultListeners = new ArrayList(1); + preResultListeners = new ArrayList<>(1); } preResultListeners.add(listener); @@ -236,9 +236,8 @@ public class DefaultActionInvocation implements ActionInvocation { String interceptorMsg = "interceptor: " + interceptor.getName(); UtilTimerStack.push(interceptorMsg); try { - resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this); - } - finally { + resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this); + } finally { UtilTimerStack.pop(interceptorMsg); } } else { @@ -289,7 +288,7 @@ public class DefaultActionInvocation implements ActionInvocation { UtilTimerStack.push(timerKey); action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap); } catch (InstantiationException e) { - throw new XWorkException("Unable to intantiate Action!", e, proxy.getConfig()); + throw new XWorkException("Unable to instantiate Action!", e, proxy.getConfig()); } catch (IllegalAccessException e) { throw new XWorkException("Illegal access to constructor, is it public?", e, proxy.getConfig()); } catch (Exception e) { @@ -367,7 +366,7 @@ public class DefaultActionInvocation implements ActionInvocation { + " and result " + getResultCode(), proxy.getConfig()); } else { if (LOG.isDebugEnabled()) { - LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig().getLocation()); + LOG.debug("No result returned for action {} at {}", getAction().getClass().getName(), proxy.getConfig().getLocation()); } } } finally { @@ -398,7 +397,7 @@ public class DefaultActionInvocation implements ActionInvocation { invocationContext.setName(proxy.getActionName()); // get a new List so we don't get problems with the iterator if someone changes the list - List interceptorList = new ArrayList(proxy.getConfig().getInterceptors()); + List interceptorList = new ArrayList<>(proxy.getConfig().getInterceptors()); interceptors = interceptorList.iterator(); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultLocaleProvider.java b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultLocaleProvider.java index b83339cf0..09a4daaa8 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultLocaleProvider.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultLocaleProvider.java @@ -17,9 +17,7 @@ public class DefaultLocaleProvider implements LocaleProvider { if (ctx != null) { return ctx.getLocale(); } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Action context not initialized"); - } + LOG.debug("Action context not initialized"); return null; } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultTextProvider.java b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultTextProvider.java index 7e331fd9b..eb57deb02 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultTextProvider.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultTextProvider.java @@ -119,7 +119,7 @@ public class DefaultTextProvider implements TextProvider, Serializable, Unchaina public String getText(String key, String defaultValue, String obj) { - List args = new ArrayList(1); + List args = new ArrayList<>(1); args.add(obj); return getText(key, defaultValue, args); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultUnknownHandlerManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultUnknownHandlerManager.java index b0fffd5c3..92f7ba796 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultUnknownHandlerManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/DefaultUnknownHandlerManager.java @@ -58,7 +58,7 @@ public class DefaultUnknownHandlerManager implements UnknownHandlerManager { if (configuration != null && container != null) { List unkownHandlerStack = configuration.getUnknownHandlerStack(); - unknownHandlers = new ArrayList(); + unknownHandlers = new ArrayList<>(); if (unkownHandlerStack != null && !unkownHandlerStack.isEmpty()) { //get UnknownHandlers in the specified order @@ -68,9 +68,9 @@ public class DefaultUnknownHandlerManager implements UnknownHandlerManager { } } else { //add all available UnknownHandlers - Set unknowHandlerNames = container.getInstanceNames(UnknownHandler.class); - for (String unknowHandlerName : unknowHandlerNames) { - UnknownHandler uh = container.getInstance(UnknownHandler.class, unknowHandlerName); + Set unknownHandlerNames = container.getInstanceNames(UnknownHandler.class); + for (String unknownHandlerName : unknownHandlerNames) { + UnknownHandler uh = container.getInstance(UnknownHandler.class, unknownHandlerName); unknownHandlers.add(uh); } } @@ -83,8 +83,9 @@ public class DefaultUnknownHandlerManager implements UnknownHandlerManager { public Result handleUnknownResult(ActionContext actionContext, String actionName, ActionConfig actionConfig, String resultCode) { for (UnknownHandler unknownHandler : unknownHandlers) { Result result = unknownHandler.handleUnknownResult(actionContext, actionName, actionConfig, resultCode); - if (result != null) + if (result != null) { return result; + } } return null; @@ -98,8 +99,9 @@ public class DefaultUnknownHandlerManager implements UnknownHandlerManager { public Object handleUnknownMethod(Object action, String methodName) throws NoSuchMethodException { for (UnknownHandler unknownHandler : unknownHandlers) { Object result = unknownHandler.handleUnknownActionMethod(action, methodName); - if (result != null) + if (result != null) { return result; + } } return null; @@ -111,8 +113,9 @@ public class DefaultUnknownHandlerManager implements UnknownHandlerManager { public ActionConfig handleUnknownAction(String namespace, String actionName) { for (UnknownHandler unknownHandler : unknownHandlers) { ActionConfig result = unknownHandler.handleUnknownAction(namespace, actionName); - if (result != null) + if (result != null) { return result; + } } return null; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/TextProviderSupport.java b/xwork-core/src/main/java/com/opensymphony/xwork2/TextProviderSupport.java index 947613327..8b641a451 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/TextProviderSupport.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/TextProviderSupport.java @@ -148,7 +148,7 @@ public class TextProviderSupport implements ResourceBundleTextProvider { * @return value of named text or the provided defaultValue if no value is found */ public String getText(String key, String defaultValue, String arg) { - List args = new ArrayList(); + List args = new ArrayList<>(); args.add(arg); return getText(key, defaultValue, args); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ValidationAwareSupport.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ValidationAwareSupport.java index 5e93b4e6b..520513be1 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ValidationAwareSupport.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ValidationAwareSupport.java @@ -38,7 +38,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { } public synchronized Collection getActionErrors() { - return new LinkedList(internalGetActionErrors()); + return new LinkedList<>(internalGetActionErrors()); } public synchronized void setActionMessages(Collection messages) { @@ -46,7 +46,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { } public synchronized Collection getActionMessages() { - return new LinkedList(internalGetActionMessages()); + return new LinkedList<>(internalGetActionMessages()); } public synchronized void setFieldErrors(Map> errorMap) { @@ -54,7 +54,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { } public synchronized Map> getFieldErrors() { - return new LinkedHashMap>(internalGetFieldErrors()); + return new LinkedHashMap<>(internalGetFieldErrors()); } public synchronized void addActionError(String anErrorMessage) { @@ -70,7 +70,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { List thisFieldErrors = errors.get(fieldName); if (thisFieldErrors == null) { - thisFieldErrors = new ArrayList(); + thisFieldErrors = new ArrayList<>(); errors.put(fieldName, thisFieldErrors); } @@ -95,7 +95,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { private Collection internalGetActionErrors() { if (actionErrors == null) { - actionErrors = new ArrayList(); + actionErrors = new ArrayList<>(); } return actionErrors; @@ -103,7 +103,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { private Collection internalGetActionMessages() { if (actionMessages == null) { - actionMessages = new ArrayList(); + actionMessages = new ArrayList<>(); } return actionMessages; @@ -111,7 +111,7 @@ public class ValidationAwareSupport implements ValidationAware, Serializable { private Map> internalGetFieldErrors() { if (fieldErrors == null) { - fieldErrors = new LinkedHashMap>(); + fieldErrors = new LinkedHashMap<>(); } return fieldErrors; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/XWorkException.java b/xwork-core/src/main/java/com/opensymphony/xwork2/XWorkException.java index 3242ce9e6..8445a1c58 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/XWorkException.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/XWorkException.java @@ -54,7 +54,7 @@ public class XWorkException extends RuntimeException implements Locatable { * @param target the target of the exception. */ public XWorkException(String s, Object target) { - this(s, (Throwable) null, target); + this(s, null, target); } /** diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationManager.java index a850f7936..38920f7ac 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationManager.java @@ -19,8 +19,8 @@ import com.opensymphony.xwork2.XWorkConstants; import com.opensymphony.xwork2.config.impl.DefaultConfiguration; import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -41,8 +41,8 @@ public class ConfigurationManager { protected static final Logger LOG = LogManager.getLogger(ConfigurationManager.class); protected Configuration configuration; protected Lock providerLock = new ReentrantLock(); - private List containerProviders = new CopyOnWriteArrayList(); - private List packageProviders = new CopyOnWriteArrayList(); + private List containerProviders = new CopyOnWriteArrayList<>(); + private List packageProviders = new CopyOnWriteArrayList<>(); protected String defaultFrameworkBeanName; private boolean providersChanged = false; private boolean reloadConfigs = true; // for the first time @@ -117,7 +117,7 @@ public class ConfigurationManager { public void setContainerProviders(List containerProviders) { providerLock.lock(); try { - this.containerProviders = new CopyOnWriteArrayList(containerProviders); + this.containerProviders = new CopyOnWriteArrayList<>(containerProviders); providersChanged = true; } finally { providerLock.unlock(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationUtil.java index ea848418a..e7ba7a616 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/ConfigurationUtil.java @@ -16,8 +16,9 @@ package com.opensymphony.xwork2.config; import com.opensymphony.xwork2.config.entities.PackageConfig; -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 java.util.ArrayList; import java.util.Collections; @@ -44,7 +45,7 @@ public class ConfigurationUtil { */ public static List buildParentsFromString(Configuration configuration, String parent) { List parentPackageNames = buildParentListFromString(parent); - List parentPackageConfigs = new ArrayList(); + List parentPackageConfigs = new ArrayList<>(); for (String parentPackageName : parentPackageNames) { PackageConfig parentPackageContext = configuration.getPackageConfig(parentPackageName); @@ -62,17 +63,17 @@ public class ConfigurationUtil { * @return A list of tokens from the specified string. */ public static List buildParentListFromString(String parent) { - if ((parent == null) || ("".equals(parent))) { + if (StringUtils.isEmpty(parent)) { return Collections.emptyList(); } StringTokenizer tokenizer = new StringTokenizer(parent, ","); - List parents = new ArrayList(); + List parents = new ArrayList<>(); while (tokenizer.hasMoreTokens()) { String parentName = tokenizer.nextToken().trim(); - if (!"".equals(parentName)) { + if (StringUtils.isNotEmpty(parentName)) { parents.add(parentName); } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ActionConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ActionConfig.java index 0bc9363b9..d796c0268 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ActionConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ActionConfig.java @@ -20,14 +20,7 @@ import com.opensymphony.xwork2.util.location.Location; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** @@ -82,11 +75,11 @@ public class ActionConfig extends Located implements Serializable { this.className = orig.className; this.methodName = orig.methodName; this.packageName = orig.packageName; - this.params = new LinkedHashMap(orig.params); - this.interceptors = new ArrayList(orig.interceptors); - this.results = new LinkedHashMap(orig.results); - this.exceptionMappings = new ArrayList(orig.exceptionMappings); - this.allowedMethods = new HashSet(orig.allowedMethods); + this.params = new LinkedHashMap<>(orig.params); + this.interceptors = new ArrayList<>(orig.interceptors); + this.results = new LinkedHashMap<>(orig.results); + this.exceptionMappings = new ArrayList<>(orig.exceptionMappings); + this.allowedMethods = new HashSet<>(orig.allowedMethods); this.location = orig.location; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ExceptionMappingConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ExceptionMappingConfig.java index 5dcd2668a..21a791e96 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ExceptionMappingConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ExceptionMappingConfig.java @@ -41,14 +41,14 @@ public class ExceptionMappingConfig extends Located implements Serializable { this.name = name; this.exceptionClassName = exceptionClassName; this.result = result; - this.params = new LinkedHashMap(); + this.params = new LinkedHashMap<>(); } protected ExceptionMappingConfig(ExceptionMappingConfig target) { this.name = target.name; this.exceptionClassName = target.exceptionClassName; this.result = target.result; - this.params = new LinkedHashMap(target.params); + this.params = new LinkedHashMap<>(target.params); this.location = target.location; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorConfig.java index 288fa552d..b04bbd993 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorConfig.java @@ -37,7 +37,7 @@ public class InterceptorConfig extends Located implements Serializable { protected String name; protected InterceptorConfig(String name, String className) { - this.params = new LinkedHashMap(); + this.params = new LinkedHashMap<>(); this.name = name; this.className = className; } @@ -45,7 +45,7 @@ public class InterceptorConfig extends Located implements Serializable { protected InterceptorConfig(InterceptorConfig orig) { this.name = orig.name; this.className = orig.className; - this.params = new LinkedHashMap(orig.params); + this.params = new LinkedHashMap<>(orig.params); this.location = orig.location; } @@ -73,8 +73,7 @@ public class InterceptorConfig extends Located implements Serializable { final InterceptorConfig interceptorConfig = (InterceptorConfig) o; - if ((className != null) ? (!className.equals(interceptorConfig.className)) : (interceptorConfig.className != null)) - { + if ((className != null) ? (!className.equals(interceptorConfig.className)) : (interceptorConfig.className != null)) { return false; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorStackConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorStackConfig.java index d3e41f93a..b9e2f78cc 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorStackConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/InterceptorStackConfig.java @@ -57,7 +57,7 @@ public class InterceptorStackConfig extends Located implements Serializable { */ protected InterceptorStackConfig(InterceptorStackConfig orig) { this.name = orig.name; - this.interceptors = new ArrayList(orig.interceptors); + this.interceptors = new ArrayList<>(orig.interceptors); this.location = orig.location; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/PackageConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/PackageConfig.java index 7d0a981f3..d4a3c5ca8 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/PackageConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/PackageConfig.java @@ -17,15 +17,11 @@ package com.opensymphony.xwork2.config.entities; import com.opensymphony.xwork2.util.location.Located; 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 java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** @@ -57,12 +53,12 @@ public class PackageConfig extends Located implements Comparable, Serializable, protected PackageConfig(String name) { this.name = name; - actionConfigs = new LinkedHashMap(); - globalResultConfigs = new LinkedHashMap(); - interceptorConfigs = new LinkedHashMap(); - resultTypeConfigs = new LinkedHashMap(); - globalExceptionMappingConfigs = new ArrayList(); - parents = new ArrayList(); + actionConfigs = new LinkedHashMap<>(); + globalResultConfigs = new LinkedHashMap<>(); + interceptorConfigs = new LinkedHashMap<>(); + resultTypeConfigs = new LinkedHashMap<>(); + globalExceptionMappingConfigs = new ArrayList<>(); + parents = new ArrayList<>(); } protected PackageConfig(PackageConfig orig) { @@ -74,12 +70,12 @@ public class PackageConfig extends Located implements Comparable, Serializable, this.namespace = orig.namespace; this.isAbstract = orig.isAbstract; this.needsRefresh = orig.needsRefresh; - this.actionConfigs = new LinkedHashMap(orig.actionConfigs); - this.globalResultConfigs = new LinkedHashMap(orig.globalResultConfigs); - this.interceptorConfigs = new LinkedHashMap(orig.interceptorConfigs); - this.resultTypeConfigs = new LinkedHashMap(orig.resultTypeConfigs); - this.globalExceptionMappingConfigs = new ArrayList(orig.globalExceptionMappingConfigs); - this.parents = new ArrayList(orig.parents); + this.actionConfigs = new LinkedHashMap<>(orig.actionConfigs); + this.globalResultConfigs = new LinkedHashMap<>(orig.globalResultConfigs); + this.interceptorConfigs = new LinkedHashMap<>(orig.interceptorConfigs); + this.resultTypeConfigs = new LinkedHashMap<>(orig.resultTypeConfigs); + this.globalExceptionMappingConfigs = new ArrayList<>(orig.globalExceptionMappingConfigs); + this.parents = new ArrayList<>(orig.parents); this.location = orig.location; } @@ -99,7 +95,7 @@ public class PackageConfig extends Located implements Comparable, Serializable, * @see ActionConfig */ public Map getAllActionConfigs() { - Map retMap = new LinkedHashMap(); + Map retMap = new LinkedHashMap<>(); if (!parents.isEmpty()) { for (PackageConfig parent : parents) { @@ -120,7 +116,7 @@ public class PackageConfig extends Located implements Comparable, Serializable, * @see ResultConfig */ public Map getAllGlobalResults() { - Map retMap = new LinkedHashMap(); + Map retMap = new LinkedHashMap<>(); if (!parents.isEmpty()) { for (PackageConfig parentConfig : parents) { @@ -142,7 +138,7 @@ public class PackageConfig extends Located implements Comparable, Serializable, * @see InterceptorStackConfig */ public Map getAllInterceptorConfigs() { - Map retMap = new LinkedHashMap(); + Map retMap = new LinkedHashMap<>(); if (!parents.isEmpty()) { for (PackageConfig parentContext : parents) { @@ -163,7 +159,7 @@ public class PackageConfig extends Located implements Comparable, Serializable, * @see ResultTypeConfig */ public Map getAllResultTypeConfigs() { - Map retMap = new LinkedHashMap(); + Map retMap = new LinkedHashMap<>(); if (!parents.isEmpty()) { for (PackageConfig parentContext : parents) { @@ -184,7 +180,7 @@ public class PackageConfig extends Located implements Comparable, Serializable, * @see ExceptionMappingConfig */ public List getAllExceptionMappingConfigs() { - List allExceptionMappings = new ArrayList(); + List allExceptionMappings = new ArrayList<>(); if (!parents.isEmpty()) { for (PackageConfig parentContext : parents) { @@ -310,7 +306,7 @@ public class PackageConfig extends Located implements Comparable, Serializable, } public List getParents() { - return new ArrayList(parents); + return new ArrayList<>(parents); } /** diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultConfig.java index 3c7ab2dfe..b9ed588dc 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultConfig.java @@ -40,7 +40,7 @@ public class ResultConfig extends Located implements Serializable { protected ResultConfig(String name, String className) { this.name = name; this.className = className; - params = new LinkedHashMap(); + params = new LinkedHashMap<>(); } protected ResultConfig(ResultConfig orig) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultTypeConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultTypeConfig.java index 85ef0232f..96ff4ff2d 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultTypeConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/entities/ResultTypeConfig.java @@ -43,7 +43,7 @@ public class ResultTypeConfig extends Located implements Serializable { protected ResultTypeConfig(String name, String className) { this.name = name; this.className = className; - params = new LinkedHashMap(); + params = new LinkedHashMap<>(); } protected ResultTypeConfig(ResultTypeConfig orig) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/AbstractMatcher.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/AbstractMatcher.java index 5a1d33d58..5deb7cb27 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/AbstractMatcher.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/AbstractMatcher.java @@ -18,16 +18,12 @@ package com.opensymphony.xwork2.config.impl; import com.opensymphony.xwork2.util.PatternMatcher; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import org.apache.commons.lang3.math.NumberUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** *

Matches patterns against pre-compiled wildcard expressions pulled from @@ -52,7 +48,8 @@ public abstract class AbstractMatcher implements Serializable { /** *

The compiled patterns and their associated target objects

*/ - List> compiledPatterns = new ArrayList>();; + List> compiledPatterns = new ArrayList<>(); + ; public AbstractMatcher(PatternMatcher helper) { this.wildcard = (PatternMatcher) helper; @@ -86,9 +83,7 @@ public abstract class AbstractMatcher implements Serializable { name = name.substring(1); } - if (log.isDebugEnabled()) { - log.debug("Compiling pattern '" + name + "'"); - } + log.debug("Compiling pattern '{}'", name); pattern = wildcard.compilePattern(name); compiledPatterns.add(new Mapping(name, pattern, target)); @@ -119,22 +114,13 @@ public abstract class AbstractMatcher implements Serializable { E config = null; if (compiledPatterns.size() > 0) { - if (log.isDebugEnabled()) { - log.debug("Attempting to match '" + potentialMatch - + "' to a wildcard pattern, "+ compiledPatterns.size() - + " available"); - } + log.debug("Attempting to match '{}' to a wildcard pattern, {} available", potentialMatch, compiledPatterns.size()); Map vars = new LinkedHashMap(); for (Mapping m : compiledPatterns) { if (wildcard.match(vars, potentialMatch, m.getPattern())) { - if (log.isDebugEnabled()) { - log.debug("Value matches pattern '" - + m.getOriginalPattern() + "'"); - } - - config = - convert(potentialMatch, m.getTarget(), vars); + log.debug("Value matches pattern '{}'", m.getOriginalPattern()); + config = convert(potentialMatch, m.getTarget(), vars); break; } } @@ -159,11 +145,11 @@ public abstract class AbstractMatcher implements Serializable { *

Replaces parameter values *

* - * @param orig The original parameters with placehold values + * @param orig The original parameters with placeholder values * @param vars A Map of wildcard-matched strings */ protected Map replaceParameters(Map orig, Map vars) { - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap<>(); //this will set the group index references, like {1} for (String key : orig.keySet()) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcher.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcher.java index b92e420a6..e282c1ade 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcher.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcher.java @@ -120,7 +120,7 @@ public class ActionConfigMatcher extends AbstractMatcher implement Map params = replaceParameters(orig.getParams(), vars); - Map results = new LinkedHashMap(); + Map results = new LinkedHashMap<>(); for (String name : orig.getResults().keySet()) { ResultConfig result = orig.getResults().get(name); name = convertParam(name, vars); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/DefaultConfiguration.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/DefaultConfiguration.java index d811c43d8..7d5e5ccda 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/DefaultConfiguration.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/DefaultConfiguration.java @@ -15,91 +15,29 @@ */ package com.opensymphony.xwork2.config.impl; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.DefaultLocaleProvider; -import com.opensymphony.xwork2.DefaultTextProvider; -import com.opensymphony.xwork2.FileManager; -import com.opensymphony.xwork2.FileManagerFactory; -import com.opensymphony.xwork2.LocaleProvider; -import com.opensymphony.xwork2.ObjectFactory; -import com.opensymphony.xwork2.TextProvider; -import com.opensymphony.xwork2.XWorkConstants; -import com.opensymphony.xwork2.config.Configuration; -import com.opensymphony.xwork2.config.ConfigurationException; -import com.opensymphony.xwork2.config.ConfigurationProvider; -import com.opensymphony.xwork2.config.ContainerProvider; -import com.opensymphony.xwork2.config.FileManagerFactoryProvider; -import com.opensymphony.xwork2.config.FileManagerProvider; -import com.opensymphony.xwork2.config.PackageProvider; -import com.opensymphony.xwork2.config.RuntimeConfiguration; -import com.opensymphony.xwork2.config.entities.ActionConfig; -import com.opensymphony.xwork2.config.entities.InterceptorMapping; -import com.opensymphony.xwork2.config.entities.PackageConfig; -import com.opensymphony.xwork2.config.entities.ResultConfig; -import com.opensymphony.xwork2.config.entities.ResultTypeConfig; -import com.opensymphony.xwork2.config.entities.UnknownHandlerConfig; +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.config.*; +import com.opensymphony.xwork2.config.entities.*; import com.opensymphony.xwork2.config.providers.InterceptorBuilder; -import com.opensymphony.xwork2.conversion.ConversionAnnotationProcessor; -import com.opensymphony.xwork2.conversion.ConversionFileProcessor; -import com.opensymphony.xwork2.conversion.ConversionPropertiesProcessor; -import com.opensymphony.xwork2.conversion.ObjectTypeDeterminer; -import com.opensymphony.xwork2.conversion.TypeConverter; -import com.opensymphony.xwork2.conversion.TypeConverterCreator; -import com.opensymphony.xwork2.conversion.TypeConverterHolder; -import com.opensymphony.xwork2.conversion.impl.ArrayConverter; -import com.opensymphony.xwork2.conversion.impl.CollectionConverter; -import com.opensymphony.xwork2.conversion.impl.DateConverter; -import com.opensymphony.xwork2.conversion.impl.DefaultConversionAnnotationProcessor; -import com.opensymphony.xwork2.conversion.impl.DefaultConversionFileProcessor; -import com.opensymphony.xwork2.conversion.impl.DefaultConversionPropertiesProcessor; -import com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer; -import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverterCreator; -import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverterHolder; -import com.opensymphony.xwork2.conversion.impl.NumberConverter; -import com.opensymphony.xwork2.conversion.impl.StringConverter; -import com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter; -import com.opensymphony.xwork2.conversion.impl.XWorkConverter; -import com.opensymphony.xwork2.factory.ActionFactory; -import com.opensymphony.xwork2.factory.ConverterFactory; -import com.opensymphony.xwork2.factory.DefaultActionFactory; -import com.opensymphony.xwork2.factory.DefaultConverterFactory; -import com.opensymphony.xwork2.factory.DefaultInterceptorFactory; -import com.opensymphony.xwork2.factory.DefaultResultFactory; -import com.opensymphony.xwork2.factory.DefaultUnknownHandlerFactory; -import com.opensymphony.xwork2.factory.InterceptorFactory; -import com.opensymphony.xwork2.factory.ResultFactory; -import com.opensymphony.xwork2.factory.UnknownHandlerFactory; -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.conversion.*; +import com.opensymphony.xwork2.conversion.impl.*; +import com.opensymphony.xwork2.factory.*; +import com.opensymphony.xwork2.inject.*; import com.opensymphony.xwork2.ognl.OgnlReflectionProvider; import com.opensymphony.xwork2.ognl.OgnlUtil; import com.opensymphony.xwork2.ognl.OgnlValueStackFactory; import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor; -import com.opensymphony.xwork2.util.CompoundRoot; -import com.opensymphony.xwork2.util.OgnlTextParser; -import com.opensymphony.xwork2.util.PatternMatcher; -import com.opensymphony.xwork2.util.TextParser; -import com.opensymphony.xwork2.util.ValueStack; -import com.opensymphony.xwork2.util.ValueStackFactory; +import com.opensymphony.xwork2.util.*; import com.opensymphony.xwork2.util.fs.DefaultFileManager; import com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory; import com.opensymphony.xwork2.util.location.LocatableProperties; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import com.opensymphony.xwork2.util.reflection.ReflectionProvider; import ognl.PropertyAccessor; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; +import java.util.*; /** @@ -114,11 +52,11 @@ public class DefaultConfiguration implements Configuration { // Programmatic Action Configurations - protected Map packageContexts = new LinkedHashMap(); + protected Map packageContexts = new LinkedHashMap<>(); protected RuntimeConfiguration runtimeConfiguration; protected Container container; protected String defaultFrameworkBeanName; - protected Set loadedFileNames = new TreeSet(); + protected Set loadedFileNames = new TreeSet<>(); protected List unknownHandlerStack; @@ -173,11 +111,8 @@ public class DefaultConfiguration implements Configuration { if (check != null) { if (check.getLocation() != null && packageContext.getLocation() != null && check.getLocation().equals(packageContext.getLocation())) { - if (LOG.isDebugEnabled()) { - LOG.debug("The package name '" + name - + "' is already been loaded by the same location and could be removed: " - + packageContext.getLocation()); - } + LOG.debug("The package name '{}' is already been loaded by the same location and could be removed: {}", + name, packageContext.getLocation()); } else { throw new ConfigurationException("The package name '" + name + "' at location "+packageContext.getLocation() @@ -213,7 +148,7 @@ public class DefaultConfiguration implements Configuration { public synchronized void reload(List providers) throws ConfigurationException { // Silly copy necessary due to lack of ability to cast generic lists - List contProviders = new ArrayList(); + List contProviders = new ArrayList<>(); contProviders.addAll(providers); reloadContainer(contProviders); @@ -228,7 +163,7 @@ public class DefaultConfiguration implements Configuration { public synchronized List reloadContainer(List providers) throws ConfigurationException { packageContexts.clear(); loadedFileNames.clear(); - List packageProviders = new ArrayList(); + List packageProviders = new ArrayList<>(); ContainerProperties props = new ContainerProperties(); ContainerBuilder builder = new ContainerBuilder(); @@ -362,8 +297,8 @@ public class DefaultConfiguration implements Configuration { * will have two results. */ protected synchronized RuntimeConfiguration buildRuntimeConfiguration() throws ConfigurationException { - Map> namespaceActionConfigs = new LinkedHashMap>(); - Map namespaceConfigs = new LinkedHashMap(); + Map> namespaceActionConfigs = new LinkedHashMap<>(); + Map namespaceConfigs = new LinkedHashMap<>(); for (PackageConfig packageConfig : packageContexts.values()) { @@ -372,7 +307,7 @@ public class DefaultConfiguration implements Configuration { Map configs = namespaceActionConfigs.get(namespace); if (configs == null) { - configs = new LinkedHashMap(); + configs = new LinkedHashMap<>(); } Map actionConfigs = packageConfig.getAllActionConfigs(); @@ -418,8 +353,8 @@ public class DefaultConfiguration implements Configuration { * */ private ActionConfig buildFullActionConfig(PackageConfig packageContext, ActionConfig baseConfig) throws ConfigurationException { - Map params = new TreeMap(baseConfig.getParams()); - Map results = new TreeMap(); + Map params = new TreeMap<>(baseConfig.getParams()); + Map results = new TreeMap<>(); if (!baseConfig.getPackageName().equals(packageContext.getName()) && packageContexts.containsKey(baseConfig.getPackageName())) { results.putAll(packageContexts.get(baseConfig.getPackageName()).getAllGlobalResults()); @@ -431,7 +366,7 @@ public class DefaultConfiguration implements Configuration { setDefaultResults(results, packageContext); - List interceptors = new ArrayList(baseConfig.getInterceptors()); + List interceptors = new ArrayList<>(baseConfig.getInterceptors()); if (interceptors.size() <= 0) { String defaultInterceptorRefName = packageContext.getFullDefaultInterceptorRef(); @@ -465,7 +400,7 @@ public class DefaultConfiguration implements Configuration { this.namespaceActionConfigs = namespaceActionConfigs; this.namespaceConfigs = namespaceConfigs; - this.namespaceActionConfigMatchers = new LinkedHashMap(); + this.namespaceActionConfigMatchers = new LinkedHashMap<>(); this.namespaceMatcher = new NamespaceMatcher(matcher, namespaceActionConfigs.keySet()); for (String ns : namespaceActionConfigs.keySet()) { @@ -501,7 +436,7 @@ public class DefaultConfiguration implements Configuration { } // fail over to empty namespace - if ((config == null) && (namespace != null) && (!"".equals(namespace.trim()))) { + if (config == null && StringUtils.isNotBlank(namespace)) { config = findActionConfigInNamespace("", name); } @@ -564,7 +499,7 @@ public class DefaultConfiguration implements Configuration { public Object setProperty(String key, String value) { String oldValue = getProperty(key); if (LOG.isInfoEnabled() && oldValue != null && !oldValue.equals(value) && !defaultFrameworkBeanName.equals(oldValue)) { - LOG.info("Overriding property "+key+" - old value: "+oldValue+" new value: "+value); + LOG.info("Overriding property {} - old value: {} new value: {}", key, oldValue, value); } return super.setProperty(key, value); } @@ -572,8 +507,7 @@ public class DefaultConfiguration implements Configuration { public void setConstants(ContainerBuilder builder) { for (Object keyobj : keySet()) { String key = (String)keyobj; - builder.factory(String.class, key, - new LocatableConstantFactory(getProperty(key), getPropertyLocation(key))); + builder.factory(String.class, key, new LocatableConstantFactory<>(getProperty(key), getPropertyLocation(key))); } } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/MockConfiguration.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/MockConfiguration.java index 7238e012d..d5359feeb 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/MockConfiguration.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/impl/MockConfiguration.java @@ -16,12 +16,7 @@ package com.opensymphony.xwork2.config.impl; import com.opensymphony.xwork2.XWorkConstants; -import com.opensymphony.xwork2.config.Configuration; -import com.opensymphony.xwork2.config.ConfigurationException; -import com.opensymphony.xwork2.config.ConfigurationProvider; -import com.opensymphony.xwork2.config.ContainerProvider; -import com.opensymphony.xwork2.config.PackageProvider; -import com.opensymphony.xwork2.config.RuntimeConfiguration; +import com.opensymphony.xwork2.config.*; import com.opensymphony.xwork2.config.entities.PackageConfig; import com.opensymphony.xwork2.config.entities.UnknownHandlerConfig; import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; @@ -30,11 +25,7 @@ import com.opensymphony.xwork2.inject.ContainerBuilder; import com.opensymphony.xwork2.inject.Scope; import com.opensymphony.xwork2.util.location.LocatableProperties; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** @@ -42,8 +33,8 @@ import java.util.Set; */ public class MockConfiguration implements Configuration { - private Map packages = new HashMap(); - private Set loadedFiles = new HashSet(); + private Map packages = new HashMap<>(); + private Set loadedFiles = new HashSet<>(); private Container container; protected List unknownHandlerStack; private ContainerBuilder builder; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/CycleDetector.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/CycleDetector.java index 0bba85c06..82a72662a 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/CycleDetector.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/CycleDetector.java @@ -14,8 +14,8 @@ public class CycleDetector { public CycleDetector(DirectedGraph graph) { this.graph = graph; - marks = new HashMap(); - verticesInCycles = new ArrayList(); + marks = new HashMap<>(); + verticesInCycles = new ArrayList<>(); } public boolean containsCycle() { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/InterceptorBuilder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/InterceptorBuilder.java index 5c3e36029..132820579 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/InterceptorBuilder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/InterceptorBuilder.java @@ -23,8 +23,8 @@ import com.opensymphony.xwork2.config.entities.InterceptorMapping; import com.opensymphony.xwork2.config.entities.InterceptorStackConfig; import com.opensymphony.xwork2.interceptor.Interceptor; 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 java.util.ArrayList; import java.util.LinkedHashMap; @@ -57,14 +57,14 @@ public class InterceptorBuilder { public static List constructInterceptorReference(InterceptorLocator interceptorLocator, String refName, Map refParams, Location location, ObjectFactory objectFactory) throws ConfigurationException { Object referencedConfig = interceptorLocator.getInterceptorConfig(refName); - List result = new ArrayList(); + List result = new ArrayList<>(); if (referencedConfig == null) { throw new ConfigurationException("Unable to find interceptor class referenced by ref-name " + refName, location); } else { if (referencedConfig instanceof InterceptorConfig) { InterceptorConfig config = (InterceptorConfig) referencedConfig; - Interceptor inter = null; + Interceptor inter; try { inter = objectFactory.buildInterceptor(config, refParams); @@ -105,7 +105,7 @@ public class InterceptorBuilder { InterceptorLocator interceptorLocator, InterceptorStackConfig stackConfig, Map refParams, ObjectFactory objectFactory) { List result; - Map> params = new LinkedHashMap>(); + Map> params = new LinkedHashMap<>(); /* * We strip @@ -139,7 +139,7 @@ public class InterceptorBuilder { if (params.containsKey(name)) { map = params.get(name); } else { - map = new LinkedHashMap(); + map = new LinkedHashMap<>(); } map.put(key, value); @@ -150,7 +150,7 @@ public class InterceptorBuilder { } } - result = new ArrayList(stackConfig.getInterceptors()); + result = new ArrayList<>(stackConfig.getInterceptors()); for (String key : params.keySet()) { @@ -192,7 +192,7 @@ public class InterceptorBuilder { } else if (interceptorCfgObj instanceof InterceptorStackConfig) { // interceptor-ref param refer to an interceptor stack - // If its an interceptor-stack, we call this method recursively untill, + // If its an interceptor-stack, we call this method recursively until, // all the params (eg. interceptorStack1.interceptor1.param etc.) // are resolved down to a specific interceptor. diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProvider.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProvider.java index fe84e09fc..0cf7059e4 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProvider.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProvider.java @@ -15,36 +15,33 @@ */ package com.opensymphony.xwork2.config.providers; -import com.opensymphony.xwork2.Action; -import com.opensymphony.xwork2.FileManager; -import com.opensymphony.xwork2.FileManagerFactory; -import com.opensymphony.xwork2.ObjectFactory; -import com.opensymphony.xwork2.XWorkException; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.Configuration; import com.opensymphony.xwork2.config.ConfigurationException; import com.opensymphony.xwork2.config.ConfigurationProvider; import com.opensymphony.xwork2.config.ConfigurationUtil; import com.opensymphony.xwork2.config.entities.*; -import com.opensymphony.xwork2.config.entities.UnknownHandlerConfig; import com.opensymphony.xwork2.config.impl.LocatableFactory; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.inject.ContainerBuilder; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.inject.Scope; -import com.opensymphony.xwork2.util.*; +import com.opensymphony.xwork2.util.ClassLoaderUtil; +import com.opensymphony.xwork2.util.ClassPathFinder; +import com.opensymphony.xwork2.util.DomHelper; +import com.opensymphony.xwork2.util.TextParseUtil; 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.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; - +import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; @@ -71,12 +68,12 @@ public class XmlConfigurationProvider implements ConfigurationProvider { private String configFileName; private ObjectFactory objectFactory; - private Set loadedFileUrls = new HashSet(); + private Set loadedFileUrls = new HashSet<>(); private boolean errorIfMissing; private Map dtdMappings; private Configuration configuration; private boolean throwExceptionOnDuplicateBeans = true; - private Map declaredPackages = new HashMap(); + private Map declaredPackages = new HashMap<>(); private FileManager fileManager; @@ -92,7 +89,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { this.configFileName = filename; this.errorIfMissing = errorIfMissing; - Map mappings = new HashMap(); + Map mappings = new HashMap<>(); mappings.put("-//Apache Struts//XWork 2.3//EN", "xwork-2.3.dtd"); mappings.put("-//Apache Struts//XWork 2.1.3//EN", "xwork-2.1.3.dtd"); mappings.put("-//Apache Struts//XWork 2.1//EN", "xwork-2.1.dtd"); @@ -173,10 +170,8 @@ public class XmlConfigurationProvider implements ConfigurationProvider { } public void register(ContainerBuilder containerBuilder, LocatableProperties props) throws ConfigurationException { - if (LOG.isInfoEnabled()) { - LOG.info("Parsing configuration file [" + configFileName + "]"); - } - Map loadedBeans = new HashMap(); + LOG.info("Parsing configuration file [{}]", configFileName); + Map loadedBeans = new HashMap<>(); for (Document doc : documents) { Element rootElement = doc.getDocumentElement(); NodeList children = rootElement.getChildNodes(); @@ -215,33 +210,31 @@ public class XmlConfigurationProvider implements ConfigurationProvider { } try { - Class cimpl = ClassLoaderUtil.loadClass(impl, getClass()); - Class ctype = cimpl; + Class classImpl = ClassLoaderUtil.loadClass(impl, getClass()); + Class classType = classImpl; if (StringUtils.isNotEmpty(type)) { - ctype = ClassLoaderUtil.loadClass(type, getClass()); + classType = ClassLoaderUtil.loadClass(type, getClass()); } if ("true".equals(onlyStatic)) { // Force loading of class to detect no class def found exceptions - cimpl.getDeclaredClasses(); - containerBuilder.injectStatics(cimpl); + classImpl.getDeclaredClasses(); + containerBuilder.injectStatics(classImpl); } else { - if (containerBuilder.contains(ctype, name)) { - Location loc = LocationUtils.getLocation(loadedBeans.get(ctype.getName() + name)); + if (containerBuilder.contains(classType, name)) { + Location loc = LocationUtils.getLocation(loadedBeans.get(classType.getName() + name)); if (throwExceptionOnDuplicateBeans) { - throw new ConfigurationException("Bean type " + ctype + " with the name " + + throw new ConfigurationException("Bean type " + classType + " with the name " + name + " has already been loaded by " + loc, child); } } // Force loading of class to detect no class def found exceptions - cimpl.getDeclaredConstructors(); + classImpl.getDeclaredConstructors(); - if (LOG.isDebugEnabled()) { - LOG.debug("Loaded type:" + type + " name:" + name + " impl:" + impl); - } - containerBuilder.factory(ctype, name, new LocatableFactory(name, ctype, cimpl, scope, childNode), scope); + LOG.debug("Loaded type: {} name: {} impl: {}", type, name, impl); + containerBuilder.factory(classType, name, new LocatableFactory(name, classType, classImpl, scope, childNode), scope); } - loadedBeans.put(ctype.getName() + name, child); + loadedBeans.put(classType.getName() + name, child); } catch (Throwable ex) { if (!optional) { throw new ConfigurationException("Unable to load bean: type:" + type + " class:" + impl, ex, childNode); @@ -314,7 +307,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { } private void verifyPackageStructure() { - DirectedGraph graph = new DirectedGraph(); + DirectedGraph graph = new DirectedGraph<>(); for (Document doc : documents) { Element rootElement = doc.getDocumentElement(); @@ -343,7 +336,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { } } - CycleDetector detector = new CycleDetector(graph); + CycleDetector detector = new CycleDetector<>(graph); if (detector.containsCycle()) { StringBuilder builder = new StringBuilder("The following packages participate in cycles:"); for (String packageName : detector.getVerticesInCycles()) { @@ -356,7 +349,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { private void reloadRequiredPackages(List reloads) { if (reloads.size() > 0) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (Element pkg : reloads) { PackageConfig cfg = addPackage(pkg); if (cfg.isNeedsRefresh()) { @@ -368,14 +361,14 @@ public class XmlConfigurationProvider implements ConfigurationProvider { return; } - // Print out error messages for all misconfigured inheritence packages + // Print out error messages for all misconfigured inheritance packages if (result.size() > 0) { for (Element rp : result) { String parent = rp.getAttribute("extends"); if (parent != null) { List parents = ConfigurationUtil.buildParentsFromString(configuration, parent); if (parents != null && parents.size() <= 0) { - LOG.error("Unable to find parent packages " + parent); + LOG.error("Unable to find parent packages {}", parent); } } } @@ -402,18 +395,15 @@ public class XmlConfigurationProvider implements ConfigurationProvider { protected void addAction(Element actionElement, PackageConfig.Builder packageContext) throws ConfigurationException { String name = actionElement.getAttribute("name"); String className = actionElement.getAttribute("class"); - String methodName = actionElement.getAttribute("method"); + //methodName should be null if it's not set + String methodName = StringUtils.trimToNull(actionElement.getAttribute("method")); Location location = DomHelper.getLocationObject(actionElement); if (location == null) { - if (LOG.isWarnEnabled()) { - LOG.warn("location null for " + className); - } + LOG.warn("Location null for {}", className); } - //methodName should be null if it's not set - methodName = (methodName.trim().length() > 0) ? methodName.trim() : null; - // if there isnt a class name specified for an then try to + // if there isn't a class name specified for an then try to // use the default-class-ref from the if (StringUtils.isEmpty(className)) { // if there is a package default-class-ref use that, otherwise use action support @@ -455,12 +445,14 @@ public class XmlConfigurationProvider implements ConfigurationProvider { packageContext.addActionConfig(name, actionConfig); if (LOG.isDebugEnabled()) { - LOG.debug("Loaded " + (StringUtils.isNotEmpty(packageContext.getNamespace()) ? (packageContext.getNamespace() + "/") : "") + name + " in '" + packageContext.getName() + "' package:" + actionConfig); + LOG.debug("Loaded {}{} in '{}' package: {}", + StringUtils.isNotEmpty(packageContext.getNamespace()) ? (packageContext.getNamespace() + "/") : "", + name, packageContext.getName(), actionConfig); } } protected boolean verifyAction(String className, String name, Location loc) { - if (className.indexOf('{') > -1) { + if (className.contains("{")) { LOG.debug("Action class [{}] contains a wildcard replacement value, so it can't be verified", className); return true; } @@ -479,7 +471,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { LOG.debug("No constructor found for action [{}]", className, e); throw new ConfigurationException("Action class [" + className + "] does not have a public no-arg constructor", e, loc); } catch (RuntimeException ex) { - // Probably not a big deal, like request or session-scoped Spring 2 beans that need a real request + // Probably not a big deal, like request or session-scoped Spring beans that need a real request LOG.info("Unable to verify action class [{}] exists at initialization", className); LOG.debug("Action verification cause", ex); } catch (Exception ex) { @@ -573,7 +565,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { packageContext.addResultTypeConfig(resultType.build()); // set the default result type - if ("true".equals(def)) { + if (BooleanUtils.toBoolean(def)) { packageContext.defaultResultType(name); } } @@ -583,17 +575,15 @@ public class XmlConfigurationProvider implements ConfigurationProvider { protected Class verifyResultType(String className, Location loc) { try { return objectFactory.getClassInstance(className); - } catch (ClassNotFoundException e) { - LOG.warn("Result class [{}] doesn't exist (ClassNotFoundException) at {}, ignoring", className, loc, e); - } catch (NoClassDefFoundError e) { - LOG.warn("Result class [{}] doesn't exist (NoClassDefFoundError) at {}, ignoring", className, loc, e); + } catch (ClassNotFoundException | NoClassDefFoundError e) { + LOG.warn("Result class [{}] doesn't exist ({}) at {}, ignoring", className, e.getClass().getSimpleName(), loc, e); } return null; } protected List buildInterceptorList(Element element, PackageConfig.Builder context) throws ConfigurationException { - List interceptorList = new ArrayList(); + List interceptorList = new ArrayList<>(); NodeList interceptorRefList = element.getElementsByTagName("interceptor-ref"); for (int i = 0; i < interceptorRefList.getLength(); i++) { @@ -634,7 +624,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { .location(DomHelper.getLocationObject(packageElement)); if (StringUtils.isNotEmpty(StringUtils.defaultString(parent))) { // has parents, let's look it up - List parents = new ArrayList(); + List parents = new ArrayList<>(); for (String parentPackageName : ConfigurationUtil.buildParentListFromString(parent)) { if (configuration.getPackageConfigNames().contains(parentPackageName)) { parents.add(configuration.getPackageConfig(parentPackageName)); @@ -665,7 +655,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { protected Map buildResults(Element element, PackageConfig.Builder packageContext) { NodeList resultEls = element.getElementsByTagName("result"); - Map results = new LinkedHashMap(); + Map results = new LinkedHashMap<>(); for (int i = 0; i < resultEls.getLength(); i++) { Element resultElement = (Element) resultEls.item(i); @@ -781,7 +771,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { protected List buildExceptionMappings(Element element, PackageConfig.Builder packageContext) { NodeList exceptionMappingEls = element.getElementsByTagName("exception-mapping"); - List exceptionMappings = new ArrayList(); + List exceptionMappings = new ArrayList<>(); for (int i = 0; i < exceptionMappingEls.getLength(); i++) { Element ehElement = (Element) exceptionMappingEls.item(i); @@ -814,7 +804,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { Set allowedMethods = null; if (allowedMethodsEls.getLength() > 0) { - allowedMethods = new HashSet(); + allowedMethods = new HashSet<>(); Node n = allowedMethodsEls.item(0).getFirstChild(); if (n != null) { String s = n.getNodeValue().trim(); @@ -823,7 +813,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { } } } else if (packageContext.isStrictMethodInvocation()) { - allowedMethods = new HashSet(); + allowedMethods = new HashSet<>(); } return allowedMethods; @@ -881,16 +871,6 @@ public class XmlConfigurationProvider implements ConfigurationProvider { } } - // protected void loadIncludes(Element rootElement, DocumentBuilder db) throws Exception { - // NodeList includeList = rootElement.getElementsByTagName("include"); - // - // for (int i = 0; i < includeList.getLength(); i++) { - // Element includeElement = (Element) includeList.item(i); - // String fileName = includeElement.getAttribute("file"); - // includedFileNames.add(fileName); - // loadConfigurationFile(fileName, db); - // } - // } protected InterceptorStackConfig loadInterceptorStack(Element element, PackageConfig.Builder context) throws ConfigurationException { String name = element.getAttribute("name"); @@ -948,12 +928,10 @@ public class XmlConfigurationProvider implements ConfigurationProvider { // } // } private List loadConfigurationFiles(String fileName, Element includeElement) { - List docs = new ArrayList(); - List finalDocs = new ArrayList(); + List docs = new ArrayList<>(); + List finalDocs = new ArrayList<>(); if (!includedFileNames.contains(fileName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Loading action configurations from: " + fileName); - } + LOG.debug("Loading action configurations from: {}", fileName); includedFileNames.add(fileName); @@ -971,10 +949,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { if (errorIfMissing) { throw new ConfigurationException("Could not open files of the name " + fileName, ioException); } else { - if (LOG.isInfoEnabled()) { - LOG.info("Unable to locate configuration files of the name " - + fileName + ", skipping"); - } + LOG.info("Unable to locate configuration files of the name {}, skipping", fileName); return docs; } } @@ -1049,9 +1024,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider { finalDocs.add(doc); } - if (LOG.isDebugEnabled()) { - LOG.debug("Loaded action configuration from: " + fileName); - } + LOG.debug("Loaded action configuration from: {}", fileName); } return finalDocs; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlHelper.java b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlHelper.java index e8b2d1f42..84e09d3f8 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlHelper.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlHelper.java @@ -15,11 +15,11 @@ */ package com.opensymphony.xwork2.config.providers; +import org.apache.commons.lang3.StringUtils; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.w3c.dom.Document; -import org.apache.commons.lang3.StringUtils; import java.util.LinkedHashMap; import java.util.Map; @@ -54,7 +54,7 @@ public class XmlHelper { * @return */ public static Map getParams(Element paramsElement) { - LinkedHashMap params = new LinkedHashMap(); + LinkedHashMap params = new LinkedHashMap<>(); if (paramsElement == null) { return params; @@ -97,8 +97,7 @@ public class XmlHelper { NodeList childNodes = element.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node currentNode = childNodes.item(j); - if (currentNode != null && - currentNode.getNodeType() == Node.TEXT_NODE) { + if (currentNode != null && currentNode.getNodeType() == Node.TEXT_NODE) { String val = currentNode.getNodeValue(); if (val != null) { paramValue.append(val.trim()); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionAnnotationProcessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionAnnotationProcessor.java index 2f64dbced..c3faae3a5 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionAnnotationProcessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionAnnotationProcessor.java @@ -8,8 +8,8 @@ import com.opensymphony.xwork2.conversion.annotations.ConversionRule; import com.opensymphony.xwork2.conversion.annotations.ConversionType; import com.opensymphony.xwork2.conversion.annotations.TypeConversion; 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 java.util.Map; @@ -34,9 +34,7 @@ public class DefaultConversionAnnotationProcessor implements ConversionAnnotatio } public void process(Map mapping, TypeConversion tc, String key) { - if (LOG.isDebugEnabled()) { - LOG.debug("TypeConversion [{}] with key: [{}]", tc.converter(), key); - } + LOG.debug("TypeConversion [{}] with key: [{}]", tc.converter(), key); if (key == null) { return; } @@ -62,9 +60,7 @@ public class DefaultConversionAnnotationProcessor implements ConversionAnnotatio mapping.put(key, converterCreator.createTypeConverter(tc.converter())); } else { mapping.put(key, converterClass); - if (LOG.isDebugEnabled()) { - LOG.debug("Object placed in mapping for key [{}] is [{}]", key, mapping.get(key)); - } + LOG.debug("Object placed in mapping for key [{}] is [{}]", key, mapping.get(key)); } } //elements(values) of maps / lists diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionFileProcessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionFileProcessor.java index 5fd0d070a..488d9ce85 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionFileProcessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionFileProcessor.java @@ -7,8 +7,8 @@ import com.opensymphony.xwork2.conversion.TypeConverter; import com.opensymphony.xwork2.conversion.TypeConverterCreator; import com.opensymphony.xwork2.inject.Inject; 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 java.io.InputStream; import java.util.Map; @@ -39,9 +39,7 @@ public class DefaultConversionFileProcessor implements ConversionFileProcessor { InputStream is = fileManager.loadFile(ClassLoaderUtil.getResource(converterFilename, clazz)); if (is != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Processing conversion file [{}] for class [{}]", converterFilename, clazz); - } + LOG.debug("Processing conversion file [{}] for class [{}]", converterFilename, clazz); Properties prop = new Properties(); prop.load(is); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultObjectTypeDeterminer.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultObjectTypeDeterminer.java index 3df9f9494..3b35102c0 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultObjectTypeDeterminer.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultObjectTypeDeterminer.java @@ -21,10 +21,11 @@ import com.opensymphony.xwork2.util.CreateIfNull; import com.opensymphony.xwork2.util.Element; import com.opensymphony.xwork2.util.Key; import com.opensymphony.xwork2.util.KeyProperty; -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.ReflectionProvider; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.beans.IntrospectionException; import java.lang.annotation.Annotation; @@ -64,9 +65,9 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { private XWorkConverter xworkConverter; @Inject - public DefaultObjectTypeDeterminer(@Inject XWorkConverter conv, @Inject ReflectionProvider prov) { - this.reflectionProvider = prov; - this.xworkConverter = conv; + public DefaultObjectTypeDeterminer(@Inject XWorkConverter converter, @Inject ReflectionProvider provider) { + this.reflectionProvider = provider; + this.xworkConverter = converter; } /** @@ -116,7 +117,7 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { clazz = (Class) xworkConverter.getConverter(parentClass, ELEMENT_PREFIX + property); if (clazz == null) { clazz = (Class) xworkConverter.getConverter(parentClass, DEPRECATED_ELEMENT_PREFIX + property); - if (LOG.isInfoEnabled() && clazz != null) { + if (clazz != null) { LOG.info("The Collection_xxx pattern for collection type conversion is deprecated. Please use Element_xxx!"); } } @@ -163,12 +164,7 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { String configValue = (String) xworkConverter.getConverter(parentClass, CREATE_IF_NULL_PREFIX + property); //check if a value is in the config if (configValue != null) { - if ("true".equalsIgnoreCase(configValue)) { - return true; - } - if ("false".equalsIgnoreCase(configValue)) { - return false; - } + return BooleanUtils.toBoolean(configValue); } //default values depend on target type @@ -218,9 +214,7 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { if (getter != null) { return getter.getAnnotation(annotationClass); } - } catch (ReflectionException ognle) { - // ignore - } catch (IntrospectionException ie) { + } catch (ReflectionException | IntrospectionException e) { // ignore } return null; @@ -241,9 +235,7 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { if (setter != null) { return setter.getAnnotation(annotationClass); } - } catch (ReflectionException ognle) { - // ignore - } catch (IntrospectionException ie) { + } catch (ReflectionException | IntrospectionException e) { // ignore } return null; @@ -270,9 +262,7 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { try { Method setter = reflectionProvider.getSetMethod(parentClass, property); genericType = setter != null ? setter.getGenericParameterTypes()[0] : null; - } catch (ReflectionException ognle) { - // ignore - } catch (IntrospectionException ie) { + } catch (ReflectionException | IntrospectionException e) { // ignore } } @@ -282,9 +272,7 @@ public class DefaultObjectTypeDeterminer implements ObjectTypeDeterminer { try { Method getter = reflectionProvider.getGetMethod(parentClass, property); genericType = getter.getGenericReturnType(); - } catch (ReflectionException ognle) { - // ignore - } catch (IntrospectionException ie) { + } catch (ReflectionException | IntrospectionException e) { // ignore } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverter.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverter.java index 039412234..47bcd1b0e 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverter.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverter.java @@ -64,7 +64,7 @@ public abstract class DefaultTypeConverter implements TypeConverter { private Container container; static { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(Boolean.TYPE, Boolean.FALSE); map.put(Byte.TYPE, Byte.valueOf((byte) 0)); map.put(Short.TYPE, Short.valueOf((short) 0)); @@ -134,19 +134,19 @@ public abstract class DefaultTypeConverter implements TypeConverter { } } else { if ((toType == Integer.class) || (toType == Integer.TYPE)) - result = Integer.valueOf((int) longValue(value)); + result = (int) longValue(value); if ((toType == Double.class) || (toType == Double.TYPE)) - result = new Double(doubleValue(value)); + result = doubleValue(value); if ((toType == Boolean.class) || (toType == Boolean.TYPE)) result = booleanValue(value) ? Boolean.TRUE : Boolean.FALSE; if ((toType == Byte.class) || (toType == Byte.TYPE)) - result = Byte.valueOf((byte) longValue(value)); + result = (byte) longValue(value); if ((toType == Character.class) || (toType == Character.TYPE)) - result = new Character((char) longValue(value)); + result = (char) longValue(value); if ((toType == Short.class) || (toType == Short.TYPE)) - result = Short.valueOf((short) longValue(value)); + result = (short) longValue(value); if ((toType == Long.class) || (toType == Long.TYPE)) - result = Long.valueOf(longValue(value)); + result = longValue(value); if ((toType == Float.class) || (toType == Float.TYPE)) result = new Float(doubleValue(value)); if (toType == BigInteger.class) @@ -156,7 +156,7 @@ public abstract class DefaultTypeConverter implements TypeConverter { if (toType == String.class) result = stringValue(value); if (Enum.class.isAssignableFrom(toType)) - result = enumValue((Class)toType, value); + result = enumValue(toType, value); } } else { if (toType.isPrimitive()) { @@ -180,11 +180,11 @@ public abstract class DefaultTypeConverter implements TypeConverter { return false; Class c = value.getClass(); if (c == Boolean.class) - return ((Boolean) value).booleanValue(); + return (Boolean) value; // if ( c == String.class ) // return ((String)value).length() > 0; if (c == Character.class) - return ((Character) value).charValue() != 0; + return (Character) value != 0; if (value instanceof Number) return ((Number) value).doubleValue() != 0; return true; // non-null @@ -218,9 +218,9 @@ public abstract class DefaultTypeConverter implements TypeConverter { if (c.getSuperclass() == Number.class) return ((Number) value).longValue(); if (c == Boolean.class) - return ((Boolean) value).booleanValue() ? 1 : 0; + return (Boolean) value ? 1 : 0; if (c == Character.class) - return ((Character) value).charValue(); + return (Character) value; return Long.parseLong(stringValue(value, true)); } @@ -240,9 +240,9 @@ public abstract class DefaultTypeConverter implements TypeConverter { if (c.getSuperclass() == Number.class) return ((Number) value).doubleValue(); if (c == Boolean.class) - return ((Boolean) value).booleanValue() ? 1 : 0; + return (Boolean) value ? 1 : 0; if (c == Character.class) - return ((Character) value).charValue(); + return (Character) value; String s = stringValue(value, true); return (s.length() == 0) ? 0.0 : Double.parseDouble(s); @@ -273,7 +273,7 @@ public abstract class DefaultTypeConverter implements TypeConverter { if (c.getSuperclass() == Number.class) return BigInteger.valueOf(((Number) value).longValue()); if (c == Boolean.class) - return BigInteger.valueOf(((Boolean) value).booleanValue() ? 1 : 0); + return BigInteger.valueOf((Boolean) value ? 1 : 0); if (c == Character.class) return BigInteger.valueOf(((Character) value).charValue()); return new BigInteger(stringValue(value, true)); @@ -300,7 +300,7 @@ public abstract class DefaultTypeConverter implements TypeConverter { if (c.getSuperclass() == Number.class) return new BigDecimal(((Number) value).doubleValue()); if (c == Boolean.class) - return BigDecimal.valueOf(((Boolean) value).booleanValue() ? 1 : 0); + return BigDecimal.valueOf((Boolean) value ? 1 : 0); if (c == Character.class) return BigDecimal.valueOf(((Character) value).charValue()); return new BigDecimal(stringValue(value, true)); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverterHolder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverterHolder.java index b547f05ac..2acaf96ac 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverterHolder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverterHolder.java @@ -19,7 +19,7 @@ public class DefaultTypeConverterHolder implements TypeConverterHolder { * - TypeConverter - instance of TypeConverter * */ - private HashMap defaultMappings = new HashMap(); // non-action (eg. returned value) + private HashMap defaultMappings = new HashMap<>(); // non-action (eg. returned value) /** * Target class conversion Mappings. @@ -40,12 +40,12 @@ public class DefaultTypeConverterHolder implements TypeConverterHolder { * Element_property=foo.bar.MyObject * */ - private HashMap> mappings = new HashMap>(); // action + private HashMap> mappings = new HashMap<>(); // action /** * Unavailable target class conversion mappings, serves as a simple cache. */ - private HashSet noMapping = new HashSet(); // action + private HashSet noMapping = new HashSet<>(); // action /** * Record classes that doesn't have conversion mapping defined. @@ -53,7 +53,7 @@ public class DefaultTypeConverterHolder implements TypeConverterHolder { * - String -> classname as String * */ - protected HashSet unknownMappings = new HashSet(); // non-action (eg. returned value) + protected HashSet unknownMappings = new HashSet<>(); // non-action (eg. returned value) public void addDefaultMapping(String className, TypeConverter typeConverter) { defaultMappings.put(className, typeConverter); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/InstantiatingNullHandler.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/InstantiatingNullHandler.java index da49d66e3..386d070fc 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/InstantiatingNullHandler.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/InstantiatingNullHandler.java @@ -19,10 +19,10 @@ import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.conversion.NullHandler; import com.opensymphony.xwork2.conversion.ObjectTypeDeterminer; import com.opensymphony.xwork2.inject.Inject; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; import com.opensymphony.xwork2.util.reflection.ReflectionProvider; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.beans.PropertyDescriptor; import java.util.*; @@ -93,18 +93,12 @@ public class InstantiatingNullHandler implements NullHandler { } public Object nullMethodResult(Map context, Object target, String methodName, Object[] args) { - if (LOG.isDebugEnabled()) { - LOG.debug("Entering nullMethodResult "); - } - + LOG.debug("Entering nullMethodResult"); return null; } public Object nullPropertyValue(Map context, Object target, Object property) { - if (LOG.isDebugEnabled()) { - LOG.debug("Entering nullPropertyValue [target="+target+", property="+property+"]"); - } - + LOG.debug("Entering nullPropertyValue [target={}, property={}]", target, property); boolean c = ReflectionContextState.isCreatingNullObjects(context); if (!c) { @@ -140,9 +134,7 @@ public class InstantiatingNullHandler implements NullHandler { return param; } catch (Exception e) { - if (LOG.isErrorEnabled()) { - LOG.error("Could not create and/or set value back on to object", e); - } + LOG.error("Could not create and/or set value back on to object", e); } return null; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/StringConverter.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/StringConverter.java index e9c141737..9c6cc8f18 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/StringConverter.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/StringConverter.java @@ -18,7 +18,7 @@ public class StringConverter extends DefaultTypeConverter { if (value instanceof int[]) { int[] x = (int[]) value; - List intArray = new ArrayList(x.length); + List intArray = new ArrayList<>(x.length); for (int aX : x) { intArray.add(Integer.valueOf(aX)); @@ -27,7 +27,7 @@ public class StringConverter extends DefaultTypeConverter { result = StringUtils.join(intArray, ", "); } else if (value instanceof long[]) { long[] x = (long[]) value; - List longArray = new ArrayList(x.length); + List longArray = new ArrayList<>(x.length); for (long aX : x) { longArray.add(Long.valueOf(aX)); @@ -36,7 +36,7 @@ public class StringConverter extends DefaultTypeConverter { result = StringUtils.join(longArray, ", "); } else if (value instanceof double[]) { double[] x = (double[]) value; - List doubleArray = new ArrayList(x.length); + List doubleArray = new ArrayList<>(x.length); for (double aX : x) { doubleArray.add(new Double(aX)); @@ -45,7 +45,7 @@ public class StringConverter extends DefaultTypeConverter { result = StringUtils.join(doubleArray, ", "); } else if (value instanceof boolean[]) { boolean[] x = (boolean[]) value; - List booleanArray = new ArrayList(x.length); + List booleanArray = new ArrayList<>(x.length); for (boolean aX : x) { booleanArray.add(new Boolean(aX)); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/XWorkConverter.java b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/XWorkConverter.java index eaae00705..c0086eec8 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/XWorkConverter.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/XWorkConverter.java @@ -15,28 +15,16 @@ */ package com.opensymphony.xwork2.conversion.impl; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.FileManager; -import com.opensymphony.xwork2.FileManagerFactory; -import com.opensymphony.xwork2.XWorkConstants; -import com.opensymphony.xwork2.XWorkMessages; -import com.opensymphony.xwork2.conversion.ConversionAnnotationProcessor; -import com.opensymphony.xwork2.conversion.ConversionFileProcessor; -import com.opensymphony.xwork2.conversion.ConversionPropertiesProcessor; -import com.opensymphony.xwork2.conversion.TypeConverter; -import com.opensymphony.xwork2.conversion.TypeConverterHolder; +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.conversion.*; import com.opensymphony.xwork2.conversion.annotations.Conversion; import com.opensymphony.xwork2.conversion.annotations.TypeConversion; import com.opensymphony.xwork2.inject.Inject; -import com.opensymphony.xwork2.util.AnnotationUtils; -import com.opensymphony.xwork2.util.ClassLoaderUtil; -import com.opensymphony.xwork2.util.CompoundRoot; -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 com.opensymphony.xwork2.util.*; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.lang.annotation.Annotation; import java.lang.reflect.Member; @@ -158,8 +146,8 @@ public class XWorkConverter extends DefaultTypeConverter { } @Inject - public void setDefaultTypeConverter(XWorkBasicConverter conv) { - this.defaultTypeConverter = conv; + public void setDefaultTypeConverter(XWorkBasicConverter converter) { + this.defaultTypeConverter = converter; } @Inject @@ -203,7 +191,7 @@ public class XWorkConverter extends DefaultTypeConverter { List indexValues = getIndexValues(propertyName); - propertyName = removeAllIndexesInProperytName(propertyName); + propertyName = removeAllIndexesInPropertyName(propertyName); String getTextExpression = "getText('" + CONVERSION_ERROR_PROPERTY_PREFIX + propertyName + "','" + defaultMessage + "')"; String message = (String) stack.findValue(getTextExpression); @@ -217,13 +205,13 @@ public class XWorkConverter extends DefaultTypeConverter { return message; } - private static String removeAllIndexesInProperytName(String propertyName) { + private static String removeAllIndexesInPropertyName(String propertyName) { return propertyName.replaceAll(MESSAGE_INDEX_PATTERN, PERIOD); } private static List getIndexValues(String propertyName) { Matcher matcher = messageIndexPattern.matcher(propertyName); - List indexes = new ArrayList(); + List indexes = new ArrayList<>(); while (matcher.find()) { Integer index = new Integer(matcher.group().replaceAll(MESSAGE_INDEX_BRACKET_PATTERN, "")) + 1; indexes.add(Integer.toString(index)); @@ -280,9 +268,7 @@ public class XWorkConverter extends DefaultTypeConverter { } tc = (TypeConverter) getConverter(clazz, property); - - if (LOG.isDebugEnabled()) - LOG.debug("field-level type converter for property [" + property + "] = " + (tc == null ? "none found" : tc)); + LOG.debug("field-level type converter for property [{}] = {}", property, (tc == null ? "none found" : tc)); } if (tc == null && context != null) { @@ -305,7 +291,7 @@ public class XWorkConverter extends DefaultTypeConverter { } if (LOG.isDebugEnabled()) - LOG.debug("global-level type converter for property [" + property + "] = " + (tc == null ? "none found" : tc)); + LOG.debug("global-level type converter for property [{}] = {} ", property, (tc == null ? "none found" : tc)); } @@ -443,7 +429,7 @@ public class XWorkConverter extends DefaultTypeConverter { Map conversionErrors = (Map) context.get(ActionContext.CONVERSION_ERRORS); if (conversionErrors == null) { - conversionErrors = new HashMap(); + conversionErrors = new HashMap<>(); context.put(ActionContext.CONVERSION_ERRORS, conversionErrors); } @@ -530,7 +516,7 @@ public class XWorkConverter extends DefaultTypeConverter { * @return the converter mappings */ protected Map buildConverterMapping(Class clazz) throws Exception { - Map mapping = new HashMap(); + Map mapping = new HashMap<>(); // check for conversion mapping associated with super classes and any implemented interfaces Class curClazz = clazz; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/factory/DefaultInterceptorFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/factory/DefaultInterceptorFactory.java index d7841e675..9f0195fd0 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/factory/DefaultInterceptorFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/factory/DefaultInterceptorFactory.java @@ -31,7 +31,7 @@ public class DefaultInterceptorFactory implements InterceptorFactory { public Interceptor buildInterceptor(InterceptorConfig interceptorConfig, Map interceptorRefParams) throws ConfigurationException { String interceptorClassName = interceptorConfig.getClassName(); Map thisInterceptorClassParams = interceptorConfig.getParams(); - Map params = (thisInterceptorClassParams == null) ? new HashMap() : new HashMap(thisInterceptorClassParams); + Map params = (thisInterceptorClassParams == null) ? new HashMap() : new HashMap<>(thisInterceptorClassParams); params.putAll(interceptorRefParams); String message; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ConstructionContext.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ConstructionContext.java index 44a9e2010..d75d46493 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ConstructionContext.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ConstructionContext.java @@ -66,16 +66,14 @@ class ConstructionContext { // instance (as opposed to one per caller). if (!expectedType.isInterface()) { - throw new DependencyException( - expectedType.getName() + " is not an interface."); + throw new DependencyException(expectedType.getName() + " is not an interface."); } if (invocationHandlers == null) { invocationHandlers = new ArrayList>(); } - DelegatingInvocationHandler invocationHandler = - new DelegatingInvocationHandler(); + DelegatingInvocationHandler invocationHandler = new DelegatingInvocationHandler<>(); invocationHandlers.add(invocationHandler); return Proxy.newProxyInstance( @@ -87,8 +85,7 @@ class ConstructionContext { void setProxyDelegates(T delegate) { if (invocationHandlers != null) { - for (DelegatingInvocationHandler invocationHandler - : invocationHandlers) { + for (DelegatingInvocationHandler invocationHandler : invocationHandlers) { invocationHandler.setDelegate(delegate); } } @@ -108,9 +105,7 @@ class ConstructionContext { try { return method.invoke(delegate, args); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (IllegalArgumentException e) { + } catch (IllegalAccessException | IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw e.getTargetException(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerBuilder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerBuilder.java index 7eec8208d..54f5be6ff 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerBuilder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerBuilder.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,492 +36,475 @@ import java.util.logging.Logger; */ public final class ContainerBuilder { - final Map, InternalFactory> factories = - new HashMap, InternalFactory>(); - final List> singletonFactories = - new ArrayList>(); - final List> staticInjections = new ArrayList>(); - boolean created; - boolean allowDuplicates = false; + final Map, InternalFactory> factories = new HashMap<>(); + final List> singletonFactories = new ArrayList<>(); + final List> staticInjections = new ArrayList<>(); + boolean created; + boolean allowDuplicates = false; - private static final InternalFactory CONTAINER_FACTORY = - new InternalFactory() { - public Container create(InternalContext context) { - return context.getContainer(); - } - }; + private static final InternalFactory CONTAINER_FACTORY = + new InternalFactory() { + public Container create(InternalContext context) { + return context.getContainer(); + } + }; - private static final InternalFactory LOGGER_FACTORY = - new InternalFactory() { - public Logger create(InternalContext context) { - Member member = context.getExternalContext().getMember(); - return member == null ? Logger.getAnonymousLogger() - : Logger.getLogger(member.getDeclaringClass().getName()); - } - }; - - /** - * Constructs a new builder. - */ - public ContainerBuilder() { - // In the current container as the default Container implementation. - factories.put(Key.newInstance(Container.class, Container.DEFAULT_NAME), - CONTAINER_FACTORY); - - // Inject the logger for the injected member's declaring class. - factories.put(Key.newInstance(Logger.class, Container.DEFAULT_NAME), - LOGGER_FACTORY); - } - - /** - * Maps a dependency. All methods in this class ultimately funnel through - * here. - */ - private ContainerBuilder factory(final Key key, - InternalFactory factory, Scope scope) { - ensureNotCreated(); - checkKey(key); - final InternalFactory scopedFactory = - scope.scopeFactory(key.getType(), key.getName(), factory); - factories.put(key, scopedFactory); - if (scope == Scope.SINGLETON) { - singletonFactories.add(new InternalFactory() { - public T create(InternalContext context) { - try { - context.setExternalContext(ExternalContext.newInstance( - null, key, context.getContainerImpl())); - return scopedFactory.create(context); - } finally { - context.setExternalContext(null); - } - } - }); - } - return this; - } - - /** - * Ensures a key isn't already mapped. - */ - private void checkKey(Key key) { - if (factories.containsKey(key) && !allowDuplicates) { - throw new DependencyException( - "Dependency mapping for " + key + " already exists."); - } - } - - /** - * Maps a factory to a given dependency type and name. - * - * @param type of dependency - * @param name of dependency - * @param factory creates objects to inject - * @param scope scope of injected instances - * @return this builder - */ - public ContainerBuilder factory(final Class type, final String name, - final Factory factory, Scope scope) { - InternalFactory internalFactory = - new InternalFactory() { - - public T create(InternalContext context) { - try { - Context externalContext = context.getExternalContext(); - return factory.create(externalContext); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public String toString() { - return new LinkedHashMap() {{ - put("type", type); - put("name", name); - put("factory", factory); - }}.toString(); - } - }; - - return factory(Key.newInstance(type, name), internalFactory, scope); - } - - /** - * Convenience method. Equivalent to {@code factory(type, - * Container.DEFAULT_NAME, factory, scope)}. - * - * @see #factory(Class, String, Factory, Scope) - */ - public ContainerBuilder factory(Class type, - Factory factory, Scope scope) { - return factory(type, Container.DEFAULT_NAME, factory, scope); - } - - /** - * Convenience method. Equivalent to {@code factory(type, name, factory, - * Scope.DEFAULT)}. - * - * @see #factory(Class, String, Factory, Scope) - */ - public ContainerBuilder factory(Class type, String name, - Factory factory) { - return factory(type, name, factory, Scope.DEFAULT); - } - - /** - * Convenience method. Equivalent to {@code factory(type, - * Container.DEFAULT_NAME, factory, Scope.DEFAULT)}. - * - * @see #factory(Class, String, Factory, Scope) - */ - public ContainerBuilder factory(Class type, - Factory factory) { - return factory(type, Container.DEFAULT_NAME, factory, Scope.DEFAULT); - } - - /** - * Maps an implementation class to a given dependency type and name. Creates - * instances using the container, recursively injecting dependencies. - * - * @param type of dependency - * @param name of dependency - * @param implementation class - * @param scope scope of injected instances - * @return this builder - */ - public ContainerBuilder factory(final Class type, final String name, - final Class implementation, final Scope scope) { - // This factory creates new instances of the given implementation. - // We have to lazy load the constructor because the Container - // hasn't been created yet. - InternalFactory factory = new InternalFactory() { - - volatile ContainerImpl.ConstructorInjector constructor; - - @SuppressWarnings("unchecked") - public T create(InternalContext context) { - if (constructor == null) { - this.constructor = - context.getContainerImpl().getConstructor(implementation); - } - return (T) constructor.construct(context, type); - } - - @Override - public String toString() { - return new LinkedHashMap() {{ - put("type", type); - put("name", name); - put("implementation", implementation); - put("scope", scope); - }}.toString(); - } - }; - - return factory(Key.newInstance(type, name), factory, scope); - } - - /** - * Maps an implementation class to a given dependency type and name. Creates - * instances using the container, recursively injecting dependencies. - * - *

Sets scope to value from {@link Scoped} annotation on the - * implementation class. Defaults to {@link Scope#DEFAULT} if no annotation - * is found. - * - * @param type of dependency - * @param name of dependency - * @param implementation class - * @return this builder - */ - public ContainerBuilder factory(final Class type, String name, - final Class implementation) { - Scoped scoped = implementation.getAnnotation(Scoped.class); - Scope scope = scoped == null ? Scope.DEFAULT : scoped.value(); - return factory(type, name, implementation, scope); - } - - /** - * Convenience method. Equivalent to {@code factory(type, - * Container.DEFAULT_NAME, implementation)}. - * - * @see #factory(Class, String, Class) - */ - public ContainerBuilder factory(Class type, - Class implementation) { - return factory(type, Container.DEFAULT_NAME, implementation); - } - - /** - * Convenience method. Equivalent to {@code factory(type, - * Container.DEFAULT_NAME, type)}. - * - * @see #factory(Class, String, Class) - */ - public ContainerBuilder factory(Class type) { - return factory(type, Container.DEFAULT_NAME, type); - } - - /** - * Convenience method. Equivalent to {@code factory(type, name, type)}. - * - * @see #factory(Class, String, Class) - */ - public ContainerBuilder factory(Class type, String name) { - return factory(type, name, type); - } - - /** - * Convenience method. Equivalent to {@code factory(type, - * Container.DEFAULT_NAME, implementation, scope)}. - * - * @see #factory(Class, String, Class, Scope) - */ - public ContainerBuilder factory(Class type, - Class implementation, Scope scope) { - return factory(type, Container.DEFAULT_NAME, implementation, scope); - } - - /** - * Convenience method. Equivalent to {@code factory(type, - * Container.DEFAULT_NAME, type, scope)}. - * - * @see #factory(Class, String, Class, Scope) - */ - public ContainerBuilder factory(Class type, Scope scope) { - return factory(type, Container.DEFAULT_NAME, type, scope); - } - - /** - * Convenience method. Equivalent to {@code factory(type, name, type, - * scope)}. - * - * @see #factory(Class, String, Class, Scope) - */ - public ContainerBuilder factory(Class type, String name, Scope scope) { - return factory(type, name, type, scope); - } - - /** - * Convenience method. Equivalent to {@code alias(type, Container.DEFAULT_NAME, - * type)}. - * - * @see #alias(Class, String, String) - */ - public ContainerBuilder alias(Class type, String alias) { - return alias(type, Container.DEFAULT_NAME, alias); - } - - /** - * Maps an existing factory to a new name. - * - * @param type of dependency - * @param name of dependency - * @param alias of to the dependency - * @return this builder - */ - public ContainerBuilder alias(Class type, String name, String alias) { - return alias(Key.newInstance(type, name), Key.newInstance(type, alias)); - } - - /** - * Maps an existing dependency. All methods in this class ultimately funnel through - * here. - */ - private ContainerBuilder alias(final Key key, - final Key aliasKey) { - ensureNotCreated(); - checkKey(aliasKey); - - final InternalFactory scopedFactory = - (InternalFactory)factories.get(key); - if (scopedFactory == null) { - throw new DependencyException( - "Dependency mapping for " + key + " doesn't exists."); - } - factories.put(aliasKey, scopedFactory); - return this; - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, String value) { - return constant(String.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, int value) { - return constant(int.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, long value) { - return constant(long.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, boolean value) { - return constant(boolean.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, double value) { - return constant(double.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, float value) { - return constant(float.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, short value) { - return constant(short.class, name, value); - } - - /** - * Maps a constant value to the given name. - */ - public ContainerBuilder constant(String name, char value) { - return constant(char.class, name, value); - } - - /** - * Maps a class to the given name. - */ - public ContainerBuilder constant(String name, Class value) { - return constant(Class.class, name, value); - } - - /** - * Maps an enum to the given name. - */ - public > ContainerBuilder constant(String name, E value) { - return constant(value.getDeclaringClass(), name, value); - } - - /** - * Maps a constant value to the given type and name. - */ - private ContainerBuilder constant(final Class type, final String name, - final T value) { - InternalFactory factory = new InternalFactory() { - public T create(InternalContext ignored) { - return value; - } - - @Override - public String toString() { - return new LinkedHashMap() { - { - put("type", type); - put("name", name); - put("value", value); - } - }.toString(); - } - }; - - return factory(Key.newInstance(type, name), factory, Scope.DEFAULT); - } - - /** - * Upon creation, the {@link Container} will inject static fields and methods - * into the given classes. - * - * @param types for which static members will be injected - */ - public ContainerBuilder injectStatics(Class... types) { - staticInjections.addAll(Arrays.asList(types)); - return this; - } - - /** - * Returns true if this builder contains a mapping for the given type and - * name. - */ - public boolean contains(Class type, String name) { - return factories.containsKey(Key.newInstance(type, name)); - } - - /** - * Convenience method. Equivalent to {@code contains(type, - * Container.DEFAULT_NAME)}. - */ - public boolean contains(Class type) { - return contains(type, Container.DEFAULT_NAME); - } - - /** - * Creates a {@link Container} instance. Injects static members for classes - * which were registered using {@link #injectStatics(Class...)}. - * - * @param loadSingletons If true, the container will load all singletons - * now. If false, the container will lazily load singletons. Eager loading - * is appropriate for production use while lazy loading can speed - * development. - * @throws IllegalStateException if called more than once - */ - public Container create(boolean loadSingletons) { - ensureNotCreated(); - created = true; - final ContainerImpl container = new ContainerImpl( - new HashMap, InternalFactory>(factories)); - if (loadSingletons) { - container.callInContext(new ContainerImpl.ContextualCallable() { - public Void call(InternalContext context) { - for (InternalFactory factory : singletonFactories) { - factory.create(context); - } - return null; - } - }); - } - container.injectStatics(staticInjections); - return container; - } - - /** - * Currently we only support creating one Container instance per builder. - * If we want to support creating more than one container per builder, - * we should move to a "factory factory" model where we create a factory - * instance per Container. Right now, one factory instance would be - * shared across all the containers, singletons synchronize on the - * container when lazy loading, etc. - */ - private void ensureNotCreated() { - if (created) { - throw new IllegalStateException("Container already created."); - } - } - - public void setAllowDuplicates(boolean val) { - allowDuplicates = val; - } - - /** - * Implemented by classes which participate in building a container. - */ - public interface Command { + private static final InternalFactory LOGGER_FACTORY = + new InternalFactory() { + public Logger create(InternalContext context) { + Member member = context.getExternalContext().getMember(); + return member == null ? Logger.getAnonymousLogger() + : Logger.getLogger(member.getDeclaringClass().getName()); + } + }; /** - * Contributes factories to the given builder. - * - * @param builder + * Constructs a new builder. */ - void build(ContainerBuilder builder); - } + public ContainerBuilder() { + // In the current container as the default Container implementation. + factories.put(Key.newInstance(Container.class, Container.DEFAULT_NAME), CONTAINER_FACTORY); + + // Inject the logger for the injected member's declaring class. + factories.put(Key.newInstance(Logger.class, Container.DEFAULT_NAME), LOGGER_FACTORY); + } + + /** + * Maps a dependency. All methods in this class ultimately funnel through + * here. + */ + private ContainerBuilder factory(final Key key, + InternalFactory factory, Scope scope) { + ensureNotCreated(); + checkKey(key); + final InternalFactory scopedFactory = scope.scopeFactory(key.getType(), key.getName(), factory); + factories.put(key, scopedFactory); + if (scope == Scope.SINGLETON) { + singletonFactories.add(new InternalFactory() { + public T create(InternalContext context) { + try { + context.setExternalContext(ExternalContext.newInstance(null, key, context.getContainerImpl())); + return scopedFactory.create(context); + } finally { + context.setExternalContext(null); + } + } + }); + } + return this; + } + + /** + * Ensures a key isn't already mapped. + */ + private void checkKey(Key key) { + if (factories.containsKey(key) && !allowDuplicates) { + throw new DependencyException("Dependency mapping for " + key + " already exists."); + } + } + + /** + * Maps a factory to a given dependency type and name. + * + * @param type of dependency + * @param name of dependency + * @param factory creates objects to inject + * @param scope scope of injected instances + * @return this builder + */ + public ContainerBuilder factory(final Class type, final String name, + final Factory factory, Scope scope) { + InternalFactory internalFactory = new InternalFactory() { + + public T create(InternalContext context) { + try { + Context externalContext = context.getExternalContext(); + return factory.create(externalContext); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public String toString() { + return new LinkedHashMap() {{ + put("type", type); + put("name", name); + put("factory", factory); + }}.toString(); + } + }; + + return factory(Key.newInstance(type, name), internalFactory, scope); + } + + /** + * Convenience method. Equivalent to {@code factory(type, + * Container.DEFAULT_NAME, factory, scope)}. + * + * @see #factory(Class, String, Factory, Scope) + */ + public ContainerBuilder factory(Class type, Factory factory, Scope scope) { + return factory(type, Container.DEFAULT_NAME, factory, scope); + } + + /** + * Convenience method. Equivalent to {@code factory(type, name, factory, + * Scope.DEFAULT)}. + * + * @see #factory(Class, String, Factory, Scope) + */ + public ContainerBuilder factory(Class type, String name, Factory factory) { + return factory(type, name, factory, Scope.DEFAULT); + } + + /** + * Convenience method. Equivalent to {@code factory(type, + * Container.DEFAULT_NAME, factory, Scope.DEFAULT)}. + * + * @see #factory(Class, String, Factory, Scope) + */ + public ContainerBuilder factory(Class type, Factory factory) { + return factory(type, Container.DEFAULT_NAME, factory, Scope.DEFAULT); + } + + /** + * Maps an implementation class to a given dependency type and name. Creates + * instances using the container, recursively injecting dependencies. + * + * @param type of dependency + * @param name of dependency + * @param implementation class + * @param scope scope of injected instances + * @return this builder + */ + public ContainerBuilder factory(final Class type, final String name, + final Class implementation, final Scope scope) { + // This factory creates new instances of the given implementation. + // We have to lazy load the constructor because the Container + // hasn't been created yet. + InternalFactory factory = new InternalFactory() { + + volatile ContainerImpl.ConstructorInjector constructor; + + @SuppressWarnings("unchecked") + public T create(InternalContext context) { + if (constructor == null) { + this.constructor = + context.getContainerImpl().getConstructor(implementation); + } + return (T) constructor.construct(context, type); + } + + @Override + public String toString() { + return new LinkedHashMap() {{ + put("type", type); + put("name", name); + put("implementation", implementation); + put("scope", scope); + }}.toString(); + } + }; + + return factory(Key.newInstance(type, name), factory, scope); + } + + /** + * Maps an implementation class to a given dependency type and name. Creates + * instances using the container, recursively injecting dependencies. + *

+ *

Sets scope to value from {@link Scoped} annotation on the + * implementation class. Defaults to {@link Scope#DEFAULT} if no annotation + * is found. + * + * @param type of dependency + * @param name of dependency + * @param implementation class + * @return this builder + */ + public ContainerBuilder factory(final Class type, String name, + final Class implementation) { + Scoped scoped = implementation.getAnnotation(Scoped.class); + Scope scope = scoped == null ? Scope.DEFAULT : scoped.value(); + return factory(type, name, implementation, scope); + } + + /** + * Convenience method. Equivalent to {@code factory(type, + * Container.DEFAULT_NAME, implementation)}. + * + * @see #factory(Class, String, Class) + */ + public ContainerBuilder factory(Class type, Class implementation) { + return factory(type, Container.DEFAULT_NAME, implementation); + } + + /** + * Convenience method. Equivalent to {@code factory(type, + * Container.DEFAULT_NAME, type)}. + * + * @see #factory(Class, String, Class) + */ + public ContainerBuilder factory(Class type) { + return factory(type, Container.DEFAULT_NAME, type); + } + + /** + * Convenience method. Equivalent to {@code factory(type, name, type)}. + * + * @see #factory(Class, String, Class) + */ + public ContainerBuilder factory(Class type, String name) { + return factory(type, name, type); + } + + /** + * Convenience method. Equivalent to {@code factory(type, + * Container.DEFAULT_NAME, implementation, scope)}. + * + * @see #factory(Class, String, Class, Scope) + */ + public ContainerBuilder factory(Class type, Class implementation, Scope scope) { + return factory(type, Container.DEFAULT_NAME, implementation, scope); + } + + /** + * Convenience method. Equivalent to {@code factory(type, + * Container.DEFAULT_NAME, type, scope)}. + * + * @see #factory(Class, String, Class, Scope) + */ + public ContainerBuilder factory(Class type, Scope scope) { + return factory(type, Container.DEFAULT_NAME, type, scope); + } + + /** + * Convenience method. Equivalent to {@code factory(type, name, type, + * scope)}. + * + * @see #factory(Class, String, Class, Scope) + */ + public ContainerBuilder factory(Class type, String name, Scope scope) { + return factory(type, name, type, scope); + } + + /** + * Convenience method. Equivalent to {@code alias(type, Container.DEFAULT_NAME, + * type)}. + * + * @see #alias(Class, String, String) + */ + public ContainerBuilder alias(Class type, String alias) { + return alias(type, Container.DEFAULT_NAME, alias); + } + + /** + * Maps an existing factory to a new name. + * + * @param type of dependency + * @param name of dependency + * @param alias of to the dependency + * @return this builder + */ + public ContainerBuilder alias(Class type, String name, String alias) { + return alias(Key.newInstance(type, name), Key.newInstance(type, alias)); + } + + /** + * Maps an existing dependency. All methods in this class ultimately funnel through + * here. + */ + private ContainerBuilder alias(final Key key, + final Key aliasKey) { + ensureNotCreated(); + checkKey(aliasKey); + + final InternalFactory scopedFactory = (InternalFactory) factories.get(key); + if (scopedFactory == null) { + throw new DependencyException("Dependency mapping for " + key + " doesn't exists."); + } + factories.put(aliasKey, scopedFactory); + return this; + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, String value) { + return constant(String.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, int value) { + return constant(int.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, long value) { + return constant(long.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, boolean value) { + return constant(boolean.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, double value) { + return constant(double.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, float value) { + return constant(float.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, short value) { + return constant(short.class, name, value); + } + + /** + * Maps a constant value to the given name. + */ + public ContainerBuilder constant(String name, char value) { + return constant(char.class, name, value); + } + + /** + * Maps a class to the given name. + */ + public ContainerBuilder constant(String name, Class value) { + return constant(Class.class, name, value); + } + + /** + * Maps an enum to the given name. + */ + public > ContainerBuilder constant(String name, E value) { + return constant(value.getDeclaringClass(), name, value); + } + + /** + * Maps a constant value to the given type and name. + */ + private ContainerBuilder constant(final Class type, final String name, final T value) { + InternalFactory factory = new InternalFactory() { + public T create(InternalContext ignored) { + return value; + } + + @Override + public String toString() { + return new LinkedHashMap() { + { + put("type", type); + put("name", name); + put("value", value); + } + }.toString(); + } + }; + + return factory(Key.newInstance(type, name), factory, Scope.DEFAULT); + } + + /** + * Upon creation, the {@link Container} will inject static fields and methods + * into the given classes. + * + * @param types for which static members will be injected + */ + public ContainerBuilder injectStatics(Class... types) { + staticInjections.addAll(Arrays.asList(types)); + return this; + } + + /** + * Returns true if this builder contains a mapping for the given type and + * name. + */ + public boolean contains(Class type, String name) { + return factories.containsKey(Key.newInstance(type, name)); + } + + /** + * Convenience method. Equivalent to {@code contains(type, + * Container.DEFAULT_NAME)}. + */ + public boolean contains(Class type) { + return contains(type, Container.DEFAULT_NAME); + } + + /** + * Creates a {@link Container} instance. Injects static members for classes + * which were registered using {@link #injectStatics(Class...)}. + * + * @param loadSingletons If true, the container will load all singletons + * now. If false, the container will lazily load singletons. Eager loading + * is appropriate for production use while lazy loading can speed + * development. + * @throws IllegalStateException if called more than once + */ + public Container create(boolean loadSingletons) { + ensureNotCreated(); + created = true; + final ContainerImpl container = new ContainerImpl(new HashMap<>(factories)); + if (loadSingletons) { + container.callInContext(new ContainerImpl.ContextualCallable() { + public Void call(InternalContext context) { + for (InternalFactory factory : singletonFactories) { + factory.create(context); + } + return null; + } + }); + } + container.injectStatics(staticInjections); + return container; + } + + /** + * Currently we only support creating one Container instance per builder. + * If we want to support creating more than one container per builder, + * we should move to a "factory factory" model where we create a factory + * instance per Container. Right now, one factory instance would be + * shared across all the containers, singletons synchronize on the + * container when lazy loading, etc. + */ + private void ensureNotCreated() { + if (created) { + throw new IllegalStateException("Container already created."); + } + } + + public void setAllowDuplicates(boolean val) { + allowDuplicates = val; + } + + /** + * Implemented by classes which participate in building a container. + */ + public interface Command { + + /** + * Contributes factories to the given builder. + * + * @param builder + */ + void build(ContainerBuilder builder); + } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerImpl.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerImpl.java index 1b9abb939..187993382 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerImpl.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerImpl.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,9 +21,9 @@ import com.opensymphony.xwork2.inject.util.ReferenceCache; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.*; +import java.security.AccessControlException; import java.util.*; import java.util.Map.Entry; -import java.security.AccessControlException; /** * Default {@link Container} implementation. @@ -33,603 +33,571 @@ import java.security.AccessControlException; */ class ContainerImpl implements Container { - final Map, InternalFactory> factories; - final Map, Set> factoryNamesByType; - - ContainerImpl( Map, InternalFactory> factories ) { - this.factories = factories; - Map, Set> map = new HashMap, Set>(); - for ( Key key : factories.keySet() ) { - Set names = map.get(key.getType()); - if (names == null) { - names = new HashSet(); - map.put(key.getType(), names); - } - names.add(key.getName()); - } - - for ( Entry, Set> entry : map.entrySet() ) { - entry.setValue(Collections.unmodifiableSet(entry.getValue())); - } - - this.factoryNamesByType = Collections.unmodifiableMap(map); - } - - @SuppressWarnings("unchecked") - InternalFactory getFactory( Key key ) { - return (InternalFactory) factories.get(key); - } - - /** - * Field and method injectors. - */ - final Map, List> injectors = - new ReferenceCache, List>() { - @Override - protected List create( Class key ) { - List injectors = new ArrayList(); - addInjectors(key, injectors); - return injectors; - } - }; - - /** - * Recursively adds injectors for fields and methods from the given class to the given list. Injects parent classes - * before sub classes. - */ - void addInjectors( Class clazz, List injectors ) { - if (clazz == Object.class) { - return; - } - - // Add injectors for superclass first. - addInjectors(clazz.getSuperclass(), injectors); - - // TODO (crazybob): Filter out overridden members. - addInjectorsForFields(clazz.getDeclaredFields(), false, injectors); - addInjectorsForMethods(clazz.getDeclaredMethods(), false, injectors); - } - - void injectStatics( List> staticInjections ) { - final List injectors = new ArrayList(); - - for ( Class clazz : staticInjections ) { - addInjectorsForFields(clazz.getDeclaredFields(), true, injectors); - addInjectorsForMethods(clazz.getDeclaredMethods(), true, injectors); - } - - callInContext(new ContextualCallable() { - public Void call( InternalContext context ) { - for ( Injector injector : injectors ) { - injector.inject(context, null); - } - return null; - } - }); - } - - void addInjectorsForMethods( Method[] methods, boolean statics, - List injectors ) { - addInjectorsForMembers(Arrays.asList(methods), statics, injectors, - new InjectorFactory() { - public Injector create( ContainerImpl container, Method method, - String name ) throws MissingDependencyException { - return new MethodInjector(container, method, name); - } - }); - } - - void addInjectorsForFields( Field[] fields, boolean statics, - List injectors ) { - addInjectorsForMembers(Arrays.asList(fields), statics, injectors, - new InjectorFactory() { - public Injector create( ContainerImpl container, Field field, - String name ) throws MissingDependencyException { - return new FieldInjector(container, field, name); - } - }); - } - - void addInjectorsForMembers( - List members, boolean statics, List injectors, - InjectorFactory injectorFactory ) { - for ( M member : members ) { - if (isStatic(member) == statics) { - Inject inject = member.getAnnotation(Inject.class); - if (inject != null) { - try { - injectors.add(injectorFactory.create(this, member, inject.value())); - } catch ( MissingDependencyException e ) { - if (inject.required()) { - throw new DependencyException(e); - } - } - } - } - } - } - - interface InjectorFactory { - - Injector create( ContainerImpl container, M member, String name ) - throws MissingDependencyException; - } - - private boolean isStatic( Member member ) { - return Modifier.isStatic(member.getModifiers()); - } - - static class FieldInjector implements Injector { - - final Field field; - final InternalFactory factory; - final ExternalContext externalContext; - - public FieldInjector( ContainerImpl container, Field field, String name ) - throws MissingDependencyException { - this.field = field; - if (!field.isAccessible()) { - SecurityManager sm = System.getSecurityManager(); - try { - if (sm != null) { - sm.checkPermission(new ReflectPermission("suppressAccessChecks")); - } - field.setAccessible(true); - } catch ( AccessControlException e ) { - throw new DependencyException("Security manager in use, could not access field: " - + field.getDeclaringClass().getName() + "(" + field.getName() + ")", e); - } - } - - Key key = Key.newInstance(field.getType(), name); - factory = container.getFactory(key); - if (factory == null) { - throw new MissingDependencyException( - "No mapping found for dependency " + key + " in " + field + "."); - } - - this.externalContext = ExternalContext.newInstance(field, key, container); - } - - public void inject( InternalContext context, Object o ) { - ExternalContext previous = context.getExternalContext(); - context.setExternalContext(externalContext); - try { - field.set(o, factory.create(context)); - } catch ( IllegalAccessException e ) { - throw new AssertionError(e); - } finally { - context.setExternalContext(previous); - } - } - } - - /** - * Gets parameter injectors. - * - * @param member to which the parameters belong - * @param annotations on the parameters - * @param parameterTypes parameter types - * - * @return injections - */ - ParameterInjector[] - getParametersInjectors( M member, - Annotation[][] annotations, Class[] parameterTypes, String defaultName ) - throws MissingDependencyException { - List> parameterInjectors = - new ArrayList>(); - - Iterator annotationsIterator = - Arrays.asList(annotations).iterator(); - for ( Class parameterType : parameterTypes ) { - Inject annotation = findInject(annotationsIterator.next()); - String name = annotation == null ? defaultName : annotation.value(); - Key key = Key.newInstance(parameterType, name); - parameterInjectors.add(createParameterInjector(key, member)); - } - - return toArray(parameterInjectors); - } - - ParameterInjector createParameterInjector( - Key key, Member member ) throws MissingDependencyException { - InternalFactory factory = getFactory(key); - if (factory == null) { - throw new MissingDependencyException( - "No mapping found for dependency " + key + " in " + member + "."); - } - - ExternalContext externalContext = - ExternalContext.newInstance(member, key, this); - return new ParameterInjector(externalContext, factory); - } - - @SuppressWarnings("unchecked") - private ParameterInjector[] toArray( - List> parameterInjections ) { - return parameterInjections.toArray( - new ParameterInjector[parameterInjections.size()]); - } - - /** - * Finds the {@link Inject} annotation in an array of annotations. - */ - Inject findInject( Annotation[] annotations ) { - for ( Annotation annotation : annotations ) { - if (annotation.annotationType() == Inject.class) { - return Inject.class.cast(annotation); - } - } - return null; - } - - static class MethodInjector implements Injector { - - final Method method; - final ParameterInjector[] parameterInjectors; - - public MethodInjector( ContainerImpl container, Method method, String name ) - throws MissingDependencyException { - this.method = method; - if (!method.isAccessible()) { - SecurityManager sm = System.getSecurityManager(); - try { - if (sm != null) { - sm.checkPermission(new ReflectPermission("suppressAccessChecks")); - } - method.setAccessible(true); - } catch ( AccessControlException e ) { - throw new DependencyException("Security manager in use, could not access method: " - + name + "(" + method.getName() + ")", e); - } - } - - Class[] parameterTypes = method.getParameterTypes(); - if (parameterTypes.length == 0) { - throw new DependencyException( - method + " has no parameters to inject."); - } - parameterInjectors = container.getParametersInjectors( - method, method.getParameterAnnotations(), parameterTypes, name); - } - - public void inject( InternalContext context, Object o ) { - try { - method.invoke(o, getParameters(method, context, parameterInjectors)); - } catch ( Exception e ) { - throw new RuntimeException(e); - } - } - } - - Map, ConstructorInjector> constructors = - new ReferenceCache, ConstructorInjector>() { - @Override - @SuppressWarnings("unchecked") - protected ConstructorInjector create( Class implementation ) { - return new ConstructorInjector(ContainerImpl.this, implementation); - } - }; - - static class ConstructorInjector { - - final Class implementation; - final List injectors; - final Constructor constructor; - final ParameterInjector[] parameterInjectors; - - ConstructorInjector( ContainerImpl container, Class implementation ) { - this.implementation = implementation; - - constructor = findConstructorIn(implementation); - if (!constructor.isAccessible()) { - SecurityManager sm = System.getSecurityManager(); - try { - if (sm != null) { - sm.checkPermission(new ReflectPermission("suppressAccessChecks")); - } - constructor.setAccessible(true); - } catch ( AccessControlException e ) { - throw new DependencyException("Security manager in use, could not access constructor: " - + implementation.getName() + "(" + constructor.getName() + ")", e); - } - } - - MissingDependencyException exception = null; - Inject inject = null; - ParameterInjector[] parameters = null; - - try { - inject = constructor.getAnnotation(Inject.class); - parameters = constructParameterInjector(inject, container, constructor); - } catch ( MissingDependencyException e ) { - exception = e; - } - parameterInjectors = parameters; - - if (exception != null) { - if (inject != null && inject.required()) { - throw new DependencyException(exception); - } - } - injectors = container.injectors.get(implementation); - } - - ParameterInjector[] constructParameterInjector( - Inject inject, ContainerImpl container, Constructor constructor ) throws MissingDependencyException { - return constructor.getParameterTypes().length == 0 - ? null // default constructor. - : container.getParametersInjectors( - constructor, - constructor.getParameterAnnotations(), - constructor.getParameterTypes(), - inject.value() - ); - } - - @SuppressWarnings("unchecked") - private Constructor findConstructorIn( Class implementation ) { - Constructor found = null; - Constructor[] declaredConstructors = (Constructor[]) implementation - .getDeclaredConstructors(); - for ( Constructor constructor : declaredConstructors ) { - if (constructor.getAnnotation(Inject.class) != null) { - if (found != null) { - throw new DependencyException("More than one constructor annotated" - + " with @Inject found in " + implementation + "."); - } - found = constructor; - } - } - if (found != null) { - return found; - } - - // If no annotated constructor is found, look for a no-arg constructor - // instead. - try { - return implementation.getDeclaredConstructor(); - } catch ( NoSuchMethodException e ) { - throw new DependencyException("Could not find a suitable constructor" - + " in " + implementation.getName() + "."); - } - } - - /** - * Construct an instance. Returns {@code Object} instead of {@code T} because it may return a proxy. - */ - Object construct( InternalContext context, Class expectedType ) { - ConstructionContext constructionContext = - context.getConstructionContext(this); - - // We have a circular reference between constructors. Return a proxy. - if (constructionContext.isConstructing()) { - // TODO (crazybob): if we can't proxy this object, can we proxy the - // other object? - return constructionContext.createProxy(expectedType); - } - - // If we're re-entering this factory while injecting fields or methods, - // return the same instance. This prevents infinite loops. - T t = constructionContext.getCurrentReference(); - if (t != null) { - return t; - } - - try { - // First time through... - constructionContext.startConstruction(); - try { - Object[] parameters = - getParameters(constructor, context, parameterInjectors); - t = constructor.newInstance(parameters); - constructionContext.setProxyDelegates(t); - } finally { - constructionContext.finishConstruction(); - } - - // Store reference. If an injector re-enters this factory, they'll - // get the same reference. - constructionContext.setCurrentReference(t); - - // Inject fields and methods. - for ( Injector injector : injectors ) { - injector.inject(context, t); - } - - return t; - } catch ( InstantiationException e ) { - throw new RuntimeException(e); - } catch ( IllegalAccessException e ) { - throw new RuntimeException(e); - } catch ( InvocationTargetException e ) { - throw new RuntimeException(e); - } finally { - constructionContext.removeCurrentReference(); - } - } - } - - static class ParameterInjector { - - final ExternalContext externalContext; - final InternalFactory factory; - - public ParameterInjector( ExternalContext externalContext, - InternalFactory factory ) { - this.externalContext = externalContext; - this.factory = factory; - } - - T inject( Member member, InternalContext context ) { - ExternalContext previous = context.getExternalContext(); - context.setExternalContext(externalContext); - try { - return factory.create(context); - } finally { - context.setExternalContext(previous); - } - } - } - - private static Object[] getParameters( Member member, InternalContext context, - ParameterInjector[] parameterInjectors ) { - if (parameterInjectors == null) { - return null; - } - - Object[] parameters = new Object[parameterInjectors.length]; - for ( int i = 0; i < parameters.length; i++ ) { - parameters[i] = parameterInjectors[i].inject(member, context); - } - return parameters; - } - - void inject( Object o, InternalContext context ) { - List injectors = this.injectors.get(o.getClass()); - for ( Injector injector : injectors ) { - injector.inject(context, o); - } - } - - T inject( Class implementation, InternalContext context ) { - try { - ConstructorInjector constructor = getConstructor(implementation); - return implementation.cast( - constructor.construct(context, implementation)); - } catch ( Exception e ) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - T getInstance( Class type, String name, InternalContext context ) { - ExternalContext previous = context.getExternalContext(); - Key key = Key.newInstance(type, name); - context.setExternalContext(ExternalContext.newInstance(null, key, this)); - try { - InternalFactory o = getFactory(key); - if (o != null) { - return getFactory(key).create(context); - } else { - return null; - } - } finally { - context.setExternalContext(previous); - } - } - - T getInstance( Class type, InternalContext context ) { - return getInstance(type, DEFAULT_NAME, context); - } - - public void inject( final Object o ) { - callInContext(new ContextualCallable() { - public Void call( InternalContext context ) { - inject(o, context); - return null; - } - }); - } - - public T inject( final Class implementation ) { - return callInContext(new ContextualCallable() { - public T call( InternalContext context ) { - return inject(implementation, context); - } - }); - } - - public T getInstance( final Class type, final String name ) { - return callInContext(new ContextualCallable() { - public T call( InternalContext context ) { - return getInstance(type, name, context); - } - }); - } - - public T getInstance( final Class type ) { - return callInContext(new ContextualCallable() { - public T call( InternalContext context ) { - return getInstance(type, context); - } - }); - } - - public Set getInstanceNames( final Class type ) { + final Map, InternalFactory> factories; + final Map, Set> factoryNamesByType; + + ContainerImpl(Map, InternalFactory> factories) { + this.factories = factories; + Map, Set> map = new HashMap<>(); + for (Key key : factories.keySet()) { + Set names = map.get(key.getType()); + if (names == null) { + names = new HashSet<>(); + map.put(key.getType(), names); + } + names.add(key.getName()); + } + + for (Entry, Set> entry : map.entrySet()) { + entry.setValue(Collections.unmodifiableSet(entry.getValue())); + } + + this.factoryNamesByType = Collections.unmodifiableMap(map); + } + + @SuppressWarnings("unchecked") + InternalFactory getFactory(Key key) { + return (InternalFactory) factories.get(key); + } + + /** + * Field and method injectors. + */ + final Map, List> injectors = + new ReferenceCache, List>() { + @Override + protected List create(Class key) { + List injectors = new ArrayList<>(); + addInjectors(key, injectors); + return injectors; + } + }; + + /** + * Recursively adds injectors for fields and methods from the given class to the given list. Injects parent classes + * before sub classes. + */ + void addInjectors(Class clazz, List injectors) { + if (clazz == Object.class) { + return; + } + + // Add injectors for superclass first. + addInjectors(clazz.getSuperclass(), injectors); + + // TODO (crazybob): Filter out overridden members. + addInjectorsForFields(clazz.getDeclaredFields(), false, injectors); + addInjectorsForMethods(clazz.getDeclaredMethods(), false, injectors); + } + + void injectStatics(List> staticInjections) { + final List injectors = new ArrayList<>(); + + for (Class clazz : staticInjections) { + addInjectorsForFields(clazz.getDeclaredFields(), true, injectors); + addInjectorsForMethods(clazz.getDeclaredMethods(), true, injectors); + } + + callInContext(new ContextualCallable() { + public Void call(InternalContext context) { + for (Injector injector : injectors) { + injector.inject(context, null); + } + return null; + } + }); + } + + void addInjectorsForMethods(Method[] methods, boolean statics, List injectors) { + addInjectorsForMembers(Arrays.asList(methods), statics, injectors, + new InjectorFactory() { + public Injector create(ContainerImpl container, Method method, + String name) throws MissingDependencyException { + return new MethodInjector(container, method, name); + } + }); + } + + void addInjectorsForFields(Field[] fields, boolean statics, List injectors) { + addInjectorsForMembers(Arrays.asList(fields), statics, injectors, + new InjectorFactory() { + public Injector create(ContainerImpl container, Field field, + String name) throws MissingDependencyException { + return new FieldInjector(container, field, name); + } + }); + } + + void addInjectorsForMembers( + List members, boolean statics, List injectors, InjectorFactory injectorFactory) { + for (M member : members) { + if (isStatic(member) == statics) { + Inject inject = member.getAnnotation(Inject.class); + if (inject != null) { + try { + injectors.add(injectorFactory.create(this, member, inject.value())); + } catch (MissingDependencyException e) { + if (inject.required()) { + throw new DependencyException(e); + } + } + } + } + } + } + + interface InjectorFactory { + + Injector create(ContainerImpl container, M member, String name) + throws MissingDependencyException; + } + + private boolean isStatic(Member member) { + return Modifier.isStatic(member.getModifiers()); + } + + static class FieldInjector implements Injector { + + final Field field; + final InternalFactory factory; + final ExternalContext externalContext; + + public FieldInjector(ContainerImpl container, Field field, String name) + throws MissingDependencyException { + this.field = field; + if (!field.isAccessible()) { + SecurityManager sm = System.getSecurityManager(); + try { + if (sm != null) { + sm.checkPermission(new ReflectPermission("suppressAccessChecks")); + } + field.setAccessible(true); + } catch (AccessControlException e) { + throw new DependencyException("Security manager in use, could not access field: " + + field.getDeclaringClass().getName() + "(" + field.getName() + ")", e); + } + } + + Key key = Key.newInstance(field.getType(), name); + factory = container.getFactory(key); + if (factory == null) { + throw new MissingDependencyException("No mapping found for dependency " + key + " in " + field + "."); + } + + this.externalContext = ExternalContext.newInstance(field, key, container); + } + + public void inject(InternalContext context, Object o) { + ExternalContext previous = context.getExternalContext(); + context.setExternalContext(externalContext); + try { + field.set(o, factory.create(context)); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } finally { + context.setExternalContext(previous); + } + } + } + + /** + * Gets parameter injectors. + * + * @param member to which the parameters belong + * @param annotations on the parameters + * @param parameterTypes parameter types + * @return injections + */ + ParameterInjector[] + getParametersInjectors(M member, Annotation[][] annotations, Class[] parameterTypes, String defaultName) throws MissingDependencyException { + List> parameterInjectors = new ArrayList<>(); + + Iterator annotationsIterator = Arrays.asList(annotations).iterator(); + for (Class parameterType : parameterTypes) { + Inject annotation = findInject(annotationsIterator.next()); + String name = annotation == null ? defaultName : annotation.value(); + Key key = Key.newInstance(parameterType, name); + parameterInjectors.add(createParameterInjector(key, member)); + } + + return toArray(parameterInjectors); + } + + ParameterInjector createParameterInjector(Key key, Member member) throws MissingDependencyException { + InternalFactory factory = getFactory(key); + if (factory == null) { + throw new MissingDependencyException("No mapping found for dependency " + key + " in " + member + "."); + } + + ExternalContext externalContext = ExternalContext.newInstance(member, key, this); + return new ParameterInjector(externalContext, factory); + } + + @SuppressWarnings("unchecked") + private ParameterInjector[] toArray(List> parameterInjections) { + return parameterInjections.toArray(new ParameterInjector[parameterInjections.size()]); + } + + /** + * Finds the {@link Inject} annotation in an array of annotations. + */ + Inject findInject(Annotation[] annotations) { + for (Annotation annotation : annotations) { + if (annotation.annotationType() == Inject.class) { + return Inject.class.cast(annotation); + } + } + return null; + } + + static class MethodInjector implements Injector { + + final Method method; + final ParameterInjector[] parameterInjectors; + + public MethodInjector(ContainerImpl container, Method method, String name) throws MissingDependencyException { + this.method = method; + if (!method.isAccessible()) { + SecurityManager sm = System.getSecurityManager(); + try { + if (sm != null) { + sm.checkPermission(new ReflectPermission("suppressAccessChecks")); + } + method.setAccessible(true); + } catch (AccessControlException e) { + throw new DependencyException("Security manager in use, could not access method: " + + name + "(" + method.getName() + ")", e); + } + } + + Class[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length == 0) { + throw new DependencyException(method + " has no parameters to inject."); + } + parameterInjectors = container.getParametersInjectors( + method, method.getParameterAnnotations(), parameterTypes, name); + } + + public void inject(InternalContext context, Object o) { + try { + method.invoke(o, getParameters(method, context, parameterInjectors)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + Map, ConstructorInjector> constructors = + new ReferenceCache, ConstructorInjector>() { + @Override + @SuppressWarnings("unchecked") + protected ConstructorInjector create(Class implementation) { + return new ConstructorInjector(ContainerImpl.this, implementation); + } + }; + + static class ConstructorInjector { + + final Class implementation; + final List injectors; + final Constructor constructor; + final ParameterInjector[] parameterInjectors; + + ConstructorInjector(ContainerImpl container, Class implementation) { + this.implementation = implementation; + + constructor = findConstructorIn(implementation); + if (!constructor.isAccessible()) { + SecurityManager sm = System.getSecurityManager(); + try { + if (sm != null) { + sm.checkPermission(new ReflectPermission("suppressAccessChecks")); + } + constructor.setAccessible(true); + } catch (AccessControlException e) { + throw new DependencyException("Security manager in use, could not access constructor: " + + implementation.getName() + "(" + constructor.getName() + ")", e); + } + } + + MissingDependencyException exception = null; + Inject inject = null; + ParameterInjector[] parameters = null; + + try { + inject = constructor.getAnnotation(Inject.class); + parameters = constructParameterInjector(inject, container, constructor); + } catch (MissingDependencyException e) { + exception = e; + } + parameterInjectors = parameters; + + if (exception != null) { + if (inject != null && inject.required()) { + throw new DependencyException(exception); + } + } + injectors = container.injectors.get(implementation); + } + + ParameterInjector[] constructParameterInjector( + Inject inject, ContainerImpl container, Constructor constructor) throws MissingDependencyException { + return constructor.getParameterTypes().length == 0 + ? null // default constructor. + : container.getParametersInjectors( + constructor, + constructor.getParameterAnnotations(), + constructor.getParameterTypes(), + inject.value() + ); + } + + @SuppressWarnings("unchecked") + private Constructor findConstructorIn(Class implementation) { + Constructor found = null; + Constructor[] declaredConstructors = (Constructor[]) implementation.getDeclaredConstructors(); + for (Constructor constructor : declaredConstructors) { + if (constructor.getAnnotation(Inject.class) != null) { + if (found != null) { + throw new DependencyException("More than one constructor annotated" + + " with @Inject found in " + implementation + "."); + } + found = constructor; + } + } + if (found != null) { + return found; + } + + // If no annotated constructor is found, look for a no-arg constructor + // instead. + try { + return implementation.getDeclaredConstructor(); + } catch (NoSuchMethodException e) { + throw new DependencyException("Could not find a suitable constructor in " + implementation.getName() + "."); + } + } + + /** + * Construct an instance. Returns {@code Object} instead of {@code T} because it may return a proxy. + */ + Object construct(InternalContext context, Class expectedType) { + ConstructionContext constructionContext = context.getConstructionContext(this); + + // We have a circular reference between constructors. Return a proxy. + if (constructionContext.isConstructing()) { + // TODO (crazybob): if we can't proxy this object, can we proxy the + // other object? + return constructionContext.createProxy(expectedType); + } + + // If we're re-entering this factory while injecting fields or methods, + // return the same instance. This prevents infinite loops. + T t = constructionContext.getCurrentReference(); + if (t != null) { + return t; + } + + try { + // First time through... + constructionContext.startConstruction(); + try { + Object[] parameters = getParameters(constructor, context, parameterInjectors); + t = constructor.newInstance(parameters); + constructionContext.setProxyDelegates(t); + } finally { + constructionContext.finishConstruction(); + } + + // Store reference. If an injector re-enters this factory, they'll + // get the same reference. + constructionContext.setCurrentReference(t); + + // Inject fields and methods. + for (Injector injector : injectors) { + injector.inject(context, t); + } + + return t; + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } finally { + constructionContext.removeCurrentReference(); + } + } + } + + static class ParameterInjector { + + final ExternalContext externalContext; + final InternalFactory factory; + + public ParameterInjector(ExternalContext externalContext, InternalFactory factory) { + this.externalContext = externalContext; + this.factory = factory; + } + + T inject(Member member, InternalContext context) { + ExternalContext previous = context.getExternalContext(); + context.setExternalContext(externalContext); + try { + return factory.create(context); + } finally { + context.setExternalContext(previous); + } + } + } + + private static Object[] getParameters(Member member, InternalContext context, ParameterInjector[] parameterInjectors) { + if (parameterInjectors == null) { + return null; + } + + Object[] parameters = new Object[parameterInjectors.length]; + for (int i = 0; i < parameters.length; i++) { + parameters[i] = parameterInjectors[i].inject(member, context); + } + return parameters; + } + + void inject(Object o, InternalContext context) { + List injectors = this.injectors.get(o.getClass()); + for (Injector injector : injectors) { + injector.inject(context, o); + } + } + + T inject(Class implementation, InternalContext context) { + try { + ConstructorInjector constructor = getConstructor(implementation); + return implementation.cast(constructor.construct(context, implementation)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @SuppressWarnings("unchecked") + T getInstance(Class type, String name, InternalContext context) { + ExternalContext previous = context.getExternalContext(); + Key key = Key.newInstance(type, name); + context.setExternalContext(ExternalContext.newInstance(null, key, this)); + try { + InternalFactory o = getFactory(key); + if (o != null) { + return getFactory(key).create(context); + } else { + return null; + } + } finally { + context.setExternalContext(previous); + } + } + + T getInstance(Class type, InternalContext context) { + return getInstance(type, DEFAULT_NAME, context); + } + + public void inject(final Object o) { + callInContext(new ContextualCallable() { + public Void call(InternalContext context) { + inject(o, context); + return null; + } + }); + } + + public T inject(final Class implementation) { + return callInContext(new ContextualCallable() { + public T call(InternalContext context) { + return inject(implementation, context); + } + }); + } + + public T getInstance(final Class type, final String name) { + return callInContext(new ContextualCallable() { + public T call(InternalContext context) { + return getInstance(type, name, context); + } + }); + } + + public T getInstance(final Class type) { + return callInContext(new ContextualCallable() { + public T call(InternalContext context) { + return getInstance(type, context); + } + }); + } + + public Set getInstanceNames(final Class type) { Set names = factoryNamesByType.get(type); if (names == null) { names = Collections.emptySet(); } return names; - } + } - ThreadLocal localContext = - new ThreadLocal() { - @Override - protected Object[] initialValue() { - return new Object[1]; - } - }; + ThreadLocal localContext = new ThreadLocal() { + @Override + protected Object[] initialValue() { + return new Object[1]; + } + }; - /** - * Looks up thread local context. Creates (and removes) a new context if necessary. - */ - T callInContext( ContextualCallable callable ) { - Object[] reference = localContext.get(); - if (reference[0] == null) { - reference[0] = new InternalContext(this); - try { - return callable.call((InternalContext) reference[0]); - } finally { - // Only remove the context if this call created it. - reference[0] = null; - // WW-3768: ThreadLocal was not removed - localContext.remove(); - } - } else { - // Someone else will clean up this context. - return callable.call((InternalContext) reference[0]); - } - } + /** + * Looks up thread local context. Creates (and removes) a new context if necessary. + */ + T callInContext(ContextualCallable callable) { + Object[] reference = localContext.get(); + if (reference[0] == null) { + reference[0] = new InternalContext(this); + try { + return callable.call((InternalContext) reference[0]); + } finally { + // Only remove the context if this call created it. + reference[0] = null; + // WW-3768: ThreadLocal was not removed + localContext.remove(); + } + } else { + // Someone else will clean up this context. + return callable.call((InternalContext) reference[0]); + } + } - interface ContextualCallable { + interface ContextualCallable { + T call(InternalContext context); + } - T call( InternalContext context ); - } + /** + * Gets a constructor function for a given implementation class. + */ + @SuppressWarnings("unchecked") + ConstructorInjector getConstructor(Class implementation) { + return constructors.get(implementation); + } - /** - * Gets a constructor function for a given implementation class. - */ - @SuppressWarnings("unchecked") - ConstructorInjector getConstructor( Class implementation ) { - return constructors.get(implementation); - } + final ThreadLocal localScopeStrategy = new ThreadLocal<>(); - final ThreadLocal localScopeStrategy = - new ThreadLocal(); + public void setScopeStrategy(Scope.Strategy scopeStrategy) { + this.localScopeStrategy.set(scopeStrategy); + } - public void setScopeStrategy( Scope.Strategy scopeStrategy ) { - this.localScopeStrategy.set(scopeStrategy); - } + public void removeScopeStrategy() { + this.localScopeStrategy.remove(); + } - public void removeScopeStrategy() { - this.localScopeStrategy.remove(); - } + /** + * Injects a field or method in a given object. + */ + interface Injector extends Serializable { + void inject(InternalContext context, Object o); + } - /** - * Injects a field or method in a given object. - */ - interface Injector extends Serializable { - - void inject( InternalContext context, Object o ); - } - - static class MissingDependencyException extends Exception { - - MissingDependencyException( String message ) { - super(message); - } - } + static class MissingDependencyException extends Exception { + MissingDependencyException(String message) { + super(message); + } + } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ExternalContext.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ExternalContext.java index 8a3880e1b..0c054e8a2 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ExternalContext.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ExternalContext.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,48 +27,47 @@ import java.util.LinkedHashMap; */ class ExternalContext implements Context { - final Member member; - final Key key; - final ContainerImpl container; + final Member member; + final Key key; + final ContainerImpl container; - public ExternalContext(Member member, Key key, ContainerImpl container) { - this.member = member; - this.key = key; - this.container = container; - } + public ExternalContext(Member member, Key key, ContainerImpl container) { + this.member = member; + this.key = key; + this.container = container; + } - public Class getType() { - return key.getType(); - } + public Class getType() { + return key.getType(); + } - public Scope.Strategy getScopeStrategy() { - return (Scope.Strategy) container.localScopeStrategy.get(); - } + public Scope.Strategy getScopeStrategy() { + return (Scope.Strategy) container.localScopeStrategy.get(); + } - public Container getContainer() { - return container; - } + public Container getContainer() { + return container; + } - public Member getMember() { - return member; - } + public Member getMember() { + return member; + } - public String getName() { - return key.getName(); - } + public String getName() { + return key.getName(); + } - @Override - public String toString() { - return "Context" + new LinkedHashMap() {{ - put("member", member); - put("type", getType()); - put("name", getName()); - put("container", container); - }}.toString(); - } + @Override + public String toString() { + return "Context" + new LinkedHashMap() {{ + put("member", member); + put("type", getType()); + put("name", getName()); + put("container", container); + }}.toString(); + } - static ExternalContext newInstance(Member member, Key key, - ContainerImpl container) { - return new ExternalContext(member, key, container); - } + static ExternalContext newInstance(Member member, Key key, ContainerImpl container) { + return new ExternalContext(member, key, container); + } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/InternalContext.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/InternalContext.java index 16fa0c130..7014480bd 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/InternalContext.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/InternalContext.java @@ -28,8 +28,7 @@ import java.util.Map; class InternalContext { final ContainerImpl container; - final Map> constructionContexts = - new HashMap>(); + final Map> constructionContexts = new HashMap>(); Scope.Strategy scopeStrategy; ExternalContext externalContext; @@ -50,8 +49,7 @@ class InternalContext { scopeStrategy = (Scope.Strategy) container.localScopeStrategy.get(); if (scopeStrategy == null) { - throw new IllegalStateException("Scope strategy not set. " - + "Please call Container.setScopeStrategy()."); + throw new IllegalStateException("Scope strategy not set. Please call Container.setScopeStrategy()."); } } @@ -60,8 +58,7 @@ class InternalContext { @SuppressWarnings("unchecked") ConstructionContext getConstructionContext(Object key) { - ConstructionContext constructionContext = - (ConstructionContext) constructionContexts.get(key); + ConstructionContext constructionContext = (ConstructionContext) constructionContexts.get(key); if (constructionContext == null) { constructionContext = new ConstructionContext(); constructionContexts.put(key, constructionContext); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Key.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Key.java index 03756b9f6..ad9e0ba02 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Key.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Key.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,55 +23,55 @@ package com.opensymphony.xwork2.inject; */ class Key { - final Class type; - final String name; - final int hashCode; + final Class type; + final String name; + final int hashCode; - private Key(Class type, String name) { - if (type == null) { - throw new NullPointerException("Type is null."); - } - if (name == null) { - throw new NullPointerException("Name is null."); + private Key(Class type, String name) { + if (type == null) { + throw new NullPointerException("Type is null."); + } + if (name == null) { + throw new NullPointerException("Name is null."); + } + + this.type = type; + this.name = name; + + hashCode = type.hashCode() * 31 + name.hashCode(); } - this.type = type; - this.name = name; - - hashCode = type.hashCode() * 31 + name.hashCode(); - } - - Class getType() { - return type; - } - - String getName() { - return name; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Key)) { - return false; + Class getType() { + return type; } - if (o == this) { - return true; + + String getName() { + return name; } - Key other = (Key) o; - return name.equals(other.name) && type.equals(other.type); - } - @Override - public String toString() { - return "[type=" + type.getName() + ", name='" + name + "']"; - } + @Override + public int hashCode() { + return hashCode; + } - static Key newInstance(Class type, String name) { - return new Key(type, name); - } + @Override + public boolean equals(Object o) { + if (!(o instanceof Key)) { + return false; + } + if (o == this) { + return true; + } + Key other = (Key) o; + return name.equals(other.name) && type.equals(other.type); + } + + @Override + public String toString() { + return "[type=" + type.getName() + ", name='" + name + "']"; + } + + static Key newInstance(Class type, String name) { + return new Key(type, name); + } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Scope.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Scope.java index b327db837..62443f79a 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Scope.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/Scope.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,193 +25,190 @@ import java.util.concurrent.Callable; */ public enum Scope { - /** - * One instance per injection. - */ - DEFAULT { - @Override - InternalFactory scopeFactory(Class type, String name, - InternalFactory factory) { - return factory; - } - }, - - /** - * One instance per container. - */ - SINGLETON { - @Override - InternalFactory scopeFactory(Class type, String name, - final InternalFactory factory) { - return new InternalFactory() { - T instance; - public T create(InternalContext context) { - synchronized (context.getContainer()) { - if (instance == null) { - instance = factory.create(context); - } - return instance; - } - } - + /** + * One instance per injection. + */ + DEFAULT { @Override - public String toString() { - return factory.toString(); - } - }; - } - }, - - /** - * One instance per thread. - * - *

Note: if a thread local object strongly references its {@link - * Container}, neither the {@code Container} nor the object will be - * eligible for garbage collection, i.e. memory leak. - */ - THREAD { - @Override - InternalFactory scopeFactory(Class type, String name, - final InternalFactory factory) { - return new InternalFactory() { - final ThreadLocal threadLocal = new ThreadLocal(); - public T create(final InternalContext context) { - T t = threadLocal.get(); - if (t == null) { - t = factory.create(context); - threadLocal.set(t); - } - return t; + InternalFactory scopeFactory(Class type, String name, + InternalFactory factory) { + return factory; } + }, + /** + * One instance per container. + */ + SINGLETON { @Override - public String toString() { - return factory.toString(); - } - }; - } - }, + InternalFactory scopeFactory(Class type, String name, final InternalFactory factory) { + return new InternalFactory() { + T instance; - /** - * One instance per request. - */ - REQUEST { - @Override - InternalFactory scopeFactory(final Class type, - final String name, final InternalFactory factory) { - return new InternalFactory() { - public T create(InternalContext context) { - Strategy strategy = context.getScopeStrategy(); - try { - return strategy.findInRequest( - type, name, toCallable(context, factory)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + public T create(InternalContext context) { + synchronized (context.getContainer()) { + if (instance == null) { + instance = factory.create(context); + } + return instance; + } + } + @Override + public String toString() { + return factory.toString(); + } + }; + } + }, + + /** + * One instance per thread. + *

+ *

Note: if a thread local object strongly references its {@link + * Container}, neither the {@code Container} nor the object will be + * eligible for garbage collection, i.e. memory leak. + */ + THREAD { @Override - public String toString() { - return factory.toString(); - } - }; - } - }, + InternalFactory scopeFactory(Class type, String name, final InternalFactory factory) { + return new InternalFactory() { + final ThreadLocal threadLocal = new ThreadLocal(); - /** - * One instance per session. - */ - SESSION { - @Override - InternalFactory scopeFactory(final Class type, - final String name, final InternalFactory factory) { - return new InternalFactory() { - public T create(InternalContext context) { - Strategy strategy = context.getScopeStrategy(); - try { - return strategy.findInSession( - type, name, toCallable(context, factory)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + public T create(final InternalContext context) { + T t = threadLocal.get(); + if (t == null) { + t = factory.create(context); + threadLocal.set(t); + } + return t; + } + @Override + public String toString() { + return factory.toString(); + } + }; + } + }, + + /** + * One instance per request. + */ + REQUEST { @Override - public String toString() { - return factory.toString(); - } - }; - } - }, + InternalFactory scopeFactory(final Class type, final String name, final InternalFactory factory) { + return new InternalFactory() { + public T create(InternalContext context) { + Strategy strategy = context.getScopeStrategy(); + try { + return strategy.findInRequest( + type, name, toCallable(context, factory)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - /** - * One instance per wizard. - */ - WIZARD { - @Override - InternalFactory scopeFactory(final Class type, - final String name, final InternalFactory factory) { - return new InternalFactory() { - public T create(InternalContext context) { - Strategy strategy = context.getScopeStrategy(); - try { - return strategy.findInWizard( - type, name, toCallable(context, factory)); - } catch (Exception e) { - throw new RuntimeException(e); - } + @Override + public String toString() { + return factory.toString(); + } + }; } + }, + /** + * One instance per session. + */ + SESSION { @Override - public String toString() { - return factory.toString(); - } - }; - } - }; + InternalFactory scopeFactory(final Class type, final String name, final InternalFactory factory) { + return new InternalFactory() { + public T create(InternalContext context) { + Strategy strategy = context.getScopeStrategy(); + try { + return strategy.findInSession( + type, name, toCallable(context, factory)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - Callable toCallable(final InternalContext context, - final InternalFactory factory) { - return new Callable() { - public T call() throws Exception { - return factory.create(context); - } + @Override + public String toString() { + return factory.toString(); + } + }; + } + }, + + /** + * One instance per wizard. + */ + WIZARD { + @Override + InternalFactory scopeFactory(final Class type, final String name, final InternalFactory factory) { + return new InternalFactory() { + public T create(InternalContext context) { + Strategy strategy = context.getScopeStrategy(); + try { + return strategy.findInWizard( + type, name, toCallable(context, factory)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public String toString() { + return factory.toString(); + } + }; + } }; - } - /** - * Wraps factory with scoping logic. - */ - abstract InternalFactory scopeFactory( - Class type, String name, InternalFactory factory); - - /** - * Pluggable scoping strategy. Enables users to provide custom - * implementations of request, session, and wizard scopes. Implement and - * pass to {@link - * Container#setScopeStrategy(com.opensymphony.xwork2.inject.Scope.Strategy)}. - */ - public interface Strategy { + Callable toCallable(final InternalContext context, + final InternalFactory factory) { + return new Callable() { + public T call() throws Exception { + return factory.create(context); + } + }; + } /** - * Finds an object for the given type and name in the request scope. - * Creates a new object if necessary using the given factory. + * Wraps factory with scoping logic. */ - T findInRequest(Class type, String name, - Callable factory) throws Exception; + abstract InternalFactory scopeFactory( + Class type, String name, InternalFactory factory); /** - * Finds an object for the given type and name in the session scope. - * Creates a new object if necessary using the given factory. + * Pluggable scoping strategy. Enables users to provide custom + * implementations of request, session, and wizard scopes. Implement and + * pass to {@link + * Container#setScopeStrategy(com.opensymphony.xwork2.inject.Scope.Strategy)}. */ - T findInSession(Class type, String name, - Callable factory) throws Exception; + public interface Strategy { - /** - * Finds an object for the given type and name in the wizard scope. - * Creates a new object if necessary using the given factory. - */ - T findInWizard(Class type, String name, - Callable factory) throws Exception; - } + /** + * Finds an object for the given type and name in the request scope. + * Creates a new object if necessary using the given factory. + */ + T findInRequest(Class type, String name, + Callable factory) throws Exception; + + /** + * Finds an object for the given type and name in the session scope. + * Creates a new object if necessary using the given factory. + */ + T findInSession(Class type, String name, + Callable factory) throws Exception; + + /** + * Finds an object for the given type and name in the wizard scope. + * Creates a new object if necessary using the given factory. + */ + T findInWizard(Class type, String name, + Callable factory) throws Exception; + } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceCache.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceCache.java index 166742cfa..9ebf54558 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceCache.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceCache.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,12 +16,12 @@ package com.opensymphony.xwork2.inject.util; -import static com.opensymphony.xwork2.inject.util.ReferenceType.STRONG; - import java.io.IOException; import java.io.ObjectInputStream; import java.util.concurrent.*; +import static com.opensymphony.xwork2.inject.util.ReferenceType.STRONG; + /** * Extends {@link ReferenceMap} to support lazy loading values by overriding * {@link #create(Object)}. @@ -30,155 +30,148 @@ import java.util.concurrent.*; */ public abstract class ReferenceCache extends ReferenceMap { - private static final long serialVersionUID = 0; + private static final long serialVersionUID = 0; - transient ConcurrentMap> futures = - new ConcurrentHashMap>(); + transient ConcurrentMap> futures = new ConcurrentHashMap<>(); + transient ThreadLocal> localFuture = new ThreadLocal<>(); - transient ThreadLocal> localFuture = new ThreadLocal>(); + public ReferenceCache(ReferenceType keyReferenceType, ReferenceType valueReferenceType) { + super(keyReferenceType, valueReferenceType); + } - public ReferenceCache(ReferenceType keyReferenceType, - ReferenceType valueReferenceType) { - super(keyReferenceType, valueReferenceType); - } + /** + * Equivalent to {@code new ReferenceCache(STRONG, STRONG)}. + */ + public ReferenceCache() { + super(STRONG, STRONG); + } - /** - * Equivalent to {@code new ReferenceCache(STRONG, STRONG)}. - */ - public ReferenceCache() { - super(STRONG, STRONG); - } + /** + * Override to lazy load values. Use as an alternative to {@link + * #put(Object, Object)}. Invoked by getter if value isn't already cached. + * Must not return {@code null}. This method will not be called again until + * the garbage collector reclaims the returned value. + */ + protected abstract V create(K key); - /** - * Override to lazy load values. Use as an alternative to {@link - * #put(Object,Object)}. Invoked by getter if value isn't already cached. - * Must not return {@code null}. This method will not be called again until - * the garbage collector reclaims the returned value. - */ - protected abstract V create(K key); - - V internalCreate(K key) { - try { - FutureTask futureTask = new FutureTask( - new CallableCreate(key)); - - // use a reference so we get the same equality semantics. - Object keyReference = referenceKey(key); - Future future = futures.putIfAbsent(keyReference, futureTask); - if (future == null) { - // winning thread. + V internalCreate(K key) { try { - if (localFuture.get() != null) { - throw new IllegalStateException( - "Nested creations within the same cache are not allowed."); - } - localFuture.set(futureTask); - futureTask.run(); - V value = futureTask.get(); - putStrategy().execute(this, - keyReference, referenceValue(keyReference, value)); - return value; - } finally { - localFuture.remove(); - futures.remove(keyReference); + FutureTask futureTask = new FutureTask<>(new CallableCreate(key)); + + // use a reference so we get the same equality semantics. + Object keyReference = referenceKey(key); + Future future = futures.putIfAbsent(keyReference, futureTask); + if (future == null) { + // winning thread. + try { + if (localFuture.get() != null) { + throw new IllegalStateException("Nested creations within the same cache are not allowed."); + } + localFuture.set(futureTask); + futureTask.run(); + V value = futureTask.get(); + putStrategy().execute(this, keyReference, referenceValue(keyReference, value)); + return value; + } finally { + localFuture.remove(); + futures.remove(keyReference); + } + } else { + // wait for winning thread. + return future.get(); + } + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } else if (cause instanceof Error) { + throw (Error) cause; + } + throw new RuntimeException(cause); } - } else { - // wait for winning thread. - return future.get(); - } - } catch (InterruptedException e) { - throw new RuntimeException(e); - } catch (ExecutionException e) { - Throwable cause = e.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; - } else if (cause instanceof Error) { - throw (Error) cause; - } - throw new RuntimeException(cause); - } - } - - /** - * {@inheritDoc} - * - * If this map does not contain an entry for the given key and {@link - * #create(Object)} has been overridden, this method will create a new - * value, put it in the map, and return it. - * - * @throws NullPointerException if {@link #create(Object)} returns null. - * @throws java.util.concurrent.CancellationException if the creation is - * cancelled. See {@link #cancel()}. - */ - @SuppressWarnings("unchecked") - @Override public V get(final Object key) { - V value = super.get(key); - return (value == null) - ? internalCreate((K) key) - : value; - } - - /** - * Cancels the current {@link #create(Object)}. Throws {@link - * java.util.concurrent.CancellationException} to all clients currently - * blocked on {@link #get(Object)}. - */ - protected void cancel() { - Future future = localFuture.get(); - if (future == null) { - throw new IllegalStateException("Not in create()."); - } - future.cancel(false); - } - - class CallableCreate implements Callable { - - K key; - - public CallableCreate(K key) { - this.key = key; } - public V call() { - // try one more time (a previous future could have come and gone.) - V value = internalGet(key); - if (value != null) { - return value; - } - - // create value. - value = create(key); - if (value == null) { - throw new NullPointerException( - "create(K) returned null for: " + key); - } - return value; + /** + * {@inheritDoc} + *

+ * If this map does not contain an entry for the given key and {@link + * #create(Object)} has been overridden, this method will create a new + * value, put it in the map, and return it. + * + * @throws NullPointerException if {@link #create(Object)} returns null. + * @throws java.util.concurrent.CancellationException if the creation is + * cancelled. See {@link #cancel()}. + */ + @SuppressWarnings("unchecked") + @Override + public V get(final Object key) { + V value = super.get(key); + return (value == null) ? internalCreate((K) key) : value; } - } - /** - * Returns a {@code ReferenceCache} delegating to the specified {@code - * function}. The specified function must not return {@code null}. - */ - public static ReferenceCache of( - ReferenceType keyReferenceType, - ReferenceType valueReferenceType, - final Function function) { - ensureNotNull(function); - return new ReferenceCache(keyReferenceType, valueReferenceType) { - @Override - protected V create(K key) { - return function.apply(key); - } - private static final long serialVersionUID = 0; - }; - } + /** + * Cancels the current {@link #create(Object)}. Throws {@link + * java.util.concurrent.CancellationException} to all clients currently + * blocked on {@link #get(Object)}. + */ + protected void cancel() { + Future future = localFuture.get(); + if (future == null) { + throw new IllegalStateException("Not in create()."); + } + future.cancel(false); + } - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - this.futures = new ConcurrentHashMap>(); - this.localFuture = new ThreadLocal>(); - } + class CallableCreate implements Callable { + + K key; + + public CallableCreate(K key) { + this.key = key; + } + + public V call() { + // try one more time (a previous future could have come and gone.) + V value = internalGet(key); + if (value != null) { + return value; + } + + // create value. + value = create(key); + if (value == null) { + throw new NullPointerException("create(K) returned null for: " + key); + } + return value; + } + } + + /** + * Returns a {@code ReferenceCache} delegating to the specified {@code + * function}. The specified function must not return {@code null}. + */ + public static ReferenceCache of( + ReferenceType keyReferenceType, + ReferenceType valueReferenceType, + final Function function) { + ensureNotNull(function); + return new ReferenceCache(keyReferenceType, valueReferenceType) { + @Override + protected V create(K key) { + return function.apply(key); + } + + private static final long serialVersionUID = 0; + }; + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + in.defaultReadObject(); + this.futures = new ConcurrentHashMap<>(); + this.localFuture = new ThreadLocal<>(); + } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceMap.java b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceMap.java index 2542a8c96..4d8eebb38 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceMap.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/inject/util/ReferenceMap.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2006 Google Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + *

* http://www.apache.org/licenses/LICENSE-2.0 - * + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,8 +16,6 @@ package com.opensymphony.xwork2.inject.util; -import static com.opensymphony.xwork2.inject.util.ReferenceType.STRONG; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -27,6 +25,8 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static com.opensymphony.xwork2.inject.util.ReferenceType.STRONG; + /** * Concurrent hash map that wraps keys and/or values in soft or weak * references. Does not support null keys or values. Uses identity equality @@ -54,563 +54,552 @@ import java.util.concurrent.ConcurrentMap; @SuppressWarnings("unchecked") public class ReferenceMap implements Map, Serializable { - private static final long serialVersionUID = 0; + private static final long serialVersionUID = 0; - transient ConcurrentMap delegate; + transient ConcurrentMap delegate; - final ReferenceType keyReferenceType; - final ReferenceType valueReferenceType; + final ReferenceType keyReferenceType; + final ReferenceType valueReferenceType; - /** - * Concurrent hash map that wraps keys and/or values based on specified - * reference types. - * - * @param keyReferenceType key reference type - * @param valueReferenceType value reference type - */ - public ReferenceMap(ReferenceType keyReferenceType, - ReferenceType valueReferenceType) { - ensureNotNull(keyReferenceType, valueReferenceType); + /** + * Concurrent hash map that wraps keys and/or values based on specified + * reference types. + * + * @param keyReferenceType key reference type + * @param valueReferenceType value reference type + */ + public ReferenceMap(ReferenceType keyReferenceType, + ReferenceType valueReferenceType) { + ensureNotNull(keyReferenceType, valueReferenceType); - if (keyReferenceType == ReferenceType.PHANTOM - || valueReferenceType == ReferenceType.PHANTOM) { - throw new IllegalArgumentException("Phantom references not supported."); + if (keyReferenceType == ReferenceType.PHANTOM || valueReferenceType == ReferenceType.PHANTOM) { + throw new IllegalArgumentException("Phantom references not supported."); + } + + this.delegate = new ConcurrentHashMap<>(); + this.keyReferenceType = keyReferenceType; + this.valueReferenceType = valueReferenceType; } - this.delegate = new ConcurrentHashMap(); - this.keyReferenceType = keyReferenceType; - this.valueReferenceType = valueReferenceType; - } - - V internalGet(K key) { - Object valueReference = delegate.get(makeKeyReferenceAware(key)); - return valueReference == null - ? null - : (V) dereferenceValue(valueReference); - } - - public V get(final Object key) { - ensureNotNull(key); - return internalGet((K) key); - } - - V execute(Strategy strategy, K key, V value) { - ensureNotNull(key, value); - Object keyReference = referenceKey(key); - Object valueReference = strategy.execute( - this, - keyReference, - referenceValue(keyReference, value) - ); - return valueReference == null ? null - : (V) dereferenceValue(valueReference); - } - - public V put(K key, V value) { - return execute(putStrategy(), key, value); - } - - public V remove(Object key) { - ensureNotNull(key); - Object referenceAwareKey = makeKeyReferenceAware(key); - Object valueReference = delegate.remove(referenceAwareKey); - return valueReference == null ? null - : (V) dereferenceValue(valueReference); - } - - public int size() { - return delegate.size(); - } - - public boolean isEmpty() { - return delegate.isEmpty(); - } - - public boolean containsKey(Object key) { - ensureNotNull(key); - Object referenceAwareKey = makeKeyReferenceAware(key); - return delegate.containsKey(referenceAwareKey); - } - - public boolean containsValue(Object value) { - ensureNotNull(value); - for (Object valueReference : delegate.values()) { - if (value.equals(dereferenceValue(valueReference))) { - return true; - } - } - return false; - } - - public void putAll(Map t) { - for (Map.Entry entry : t.entrySet()) { - put(entry.getKey(), entry.getValue()); - } - } - - public void clear() { - delegate.clear(); - } - - /** - * Returns an unmodifiable set view of the keys in this map. As this method - * creates a defensive copy, the performance is O(n). - */ - public Set keySet() { - return Collections.unmodifiableSet( - dereferenceKeySet(delegate.keySet())); - } - - /** - * Returns an unmodifiable set view of the values in this map. As this - * method creates a defensive copy, the performance is O(n). - */ - public Collection values() { - return Collections.unmodifiableCollection( - dereferenceValues(delegate.values())); - } - - public V putIfAbsent(K key, V value) { - // TODO (crazybob) if the value has been gc'ed but the entry hasn't been - // cleaned up yet, this put will fail. - return execute(putIfAbsentStrategy(), key, value); - } - - public boolean remove(Object key, Object value) { - ensureNotNull(key, value); - Object referenceAwareKey = makeKeyReferenceAware(key); - Object referenceAwareValue = makeValueReferenceAware(value); - return delegate.remove(referenceAwareKey, referenceAwareValue); - } - - public boolean replace(K key, V oldValue, V newValue) { - ensureNotNull(key, oldValue, newValue); - Object keyReference = referenceKey(key); - - Object referenceAwareOldValue = makeValueReferenceAware(oldValue); - return delegate.replace( - keyReference, - referenceAwareOldValue, - referenceValue(keyReference, newValue) - ); - } - - public V replace(K key, V value) { - // TODO (crazybob) if the value has been gc'ed but the entry hasn't been - // cleaned up yet, this will succeed when it probably shouldn't. - return execute(replaceStrategy(), key, value); - } - - /** - * Returns an unmodifiable set view of the entries in this map. As this - * method creates a defensive copy, the performance is O(n). - */ - public Set> entrySet() { - Set> entrySet = new HashSet>(); - for (Map.Entry entry : delegate.entrySet()) { - Map.Entry dereferenced = dereferenceEntry(entry); - if (dereferenced != null) { - entrySet.add(dereferenced); - } - } - return Collections.unmodifiableSet(entrySet); - } - - /** - * Dereferences an entry. Returns null if the key or value has been gc'ed. - */ - Entry dereferenceEntry(Map.Entry entry) { - K key = dereferenceKey(entry.getKey()); - V value = dereferenceValue(entry.getValue()); - return (key == null || value == null) - ? null - : new Entry(key, value); - } - - /** - * Creates a reference for a key. - */ - Object referenceKey(K key) { - switch (keyReferenceType) { - case STRONG: return key; - case SOFT: return new SoftKeyReference(key); - case WEAK: return new WeakKeyReference(key); - default: throw new AssertionError(); - } - } - - /** - * Converts a reference to a key. - */ - K dereferenceKey(Object o) { - return (K) dereference(keyReferenceType, o); - } - - /** - * Converts a reference to a value. - */ - V dereferenceValue(Object o) { - return (V) dereference(valueReferenceType, o); - } - - /** - * Returns the refererent for reference given its reference type. - */ - Object dereference(ReferenceType referenceType, Object reference) { - return referenceType == STRONG ? reference : ((Reference) reference).get(); - } - - /** - * Creates a reference for a value. - */ - Object referenceValue(Object keyReference, Object value) { - switch (valueReferenceType) { - case STRONG: return value; - case SOFT: return new SoftValueReference(keyReference, value); - case WEAK: return new WeakValueReference(keyReference, value); - default: throw new AssertionError(); - } - } - - /** - * Dereferences a set of key references. - */ - Set dereferenceKeySet(Set keyReferences) { - return keyReferenceType == STRONG - ? keyReferences - : dereferenceCollection(keyReferenceType, keyReferences, new HashSet()); - } - - /** - * Dereferences a collection of value references. - */ - Collection dereferenceValues(Collection valueReferences) { - return valueReferenceType == STRONG - ? valueReferences - : dereferenceCollection(valueReferenceType, valueReferences, - new ArrayList(valueReferences.size())); - } - - /** - * Wraps key so it can be compared to a referenced key for equality. - */ - Object makeKeyReferenceAware(Object o) { - return keyReferenceType == STRONG ? o : new KeyReferenceAwareWrapper(o); - } - - /** - * Wraps value so it can be compared to a referenced value for equality. - */ - Object makeValueReferenceAware(Object o) { - return valueReferenceType == STRONG ? o : new ReferenceAwareWrapper(o); - } - - /** - * Dereferences elements in {@code in} using - * {@code referenceType} and puts them in {@code out}. Returns - * {@code out}. - */ - > T dereferenceCollection( - ReferenceType referenceType, T in, T out) { - for (Object reference : in) { - out.add(dereference(referenceType, reference)); - } - return out; - } - - /** - * Marker interface to differentiate external and internal references. - */ - interface InternalReference {} - - static int keyHashCode(Object key) { - return System.identityHashCode(key); - } - - /** - * Tests weak and soft references for identity equality. Compares references - * to other references and wrappers. If o is a reference, this returns true - * if r == o or if r and o reference the same non null object. If o is a - * wrapper, this returns true if r's referent is identical to the wrapped - * object. - */ - static boolean referenceEquals(Reference r, Object o) { - // compare reference to reference. - if (o instanceof InternalReference) { - // are they the same reference? used in cleanup. - if (o == r) { - return true; - } - - // do they reference identical values? used in conditional puts. - Object referent = ((Reference) o).get(); - return referent != null && referent == r.get(); + V internalGet(K key) { + Object valueReference = delegate.get(makeKeyReferenceAware(key)); + return valueReference == null ? null : (V) dereferenceValue(valueReference); } - // is the wrapped object identical to the referent? used in lookups. - return ((ReferenceAwareWrapper) o).unwrap() == r.get(); - } - - /** - * Big hack. Used to compare keys and values to referenced keys and values - * without creating more references. - */ - static class ReferenceAwareWrapper { - - Object wrapped; - - ReferenceAwareWrapper(Object wrapped) { - this.wrapped = wrapped; + public V get(final Object key) { + ensureNotNull(key); + return internalGet((K) key); } - Object unwrap() { - return wrapped; + V execute(Strategy strategy, K key, V value) { + ensureNotNull(key, value); + Object keyReference = referenceKey(key); + Object valueReference = strategy.execute(this, keyReference, referenceValue(keyReference, value)); + return valueReference == null ? null : (V) dereferenceValue(valueReference); } - @Override - public int hashCode() { - return wrapped.hashCode(); + public V put(K key, V value) { + return execute(putStrategy(), key, value); } - @Override - public boolean equals(Object obj) { - // defer to reference's equals() logic. - return obj.equals(this); - } - } - - /** - * Used for keys. Overrides hash code to use identity hash code. - */ - static class KeyReferenceAwareWrapper extends ReferenceAwareWrapper { - - public KeyReferenceAwareWrapper(Object wrapped) { - super(wrapped); + public V remove(Object key) { + ensureNotNull(key); + Object referenceAwareKey = makeKeyReferenceAware(key); + Object valueReference = delegate.remove(referenceAwareKey); + return valueReference == null ? null : (V) dereferenceValue(valueReference); } - @Override - public int hashCode() { - return System.identityHashCode(wrapped); - } - } - - class SoftKeyReference extends FinalizableSoftReference - implements InternalReference { - - int hashCode; - - public SoftKeyReference(Object key) { - super(key); - this.hashCode = keyHashCode(key); + public int size() { + return delegate.size(); } - public void finalizeReferent() { - delegate.remove(this); + public boolean isEmpty() { + return delegate.isEmpty(); } - @Override public int hashCode() { - return this.hashCode; + public boolean containsKey(Object key) { + ensureNotNull(key); + Object referenceAwareKey = makeKeyReferenceAware(key); + return delegate.containsKey(referenceAwareKey); } - @Override public boolean equals(Object o) { - return referenceEquals(this, o); - } - } - - class WeakKeyReference extends FinalizableWeakReference - implements InternalReference { - - int hashCode; - - public WeakKeyReference(Object key) { - super(key); - this.hashCode = keyHashCode(key); - } - - public void finalizeReferent() { - delegate.remove(this); - } - - @Override public int hashCode() { - return this.hashCode; - } - - @Override public boolean equals(Object o) { - return referenceEquals(this, o); - } - } - - class SoftValueReference extends FinalizableSoftReference - implements InternalReference { - - Object keyReference; - - public SoftValueReference(Object keyReference, Object value) { - super(value); - this.keyReference = keyReference; - } - - public void finalizeReferent() { - delegate.remove(keyReference, this); - } - - @Override public boolean equals(Object obj) { - return referenceEquals(this, obj); - } - } - - class WeakValueReference extends FinalizableWeakReference - implements InternalReference { - - Object keyReference; - - public WeakValueReference(Object keyReference, Object value) { - super(value); - this.keyReference = keyReference; - } - - public void finalizeReferent() { - delegate.remove(keyReference, this); - } - - @Override public boolean equals(Object obj) { - return referenceEquals(this, obj); - } - } - - protected interface Strategy { - public Object execute(ReferenceMap map, Object keyReference, - Object valueReference); - } - - protected Strategy putStrategy() { - return PutStrategy.PUT; - } - - protected Strategy putIfAbsentStrategy() { - return PutStrategy.PUT_IF_ABSENT; - } - - protected Strategy replaceStrategy() { - return PutStrategy.REPLACE; - } - - private enum PutStrategy implements Strategy { - PUT { - public Object execute(ReferenceMap map, Object keyReference, - Object valueReference) { - return map.delegate.put(keyReference, valueReference); - } - }, - - REPLACE { - public Object execute(ReferenceMap map, Object keyReference, - Object valueReference) { - return map.delegate.replace(keyReference, valueReference); - } - }, - - PUT_IF_ABSENT { - public Object execute(ReferenceMap map, Object keyReference, - Object valueReference) { - return map.delegate.putIfAbsent(keyReference, valueReference); - } - }; - }; - - private static PutStrategy defaultPutStrategy; - - protected PutStrategy getPutStrategy() { - return defaultPutStrategy; - } - - - class Entry implements Map.Entry { - - K key; - V value; - - public Entry(K key, V value) { - this.key = key; - this.value = value; - } - - public K getKey() { - return this.key; - } - - public V getValue() { - return this.value; - } - - public V setValue(V value) { - return put(key, value); - } - - @Override - public int hashCode() { - return key.hashCode() * 31 + value.hashCode(); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof ReferenceMap.Entry)) { + public boolean containsValue(Object value) { + ensureNotNull(value); + for (Object valueReference : delegate.values()) { + if (value.equals(dereferenceValue(valueReference))) { + return true; + } + } return false; - } - - Entry entry = (Entry) o; - return key.equals(entry.key) && value.equals(entry.value); } - @Override - public String toString() { - return key + "=" + value; + public void putAll(Map t) { + for (Map.Entry entry : t.entrySet()) { + put(entry.getKey(), entry.getValue()); + } } - } - static void ensureNotNull(Object o) { - if (o == null) { - throw new NullPointerException(); + public void clear() { + delegate.clear(); } - } - static void ensureNotNull(Object... array) { - for (int i = 0; i < array.length; i++) { - if (array[i] == null) { - throw new NullPointerException("Argument #" + i + " is null."); - } + /** + * Returns an unmodifiable set view of the keys in this map. As this method + * creates a defensive copy, the performance is O(n). + */ + public Set keySet() { + return Collections.unmodifiableSet(dereferenceKeySet(delegate.keySet())); } - } - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeInt(size()); - for (Map.Entry entry : delegate.entrySet()) { - Object key = dereferenceKey(entry.getKey()); - Object value = dereferenceValue(entry.getValue()); - - // don't persist gc'ed entries. - if (key != null && value != null) { - out.writeObject(key); - out.writeObject(value); - } + /** + * Returns an unmodifiable set view of the values in this map. As this + * method creates a defensive copy, the performance is O(n). + */ + public Collection values() { + return Collections.unmodifiableCollection(dereferenceValues(delegate.values())); } - out.writeObject(null); - } - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - int size = in.readInt(); - this.delegate = new ConcurrentHashMap(size); - while (true) { - K key = (K) in.readObject(); - if (key == null) { - break; - } - V value = (V) in.readObject(); - put(key, value); + public V putIfAbsent(K key, V value) { + // TODO (crazybob) if the value has been gc'ed but the entry hasn't been + // cleaned up yet, this put will fail. + return execute(putIfAbsentStrategy(), key, value); + } + + public boolean remove(Object key, Object value) { + ensureNotNull(key, value); + Object referenceAwareKey = makeKeyReferenceAware(key); + Object referenceAwareValue = makeValueReferenceAware(value); + return delegate.remove(referenceAwareKey, referenceAwareValue); + } + + public boolean replace(K key, V oldValue, V newValue) { + ensureNotNull(key, oldValue, newValue); + Object keyReference = referenceKey(key); + + Object referenceAwareOldValue = makeValueReferenceAware(oldValue); + return delegate.replace(keyReference, referenceAwareOldValue, referenceValue(keyReference, newValue)); + } + + public V replace(K key, V value) { + // TODO (crazybob) if the value has been gc'ed but the entry hasn't been + // cleaned up yet, this will succeed when it probably shouldn't. + return execute(replaceStrategy(), key, value); + } + + /** + * Returns an unmodifiable set view of the entries in this map. As this + * method creates a defensive copy, the performance is O(n). + */ + public Set> entrySet() { + Set> entrySet = new HashSet<>(); + for (Map.Entry entry : delegate.entrySet()) { + Map.Entry dereferenced = dereferenceEntry(entry); + if (dereferenced != null) { + entrySet.add(dereferenced); + } + } + return Collections.unmodifiableSet(entrySet); + } + + /** + * Dereferences an entry. Returns null if the key or value has been gc'ed. + */ + Entry dereferenceEntry(Map.Entry entry) { + K key = dereferenceKey(entry.getKey()); + V value = dereferenceValue(entry.getValue()); + return (key == null || value == null) ? null : new Entry(key, value); + } + + /** + * Creates a reference for a key. + */ + Object referenceKey(K key) { + switch (keyReferenceType) { + case STRONG: + return key; + case SOFT: + return new SoftKeyReference(key); + case WEAK: + return new WeakKeyReference(key); + default: + throw new AssertionError(); + } + } + + /** + * Converts a reference to a key. + */ + K dereferenceKey(Object o) { + return (K) dereference(keyReferenceType, o); + } + + /** + * Converts a reference to a value. + */ + V dereferenceValue(Object o) { + return (V) dereference(valueReferenceType, o); + } + + /** + * Returns the refererent for reference given its reference type. + */ + Object dereference(ReferenceType referenceType, Object reference) { + return referenceType == STRONG ? reference : ((Reference) reference).get(); + } + + /** + * Creates a reference for a value. + */ + Object referenceValue(Object keyReference, Object value) { + switch (valueReferenceType) { + case STRONG: + return value; + case SOFT: + return new SoftValueReference(keyReference, value); + case WEAK: + return new WeakValueReference(keyReference, value); + default: + throw new AssertionError(); + } + } + + /** + * Dereferences a set of key references. + */ + Set dereferenceKeySet(Set keyReferences) { + return keyReferenceType == STRONG + ? keyReferences + : dereferenceCollection(keyReferenceType, keyReferences, new HashSet()); + } + + /** + * Dereferences a collection of value references. + */ + Collection dereferenceValues(Collection valueReferences) { + return valueReferenceType == STRONG + ? valueReferences + : dereferenceCollection(valueReferenceType, valueReferences, + new ArrayList(valueReferences.size())); + } + + /** + * Wraps key so it can be compared to a referenced key for equality. + */ + Object makeKeyReferenceAware(Object o) { + return keyReferenceType == STRONG ? o : new KeyReferenceAwareWrapper(o); + } + + /** + * Wraps value so it can be compared to a referenced value for equality. + */ + Object makeValueReferenceAware(Object o) { + return valueReferenceType == STRONG ? o : new ReferenceAwareWrapper(o); + } + + /** + * Dereferences elements in {@code in} using + * {@code referenceType} and puts them in {@code out}. Returns + * {@code out}. + */ + > T dereferenceCollection(ReferenceType referenceType, T in, T out) { + for (Object reference : in) { + out.add(dereference(referenceType, reference)); + } + return out; + } + + /** + * Marker interface to differentiate external and internal references. + */ + interface InternalReference { + } + + static int keyHashCode(Object key) { + return System.identityHashCode(key); + } + + /** + * Tests weak and soft references for identity equality. Compares references + * to other references and wrappers. If o is a reference, this returns true + * if r == o or if r and o reference the same non null object. If o is a + * wrapper, this returns true if r's referent is identical to the wrapped + * object. + */ + static boolean referenceEquals(Reference r, Object o) { + // compare reference to reference. + if (o instanceof InternalReference) { + // are they the same reference? used in cleanup. + if (o == r) { + return true; + } + + // do they reference identical values? used in conditional puts. + Object referent = ((Reference) o).get(); + return referent != null && referent == r.get(); + } + + // is the wrapped object identical to the referent? used in lookups. + return ((ReferenceAwareWrapper) o).unwrap() == r.get(); + } + + /** + * Big hack. Used to compare keys and values to referenced keys and values + * without creating more references. + */ + static class ReferenceAwareWrapper { + + Object wrapped; + + ReferenceAwareWrapper(Object wrapped) { + this.wrapped = wrapped; + } + + Object unwrap() { + return wrapped; + } + + @Override + public int hashCode() { + return wrapped.hashCode(); + } + + @Override + public boolean equals(Object obj) { + // defer to reference's equals() logic. + return obj.equals(this); + } + } + + /** + * Used for keys. Overrides hash code to use identity hash code. + */ + static class KeyReferenceAwareWrapper extends ReferenceAwareWrapper { + + public KeyReferenceAwareWrapper(Object wrapped) { + super(wrapped); + } + + @Override + public int hashCode() { + return System.identityHashCode(wrapped); + } + } + + class SoftKeyReference extends FinalizableSoftReference implements InternalReference { + + int hashCode; + + public SoftKeyReference(Object key) { + super(key); + this.hashCode = keyHashCode(key); + } + + public void finalizeReferent() { + delegate.remove(this); + } + + @Override + public int hashCode() { + return this.hashCode; + } + + @Override + public boolean equals(Object o) { + return referenceEquals(this, o); + } + } + + class WeakKeyReference extends FinalizableWeakReference implements InternalReference { + + int hashCode; + + public WeakKeyReference(Object key) { + super(key); + this.hashCode = keyHashCode(key); + } + + public void finalizeReferent() { + delegate.remove(this); + } + + @Override + public int hashCode() { + return this.hashCode; + } + + @Override + public boolean equals(Object o) { + return referenceEquals(this, o); + } + } + + class SoftValueReference extends FinalizableSoftReference implements InternalReference { + + Object keyReference; + + public SoftValueReference(Object keyReference, Object value) { + super(value); + this.keyReference = keyReference; + } + + public void finalizeReferent() { + delegate.remove(keyReference, this); + } + + @Override + public boolean equals(Object obj) { + return referenceEquals(this, obj); + } + } + + class WeakValueReference extends FinalizableWeakReference implements InternalReference { + + Object keyReference; + + public WeakValueReference(Object keyReference, Object value) { + super(value); + this.keyReference = keyReference; + } + + public void finalizeReferent() { + delegate.remove(keyReference, this); + } + + @Override + public boolean equals(Object obj) { + return referenceEquals(this, obj); + } + } + + protected interface Strategy { + public Object execute(ReferenceMap map, Object keyReference, Object valueReference); + } + + protected Strategy putStrategy() { + return PutStrategy.PUT; + } + + protected Strategy putIfAbsentStrategy() { + return PutStrategy.PUT_IF_ABSENT; + } + + protected Strategy replaceStrategy() { + return PutStrategy.REPLACE; + } + + private enum PutStrategy implements Strategy { + PUT { + public Object execute(ReferenceMap map, Object keyReference, Object valueReference) { + return map.delegate.put(keyReference, valueReference); + } + }, + + REPLACE { + public Object execute(ReferenceMap map, Object keyReference, Object valueReference) { + return map.delegate.replace(keyReference, valueReference); + } + }, + + PUT_IF_ABSENT { + public Object execute(ReferenceMap map, Object keyReference, Object valueReference) { + return map.delegate.putIfAbsent(keyReference, valueReference); + } + }; + } + + private static PutStrategy defaultPutStrategy; + + protected PutStrategy getPutStrategy() { + return defaultPutStrategy; + } + + + class Entry implements Map.Entry { + + K key; + V value; + + public Entry(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return this.key; + } + + public V getValue() { + return this.value; + } + + public V setValue(V value) { + return put(key, value); + } + + @Override + public int hashCode() { + return key.hashCode() * 31 + value.hashCode(); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof ReferenceMap.Entry)) { + return false; + } + + Entry entry = (Entry) o; + return key.equals(entry.key) && value.equals(entry.value); + } + + @Override + public String toString() { + return key + "=" + value; + } + } + + static void ensureNotNull(Object o) { + if (o == null) { + throw new NullPointerException(); + } + } + + static void ensureNotNull(Object... array) { + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + throw new NullPointerException("Argument #" + i + " is null."); + } + } + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.writeInt(size()); + for (Map.Entry entry : delegate.entrySet()) { + Object key = dereferenceKey(entry.getKey()); + Object value = dereferenceValue(entry.getValue()); + + // don't persist gc'ed entries. + if (key != null && value != null) { + out.writeObject(key); + out.writeObject(value); + } + } + out.writeObject(null); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + in.defaultReadObject(); + int size = in.readInt(); + this.delegate = new ConcurrentHashMap(size); + while (true) { + K key = (K) in.readObject(); + if (key == null) { + break; + } + V value = (V) in.readObject(); + put(key, value); + } } - } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/AliasInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/AliasInterceptor.java index f05a75c57..7bd94995d 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/AliasInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/AliasInterceptor.java @@ -20,15 +20,15 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ValidationAware; import com.opensymphony.xwork2.XWorkConstants; -import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.config.entities.ActionConfig; -import com.opensymphony.xwork2.util.ValueStack; +import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.ClearableValueStack; -import com.opensymphony.xwork2.util.ValueStackFactory; import com.opensymphony.xwork2.util.LocalizedTextUtil; +import com.opensymphony.xwork2.util.ValueStack; +import com.opensymphony.xwork2.util.ValueStackFactory; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.Map; @@ -184,9 +184,7 @@ public class AliasInterceptor extends AbstractInterceptor { if (clearableStack && (stack.getContext() != null) && (newStack.getContext() != null)) stack.getContext().put(ActionContext.CONVERSION_ERRORS, newStack.getContext().get(ActionContext.CONVERSION_ERRORS)); } else { - if (LOG.isDebugEnabled()) { - LOG.debug("invalid alias expression:" + aliasesKey); - } + LOG.debug("invalid alias expression: {}", aliasesKey); } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptor.java index 802279004..47d020ac2 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptor.java @@ -115,7 +115,7 @@ public class ConversionErrorInterceptor extends AbstractInterceptor { } if (fakie == null) { - fakie = new HashMap(); + fakie = new HashMap<>(); } fakie.put(propertyName, getOverrideExpr(invocation, value)); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptor.java index a2ac59c38..13cea0e24 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptor.java @@ -19,8 +19,9 @@ import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ValidationAware; import com.opensymphony.xwork2.interceptor.annotations.InputConfig; -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 java.lang.reflect.Method; @@ -185,7 +186,7 @@ public class DefaultWorkflowInterceptor extends MethodFilterInterceptor { String resultName = currentResultName; InputConfig annotation = action.getClass().getMethod(method, EMPTY_CLASS_ARRAY).getAnnotation(InputConfig.class); if (annotation != null) { - if (!annotation.methodName().equals("")) { + if (StringUtils.isNotEmpty(annotation.methodName())) { Method m = action.getClass().getMethod(annotation.methodName()); resultName = (String) m.invoke(action); } else { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/I18nInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/I18nInterceptor.java index 99aadefd6..afdd5346e 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/I18nInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/I18nInterceptor.java @@ -18,8 +18,8 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionInvocation; 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.util.Locale; import java.util.Map; @@ -103,9 +103,7 @@ public class I18nInterceptor extends AbstractInterceptor { protected enum Storage { SESSION, NONE } public I18nInterceptor() { - if (LOG.isDebugEnabled()) { - LOG.debug("new I18nInterceptor()"); - } + LOG.debug("new I18nInterceptor()"); } public void setParameterName(String parameterName) { @@ -123,8 +121,7 @@ public class I18nInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { if (LOG.isDebugEnabled()) { - LOG.debug("Intercept '{}/{}' {", - invocation.getProxy().getNamespace(), invocation.getProxy().getActionName()); + LOG.debug("Intercept '{}/{}' {", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName()); } LocaleFinder localeFinder = new LocaleFinder(invocation); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/LoggingInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/LoggingInterceptor.java index 2ec655e08..c82532faf 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/LoggingInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/LoggingInterceptor.java @@ -16,8 +16,8 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionInvocation; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** @@ -79,9 +79,7 @@ public class LoggingInterceptor extends AbstractInterceptor { } message.append(invocation.getProxy().getActionName()); - if (LOG.isInfoEnabled()) { LOG.info(message.toString()); - } } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptor.java index 0cdedb0bf..a46cf3410 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptor.java @@ -18,8 +18,8 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionInvocation; 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 java.util.Collections; import java.util.Set; @@ -104,10 +104,8 @@ public abstract class MethodFilterInterceptor extends AbstractInterceptor { String method = invocation.getProxy().getMethod(); // ValidationInterceptor boolean applyMethod = MethodFilterInterceptorUtil.applyMethod(excludeMethods, includeMethods, method); - if (log.isDebugEnabled()) { - if (!applyMethod) { - log.debug("Skipping Interceptor... Method [" + method + "] found in exclude list."); - } + if (!applyMethod) { + log.debug("Skipping Interceptor... Method [{}] found in exclude list.", method); } return applyMethod; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtil.java index ce0dbef75..987d782f3 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtil.java @@ -86,7 +86,7 @@ public class MethodFilterInterceptorUtil { for (String pattern : includeMethods) { if (pattern.contains("*")) { int[] compiledPattern = wildcard.compilePattern(pattern); - HashMap matchedPatterns = new HashMap(); + HashMap matchedPatterns = new HashMap<>(); boolean matches = wildcard.match(matchedPatterns, methodCopy, compiledPattern); if (matches) { return true; // run it, includeMethods takes precedence @@ -106,7 +106,7 @@ public class MethodFilterInterceptorUtil { for ( String pattern : excludeMethods) { if (pattern.contains("*")) { int[] compiledPattern = wildcard.compilePattern(pattern); - HashMap matchedPatterns = new HashMap(); + HashMap matchedPatterns = new HashMap<>(); boolean matches = wildcard.match(matchedPatterns, methodCopy, compiledPattern); if (matches) { // if found, and wasn't included earlier, don't run it diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptor.java index 1e4b036ab..46767d594 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptor.java @@ -17,8 +17,9 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.util.TextParseUtil; -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 java.util.Collection; import java.util.HashSet; @@ -106,7 +107,7 @@ public class ParameterFilterInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation) throws Exception { Map parameters = invocation.getInvocationContext().getParameters(); - HashSet paramsToRemove = new HashSet(); + HashSet paramsToRemove = new HashSet<>(); Map includesExcludesMap = getIncludesExcludesMap(); @@ -116,7 +117,7 @@ public class ParameterFilterInterceptor extends AbstractInterceptor { for (String currRule : includesExcludesMap.keySet()) { if (param.startsWith(currRule) && (param.length() == currRule.length() - || isPropSeperator(param.charAt(currRule.length())))) { + || isPropertySeparator(param.charAt(currRule.length())))) { currentAllowed = includesExcludesMap.get(currRule).booleanValue(); } } @@ -125,9 +126,7 @@ public class ParameterFilterInterceptor extends AbstractInterceptor { } } - if (LOG.isDebugEnabled()) { - LOG.debug("Params to remove: " + paramsToRemove); - } + LOG.debug("Params to remove: {}", paramsToRemove); for (Object aParamsToRemove : paramsToRemove) { parameters.remove(aParamsToRemove); @@ -137,18 +136,18 @@ public class ParameterFilterInterceptor extends AbstractInterceptor { } /** - * Tests if the given char is a property seperator char .([. + * Tests if the given char is a property separator char .([. * * @param c the char * @return true, if char is property separator, false otherwise. */ - private static boolean isPropSeperator(char c) { + private static boolean isPropertySeparator(char c) { return c == '.' || c == '(' || c == '['; } private Map getIncludesExcludesMap() { if (this.includesExcludesMap == null) { - this.includesExcludesMap = new TreeMap(); + this.includesExcludesMap = new TreeMap<>(); if (getAllowedCollection() != null) { for (String e : getAllowedCollection()) { @@ -228,7 +227,7 @@ public class ParameterFilterInterceptor extends AbstractInterceptor { * @return A collection from the comma delimited String. Returns null if the string is empty. */ private Collection asCollection(String commaDelim) { - if (commaDelim == null || commaDelim.trim().length() == 0) { + if (StringUtils.isBlank(commaDelim)) { return null; } return TextParseUtil.commaDelimitedStringToSet(commaDelim); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptor.java index 523831c98..68bb1547a 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptor.java @@ -18,8 +18,8 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; 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 java.util.Collections; import java.util.Map; @@ -84,7 +84,6 @@ public class ParameterRemoverInterceptor extends AbstractInterceptor { private static final long serialVersionUID = 1; private Set paramNames = Collections.emptySet(); - private Set paramValues = Collections.emptySet(); @@ -107,18 +106,15 @@ public class ParameterRemoverInterceptor extends AbstractInterceptor { if (parameters.containsKey(removeName)) { try { - String[] values = (String[]) parameters - .get(removeName); - String value = values[0]; - if (null != value && this.paramValues.contains(value)) { + String[] values = (String[]) parameters.get(removeName); + String value = values[0]; + if (null != value && this.paramValues.contains(value)) { parameters.remove(removeName); } } catch (Exception e) { - if (LOG.isErrorEnabled()) { - LOG.error("Failed to convert parameter to string", e); - } - } - } + LOG.error("Failed to convert parameter to string", e); + } + } } } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParametersInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParametersInterceptor.java index 78d873d4b..84966103b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParametersInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ParametersInterceptor.java @@ -17,21 +17,18 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; -import com.opensymphony.xwork2.security.AcceptedPatternsChecker; -import com.opensymphony.xwork2.security.ExcludedPatternsChecker; import com.opensymphony.xwork2.ValidationAware; import com.opensymphony.xwork2.XWorkConstants; import com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.inject.Inject; -import com.opensymphony.xwork2.util.ClearableValueStack; -import com.opensymphony.xwork2.util.LocalizedTextUtil; -import com.opensymphony.xwork2.util.MemberAccessValueStack; -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 com.opensymphony.xwork2.security.AcceptedPatternsChecker; +import com.opensymphony.xwork2.security.ExcludedPatternsChecker; +import com.opensymphony.xwork2.util.*; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.Collection; import java.util.Comparator; @@ -155,7 +152,7 @@ public class ParametersInterceptor extends MethodFilterInterceptor { @Inject(XWorkConstants.DEV_MODE) public void setDevMode(String mode) { - devMode = "true".equalsIgnoreCase(mode); + this.devMode = BooleanUtils.toBoolean(mode); } @Inject @@ -207,7 +204,7 @@ public class ParametersInterceptor extends MethodFilterInterceptor { final Map parameters = retrieveParameters(ac); if (LOG.isDebugEnabled()) { - LOG.debug("Setting params " + getParameterLogMap(parameters)); + LOG.debug("Setting params {}", getParameterLogMap(parameters)); } if (parameters != null) { @@ -256,12 +253,12 @@ public class ParametersInterceptor extends MethodFilterInterceptor { Map params; Map acceptableParameters; if (ordered) { - params = new TreeMap(getOrderedComparator()); - acceptableParameters = new TreeMap(getOrderedComparator()); + params = new TreeMap<>(getOrderedComparator()); + acceptableParameters = new TreeMap<>(getOrderedComparator()); params.putAll(parameters); } else { - params = new TreeMap(parameters); - acceptableParameters = new TreeMap(); + params = new TreeMap<>(parameters); + acceptableParameters = new TreeMap<>(); } for (Map.Entry entry : params.entrySet()) { @@ -447,9 +444,7 @@ public class ParametersInterceptor extends MethodFilterInterceptor { if (devMode) { LOG.warn(message, parameters); } else { - if (LOG.isDebugEnabled()) { - LOG.debug(message, parameters); - } + LOG.debug(message, parameters); } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptor.java index 8cf10acb3..9d32fbe97 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptor.java @@ -95,7 +95,7 @@ public class ScopedModelDrivenInterceptor extends AbstractInterceptor { } protected Object resolveModel(ObjectFactory factory, ActionContext actionContext, String modelClassName, String modelScope, String modelName) throws Exception { - Object model = null; + Object model; Map scopeMap = actionContext.getContextMap(); if ("session".equals(modelScope)) { scopeMap = actionContext.getSession(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/StaticParametersInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/StaticParametersInterceptor.java index 67e121cb3..25fd8d64c 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/StaticParametersInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/StaticParametersInterceptor.java @@ -19,13 +19,14 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ValidationAware; import com.opensymphony.xwork2.XWorkConstants; -import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.config.entities.Parameterizable; +import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.*; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; -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 java.util.Collections; import java.util.Map; @@ -84,8 +85,7 @@ public class StaticParametersInterceptor extends AbstractInterceptor { private boolean parse; private boolean overwrite; private boolean merge = true; - - static boolean devMode = false; + private boolean devMode = false; private static final Logger LOG = LogManager.getLogger(StaticParametersInterceptor.class); @@ -97,16 +97,16 @@ public class StaticParametersInterceptor extends AbstractInterceptor { } @Inject(XWorkConstants.DEV_MODE) - public static void setDevMode(String mode) { - devMode = "true".equals(mode); + public void setDevMode(String mode) { + devMode = BooleanUtils.toBoolean(mode); } public void setParse(String value) { - this.parse = Boolean.valueOf(value).booleanValue(); + this.parse = BooleanUtils.toBoolean(value); } public void setMerge(String value) { - this.merge = Boolean.valueOf(value).booleanValue(); + this.merge = BooleanUtils.toBoolean(value); } /** @@ -116,7 +116,7 @@ public class StaticParametersInterceptor extends AbstractInterceptor { * @param value */ public void setOverwrite(String value) { - this.overwrite = Boolean.valueOf(value).booleanValue(); + this.overwrite = BooleanUtils.toBoolean(value); } @Override @@ -126,9 +126,7 @@ public class StaticParametersInterceptor extends AbstractInterceptor { final Map parameters = config.getParams(); - if (LOG.isDebugEnabled()) { - LOG.debug("Setting static parameters " + parameters); - } + LOG.debug("Setting static parameters: {}", parameters); // for actions marked as Parameterizable, pass the static parameters directly if (action instanceof Parameterizable) { @@ -220,18 +218,18 @@ public class StaticParametersInterceptor extends AbstractInterceptor { Map combinedParams; if ( overwrite ) { if (previousParams != null) { - combinedParams = new TreeMap(previousParams); + combinedParams = new TreeMap<>(previousParams); } else { - combinedParams = new TreeMap(); + combinedParams = new TreeMap<>(); } if ( newParams != null) { combinedParams.putAll(newParams); } } else { if (newParams != null) { - combinedParams = new TreeMap(newParams); + combinedParams = new TreeMap<>(newParams); } else { - combinedParams = new TreeMap(); + combinedParams = new TreeMap<>(); } if ( previousParams != null) { combinedParams.putAll(previousParams); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/TimerInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/TimerInterceptor.java index a52c092bf..7cc491864 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/TimerInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/TimerInterceptor.java @@ -16,8 +16,9 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.ActionInvocation; -import org.apache.logging.log4j.Logger; +import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * @@ -138,7 +139,7 @@ public class TimerInterceptor extends AbstractInterceptor { StringBuilder message = new StringBuilder(100); message.append("Executed action ["); String namespace = invocation.getProxy().getNamespace(); - if ((namespace != null) && (namespace.trim().length() > 0)) { + if (StringUtils.isNotBlank(namespace)) { message.append(namespace).append("/"); } message.append(invocation.getProxy().getActionName()); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterIntereptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterIntereptor.java index 1660b0784..f978e46ba 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterIntereptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterIntereptor.java @@ -43,8 +43,8 @@ public class AnnotationParameterFilterIntereptor extends AbstractInterceptor { } boolean blockByDefault = action.getClass().isAnnotationPresent(BlockByDefault.class); - List annotatedFields = new ArrayList(); - HashSet paramsToRemove = new HashSet(); + List annotatedFields = new ArrayList<>(); + HashSet paramsToRemove = new HashSet<>(); if (blockByDefault) { AnnotationUtils.addAllFields(Allowed.class, action.getClass(), annotatedFields); @@ -75,7 +75,6 @@ public class AnnotationParameterFilterIntereptor extends AbstractInterceptor { } for (String paramName : parameters.keySet()) { - for (Field field : annotatedFields) { //TODO only matches exact field names. need to change to it matches start of ognl expression //i.e take param name up to first . (period) and match against that diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptor.java index 648a65ae4..665ed1c35 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptor.java @@ -113,7 +113,7 @@ public class AnnotationWorkflowInterceptor extends AbstractInterceptor implement public String intercept(ActionInvocation invocation) throws Exception { final Object action = invocation.getAction(); invocation.addPreResultListener(this); - List methods = new ArrayList(AnnotationUtils.getAnnotatedMethods(action.getClass(), Before.class)); + List methods = new ArrayList<>(AnnotationUtils.getAnnotatedMethods(action.getClass(), Before.class)); if (methods.size() > 0) { // methods are only sorted by priority Collections.sort(methods, new Comparator() { @@ -123,8 +123,7 @@ public class AnnotationWorkflowInterceptor extends AbstractInterceptor implement } }); for (Method m : methods) { - final String resultCode = (String) m - .invoke(action, (Object[]) null); + final String resultCode = (String) m.invoke(action, (Object[]) null); if (resultCode != null) { // shortcircuit execution return resultCode; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionInvocation.java b/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionInvocation.java index b67b4fff8..074968905 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionInvocation.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionInvocation.java @@ -40,8 +40,8 @@ public class MockActionInvocation implements ActionInvocation { private Result result; private String resultCode; private ValueStack stack; - - private List preResultListeners = new ArrayList(); + + private List preResultListeners = new ArrayList<>(); public Object getAction() { return action; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionProxy.java b/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionProxy.java index 9e8567cf9..f3735910a 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionProxy.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockActionProxy.java @@ -20,6 +20,7 @@ import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.config.Configuration; import com.opensymphony.xwork2.config.entities.ActionConfig; +import org.apache.commons.lang3.StringUtils; /** * Mock for an {@link ActionProxy}. @@ -110,7 +111,7 @@ public class MockActionProxy implements ActionProxy { public void setMethod(String method) { this.method = method; - methodSpecified=method!=null && !"".equals(method); + methodSpecified = StringUtils.isNotEmpty(method); } public boolean isMethodSpecified() diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockResult.java b/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockResult.java index 16b2a2172..571469cb7 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockResult.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/mock/MockResult.java @@ -34,11 +34,7 @@ public class MockResult implements Result { return true; } - if (!(o instanceof MockResult)) { - return false; - } - - return true; + return o instanceof MockResult; } public void execute(ActionInvocation invocation) throws Exception { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlTypeConverterWrapper.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlTypeConverterWrapper.java index 55a71be31..ad79542cc 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlTypeConverterWrapper.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlTypeConverterWrapper.java @@ -26,12 +26,12 @@ import java.util.Map; public class OgnlTypeConverterWrapper implements ognl.TypeConverter { private TypeConverter typeConverter; - - public OgnlTypeConverterWrapper(TypeConverter conv) { - if (conv == null) { + + public OgnlTypeConverterWrapper(TypeConverter converter) { + if (converter == null) { throw new IllegalArgumentException("Wrapped type converter cannot be null"); } - this.typeConverter = conv; + this.typeConverter = converter; } public Object convertValue(Map context, Object target, Member member, diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlUtil.java index a67ede97b..45e9992d8 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlUtil.java @@ -23,27 +23,18 @@ import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor; import com.opensymphony.xwork2.util.CompoundRoot; import com.opensymphony.xwork2.util.TextParseUtil; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import com.opensymphony.xwork2.util.reflection.ReflectionException; -import ognl.ClassResolver; -import ognl.Ognl; -import ognl.OgnlContext; -import ognl.OgnlException; -import ognl.OgnlRuntime; -import ognl.SimpleNode; -import ognl.TypeConverter; +import ognl.*; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; @@ -58,16 +49,16 @@ import java.util.regex.Pattern; public class OgnlUtil { private static final Logger LOG = LogManager.getLogger(OgnlUtil.class); - private ConcurrentMap expressions = new ConcurrentHashMap(); - private final ConcurrentMap beanInfoCache = new ConcurrentHashMap(); + private ConcurrentMap expressions = new ConcurrentHashMap<>(); + private final ConcurrentMap beanInfoCache = new ConcurrentHashMap<>(); private TypeConverter defaultConverter; private boolean devMode = false; private boolean enableExpressionCache = true; private boolean enableEvalExpression; - private Set> excludedClasses = new HashSet>(); - private Set excludedPackageNamePatterns = new HashSet(); + private Set> excludedClasses = new HashSet<>(); + private Set excludedPackageNamePatterns = new HashSet<>(); private Container container; private boolean allowStaticMethodAccess; @@ -79,12 +70,12 @@ public class OgnlUtil { @Inject(XWorkConstants.DEV_MODE) public void setDevMode(String mode) { - devMode = "true".equals(mode); + this.devMode = BooleanUtils.toBoolean(mode); } @Inject(XWorkConstants.ENABLE_OGNL_EXPRESSION_CACHE) public void setEnableExpressionCache(String cache) { - enableExpressionCache = "true".equals(cache); + enableExpressionCache = BooleanUtils.toBoolean(cache); } @Inject(value = XWorkConstants.ENABLE_OGNL_EVAL_EXPRESSION, required = false) @@ -249,12 +240,9 @@ public class OgnlUtil { try { for (Object target : cr) { - if ( - OgnlRuntime.hasSetProperty((OgnlContext) context, target, property) - || - OgnlRuntime.hasGetProperty((OgnlContext) context, target, property) - || - OgnlRuntime.getIndexedPropertyType((OgnlContext) context, target.getClass(), property) != OgnlRuntime.INDEXED_PROPERTY_NONE + if (OgnlRuntime.hasSetProperty((OgnlContext) context, target, property) + || OgnlRuntime.hasGetProperty((OgnlContext) context, target, property) + || OgnlRuntime.getIndexedPropertyType((OgnlContext) context, target.getClass(), property) != OgnlRuntime.INDEXED_PROPERTY_NONE ) { return target; } @@ -269,7 +257,6 @@ public class OgnlUtil { return root; } - /** * Wrapper around Ognl.setValue() to handle type conversion for collection elements. * Ideally, this should be handled by OGNL directly. @@ -373,18 +360,15 @@ public class OgnlUtil { */ public void copy(final Object from, final Object to, final Map context, Collection exclusions, Collection inclusions) { if (from == null || to == null) { - if (LOG.isWarnEnabled()) { - LOG.warn("Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event."); - } - + LOG.warn("Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event."); return; } - TypeConverter conv = getTypeConverterFromContext(context); + TypeConverter converter = getTypeConverterFromContext(context); final Map contextFrom = createDefaultContext(from, null); - Ognl.setTypeConverter(contextFrom, conv); + Ognl.setTypeConverter(contextFrom, converter); final Map contextTo = createDefaultContext(to, null); - Ognl.setTypeConverter(contextTo, conv); + Ognl.setTypeConverter(contextTo, converter); PropertyDescriptor[] fromPds; PropertyDescriptor[] toPds; @@ -393,13 +377,11 @@ public class OgnlUtil { fromPds = getPropertyDescriptors(from); toPds = getPropertyDescriptors(to); } catch (IntrospectionException e) { - if (LOG.isErrorEnabled()) { - LOG.error("An error occured", e); - } + LOG.error("An error occurred", e); return; } - Map toPdHash = new HashMap(); + Map toPdHash = new HashMap<>(); for (PropertyDescriptor toPd : toPds) { toPdHash.put(toPd.getName(), toPd); @@ -427,9 +409,7 @@ public class OgnlUtil { }); } catch (OgnlException e) { - if (LOG.isDebugEnabled()) { - LOG.debug("Got OGNL exception", e); - } + LOG.debug("Got OGNL exception", e); } } @@ -491,7 +471,7 @@ public class OgnlUtil { * @throws OgnlException is thrown by OGNL if the property value could not be retrieved */ public Map getBeanMap(final Object source) throws IntrospectionException, OgnlException { - Map beanMap = new HashMap(); + Map beanMap = new HashMap<>(); final Map sourceMap = createDefaultContext(source, null); PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(source); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStack.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStack.java index f4cc3fede..af7fbc565 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStack.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStack.java @@ -27,11 +27,11 @@ import com.opensymphony.xwork2.util.ClearableValueStack; import com.opensymphony.xwork2.util.CompoundRoot; import com.opensymphony.xwork2.util.MemberAccessValueStack; import com.opensymphony.xwork2.util.ValueStack; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import com.opensymphony.xwork2.util.logging.LoggerUtils; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; import ognl.*; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.Serializable; import java.util.HashMap; @@ -97,12 +97,12 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS @Inject(XWorkConstants.DEV_MODE) public void setDevMode(String mode) { - devMode = "true".equalsIgnoreCase(mode); + this.devMode = BooleanUtils.toBoolean(mode); } @Inject(value = "logMissingProperties", required = false) public void setLogMissingProperties(String logMissingProperties) { - this.logMissingProperties = "true".equalsIgnoreCase(logMissingProperties); + this.logMissingProperties = BooleanUtils.toBoolean(logMissingProperties); } /** @@ -207,11 +207,9 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS boolean shouldLog = shouldLogMissingPropertyWarning(e); String msg = null; if (throwExceptionOnFailure || shouldLog) { - msg = ErrorMessageBuilder.create() - .errorSettingExpressionWithValue(expr, value) - .build(); - } - if (shouldLog) { + msg = ErrorMessageBuilder.create().errorSettingExpressionWithValue(expr, value).build(); + } + if (shouldLog) { LOG.warn(msg, e); } @@ -451,7 +449,7 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS XWorkConverter xworkConverter = cont.getInstance(XWorkConverter.class); CompoundRootAccessor accessor = (CompoundRootAccessor) cont.getInstance(PropertyAccessor.class, CompoundRoot.class.getName()); TextProvider prov = cont.getInstance(TextProvider.class, "system"); - boolean allow = "true".equals(cont.getInstance(String.class, XWorkConstants.ALLOW_STATIC_METHOD_ACCESS)); + boolean allow = BooleanUtils.toBoolean(cont.getInstance(String.class, XWorkConstants.ALLOW_STATIC_METHOD_ACCESS)); OgnlValueStack aStack = new OgnlValueStack(xworkConverter, accessor, prov, allow); aStack.setOgnlUtil(cont.getInstance(OgnlUtil.class)); aStack.setRoot(xworkConverter, accessor, this.root, allow); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStackFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStackFactory.java index 2edfa9f75..761749470 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStackFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/OgnlValueStackFactory.java @@ -28,6 +28,7 @@ import com.opensymphony.xwork2.util.ValueStackFactory; import ognl.MethodAccessor; import ognl.OgnlRuntime; import ognl.PropertyAccessor; +import org.apache.commons.lang3.BooleanUtils; import java.util.Map; import java.util.Set; @@ -44,8 +45,8 @@ public class OgnlValueStackFactory implements ValueStackFactory { private boolean allowStaticMethodAccess; @Inject - public void setXWorkConverter(XWorkConverter conv) { - this.xworkConverter = conv; + public void setXWorkConverter(XWorkConverter converter) { + this.xworkConverter = converter; } @Inject("system") @@ -55,7 +56,7 @@ public class OgnlValueStackFactory implements ValueStackFactory { @Inject(value="allowStaticMethodAccess", required=false) public void setAllowStaticMethodAccess(String allowStaticMethodAccess) { - this.allowStaticMethodAccess = "true".equalsIgnoreCase(allowStaticMethodAccess); + this.allowStaticMethodAccess = BooleanUtils.toBoolean(allowStaticMethodAccess); } public ValueStack createValueStack() { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/SecurityMemberAccess.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/SecurityMemberAccess.java index 075237bc2..2afd3d65c 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/SecurityMemberAccess.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/SecurityMemberAccess.java @@ -15,9 +15,9 @@ */ package com.opensymphony.xwork2.ognl; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import ognl.DefaultMemberAccess; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.lang.reflect.Member; import java.lang.reflect.Modifier; @@ -53,7 +53,7 @@ public class SecurityMemberAccess extends DefaultMemberAccess { @Override public boolean isAccessible(Map context, Object target, Member member, String propertyName) { if (checkEnumAccess(target, member)) { - LOG.trace("Allowing access to enum {}", target); + LOG.trace("Allowing access to enum: {}", target); return true; } @@ -89,12 +89,12 @@ public class SecurityMemberAccess extends DefaultMemberAccess { } //failed static test - if (!allow) + if (!allow) { return false; + } // Now check for standard scope rules - return super.isAccessible(context, target, member, propertyName) - && isAcceptableProperty(propertyName); + return super.isAccessible(context, target, member, propertyName) && isAcceptableProperty(propertyName); } protected boolean checkStaticMethodAccess(Member member) { @@ -109,8 +109,9 @@ public class SecurityMemberAccess extends DefaultMemberAccess { protected boolean checkEnumAccess(Object target, Member member) { if (target instanceof Class) { Class clazz = (Class) target; - if (Enum.class.isAssignableFrom(clazz) && member.getName().equals("values")) + if (Enum.class.isAssignableFrom(clazz) && member.getName().equals("values")) { return true; + } } return false; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/CompoundRootAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/CompoundRootAccessor.java index d02e84b39..3beb14a0d 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/CompoundRootAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/CompoundRootAccessor.java @@ -21,9 +21,10 @@ import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.ognl.OgnlValueStack; import com.opensymphony.xwork2.util.CompoundRoot; import com.opensymphony.xwork2.util.ValueStack; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import ognl.*; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; @@ -58,13 +59,12 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C private final static Logger LOG = LogManager.getLogger(CompoundRootAccessor.class); private final static Class[] EMPTY_CLASS_ARRAY = new Class[0]; - private static Map invalidMethods = new ConcurrentHashMap(); - - static boolean devMode = false; + private static Map invalidMethods = new ConcurrentHashMap<>(); + private boolean devMode = false; @Inject(XWorkConstants.DEV_MODE) - public static void setDevMode(String mode) { - devMode = "true".equals(mode); + public void setDevMode(String mode) { + this.devMode = BooleanUtils.toBoolean(mode); } public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException { @@ -121,7 +121,6 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C if (name instanceof Integer) { Integer index = (Integer) name; - return root.cutStack(index); } else if (name instanceof String) { if ("top".equals(name)) { @@ -187,7 +186,7 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C } } - SortedSet set = new TreeSet(); + SortedSet set = new TreeSet<>(); StringBuffer sb = new StringBuffer(); for (PropertyDescriptor pd : descriptors.values()) { @@ -209,12 +208,9 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C } return sb.toString(); - } catch (IntrospectionException e) { - LOG.debug("Got exception in callMethod", e); - } catch (OgnlException e) { + } catch (IntrospectionException | OgnlException e) { LOG.debug("Got exception in callMethod", e); } - return null; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkCollectionPropertyAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkCollectionPropertyAccessor.java index a65663407..a1e7536cd 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkCollectionPropertyAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkCollectionPropertyAccessor.java @@ -21,19 +21,17 @@ import com.opensymphony.xwork2.conversion.ObjectTypeDeterminer; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.ognl.OgnlUtil; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; - import ognl.ObjectPropertyAccessor; import ognl.OgnlException; import ognl.OgnlRuntime; import ognl.SetPropertyAccessor; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.List; import java.util.Map; /** @@ -42,7 +40,6 @@ import java.util.Map; public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { private static final Logger LOG = LogManager.getLogger(XWorkCollectionPropertyAccessor.class); - private static final String CONTEXT_COLLECTION_MAP = "xworkCollectionPropertyAccessorContextSetMap"; public static final String KEY_PROPERTY_FOR_CREATION = "makeNew"; @@ -87,18 +84,13 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { * @see ognl.PropertyAccessor#getProperty(java.util.Map, Object, Object) */ @Override - public Object getProperty(Map context, Object target, Object key) - throws OgnlException { - - if (LOG.isDebugEnabled()) { - LOG.debug("Entering getProperty()"); - } + public Object getProperty(Map context, Object target, Object key) throws OgnlException { + LOG.trace("Entering getProperty()"); //check if it is a generic type property. //if so, return the value from the //superclass which will determine this. - if (!ReflectionContextState.isGettingByKeyProperty(context) - && !key.equals(KEY_PROPERTY_FOR_CREATION)) { + if (!ReflectionContextState.isGettingByKeyProperty(context) && !key.equals(KEY_PROPERTY_FOR_CREATION)) { return super.getProperty(context, target, key); } else { //reset context property @@ -119,17 +111,15 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { ReflectionContextState.updateCurrentPropertyPath(context, key); return super.getProperty(context, target, key); } - - + //get the key property to index the //collection with from the ObjectTypeDeterminer - String keyProperty = objectTypeDeterminer - .getKeyProperty(lastBeanClass, lastPropertyClass); + String keyProperty = objectTypeDeterminer.getKeyProperty(lastBeanClass, lastPropertyClass); //get the collection class of the Class collClass = objectTypeDeterminer.getElementClass(lastBeanClass, lastPropertyClass, key); - Class keyType = null; + Class keyType; Class toGetTypeFrom = (collClass != null) ? collClass : c.iterator().next().getClass(); try { keyType = OgnlRuntime.getPropertyDescriptor(toGetTypeFrom, keyProperty).getPropertyType(); @@ -139,7 +129,7 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { if (ReflectionContextState.isCreatingNullObjects(context)) { - Map collMap = getSetMap(context, c, keyProperty, collClass); + Map collMap = getSetMap(context, c, keyProperty); if (key.toString().equals(KEY_PROPERTY_FOR_CREATION)) { //this should return the XWorkList //for this set that contains new entries @@ -171,7 +161,6 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { } catch (Exception exc) { throw new OgnlException("Error adding new element to collection", exc); - } } @@ -194,21 +183,15 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { * Gets an indexed Map by a given key property with the key being * the value of the property and the value being the */ - private Map getSetMap(Map context, Collection collection, String property, Class valueClass) - throws OgnlException { - if (LOG.isDebugEnabled()) { - LOG.debug("getting set Map"); - } - + private Map getSetMap(Map context, Collection collection, String property) throws OgnlException { + LOG.trace("getting set Map"); + String path = ReflectionContextState.getCurrentPropertyPath(context); - Map map = ReflectionContextState.getSetMap(context, - path); + Map map = ReflectionContextState.getSetMap(context, path); if (map == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("creating set Map"); - } - + LOG.trace("creating set Map"); + map = new HashMap(); map.put(null, new SurrugateList(collection)); for (Object currTest : collection) { @@ -238,9 +221,7 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor { } @Override - public void setProperty(Map context, Object target, Object name, Object value) - throws OgnlException { - + public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException { Class lastClass = (Class) context.get(XWorkConverter.LAST_BEAN_CLASS_ACCESSED); String lastProperty = (String) context.get(XWorkConverter.LAST_BEAN_PROPERTY_ACCESSED); Class convertToClass = objectTypeDeterminer.getElementClass(lastClass, lastProperty, name); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkEnumerationAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkEnumerationAccessor.java index 88e6408b3..84745e430 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkEnumerationAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkEnumerationAccessor.java @@ -29,7 +29,6 @@ public class XWorkEnumerationAccessor extends EnumerationPropertyAccessor { ObjectPropertyAccessor opa = new ObjectPropertyAccessor(); - @Override public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException { opa.setProperty(context, target, name, value); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkIteratorPropertyAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkIteratorPropertyAccessor.java index 7afe3f56f..2a6184bc1 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkIteratorPropertyAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkIteratorPropertyAccessor.java @@ -29,7 +29,6 @@ public class XWorkIteratorPropertyAccessor extends IteratorPropertyAccessor { ObjectPropertyAccessor opa = new ObjectPropertyAccessor(); - @Override public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException { opa.setProperty(context, target, name, value); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkListPropertyAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkListPropertyAccessor.java index 6dab13bf3..6201dae82 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkListPropertyAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkListPropertyAccessor.java @@ -72,17 +72,15 @@ public class XWorkListPropertyAccessor extends ListPropertyAccessor { } @Override - public Object getProperty(Map context, Object target, Object name) - throws OgnlException { + public Object getProperty(Map context, Object target, Object name) throws OgnlException { if (ReflectionContextState.isGettingByKeyProperty(context) || name.equals(XWorkCollectionPropertyAccessor.KEY_PROPERTY_FOR_CREATION)) { return _sAcc.getProperty(context, target, name); - } else if (name instanceof String) { + } else if (name instanceof String) { return super.getProperty(context, target, name); } ReflectionContextState.updateCurrentPropertyPath(context, name); - //System.out.println("Entering XWorkListPropertyAccessor. Name: " + name); Class lastClass = (Class) context.get(XWorkConverter.LAST_BEAN_CLASS_ACCESSED); String lastProperty = (String) context.get(XWorkConverter.LAST_BEAN_PROPERTY_ACCESSED); @@ -90,7 +88,6 @@ public class XWorkListPropertyAccessor extends ListPropertyAccessor { && ReflectionContextState.isCreatingNullObjects(context) && objectTypeDeterminer.shouldCreateIfNew(lastClass,lastProperty,target,null,true)) { - //System.out.println("Getting index from List"); List list = (List) target; int index = ((Number) name).intValue(); int listSize = list.size(); @@ -100,12 +97,10 @@ public class XWorkListPropertyAccessor extends ListPropertyAccessor { } Class beanClass = objectTypeDeterminer.getElementClass(lastClass, lastProperty, name); if (listSize <= index) { - Object result = null; + Object result; for (int i = listSize; i < index; i++) { - list.add(null); - } try { list.add(index, result = objectFactory.buildBean(beanClass, context)); @@ -114,7 +109,7 @@ public class XWorkListPropertyAccessor extends ListPropertyAccessor { } return result; } else if (list.get(index) == null) { - Object result = null; + Object result; try { list.set(index, result = objectFactory.buildBean(beanClass, context)); } catch (Exception exc) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMapPropertyAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMapPropertyAccessor.java index d75221641..e30f07e16 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMapPropertyAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMapPropertyAccessor.java @@ -20,11 +20,11 @@ import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.conversion.ObjectTypeDeterminer; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.inject.Inject; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; import ognl.MapPropertyAccessor; import ognl.OgnlException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.Map; @@ -38,8 +38,7 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { private static final Logger LOG = LogManager.getLogger(XWorkMapPropertyAccessor.class); - private static final String[] INDEX_ACCESS_PROPS = new String[] - {"size", "isEmpty", "keys", "values"}; + private static final String[] INDEX_ACCESS_PROPS = new String[]{"size", "isEmpty", "keys", "values"}; private XWorkConverter xworkConverter; private ObjectFactory objectFactory; @@ -62,10 +61,7 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { @Override public Object getProperty(Map context, Object target, Object name) throws OgnlException { - - if (LOG.isDebugEnabled()) { - LOG.debug("Entering getProperty ("+context+","+target+","+name+")"); - } + LOG.trace("Entering getProperty ({},{},{})", context, target, name); ReflectionContextState.updateCurrentPropertyPath(context, name); // if this is one of the regular index access @@ -79,7 +75,7 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { try{ result = super.getProperty(context, target, name); - } catch(ClassCastException ex){ + } catch (ClassCastException ex) { } if (result == null) { @@ -103,9 +99,7 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { result = objectFactory.buildBean(valueClass, context); map.put(key, result); } catch (Exception exc) { - } - } } return result; @@ -127,16 +121,14 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { @Override public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException { - if (LOG.isDebugEnabled()) { - LOG.debug("Entering setProperty("+context+","+target+","+name+","+value+")"); - } - + LOG.trace("Entering setProperty({},{},{},{})", context, target, name, value); + Object key = getKey(context, name); Map map = (Map) target; map.put(key, getValue(context, value)); } - private Object getValue(Map context, Object value) { + private Object getValue(Map context, Object value) { Class lastClass = (Class) context.get(XWorkConverter.LAST_BEAN_CLASS_ACCESSED); String lastProperty = (String) context.get(XWorkConverter.LAST_BEAN_PROPERTY_ACCESSED); if (lastClass == null || lastProperty == null) { @@ -147,7 +139,7 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { return value; // nothing is specified, we assume it will be the value passed in. } return xworkConverter.convertValue(context, value, elementClass); -} + } private Object getKey(Map context, Object name) { Class lastClass = (Class) context.get(XWorkConverter.LAST_BEAN_CLASS_ACCESSED); @@ -163,7 +155,6 @@ public class XWorkMapPropertyAccessor extends MapPropertyAccessor { } return xworkConverter.convertValue(context, name, keyClass); - } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMethodAccessor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMethodAccessor.java index 55b6280c7..7a05bc529 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMethodAccessor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/ognl/accessor/XWorkMethodAccessor.java @@ -15,21 +15,16 @@ */ package com.opensymphony.xwork2.ognl.accessor; +import com.opensymphony.xwork2.util.reflection.ReflectionContextState; +import ognl.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import java.beans.PropertyDescriptor; import java.util.Arrays; import java.util.Collection; import java.util.Map; -import ognl.MethodFailedException; -import ognl.ObjectMethodAccessor; -import ognl.OgnlContext; -import ognl.OgnlRuntime; -import ognl.PropertyAccessor; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import com.opensymphony.xwork2.util.reflection.ReflectionContextState; - /** * Allows methods to be executed under normal cirumstances, except when {@link ReflectionContextState#DENY_METHOD_EXECUTION} @@ -59,9 +54,8 @@ public class XWorkMethodAccessor extends ObjectMethodAccessor { //this if statement ensures that ognl //statements of the form someBean.mySet('keyPropVal') //return the set element with value of the keyProp given - - if (objects.length==1 - && context instanceof OgnlContext) { + + if (objects.length == 1 && context instanceof OgnlContext) { try { OgnlContext ogContext=(OgnlContext)context; if (OgnlRuntime.hasSetProperty(ogContext, object, string)) { @@ -90,11 +84,7 @@ public class XWorkMethodAccessor extends ObjectMethodAccessor { } //HACK - we pass indexed method access i.e. setXXX(A,B) pattern - if ( - (objects.length == 2 && string.startsWith("set")) - || - (objects.length == 1 && string.startsWith("get")) - ) { + if ((objects.length == 2 && string.startsWith("set")) || (objects.length == 1 && string.startsWith("get"))) { Boolean exec = (Boolean) context.get(ReflectionContextState.DENY_INDEXED_ACCESS_EXECUTION); boolean e = ((exec == null) ? false : exec.booleanValue()); if (!e) { @@ -111,18 +101,17 @@ public class XWorkMethodAccessor extends ObjectMethodAccessor { } } - private Object callMethodWithDebugInfo(Map context, Object object, String methodName, - Object[] objects) throws MethodFailedException { - try { - return super.callMethod(context, object, methodName, objects); + private Object callMethodWithDebugInfo(Map context, Object object, String methodName, Object[] objects) throws MethodFailedException { + try { + return super.callMethod(context, object, methodName, objects); } catch(MethodFailedException e) { if (LOG.isDebugEnabled()) { if (!(e.getReason() instanceof NoSuchMethodException)) { // the method exists on the target object, but something went wrong - LOG.debug( "Error calling method through OGNL: object: [{}] method: [{}] args: [{}]", e.getReason(), object.toString(), methodName, Arrays.toString(objects)); - } - } + LOG.debug("Error calling method through OGNL: object: [{}] method: [{}] args: [{}]", e.getReason(), object.toString(), methodName, Arrays.toString(objects)); + } + } throw e; } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultAcceptedPatternsChecker.java b/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultAcceptedPatternsChecker.java index deb7c03a4..00e9f794c 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultAcceptedPatternsChecker.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultAcceptedPatternsChecker.java @@ -3,8 +3,8 @@ package com.opensymphony.xwork2.security; import com.opensymphony.xwork2.XWorkConstants; import com.opensymphony.xwork2.inject.Inject; 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 java.util.Arrays; import java.util.HashSet; @@ -29,7 +29,7 @@ public class DefaultAcceptedPatternsChecker implements AcceptedPatternsChecker { public void setOverrideAcceptedPatterns(String acceptablePatterns) { LOG.warn("Overriding accepted patterns [{}] with [{}], be aware that this affects all instances and safety of your application!", XWorkConstants.OVERRIDE_ACCEPTED_PATTERNS, acceptablePatterns); - acceptedPatterns = new HashSet(); + acceptedPatterns = new HashSet<>(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) { acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } @@ -48,12 +48,12 @@ public class DefaultAcceptedPatternsChecker implements AcceptedPatternsChecker { } public void setAcceptedPatterns(String[] additionalPatterns) { - setAcceptedPatterns(new HashSet(Arrays.asList(additionalPatterns))); + setAcceptedPatterns(new HashSet<>(Arrays.asList(additionalPatterns))); } public void setAcceptedPatterns(Set patterns) { LOG.trace("Sets accepted patterns [{}]", patterns); - acceptedPatterns = new HashSet(patterns.size()); + acceptedPatterns = new HashSet<>(patterns.size()); for (String pattern : patterns) { acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsChecker.java b/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsChecker.java index 1a2d2a10b..f6d48cda0 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsChecker.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsChecker.java @@ -1,10 +1,10 @@ package com.opensymphony.xwork2.security; -import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.XWorkConstants; import com.opensymphony.xwork2.inject.Inject; 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 java.util.Arrays; import java.util.HashSet; @@ -49,12 +49,12 @@ public class DefaultExcludedPatternsChecker implements ExcludedPatternsChecker { } public void setExcludedPatterns(String[] patterns) { - setExcludedPatterns(new HashSet(Arrays.asList(patterns))); + setExcludedPatterns(new HashSet<>(Arrays.asList(patterns))); } public void setExcludedPatterns(Set patterns) { LOG.trace("Sets excluded patterns [{}]", patterns); - excludedPatterns = new HashSet(patterns.size()); + excludedPatterns = new HashSet<>(patterns.size()); for (String pattern : patterns) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringObjectFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringObjectFactory.java index 718480f33..f1137d9d4 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringObjectFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringObjectFactory.java @@ -17,6 +17,7 @@ package com.opensymphony.xwork2.spring; import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.inject.Inject; +import org.apache.commons.lang3.BooleanUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.BeansException; @@ -44,7 +45,7 @@ public class SpringObjectFactory extends ObjectFactory implements ApplicationCon protected ApplicationContext appContext; protected AutowireCapableBeanFactory autoWiringFactory; protected int autowireStrategy = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; - private final Map classes = new HashMap(); + private final Map classes = new HashMap<>(); private boolean useClassCache = true; private boolean alwaysRespectAutowireStrategy = false; /** @@ -62,7 +63,7 @@ public class SpringObjectFactory extends ObjectFactory implements ApplicationCon @Inject(value = "enableAopSupport", required = false) public void setEnableAopSupport(String enableAopSupport) { - this.enableAopSupport = Boolean.parseBoolean(enableAopSupport); + this.enableAopSupport = BooleanUtils.toBoolean(enableAopSupport); } /** @@ -203,8 +204,7 @@ public class SpringObjectFactory extends ObjectFactory implements ApplicationCon */ public Object autoWireBean(Object bean, AutowireCapableBeanFactory autoWiringFactory) { if (autoWiringFactory != null) { - autoWiringFactory.autowireBeanProperties(bean, - autowireStrategy, false); + autoWiringFactory.autowireBeanProperties(bean, autowireStrategy, false); } injectApplicationContext(bean); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringProxyableObjectFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringProxyableObjectFactory.java index 3f701a1cb..f249f5f8c 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringProxyableObjectFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/spring/SpringProxyableObjectFactory.java @@ -36,7 +36,7 @@ public class SpringProxyableObjectFactory extends SpringObjectFactory { private static final Logger LOG = LogManager.getLogger(SpringProxyableObjectFactory.class); - private List skipBeanNames = new ArrayList(); + private List skipBeanNames = new ArrayList<>(); @Override public Object buildBean(String beanName, Map extraContext) throws Exception { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptor.java index 611a1a35c..fe02ca5ca 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptor.java @@ -20,8 +20,8 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.opensymphony.xwork2.spring.SpringObjectFactory; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -97,9 +97,7 @@ public class ActionAutowiringInterceptor extends AbstractInterceptor implements WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (applicationContext == null) { - if (LOG.isWarnEnabled()) { - LOG.warn("ApplicationContext could not be found. Action classes will not be autowired."); - } + LOG.warn("ApplicationContext could not be found. Action classes will not be autowired."); } else { setApplicationContext(applicationContext); factory = new SpringObjectFactory(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/AnnotationUtils.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/AnnotationUtils.java index c9f286329..08cae039f 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/AnnotationUtils.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/AnnotationUtils.java @@ -118,14 +118,14 @@ public class AnnotationUtils { * method {@link AnnotatedElement}s matching the specified {@link Annotation}s */ public static Collection getAnnotatedMethods(Class clazz, Class... annotation){ - Collection toReturn = new HashSet(); - - for(Method m : clazz.getMethods()){ - if( ArrayUtils.isNotEmpty(annotation) && isAnnotatedBy(m, annotation) ){ - toReturn.add(m); - }else if( ArrayUtils.isEmpty(annotation) && ArrayUtils.isNotEmpty(m.getAnnotations())){ - toReturn.add(m); - } + Collection toReturn = new HashSet<>(); + + for (Method m : clazz.getMethods()) { + if (org.apache.commons.lang3.ArrayUtils.isNotEmpty(annotation) && isAnnotatedBy(m, annotation)) { + toReturn.add(m); + } else if (org.apache.commons.lang3.ArrayUtils.isEmpty(annotation) && org.apache.commons.lang3.ArrayUtils.isNotEmpty(m.getAnnotations())) { + toReturn.add(m); + } } return toReturn; @@ -136,7 +136,9 @@ public class AnnotationUtils { * @see AnnotatedElement */ public static boolean isAnnotatedBy(AnnotatedElement annotatedElement, Class... annotation) { - if(ArrayUtils.isEmpty(annotation)) return false; + if (org.apache.commons.lang3.ArrayUtils.isEmpty(annotation)) { + return false; + } for( Class c : annotation ){ if( annotatedElement.isAnnotationPresent(c) ) return true; @@ -173,20 +175,21 @@ public class AnnotationUtils { * Returns the annotation on the given class or the package of the class. This searchs up the * class hierarchy and the package hierarchy for the closest match. * - * @param klass The class to search for the annotation. + * @param clazz The class to search for the annotation. * @param annotationClass The Class of the annotation. * @return The annotation or null. */ - public static T findAnnotation(Class klass, Class annotationClass) { - T ann = klass.getAnnotation(annotationClass); - while (ann == null && klass != null) { - ann = klass.getAnnotation(annotationClass); - if (ann == null) - ann = klass.getPackage().getAnnotation(annotationClass); + public static T findAnnotation(Class clazz, Class annotationClass) { + T ann = clazz.getAnnotation(annotationClass); + while (ann == null && clazz != null) { + ann = clazz.getAnnotation(annotationClass); if (ann == null) { - klass = klass.getSuperclass(); - if (klass != null ) { - ann = klass.getAnnotation(annotationClass); + ann = clazz.getPackage().getAnnotation(annotationClass); + } + if (ann == null) { + clazz = clazz.getSuperclass(); + if (clazz != null) { + ann = clazz.getAnnotation(annotationClass); } } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/ArrayUtils.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/ArrayUtils.java index 0da159830..99f4ab60e 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/ArrayUtils.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/ArrayUtils.java @@ -22,7 +22,9 @@ import java.util.Set; /** * @author Dan Oxlade, dan d0t oxlade at gmail d0t c0m + * @deprecated Can be replaced eith ArrayUtils from lang3 package --> org.apache.commons.lang3.ArrayUtils */ +@Deprecated public class ArrayUtils { public static boolean isEmpty(Object[] array) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassLoaderUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassLoaderUtil.java index 77c468521..919f5af7d 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassLoaderUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassLoaderUtil.java @@ -48,7 +48,7 @@ public class ClassLoaderUtil { */ public static Iterator getResources(String resourceName, Class callingClass, boolean aggregate) throws IOException { - AggregateIterator iterator = new AggregateIterator(); + AggregateIterator iterator = new AggregateIterator<>(); iterator.addEnumeration(Thread.currentThread().getContextClassLoader().getResources(resourceName)); @@ -182,7 +182,7 @@ public class ClassLoaderUtil { */ static class AggregateIterator implements Iterator { - LinkedList> enums = new LinkedList>(); + LinkedList> enums = new LinkedList<>(); Enumeration cur = null; E next = null; Set loaded = new HashSet(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassPathFinder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassPathFinder.java index a8ebca2f4..5743885b7 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassPathFinder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/ClassPathFinder.java @@ -48,8 +48,8 @@ public class ClassPathFinder { * The PatternMatcher implementation to use */ private PatternMatcher patternMatcher = new WildcardHelper(); - - private Vector compared = new Vector(); + + private Vector compared = new Vector<>(); /** * retrieves the pattern in use @@ -74,13 +74,13 @@ public class ClassPathFinder { * @return Vector containing matching filenames */ public Vector findMatches() { - Vector matches = new Vector(); + Vector matches = new Vector<>(); URLClassLoader cl = getURLClassLoader(); if (cl == null ) { throw new XWorkException("unable to attain an URLClassLoader") ; } URL[] parentUrls = cl.getURLs(); - compiledPattern = (int[]) patternMatcher.compilePattern(pattern); + compiledPattern = patternMatcher.compilePattern(pattern); for (URL url : parentUrls) { if (!"file".equals(url.getProtocol())) { continue ; @@ -105,8 +105,8 @@ public class ClassPathFinder { if (entries == null ) { return null; } - - Vector matches = new Vector(); + + Vector matches = new Vector<>(); for (String listEntry : entries) { File tempFile ; if (!"".equals(prefix) ) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/DomHelper.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/DomHelper.java index 385574932..47d86e1a9 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/DomHelper.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/DomHelper.java @@ -19,8 +19,8 @@ import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.XWorkException; import com.opensymphony.xwork2.util.location.Location; import com.opensymphony.xwork2.util.location.LocationAttributes; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -92,7 +92,7 @@ public class DomHelper { factory.setValidating((dtdMappings != null)); factory.setNamespaceAware(true); - SAXParser parser = null; + SAXParser parser; try { parser = factory.newSAXParser(); } catch (Exception ex) { @@ -344,8 +344,7 @@ public class DomHelper { @Override public void error(SAXParseException exception) throws SAXException { - LOG.error(exception.getMessage() + " at (" + exception.getPublicId() + ":" + - exception.getLineNumber() + ":" + exception.getColumnNumber() + ")", exception); + LOG.error("{} at ({}:{}:{})", exception.getMessage(), exception.getPublicId(), exception.getLineNumber(), exception.getColumnNumber(), exception); throw exception; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/LocalizedTextUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/LocalizedTextUtil.java index 1a46ecf8c..2d9afa268 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/LocalizedTextUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/LocalizedTextUtil.java @@ -25,10 +25,10 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import com.opensymphony.xwork2.util.reflection.ReflectionProviderFactory; import org.apache.commons.lang3.ObjectUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; @@ -90,14 +90,14 @@ public class LocalizedTextUtil { private static final String TOMCAT_RESOURCE_ENTRIES_FIELD = "resourceEntries"; - private static final ConcurrentMap> classLoaderMap = new ConcurrentHashMap>(); + private static final ConcurrentMap> classLoaderMap = new ConcurrentHashMap<>(); private static boolean reloadBundles = false; private static boolean devMode; - private static final ConcurrentMap bundlesMap = new ConcurrentHashMap(); - private static final ConcurrentMap messageFormats = new ConcurrentHashMap(); - private static final ConcurrentMap delegatedClassLoaderMap = new ConcurrentHashMap(); + private static final ConcurrentMap bundlesMap = new ConcurrentHashMap<>(); + private static final ConcurrentMap messageFormats = new ConcurrentHashMap<>(); + private static final ConcurrentMap delegatedClassLoaderMap = new ConcurrentHashMap<>(); private static final String RELOADED = "com.opensymphony.xwork2.util.LocalizedTextUtil.reloaded"; private static final String XWORK_MESSAGES_BUNDLE = "com/opensymphony/xwork2/xwork-messages"; @@ -112,7 +112,7 @@ public class LocalizedTextUtil { */ public static void clearDefaultResourceBundles() { ClassLoader ccl = getCurrentThreadContextClassLoader(); - List bundles = new ArrayList(); + List bundles = new ArrayList<>(); classLoaderMap.put(ccl.hashCode(), bundles); bundles.add(0, XWORK_MESSAGES_BUNDLE); } @@ -417,9 +417,7 @@ public class LocalizedTextUtil { ValueStack valueStack) { String indexedTextName = null; if (aTextName == null) { - if (LOG.isWarnEnabled()) { LOG.warn("Trying to find text with null key!"); - } aTextName = ""; } // calculate indexedTextName (collection[*]) if applicable @@ -518,12 +516,13 @@ public class LocalizedTextUtil { Class clazz = propertyDescriptor.getPropertyType(); if (clazz != null) { - if (obj != null) + if (obj != null) { valueStack.push(obj); + } msg = findText(clazz, newKey, locale, null, args); - if (obj != null) + if (obj != null) { valueStack.pop(); - + } if (msg != null) { return msg; } @@ -531,7 +530,7 @@ public class LocalizedTextUtil { } } } catch (Exception e) { - LOG.debug("unable to find property " + prop, e); + LOG.debug("unable to find property {}", prop, e); } } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcher.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcher.java index 1203a49d8..8d197c697 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcher.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcher.java @@ -74,7 +74,7 @@ public class NamedVariablePatternMatcher implements PatternMatcher 0) { - List varNames = new ArrayList(); + List varNames = new ArrayList<>(); StringBuilder varName = null; for (int x=0; x * This class was pulled out of Jakarta Commons Configuration and * Jakarta Commons Lang trunk revision 476093 */ -public class PropertiesReader extends LineNumberReader -{ - /** Stores the comment lines for the currently processed property.*/ +public class PropertiesReader extends LineNumberReader { + /** + * Stores the comment lines for the currently processed property. + */ private List commentLines; - /** Stores the name of the last read property.*/ + /** + * Stores the name of the last read property. + */ private String propertyName; - /** Stores the value of the last read property.*/ + /** + * Stores the value of the last read property. + */ private String propertyValue; - /** Stores the list delimiter character.*/ + /** + * Stores the list delimiter character. + */ private char delimiter; - - /** Constant for the supported comment characters.*/ + + /** + * Constant for the supported comment characters. + */ static final String COMMENT_CHARS = "#!"; - - /** Constant for the radix of hex numbers.*/ + + /** + * Constant for the radix of hex numbers. + */ private static final int HEX_RADIX = 16; - /** Constant for the length of a unicode literal.*/ + /** + * Constant for the length of a unicode literal. + */ private static final int UNICODE_LEN = 4; - - /** The list of possible key/value separators */ - private static final char[] SEPARATORS = new char[] {'=', ':'}; - /** The white space characters used as key/value separators. */ + /** + * The list of possible key/value separators + */ + private static final char[] SEPARATORS = new char[]{'=', ':'}; + + /** + * The white space characters used as key/value separators. + */ private static final char[] WHITE_SPACE = new char[]{' ', '\t', '\f'}; /** @@ -63,8 +80,7 @@ public class PropertiesReader extends LineNumberReader * * @param reader A Reader. */ - public PropertiesReader(Reader reader) - { + public PropertiesReader(Reader reader) { this(reader, ','); } @@ -72,17 +88,16 @@ public class PropertiesReader extends LineNumberReader * Creates a new instance of PropertiesReader and sets * the underlaying reader and the list delimiter. * - * @param reader the reader + * @param reader the reader * @param listDelimiter the list delimiter character * @since 1.3 */ - public PropertiesReader(Reader reader, char listDelimiter) - { + public PropertiesReader(Reader reader, char listDelimiter) { super(reader); commentLines = new ArrayList(); delimiter = listDelimiter; } - + /** * Tests whether a line is a comment, i.e. whether it starts with a comment * character. @@ -91,8 +106,7 @@ public class PropertiesReader extends LineNumberReader * @return a flag if this is a comment line * @since 1.3 */ - boolean isCommentLine(String line) - { + boolean isCommentLine(String line) { String s = line.trim(); // blanc lines are also treated as comment lines return s.length() < 1 || COMMENT_CHARS.indexOf(s.charAt(0)) >= 0; @@ -106,38 +120,30 @@ public class PropertiesReader extends LineNumberReader * = <value>) * * @return A string containing a property value or null - * * @throws IOException in case of an I/O error */ - public String readProperty() throws IOException - { + public String readProperty() throws IOException { commentLines.clear(); StringBuilder buffer = new StringBuilder(); - while (true) - { + while (true) { String line = readLine(); - if (line == null) - { + if (line == null) { // EOF return null; } - if (isCommentLine(line)) - { + if (isCommentLine(line)) { commentLines.add(line); continue; } line = line.trim(); - if (checkCombineLines(line)) - { + if (checkCombineLines(line)) { line = line.substring(0, line.length() - 1); buffer.append(line); - } - else - { + } else { buffer.append(line); break; } @@ -156,12 +162,10 @@ public class PropertiesReader extends LineNumberReader * @throws IOException if an error occurs * @since 1.3 */ - public boolean nextProperty() throws IOException - { + public boolean nextProperty() throws IOException { String line = readProperty(); - if (line == null) - { + if (line == null) { return false; // EOF } @@ -179,8 +183,7 @@ public class PropertiesReader extends LineNumberReader * readProperty() * @since 1.3 */ - public List getCommentLines() - { + public List getCommentLines() { return commentLines; } @@ -192,8 +195,7 @@ public class PropertiesReader extends LineNumberReader * @return the name of the last read property * @since 1.3 */ - public String getPropertyName() - { + public String getPropertyName() { return propertyName; } @@ -205,8 +207,7 @@ public class PropertiesReader extends LineNumberReader * @return the value of the last read property * @since 1.3 */ - public String getPropertyValue() - { + public String getPropertyValue() { return propertyValue; } @@ -217,11 +218,9 @@ public class PropertiesReader extends LineNumberReader * @param line the line * @return a flag if the lines should be combined */ - private boolean checkCombineLines(String line) - { + private boolean checkCombineLines(String line) { int bsCount = 0; - for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--) - { + for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--) { bsCount++; } @@ -235,8 +234,7 @@ public class PropertiesReader extends LineNumberReader * @return an array with the property's key and value * @since 1.2 */ - private String[] parseProperty(String line) - { + private String[] parseProperty(String line) { // sorry for this spaghetti code, please replace it as soon as // possible with a regexp when the Java 1.3 requirement is dropped @@ -251,42 +249,30 @@ public class PropertiesReader extends LineNumberReader // 3: value parsing int state = 0; - for (int pos = 0; pos < line.length(); pos++) - { + for (int pos = 0; pos < line.length(); pos++) { char c = line.charAt(pos); - switch (state) - { + switch (state) { case 0: - if (c == '\\') - { + if (c == '\\') { state = 1; - } - else if (contains(WHITE_SPACE, c)) - { + } else if (contains(WHITE_SPACE, c)) { // switch to the separator crossing state state = 2; - } - else if (contains(SEPARATORS, c)) - { + } else if (contains(SEPARATORS, c)) { // switch to the value parsing state state = 3; - } - else - { + } else { key.append(c); } break; case 1: - if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c)) - { + if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c)) { // this is an escaped separator or white space key.append(c); - } - else - { + } else { // another escaped character, the '\' is preserved key.append('\\'); key.append(c); @@ -298,18 +284,13 @@ public class PropertiesReader extends LineNumberReader break; case 2: - if (contains(WHITE_SPACE, c)) - { + if (contains(WHITE_SPACE, c)) { // do nothing, eat all white spaces state = 2; - } - else if (contains(SEPARATORS, c)) - { + } else if (contains(SEPARATORS, c)) { // switch to the value parsing state state = 3; - } - else - { + } else { // any other character indicates we encoutered the beginning of the value value.append(c); @@ -330,22 +311,20 @@ public class PropertiesReader extends LineNumberReader return result; } - + /** *

Unescapes any Java literals found in the String to a * Writer.

This is a slightly modified version of the * StringEscapeUtils.unescapeJava() function in commons-lang that doesn't * drop escaped separators (i.e '\,'). * - * @param str the String to unescape, may be null + * @param str the String to unescape, may be null * @param delimiter the delimiter for multi-valued properties * @return the processed string * @throws IllegalArgumentException if the Writer is null */ - protected static String unescapeJava(String str, char delimiter) - { - if (str == null) - { + protected static String unescapeJava(String str, char delimiter) { + if (str == null) { return null; } int sz = str.length(); @@ -353,98 +332,67 @@ public class PropertiesReader extends LineNumberReader StringBuffer unicode = new StringBuffer(UNICODE_LEN); boolean hadSlash = false; boolean inUnicode = false; - for (int i = 0; i < sz; i++) - { + for (int i = 0; i < sz; i++) { char ch = str.charAt(i); - if (inUnicode) - { + if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); - if (unicode.length() == UNICODE_LEN) - { + if (unicode.length() == UNICODE_LEN) { // unicode now contains the four hex digits // which represents our unicode character - try - { + try { int value = Integer.parseInt(unicode.toString(), HEX_RADIX); out.append((char) value); unicode.setLength(0); inUnicode = false; hadSlash = false; - } - catch (NumberFormatException nfe) - { + } catch (NumberFormatException nfe) { throw new RuntimeException("Unable to parse unicode value: " + unicode, nfe); } } continue; } - if (hadSlash) - { + if (hadSlash) { // handle an escaped value hadSlash = false; - if (ch == '\\') - { + if (ch == '\\') { out.append('\\'); - } - else if (ch == '\'') - { + } else if (ch == '\'') { out.append('\''); - } - else if (ch == '\"') - { + } else if (ch == '\"') { out.append('"'); - } - else if (ch == 'r') - { + } else if (ch == 'r') { out.append('\r'); - } - else if (ch == 'f') - { + } else if (ch == 'f') { out.append('\f'); - } - else if (ch == 't') - { + } else if (ch == 't') { out.append('\t'); - } - else if (ch == 'n') - { + } else if (ch == 'n') { out.append('\n'); - } - else if (ch == 'b') - { + } else if (ch == 'b') { out.append('\b'); - } - else if (ch == delimiter) - { + } else if (ch == delimiter) { out.append('\\'); out.append(delimiter); - } - else if (ch == 'u') - { + } else if (ch == 'u') { // uh-oh, we're in unicode country.... inUnicode = true; - } - else - { + } else { out.append(ch); } continue; - } - else if (ch == '\\') - { + } else if (ch == '\\') { hadSlash = true; continue; } out.append(ch); } - if (hadSlash) - { + if (hadSlash) { // then we're in the weird case of a \ at the end of the // string, let's output it anyway. out.append('\\'); @@ -452,14 +400,14 @@ public class PropertiesReader extends LineNumberReader return out.toString(); } - + /** *

Checks if the object is in the given array.

- * + *

*

The method returns false if a null array is passed in.

- * - * @param array the array to search through - * @param objectToFind the object to find + * + * @param array the array to search through + * @param objectToFind the object to find * @return true if the array contains the object */ public boolean contains(char[] array, char objectToFind) { @@ -473,14 +421,14 @@ public class PropertiesReader extends LineNumberReader } return false; } - + /** *

Unescapes any Java literals found in the String. * For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

- * - * @param str the String to unescape, may be null + * + * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input */ public static String unescapeJava(String str) { @@ -501,17 +449,17 @@ public class PropertiesReader extends LineNumberReader /** *

Unescapes any Java literals found in the String to a * Writer.

- * + *

*

For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

- * + *

*

A null string input has no effect.

- * - * @param out the Writer used to output unescaped characters - * @param str the String to unescape, may be null + * + * @param out the Writer used to output unescaped characters + * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null - * @throws IOException if error occurs on underlying Writer + * @throws IOException if error occurs on underlying Writer */ public static void unescapeJava(Writer out, String str) throws IOException { if (out == null) { @@ -573,13 +521,12 @@ public class PropertiesReader extends LineNumberReader case 'b': out.write('\b'); break; - case 'u': - { - // uh-oh, we're in unicode country.... - inUnicode = true; - break; - } - default : + case 'u': { + // uh-oh, we're in unicode country.... + inUnicode = true; + break; + } + default: out.write(ch); break; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/TextParseUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/TextParseUtil.java index 211d08c6c..db1af6d81 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/TextParseUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/TextParseUtil.java @@ -19,11 +19,7 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.inject.Container; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; /** @@ -119,7 +115,7 @@ public class TextParseUtil { /** * Converted object from variable translation. * - * @param open + * @param openChars * @param expression * @param stack * @param asType @@ -147,7 +143,7 @@ public class TextParseUtil { /** * Converted object from variable translation. * - * @param open + * @param openChars * @param expression * @param stack * @param asType @@ -216,7 +212,7 @@ public class TextParseUtil { if (result instanceof Collection) { @SuppressWarnings("unchecked") Collection casted = (Collection)result; - resultCol = new ArrayList(); + resultCol = new ArrayList<>(); XWorkConverter conv = ((Container)context.get(ActionContext.CONTAINER)).getInstance(XWorkConverter.class); @@ -230,7 +226,7 @@ public class TextParseUtil { } } } else { - resultCol = new ArrayList(); + resultCol = new ArrayList<>(); String resultStr = translateVariables(expression, stack, evaluator); if (shallBeIncluded(resultStr, excludeEmptyElements)) { resultCol.add(resultStr); @@ -258,7 +254,7 @@ public class TextParseUtil { * @return A set from comma delimted Strings. */ public static Set commaDelimitedStringToSet(String s) { - Set set = new HashSet(); + Set set = new HashSet<>(); String[] split = s.split(","); for (String aSplit : split) { String trimmed = aSplit.trim(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/URLUtil.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/URLUtil.java index 58ce87011..006fd5e41 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/URLUtil.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/URLUtil.java @@ -15,10 +15,12 @@ */ package com.opensymphony.xwork2.util; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; /** @@ -46,10 +48,14 @@ public class URLUtil { } try { - new URL(url); - + URL u = new URL(url); + URI uri = u.toURI(); // perform a additional url syntax check + if (uri.getHost() == null) { + LOG.debug("Url [{}] does not contains a valid host: {}", url, uri); + return false; + } return true; - } catch (MalformedURLException e) { + } catch (MalformedURLException | URISyntaxException e) { LOG.debug("Url [{}] is invalid: {}", url, e.getMessage(), e); return false; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkList.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkList.java index d62747384..2a50197a0 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkList.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkList.java @@ -20,8 +20,8 @@ import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.XWorkException; import com.opensymphony.xwork2.conversion.TypeConverter; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Collection; @@ -98,18 +98,18 @@ public class XWorkList extends ArrayList { *

* This method performs any necessary type conversion. * - * @param c the elements to be inserted into this list. + * @param collection the elements to be inserted into this list. * @return true if this list changed as a result of the call. * @throws NullPointerException if the specified collection is null. */ @Override - public boolean addAll(Collection c) { - if (c == null) { + public boolean addAll(Collection collection) { + if (collection == null) { throw new NullPointerException("Collection to add is null"); } - for (Object aC : c) { - add(aC); + for (Object nextElement : collection) { + add(nextElement); } return true; @@ -126,12 +126,12 @@ public class XWorkList extends ArrayList { * also performs any necessary type conversion. * * @param index index at which to insert first element from the specified collection. - * @param c elements to be inserted into this list. + * @param collection elements to be inserted into this list. * @return true if this list changed as a result of the call. */ @Override - public boolean addAll(int index, Collection c) { - if (c == null) { + public boolean addAll(int index, Collection collection) { + if (collection == null) { throw new NullPointerException("Collection to add is null"); } @@ -141,7 +141,7 @@ public class XWorkList extends ArrayList { trim = true; } - for (Iterator it = c.iterator(); it.hasNext(); index++) { + for (Iterator it = collection.iterator(); it.hasNext(); index++) { add(index, it.next()); } @@ -203,12 +203,10 @@ public class XWorkList extends ArrayList { private Object convert(Object element) { if ((element != null) && !clazz.isAssignableFrom(element.getClass())) { // convert to correct type - if (LOG.isDebugEnabled()) { - LOG.debug("Converting from " + element.getClass().getName() + " to " + clazz.getName()); - } - TypeConverter conv = getTypeConverter(); + LOG.debug("Converting from {} to {}", element.getClass().getName(), clazz.getName()); + TypeConverter converter = getTypeConverter(); Map context = ActionContext.getContext().getContextMap(); - element = conv.convertValue(context, null, null, null, element, clazz); + element = converter.convertValue(context, null, null, null, element, clazz); } return element; @@ -221,7 +219,6 @@ public class XWorkList extends ArrayList { @Override public boolean contains(Object element) { element = convert(element); - return super.contains(element); } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkTestCaseHelper.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkTestCaseHelper.java index f5f70edf7..d81b84ec9 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkTestCaseHelper.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/XWorkTestCaseHelper.java @@ -60,8 +60,7 @@ public class XWorkTestCaseHelper { public void init(Configuration configuration) throws ConfigurationException {} public boolean needsReload() { return false; } - public void register(ContainerBuilder builder, - LocatableProperties props) throws ConfigurationException { + public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { builder.setAllowDuplicates(true); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/AbstractResourceStore.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/AbstractResourceStore.java new file mode 100644 index 000000000..916638919 --- /dev/null +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/AbstractResourceStore.java @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2015 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.opensymphony.xwork2.util.classloader; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + + +public abstract class AbstractResourceStore implements ResourceStore { + private static final Logger log = LogManager.getLogger(JarResourceStore.class); + protected final File file; + + public AbstractResourceStore(final File file) { + this.file = file; + } + + protected void closeQuietly(InputStream is) { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + log.error("Unable to close file input stream", e); + } + } + + public void write(String pResourceName, byte[] pResourceData) { + } + + public String toString() { + return this.getClass().getName() + file.toString(); + } +} diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/FileResourceStore.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/FileResourceStore.java index 3b2714ee2..c2c79ea61 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/FileResourceStore.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/FileResourceStore.java @@ -15,25 +15,22 @@ */ package com.opensymphony.xwork2.util.classloader; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; /** * Reads a class from disk * class taken from Apache JCI */ -public final class FileResourceStore implements ResourceStore { +public final class FileResourceStore extends AbstractResourceStore { private static final Logger LOG = LogManager.getLogger(FileResourceStore.class); - private final File root; - public FileResourceStore(final File pFile) { - root = pFile; + public FileResourceStore(final File file) { + super(file); } public byte[] read(final String pResourceName) { @@ -53,25 +50,8 @@ public final class FileResourceStore implements ResourceStore { } } - public void write(final String pResourceName, final byte[] pData) { - - } - - private void closeQuietly(InputStream is) { - try { - if (is != null) - is.close(); - } catch (IOException e) { - LOG.error("Unable to close file input stream", e); - } - } - private File getFile(final String pResourceName) { final String fileName = pResourceName.replace('/', File.separatorChar); - return new File(root, fileName); - } - - public String toString() { - return this.getClass().getName() + root.toString(); + return new File(file, fileName); } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/JarResourceStore.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/JarResourceStore.java index f7528b09b..c5c1cc7c0 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/JarResourceStore.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/JarResourceStore.java @@ -16,8 +16,8 @@ package com.opensymphony.xwork2.util.classloader; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.*; import java.util.zip.ZipEntry; @@ -26,16 +26,11 @@ import java.util.zip.ZipFile; /** * Read resources from a jar file */ -public class JarResourceStore implements ResourceStore { +public class JarResourceStore extends AbstractResourceStore { private static final Logger LOG = LogManager.getLogger(JarResourceStore.class); - private final File file; - public JarResourceStore(File file) { - this.file = file; - } - - public void write(String pResourceName, byte[] pResourceData) { + super(file); } public byte[] read(String pResourceName) { @@ -58,8 +53,7 @@ public class JarResourceStore implements ResourceStore { } } - public static long copy(InputStream input, OutputStream output) - throws IOException { + public static long copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024 * 4]; long count = 0; int n = 0; @@ -69,13 +63,4 @@ public class JarResourceStore implements ResourceStore { } return count; } - - private void closeQuietly(InputStream is) { - try { - if (is != null) - is.close(); - } catch (IOException e) { - LOG.error("Unable to close input stream", e); - } - } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ReloadingClassLoader.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ReloadingClassLoader.java index 3d17ca4d6..55fe34f26 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ReloadingClassLoader.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ReloadingClassLoader.java @@ -19,9 +19,9 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.FileManager; import com.opensymphony.xwork2.FileManagerFactory; import com.opensymphony.xwork2.XWorkException; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import org.apache.commons.lang3.ObjectUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.File; import java.io.InputStream; @@ -125,8 +125,7 @@ public class ReloadingClassLoader extends ClassLoader { } public void reload() { - if (LOG.isTraceEnabled()) - LOG.trace("Reloading class loader"); + LOG.trace("Reloading class loader"); delegate = new ResourceStoreClassLoader(parent, stores); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ResourceStoreClassLoader.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ResourceStoreClassLoader.java index d84c1062b..8d4a6882b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ResourceStoreClassLoader.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/classloader/ResourceStoreClassLoader.java @@ -15,16 +15,11 @@ */ package com.opensymphony.xwork2.util.classloader; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - /** * class taken from Apache JCI */ public final class ResourceStoreClassLoader extends ClassLoader { - private static final Logger LOG = LogManager.getLogger(ResourceStoreClassLoader.class); - private final ResourceStore[] stores; public ResourceStoreClassLoader(final ClassLoader pParent, final ResourceStore[] pStores) { @@ -63,7 +58,6 @@ public final class ResourceStoreClassLoader extends ClassLoader { } else { throw new ClassNotFoundException(name); } - } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ClassFinder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ClassFinder.java index cf8fb9b56..50fde4ae2 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ClassFinder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ClassFinder.java @@ -90,7 +90,7 @@ public interface ClassFinder { } public class Annotatable { - private final List annotations = new ArrayList(); + private final List annotations = new ArrayList<>(); public Annotatable(AnnotatedElement element) { for (Annotation annotation : element.getAnnotations()) { @@ -136,12 +136,12 @@ public interface ClassFinder { public class ClassInfo extends Annotatable implements Info { private final String name; - private final List methods = new ArrayList(); - private final List constructors = new ArrayList(); + private final List methods = new ArrayList<>(); + private final List constructors = new ArrayList<>(); private final String superType; - private final List interfaces = new ArrayList(); - private final List superInterfaces = new ArrayList(); - private final List fields = new ArrayList(); + private final List interfaces = new ArrayList<>(); + private final List superInterfaces = new ArrayList<>(); + private final List fields = new ArrayList<>(); private Class clazz; private ClassFinder classFinder; private ClassNotFoundException notFound; @@ -216,7 +216,7 @@ public interface ClassFinder { private final ClassInfo declaringClass; private final String returnType; private final String name; - private final List> parameterAnnotations = new ArrayList>(); + private final List> parameterAnnotations = new ArrayList<>(); public MethodInfo(ClassInfo info, Constructor constructor){ super(constructor); @@ -245,7 +245,7 @@ public interface ClassFinder { public List getParameterAnnotations(int index) { if (index >= parameterAnnotations.size()) { for (int i = parameterAnnotations.size(); i <= index; i++) { - List annotationInfos = new ArrayList(); + List annotationInfos = new ArrayList<>(); parameterAnnotations.add(i, annotationInfos); } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java index 80f205ac3..b70363954 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java @@ -19,9 +19,9 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.FileManager; import com.opensymphony.xwork2.FileManagerFactory; import com.opensymphony.xwork2.XWorkException; -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.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.FieldVisitor; @@ -38,26 +38,17 @@ import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; public class DefaultClassFinder implements ClassFinder { private static final Logger LOG = LogManager.getLogger(DefaultClassFinder.class); - private final Map> annotated = new HashMap>(); - private final Map classInfos = new LinkedHashMap(); + private final Map> annotated = new HashMap<>(); + private final Map classInfos = new LinkedHashMap<>(); - private final List classesNotLoaded = new ArrayList(); + private final List classesNotLoaded = new ArrayList<>(); private boolean extractBaseInterfaces; private ClassLoaderInterface classLoaderInterface; @@ -68,7 +59,7 @@ public class DefaultClassFinder implements ClassFinder { this.extractBaseInterfaces = extractBaseInterfaces; this.fileManager = ActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager(); - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); for (URL location : urls) { try { if (protocols.contains(location.getProtocol())) { @@ -105,8 +96,8 @@ public class DefaultClassFinder implements ClassFinder { public DefaultClassFinder(List classes){ this.classLoaderInterface = null; - List infos = new ArrayList(); - List packages = new ArrayList(); + List infos = new ArrayList<>(); + List packages = new ArrayList<>(); for (Class clazz : classes) { Package aPackage = clazz.getPackage(); @@ -154,7 +145,7 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedPackages(Class annotation) { classesNotLoaded.clear(); - List packages = new ArrayList(); + List packages = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof PackageInfo) { @@ -175,7 +166,7 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedClasses(Class annotation) { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof ClassInfo) { @@ -197,8 +188,8 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedMethods(Class annotation) { classesNotLoaded.clear(); - List seen = new ArrayList(); - List methods = new ArrayList(); + List seen = new ArrayList<>(); + List methods = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && !"".equals(info.getName())) { @@ -227,8 +218,8 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedConstructors(Class annotation) { classesNotLoaded.clear(); - List seen = new ArrayList(); - List constructors = new ArrayList(); + List seen = new ArrayList<>(); + List constructors = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && "".equals(info.getName())) { @@ -257,15 +248,17 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedFields(Class annotation) { classesNotLoaded.clear(); - List seen = new ArrayList(); - List fields = new ArrayList(); + List seen = new ArrayList<>(); + List fields = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof FieldInfo) { FieldInfo fieldInfo = (FieldInfo) info; ClassInfo classInfo = fieldInfo.getDeclaringClass(); - if (seen.contains(classInfo)) continue; + if (seen.contains(classInfo)) { + continue; + } seen.add(classInfo); @@ -287,7 +280,7 @@ public class DefaultClassFinder implements ClassFinder { public List findClassesInPackage(String packageName, boolean recursive) { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (ClassInfo classInfo : classInfos.values()) { try { if (recursive && classInfo.getPackageName().startsWith(packageName)){ @@ -305,7 +298,7 @@ public class DefaultClassFinder implements ClassFinder { public List findClasses(Test test) { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (ClassInfo classInfo : classInfos.values()) { try { if (test.test(classInfo)) { @@ -321,7 +314,7 @@ public class DefaultClassFinder implements ClassFinder { public List findClasses() { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (ClassInfo classInfo : classInfos.values()) { try { classes.add(classInfo.get()); @@ -334,7 +327,7 @@ public class DefaultClassFinder implements ClassFinder { } private static List getURLs(ClassLoaderInterface classLoader, String[] dirNames) { - List urls = new ArrayList(); + List urls = new ArrayList<>(); for (String dirName : dirNames) { try { Enumeration classLoaderURLs = classLoader.getResources(dirName); @@ -351,7 +344,7 @@ public class DefaultClassFinder implements ClassFinder { } private List file(URL location) { - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); File dir = new File(URLDecoder.decode(location.getPath())); if ("META-INF".equals(dir.getName())) { dir = dir.getParentFile(); // Scrape "META-INF" off @@ -394,7 +387,7 @@ public class DefaultClassFinder implements ClassFinder { } private List jar(JarInputStream jarStream) throws IOException { - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { @@ -444,7 +437,7 @@ public class DefaultClassFinder implements ClassFinder { private List getAnnotationInfos(String name) { List infos = annotated.get(name); if (infos == null) { - infos = new ArrayList(); + infos = new ArrayList<>(); annotated.put(name, infos); } return infos; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java index 8e8d2a61c..e07503d28 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java @@ -15,30 +15,16 @@ */ package com.opensymphony.xwork2.util.finder; -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 java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.JarURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.Vector; +import java.net.*; +import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -52,7 +38,7 @@ public class ResourceFinder { private final URL[] urls; private final String path; private final ClassLoaderInterface classLoaderInterface; - private final List resourcesNotLoaded = new ArrayList(); + private final List resourcesNotLoaded = new ArrayList<>(); public ResourceFinder(URL... urls) { this(null, new ClassLoaderInterfaceDelegate(Thread.currentThread().getContextClassLoader()), urls); @@ -71,9 +57,8 @@ public class ResourceFinder { } public ResourceFinder(String path, ClassLoaderInterface classLoaderInterface, URL... urls) { - if (path == null){ - path = ""; - } else if (path.length() > 0 && !path.endsWith("/")) { + path = StringUtils.trimToEmpty(path); + if (!StringUtils.endsWith(path, "/")) { path += "/"; } this.path = path; @@ -131,7 +116,7 @@ public class ResourceFinder { String fullUri = path + uri; Enumeration resources = getResources(fullUri); - List list = new ArrayList(); + List list = new ArrayList<>(); while (resources.hasMoreElements()) { URL url = resources.nextElement(); list.add(url); @@ -175,7 +160,7 @@ public class ResourceFinder { public List findAllStrings(String uri) throws IOException { String fulluri = path + uri; - List strings = new ArrayList(); + List strings = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -199,7 +184,7 @@ public class ResourceFinder { resourcesNotLoaded.clear(); String fulluri = path + uri; - List strings = new ArrayList(); + List strings = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -239,7 +224,7 @@ public class ResourceFinder { * @throws IOException if any of the urls cannot be read */ public Map mapAllStrings(String uri) throws IOException { - Map strings = new HashMap(); + Map strings = new HashMap<>(); Map resourcesMap = getResourcesMap(uri); for (Map.Entry entry : resourcesMap.entrySet()) { String name = entry.getKey(); @@ -277,7 +262,7 @@ public class ResourceFinder { */ public Map mapAvailableStrings(String uri) throws IOException { resourcesNotLoaded.clear(); - Map strings = new HashMap(); + Map strings = new HashMap<>(); Map resourcesMap = getResourcesMap(uri); for (Map.Entry entry : resourcesMap.entrySet()) { String name = entry.getKey(); @@ -324,7 +309,7 @@ public class ResourceFinder { * @throws ClassNotFoundException */ public List findAllClasses(String uri) throws IOException, ClassNotFoundException { - List classes = new ArrayList(); + List classes = new ArrayList<>(); List strings = findAllStrings(uri); for (String className : strings) { Class clazz = classLoaderInterface.loadClass(className); @@ -346,7 +331,7 @@ public class ResourceFinder { */ public List findAvailableClasses(String uri) throws IOException { resourcesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); List strings = findAvailableStrings(uri); for (String className : strings) { try { @@ -383,7 +368,7 @@ public class ResourceFinder { * @throws ClassNotFoundException */ public Map mapAllClasses(String uri) throws IOException, ClassNotFoundException { - Map classes = new HashMap(); + Map classes = new HashMap<>(); Map map = mapAllStrings(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -419,7 +404,7 @@ public class ResourceFinder { */ public Map mapAvailableClasses(String uri) throws IOException { resourcesNotLoaded.clear(); - Map classes = new HashMap(); + Map classes = new HashMap<>(); Map map = mapAvailableStrings(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -496,7 +481,7 @@ public class ResourceFinder { * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public List findAllImplementations(Class interfase) throws IOException, ClassNotFoundException { - List implementations = new ArrayList(); + List implementations = new ArrayList<>(); List strings = findAllStrings(interfase.getName()); for (String className : strings) { Class impl = classLoaderInterface.loadClass(className); @@ -533,7 +518,7 @@ public class ResourceFinder { */ public List findAvailableImplementations(Class interfase) throws IOException { resourcesNotLoaded.clear(); - List implementations = new ArrayList(); + List implementations = new ArrayList<>(); List strings = findAvailableStrings(interfase.getName()); for (String className : strings) { try { @@ -576,7 +561,7 @@ public class ResourceFinder { * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public Map mapAllImplementations(Class interfase) throws IOException, ClassNotFoundException { - Map implementations = new HashMap(); + Map implementations = new HashMap<>(); Map map = mapAllStrings(interfase.getName()); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -615,7 +600,7 @@ public class ResourceFinder { */ public Map mapAvailableImplementations(Class interfase) throws IOException { resourcesNotLoaded.clear(); - Map implementations = new HashMap(); + Map implementations = new HashMap<>(); Map map = mapAvailableStrings(interfase.getName()); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -686,7 +671,7 @@ public class ResourceFinder { public List findAllProperties(String uri) throws IOException { String fulluri = path + uri; - List properties = new ArrayList(); + List properties = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -720,7 +705,7 @@ public class ResourceFinder { resourcesNotLoaded.clear(); String fulluri = path + uri; - List properties = new ArrayList(); + List properties = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -757,7 +742,7 @@ public class ResourceFinder { * @throws IOException if the URL cannot be read or is not in properties file format */ public Map mapAllProperties(String uri) throws IOException { - Map propertiesMap = new HashMap(); + Map propertiesMap = new HashMap<>(); Map map = getResourcesMap(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -792,7 +777,7 @@ public class ResourceFinder { */ public Map mapAvailableProperties(String uri) throws IOException { resourcesNotLoaded.clear(); - Map propertiesMap = new HashMap(); + Map propertiesMap = new HashMap<>(); Map map = getResourcesMap(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -816,7 +801,7 @@ public class ResourceFinder { public Map getResourcesMap(String uri) throws IOException { String basePath = path + uri; - Map resources = new HashMap(); + Map resources = new HashMap<>(); if (!basePath.endsWith("/")) { basePath += "/"; } @@ -827,13 +812,9 @@ public class ResourceFinder { try { if ("jar".equals(location.getProtocol())) { - readJarEntries(location, basePath, resources); - } else if ("file".equals(location.getProtocol())) { - readDirectoryEntries(location, resources); - } } catch (Exception e) { LOG.debug("Got exception loading resources for {}", uri, e); @@ -849,7 +830,7 @@ public class ResourceFinder { public Set findPackages(String uri) throws IOException { String basePath = path + uri; - Set resources = new HashSet(); + Set resources = new HashSet<>(); if (!basePath.endsWith("/")) { basePath += "/"; } @@ -860,13 +841,9 @@ public class ResourceFinder { try { if ("jar".equals(location.getProtocol())) { - readJarDirectoryEntries(location, basePath, resources); - } else if ("file".equals(location.getProtocol())) { - readSubDirectories(new File(location.toURI()), uri, resources); - } } catch (Exception e) { LOG.debug("Got exception search for subpackages for {}", uri, e); @@ -886,18 +863,18 @@ public class ResourceFinder { basePath += "/"; } Enumeration urls = getResources(basePath); - Map> result = new HashMap>(); + Map> result = new HashMap<>(); while (urls.hasMoreElements()) { URL location = urls.nextElement(); try { if ("jar".equals(location.getProtocol())) { - Set resources = new HashSet(); + Set resources = new HashSet<>(); readJarDirectoryEntries(location, basePath, resources); result.put(location, convertPathsToPackages(resources)); } else if ("file".equals(location.getProtocol())) { - Set resources = new HashSet(); + Set resources = new HashSet<>(); readSubDirectories(new File(location.toURI()), uri, resources); result.put(location, convertPathsToPackages(resources)); } @@ -910,9 +887,9 @@ public class ResourceFinder { } private Set convertPathsToPackages(Set resources) { - Set packageNames = new HashSet(resources.size()); + Set packageNames = new HashSet<>(resources.size()); for(String resource : resources) { - packageNames.add(StringUtils.chomp(StringUtils.replace(resource, "/", "."), ".")); + packageNames.add(StringUtils.removeEnd(StringUtils.replace(resource, "/", "."), ".")); } return packageNames; @@ -941,7 +918,7 @@ public class ResourceFinder { for (File file : files) { if (file.isDirectory()) { String name = file.getName(); - String subName = StringUtils.chomp(basePath, "/") + "/" + name; + String subName = StringUtils.removeEnd(basePath, "/") + "/" + name; resources.add(subName); readSubDirectories(file, subName, resources); } @@ -951,7 +928,7 @@ public class ResourceFinder { private static void readJarEntries(URL location, String basePath, Map resources) throws IOException { JarURLConnection conn = (JarURLConnection) location.openConnection(); - JarFile jarfile = null; + JarFile jarfile; jarfile = conn.getJarFile(); Enumeration entries = jarfile.entries(); @@ -977,7 +954,7 @@ public class ResourceFinder { //read directories in the jar that start with the basePath private static void readJarDirectoryEntries(URL location, String basePath, Set resources) throws IOException { JarURLConnection conn = (JarURLConnection) location.openConnection(); - JarFile jarfile = null; + JarFile jarfile; jarfile = conn.getJarFile(); Enumeration entries = jarfile.entries(); @@ -1058,7 +1035,7 @@ public class ResourceFinder { if (currentUrl == null) { continue; } - JarFile jarFile = null; + JarFile jarFile; try { String protocol = currentUrl.getProtocol(); if ("jar".equals(protocol)) { @@ -1147,10 +1124,8 @@ public class ResourceFinder { return resourceURL; } } - } catch (MalformedURLException e) { + } catch (IOException | SecurityException e) { // Keep iterating through the URL list - } catch (IOException e) { - } catch (SecurityException e) { } } return null; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java index f5de6fd2e..34e093756 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java @@ -15,24 +15,16 @@ */ package com.opensymphony.xwork2.util.finder; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; 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 java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -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.*; /** * Use with ClassFinder to filter the Urls to be scanned, example: @@ -57,7 +49,7 @@ public class UrlSet { private Set protocols; private UrlSet() { - this.urls = new HashMap(); + this.urls = new HashMap<>(); } public UrlSet(ClassLoaderInterface classLoader) throws IOException { @@ -92,21 +84,19 @@ public class UrlSet { try { this.urls.put(location.toExternalForm(), location); } catch (Exception e) { - if (LOG.isWarnEnabled()) { - LOG.warn("Cannot translate url to external form!", e); - } + LOG.warn("Cannot translate url to external form!", e); } } } public UrlSet include(UrlSet urlSet){ - Map urls = new HashMap(this.urls); + Map urls = new HashMap<>(this.urls); urls.putAll(urlSet.urls); return new UrlSet(urls); } public UrlSet exclude(UrlSet urlSet) { - Map urls = new HashMap(this.urls); + Map urls = new HashMap<>(this.urls); Map parentUrls = urlSet.urls; for (String url : parentUrls.keySet()) { urls.remove(url); @@ -148,9 +138,7 @@ public class UrlSet { public UrlSet excludeJavaHome() throws MalformedURLException { String path = System.getProperty("java.home"); if (path != null) { - File java = new File(path); - if (path.matches("/System/Library/Frameworks/JavaVM.framework/Versions/[^/]+/Home")){ java = java.getParentFile(); } @@ -173,7 +161,7 @@ public class UrlSet { } public UrlSet matching(String pattern) { - Map urls = new HashMap(); + Map urls = new HashMap<>(); for (Map.Entry entry : this.urls.entrySet()) { String url = entry.getKey(); if (url.matches(pattern)){ @@ -198,7 +186,7 @@ public class UrlSet { URL normalizedUrl = normalizer.normalizeToFileProtocol(warUrl); URL finalUrl = ObjectUtils.defaultIfNull(normalizedUrl, warUrl); - Map newUrls = new HashMap(this.urls); + Map newUrls = new HashMap<>(this.urls); if ("jar".equals(finalUrl.getProtocol()) || "file".equals(finalUrl.getProtocol())) { newUrls.put(finalUrl.toExternalForm(), finalUrl); } @@ -211,7 +199,7 @@ public class UrlSet { public UrlSet relative(File file) throws MalformedURLException { String urlPath = file.toURI().toURL().toExternalForm(); - Map urls = new HashMap(); + Map urls = new HashMap<>(); for (Map.Entry entry : this.urls.entrySet()) { String url = entry.getKey(); if (url.startsWith(urlPath) || url.startsWith("jar:"+urlPath)){ @@ -222,11 +210,11 @@ public class UrlSet { } public List getUrls() { - return new ArrayList(urls.values()); + return new ArrayList<>(urls.values()); } private List getUrls(ClassLoaderInterface classLoader) throws IOException { - List list = new ArrayList(); + List list = new ArrayList<>(); //find jars ArrayList urls = Collections.list(classLoader.getResources("META-INF")); @@ -253,7 +241,7 @@ public class UrlSet { return getUrls(classLoader); } - List list = new ArrayList(); + List list = new ArrayList<>(); //find jars ArrayList urls = Collections.list(classLoader.getResources("META-INF")); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java index 42d2a38ca..86fda9b2e 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java @@ -16,18 +16,14 @@ package com.opensymphony.xwork2.util.fs; import com.opensymphony.xwork2.FileManager; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -90,9 +86,7 @@ public class DefaultFileManager implements FileManager { public void monitorFile(URL fileUrl) { String fileName = fileUrl.toString(); Revision revision; - if (LOG.isDebugEnabled()) { - LOG.debug("Creating revision for URL: " + fileName); - } + LOG.debug("Creating revision for URL: {}", fileName); if (isJarURL(fileUrl)) { revision = JarEntryRevision.build(fileUrl, this); } else { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java index 7c872f310..c19385fd1 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java @@ -5,8 +5,8 @@ import com.opensymphony.xwork2.FileManagerFactory; import com.opensymphony.xwork2.XWorkConstants; 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 java.util.HashSet; import java.util.Set; @@ -52,8 +52,8 @@ public class DefaultFileManagerFactory implements FileManagerFactory { private FileManager lookupFileManager() { Set names = container.getInstanceNames(FileManager.class); LOG.debug("Found following implementations of FileManager interface: {}", names); - Set internals = new HashSet(); - Set users = new HashSet(); + Set internals = new HashSet<>(); + Set users = new HashSet<>(); for (String fmName : names) { FileManager fm = container.getInstance(FileManager.class, fmName); if (fm.internal()) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java index 9b41eb1a6..8df44f3c6 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java @@ -28,7 +28,7 @@ public class LocatableProperties extends Properties implements Locatable { public LocatableProperties(Location loc) { super(); this.location = loc; - this.propLocations = new HashMap(); + this.propLocations = new HashMap<>(); } @Override @@ -48,7 +48,7 @@ public class LocatableProperties extends Properties implements Locatable { String convertCommentsToString(List lines) { StringBuilder sb = new StringBuilder(); - if (lines != null && lines.size() > 0) { + if (lines != null && !lines.isEmpty()) { for (String line : lines) { sb.append(line).append('\n'); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java index 3a1974f75..ca101ca21 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java @@ -15,6 +15,8 @@ */ package com.opensymphony.xwork2.util.location; +import org.apache.commons.lang3.StringUtils; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -53,7 +55,7 @@ public class LocationImpl implements Location, Serializable { * @param column the column number (starts at 1) */ public LocationImpl(String description, String uri, int line, int column) { - if (uri == null || uri.length() == 0) { + if (StringUtils.isEmpty(uri)) { this.uri = null; this.line = -1; this.column = -1; @@ -62,11 +64,7 @@ public class LocationImpl implements Location, Serializable { this.line = line; this.column = column; } - - if (description != null && description.length() == 0) { - description = null; - } - this.description = description; + this.description = StringUtils.trimToNull(description); } /** @@ -147,7 +145,7 @@ public class LocationImpl implements Location, Serializable { * @param padding The amount of lines before and after the error to include */ public List getSnippet(int padding) { - List snippet = new ArrayList(); + List snippet = new ArrayList<>(); if (getLineNumber() > 0) { try { InputStream in = new URL(getURI()).openStream(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java index fd2c55d4b..892d3c7e1 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java @@ -36,8 +36,8 @@ public class LocationUtils { * The string representation of an unknown location: "[unknown location]". */ public static final String UNKNOWN_STRING = "[unknown location]"; - - private static List> finders = new ArrayList>(); + + private static List> finders = new ArrayList<>(); /** * An finder or object locations @@ -182,7 +182,7 @@ public class LocationUtils { synchronized(LocationFinder.class) { // Update a clone of the current finder list to avoid breaking // any iteration occuring in another thread. - List> newFinders = new ArrayList>(finders); + List> newFinders = new ArrayList<>(finders); newFinders.add(new WeakReference(finder)); finders = newFinders; } @@ -259,7 +259,7 @@ public class LocationUtils { // This finder was garbage collected: update finders synchronized(LocationFinder.class) { // Update a clone of the current list to avoid breaking current iterations - List> newFinders = new ArrayList>(finders); + List> newFinders = new ArrayList<>(finders); newFinders.remove(ref); finders = newFinders; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java index d374a2c0c..743811383 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java @@ -34,13 +34,12 @@ import java.lang.reflect.Proxy; /** * @author Scott Farquhar */ -public class ObjectProfiler -{ +public class ObjectProfiler { /** * Given a class, and an interface that it implements, return a proxied version of the class that implements * the interface. - *

+ *

* The usual use of this is to profile methods from Factory objects: *

      * public PersistenceManager getPersistenceManager()
@@ -54,28 +53,25 @@ public class ObjectProfiler
      *   return ObjectProfiler.getProfiledObject(PersistenceManager.class, new DefaultPersistenceManager());
      * }
      * 
- *

+ *

* A side effect of this is that you will no longer be able to downcast to DefaultPersistenceManager. This is probably a *good* thing. * - * @param interfaceClazz The interface to implement. - * @param o The object to proxy - * @return A proxied object, or the input object if the interfaceClazz wasn't an interface. + * @param interfaceClazz The interface to implement. + * @param o The object to proxy + * @return A proxied object, or the input object if the interfaceClazz wasn't an interface. */ - public static Object getProfiledObject(Class interfaceClazz, Object o) - { + public static Object getProfiledObject(Class interfaceClazz, Object o) { //if we are not active - then do nothing - if (!UtilTimerStack.isActive()) + if (!UtilTimerStack.isActive()) { return o; + } //this should always be true - you shouldn't be passing something that isn't an interface - if (interfaceClazz.isInterface()) - { + if (interfaceClazz.isInterface()) { InvocationHandler timerHandler = new TimerInvocationHandler(o); return Proxy.newProxyInstance(interfaceClazz.getClassLoader(), new Class[]{interfaceClazz}, timerHandler); - } - else - { + } else { return o; } } @@ -84,34 +80,27 @@ public class ObjectProfiler * A profiled call {@link Method#invoke(java.lang.Object, java.lang.Object[])}. If {@link UtilTimerStack#isActive() } * returns false, then no profiling is performed. */ - public static Object profiledInvoke(Method target, Object value, Object[] args) throws IllegalAccessException, InvocationTargetException - { + public static Object profiledInvoke(Method target, Object value, Object[] args) throws IllegalAccessException, InvocationTargetException { //if we are not active - then do nothing - if (!UtilTimerStack.isActive()) + if (!UtilTimerStack.isActive()) { return target.invoke(value, args); + } String logLine = new String(getTrimmedClassName(target) + "." + target.getName() + "()"); UtilTimerStack.push(logLine); - try - { + try { Object returnValue = target.invoke(value, args); //if the return value is an interface then we should also proxy it! - if (returnValue != null && target.getReturnType().isInterface()) - { -// System.out.println("Return type " + returnValue.getClass().getName() + " is being proxied " + target.getReturnType().getName() + " " + logLine); + if (returnValue != null && target.getReturnType().isInterface()) { InvocationHandler timerHandler = new TimerInvocationHandler(returnValue); return Proxy.newProxyInstance(returnValue.getClass().getClassLoader(), new Class[]{target.getReturnType()}, timerHandler); - } - else - { + } else { return returnValue; } - } - finally - { + } finally { UtilTimerStack.pop(logLine); } } @@ -119,27 +108,24 @@ public class ObjectProfiler /** * Given a method, get the Method name, with no package information. */ - public static String getTrimmedClassName(Method method) - { + public static String getTrimmedClassName(Method method) { String classname = method.getDeclaringClass().getName(); return classname.substring(classname.lastIndexOf('.') + 1); } } -class TimerInvocationHandler implements InvocationHandler -{ +class TimerInvocationHandler implements InvocationHandler { protected Object target; - public TimerInvocationHandler(Object target) - { - if (target == null) + public TimerInvocationHandler(Object target) { + if (target == null) { throw new IllegalArgumentException("Target Object passed to timer cannot be null"); + } this.target = target; } - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return ObjectProfiler.profiledInvoke(method, target, args); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java index 35baaa4d4..a475c62bc 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java @@ -34,14 +34,13 @@ import java.util.List; * * @author Mike Cannon-Brookes * @author Scott Farquhar - * * @version $Date$ $Id$ */ public class ProfilingTimerBean implements java.io.Serializable { - - private static final long serialVersionUID = -6180672043920208784L; - - List children = new ArrayList(); + + private static final long serialVersionUID = -6180672043920208784L; + + List children = new ArrayList<>(); ProfilingTimerBean parent = null; String resource; @@ -49,41 +48,34 @@ public class ProfilingTimerBean implements java.io.Serializable { long startTime; long totalTime; - public ProfilingTimerBean(String resource) - { + public ProfilingTimerBean(String resource) { this.resource = resource; } - protected void addParent(ProfilingTimerBean parent) - { + protected void addParent(ProfilingTimerBean parent) { this.parent = parent; } - public ProfilingTimerBean getParent() - { + public ProfilingTimerBean getParent() { return parent; } - public void addChild(ProfilingTimerBean child) - { + public void addChild(ProfilingTimerBean child) { children.add(child); child.addParent(this); } - public void setStartTime() - { + public void setStartTime() { this.startTime = System.currentTimeMillis(); } - public void setEndTime() - { + public void setEndTime() { this.totalTime = System.currentTimeMillis() - startTime; } - public String getResource() - { + public String getResource() { return resource; } @@ -91,16 +83,13 @@ public class ProfilingTimerBean implements java.io.Serializable { * Get a formatted string representing all the methods that took longer than a specified time. */ - public String getPrintable(long minTime) - { + public String getPrintable(long minTime) { return getPrintable("", minTime); } - protected String getPrintable(String indent, long minTime) - { + protected String getPrintable(String indent, long minTime) { //only print the value if we are larger or equal to the min time. - if (totalTime >= minTime) - { + if (totalTime >= minTime) { StringBuilder buffer = new StringBuilder(); buffer.append(indent); buffer.append("[" + totalTime + "ms] - " + resource); @@ -111,8 +100,7 @@ public class ProfilingTimerBean implements java.io.Serializable { } return buffer.toString(); - } - else + } else return ""; } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java index d9bbf2712..7fb7ae2fa 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java @@ -26,204 +26,204 @@ */ package com.opensymphony.xwork2.util.profiling; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * A timer stack. - * - *

- * + *

+ *

+ *

* - * + *

* Struts2 profiling aspects involves the following :- *

    - *
  • ActionContextCleanUp
  • - *
  • FreemarkerPageFilter
  • - *
  • DispatcherFilter
  • - *
      - *
    • Dispatcher
    • - *
        - *
      • creation of DefaultActionProxy
      • - *
          - *
        • creation of DefaultActionInvocation
        • - *
            - *
          • creation of Action
          • - *
          - *
        - *
      • execution of DefaultActionProxy
      • - *
          - *
        • invocation of DefaultActionInvocation
        • - *
            - *
          • invocation of Interceptors
          • - *
          • invocation of Action
          • - *
          • invocation of PreResultListener
          • - *
          • invocation of Result
          • - *
          - *
        - *
      - *
    + *
  • ActionContextCleanUp
  • + *
  • FreemarkerPageFilter
  • + *
  • DispatcherFilter
  • + *
      + *
    • Dispatcher
    • + *
        + *
      • creation of DefaultActionProxy
      • + *
          + *
        • creation of DefaultActionInvocation
        • + *
            + *
          • creation of Action
          • *
          - * + *
        + *
      • execution of DefaultActionProxy
      • + *
          + *
        • invocation of DefaultActionInvocation
        • + *
            + *
          • invocation of Interceptors
          • + *
          • invocation of Action
          • + *
          • invocation of PreResultListener
          • + *
          • invocation of Result
          • + *
          + *
        + *
      + *
    + *
+ *

* - * - * + *

+ *

* - * + *

* XWork2 profiling aspects involves the following :- *

    - *
      - *
    • creation of DefaultActionProxy
    • - *
        - *
      • creation of DefaultActionInvocation
      • - *
          - *
        • creation of Action
        • - *
        - *
      - *
    • execution of DefaultActionProxy
    • - *
        - *
      • invocation of DefaultActionInvocation
      • - *
          - *
        • invocation of Interceptors
        • - *
        • invocation of Action
        • - *
        • invocation of PreResultListener
        • - *
        • invocation of Result
        • - *
        - *
      - *
    + *
      + *
    • creation of DefaultActionProxy
    • + *
        + *
      • creation of DefaultActionInvocation
      • + *
          + *
        • creation of Action
        • + *
        + *
      + *
    • execution of DefaultActionProxy
    • + *
        + *
      • invocation of DefaultActionInvocation
      • + *
          + *
        • invocation of Interceptors
        • + *
        • invocation of Action
        • + *
        • invocation of PreResultListener
        • + *
        • invocation of Result
        • + *
        + *
      + *
    *
- * - * - * - * - * - * - * Activating / Deactivating of the profiling feature could be done through:- - * - * - * *

- * + * + *

+ *

+ * + *

+ * Activating / Deactivating of the profiling feature could be done through:- + *

+ * + *

+ *

+ *

* System properties:-

*

  * 
- * 
+ *
  *  -Dxwork.profile.activate=true
- *  
- *  
+ *
+ * 
  * 
- * + *

* - * - * This could be done in the container startup script eg. CATALINA_OPTS in catalina.sh - * (tomcat) or using "java -Dxwork.profile.activate=true -jar start.jar" (jetty) - * + *

+ * This could be done in the container startup script eg. CATALINA_OPTS in catalina.sh + * (tomcat) or using "java -Dxwork.profile.activate=true -jar start.jar" (jetty) + *

* - * + *

*

* Code :-

*

  * 
- *   
+ *
  *  UtilTimerStack.setActivate(true);
- *    
- *  
+ *
+ * 
  * 
- * - * - * - * - * - * This could be done in a static block, in a Spring bean with lazy-init="false", - * in a Servlet with init-on-startup as some numeric value, in a Filter or - * Listener's init method etc. - * - * - * *

- * Parameter:- - * + *

+ *

+ * + *

+ * This could be done in a static block, in a Spring bean with lazy-init="false", + * in a Servlet with init-on-startup as some numeric value, in a Filter or + * Listener's init method etc. + *

+ * + *

+ *

+ * Parameter:- + *

*

  * 
- * 
- * <action ... >  
+ *
+ * <action ... >
  *  ...
  *  <interceptor-ref name="profiling">
  *      <param name="profilingKey">profiling</param>
  *  </interceptor-ref>
  *  ...
  * </action>
- * 
- * or 
- * 
+ *
+ * or
+ *
  * <action .... >
  * ...
  *  <interceptor-ref name="profiling" />
  * ...
  * </action>
- * 
+ *
  * through url
- * 
+ *
  * http://host:port/context/namespace/someAction.action?profiling=true
- * 
+ *
  * through code
- * 
+ *
  * ActionContext.getContext().getParameters().put("profiling", "true);
- * 
+ *
  * 
  * 
- * - * + *

+ *

* - * - * To use profiling activation through parameter, one will need to pass in through - * the 'profiling' parameter (which is the default) and could be changed through - * the param tag in the interceptor-ref. - * + *

+ * To use profiling activation through parameter, one will need to pass in through + * the 'profiling' parameter (which is the default) and could be changed through + * the param tag in the interceptor-ref. + *

* - * + *

*

* Warning:

* - * - * Profiling activation through a parameter requires the following: - * - *

    - *
  • Profiling interceptor in interceptor stack
  • - *
  • dev mode on (struts.devMode=true in struts.properties) - *
- * - * - * *

- * + * Profiling activation through a parameter requires the following: + *

+ *

    + *
  • Profiling interceptor in interceptor stack
  • + *
  • dev mode on (struts.devMode=true in struts.properties) + *
+ *

+ * + *

+ *

+ *

* - * + *

* One could filter out the profile logging by having a System property as follows. With this - * 'xwork.profile.mintime' property, one could only log profile information when its execution time - * exceed those specified in 'xwork.profile.mintime' system property. If no such property is specified, + * 'xwork.profile.mintime' property, one could only log profile information when its execution time + * exceed those specified in 'xwork.profile.mintime' system property. If no such property is specified, * it will be assumed to be 0, hence all profile information will be logged. - * + *

* - * + *

*

  * 
- * 
+ *
  *  -Dxwork.profile.mintime=10000
- * 
+ *
  * 
  * 
- * + *

* - * - * One could extend the profiling feature provided by Struts2 in their web application as well. - * + *

+ * One could extend the profiling feature provided by Struts2 in their web application as well. + *

* - * + *

*

  * 
- * 
+ *
  *    String logMessage = "Log message";
  *    UtilTimerStack.push(logMessage);
  *    try {
@@ -232,43 +232,42 @@ import org.apache.logging.log4j.LogManager;
  *    finally {
  *        UtilTimerStack.pop(logMessage); // this needs to be the same text as above
  *    }
- *    
- *    
+ *
+ * 
  * 
- * - * or - * + *

+ * or + *

*

  * 
- * 
- *   String result = UtilTimerStack.profile("purchaseItem: ", 
+ *
+ *   String result = UtilTimerStack.profile("purchaseItem: ",
  *       new UtilTimerStack.ProfilingBlock() {
  *            public String doProfiling() {
  *               // do some code
  *               return "Ok";
  *            }
  *       });
- *       
- *       
+ *
+ * 
  * 
- * - * + *

+ *

* - * - * Profiled result is logged using commons-logging under the logger named + *

+ * Profiled result is logged using commons-logging under the logger named * 'com.opensymphony.xwork2.util.profiling.UtilTimerStack'. Depending on the underlying logging implementation - * say if it is Log4j, one could direct the log to appear in a different file, being emailed to someone or have + * say if it is Log4j, one could direct the log to appear in a different file, being emailed to someone or have * it stored in the db. - * + *

* - * + * * @version $Date$ $Id$ */ -public class UtilTimerStack -{ +public class UtilTimerStack { // A reference to the current ProfilingTimerBean - protected static ThreadLocal current = new ThreadLocal(); + protected static ThreadLocal current = new ThreadLocal<>(); /** * System property that controls whether this timer should be used or not. Set to "true" activates @@ -281,7 +280,7 @@ public class UtilTimerStack * created. */ public static final String MIN_TIME = "xwork.profile.mintime"; - + private static final Logger LOG = LogManager.getLogger(UtilTimerStack.class); /** @@ -294,15 +293,15 @@ public class UtilTimerStack } /** - * Create and start a performance profiling with the name given. Deal with + * Create and start a performance profiling with the name given. Deal with * profile hierarchy automatically, so caller don't have to be concern about it. - * + * * @param name profile name */ - public static void push(String name) - { - if (!isActive()) + public static void push(String name) { + if (!isActive()) { return; + } //create a new timer and start it ProfilingTimerBean newTimer = new ProfilingTimerBean(name); @@ -310,8 +309,7 @@ public class UtilTimerStack //if there is a current timer - add the new timer as a child of it ProfilingTimerBean currentTimer = (ProfilingTimerBean) current.get(); - if (currentTimer != null) - { + if (currentTimer != null) { currentTimer.addChild(newTimer); } @@ -322,116 +320,96 @@ public class UtilTimerStack /** * End a preformance profiling with the name given. Deal with * profile hierarchy automatically, so caller don't have to be concern about it. - * + * * @param name profile name */ - public static void pop(String name) - { - if (!isActive()) + public static void pop(String name) { + if (!isActive()) { return; + } - ProfilingTimerBean currentTimer = (ProfilingTimerBean) current.get(); + ProfilingTimerBean currentTimer = current.get(); //if the timers are matched up with each other (ie push("a"); pop("a")); - if (currentTimer != null && name != null && name.equals(currentTimer.getResource())) - { + if (currentTimer != null && name != null && name.equals(currentTimer.getResource())) { currentTimer.setEndTime(); ProfilingTimerBean parent = currentTimer.getParent(); //if we are the root timer, then print out the times - if (parent == null) - { + if (parent == null) { printTimes(currentTimer); current.set(null); //for those servers that use thread pooling - } - else - { + } else { current.set(parent); } - } - else - { + } else { //if timers are not matched up, then print what we have, and then print warning. - if (currentTimer != null) - { + if (currentTimer != null) { printTimes(currentTimer); current.set(null); //prevent printing multiple times - if (LOG.isWarnEnabled()) { - LOG.warn("Unmatched Timer. Was expecting " + currentTimer.getResource() + ", instead got " + name); - } + LOG.warn("Unmatched Timer. Was expecting {}, instead got {}", currentTimer.getResource(), name); } } - - } /** * Do a log (at INFO level) of the time taken for this particular profiling. - * + * * @param currentTimer profiling timer bean */ - private static void printTimes(ProfilingTimerBean currentTimer) - { - if (LOG.isInfoEnabled()) { - LOG.info(currentTimer.getPrintable(getMinTime())); - } + private static void printTimes(ProfilingTimerBean currentTimer) { + LOG.info(currentTimer.getPrintable(getMinTime())); } /** * Get the min time for this profiling, it searches for a System property * 'xwork.profile.mintime' and default to 0. - * + * * @return long */ - private static long getMinTime() - { - try - { + private static long getMinTime() { + try { return Long.parseLong(System.getProperty(MIN_TIME, "0")); - } - catch (NumberFormatException e) - { - return -1; + } catch (NumberFormatException e) { + return -1; } } /** * Determine if profiling is being activated, by searching for a system property * 'xwork.profile.activate', default to false (profiling is off). - * + * * @return true, if active, false otherwise. */ - public static boolean isActive() - { + public static boolean isActive() { return active; } /** * Turn profiling on or off. - * + * * @param active */ - public static void setActive(boolean active) - { - if (active) + public static void setActive(boolean active) { + if (active) { System.setProperty(ACTIVATE_PROPERTY, "true"); - else - System.clearProperty(ACTIVATE_PROPERTY); - - UtilTimerStack.active = active; + } else { + System.clearProperty(ACTIVATE_PROPERTY); + } + UtilTimerStack.active = active; } /** - * A convenience method that allows block of code subjected to profiling to be executed - * and avoid the need of coding boiler code that does pushing (UtilTimeBean.push(...)) and + * A convenience method that allows block of code subjected to profiling to be executed + * and avoid the need of coding boiler code that does pushing (UtilTimeBean.push(...)) and * poping (UtilTimerBean.pop(...)) in a try ... finally ... block. - * *

- * + *

+ *

* Example of usage: *

      * 	 // we need a returning result
-     *   String result = UtilTimerStack.profile("purchaseItem: ", 
+     *   String result = UtilTimerStack.profile("purchaseItem: ",
      *       new UtilTimerStack.ProfilingBlock() {
      *            public String doProfiling() {
      *               getMyService().purchaseItem(....)
@@ -442,7 +420,7 @@ public class UtilTimerStack
      * or
      * 
      *   // we don't need a returning result
-     *   UtilTimerStack.profile("purchaseItem: ", 
+     *   UtilTimerStack.profile("purchaseItem: ",
      *       new UtilTimerStack.ProfilingBlock() {
      *            public String doProfiling() {
      *               getMyService().purchaseItem(....)
@@ -450,40 +428,38 @@ public class UtilTimerStack
      *            }
      *       });
      * 
- * - * @param any return value if there's one. - * @param name profile name + * + * @param any return value if there's one. + * @param name profile name * @param block code block subjected to profiling * @return T * @throws Exception */ public static T profile(String name, ProfilingBlock block) throws Exception { - UtilTimerStack.push(name); - try { - return block.doProfiling(); - } - finally { - UtilTimerStack.pop(name); - } + UtilTimerStack.push(name); + try { + return block.doProfiling(); + } finally { + UtilTimerStack.pop(name); + } } - + /** * A callback interface where code subjected to profile is to be executed. This eliminates the need * of coding boiler code that does pushing (UtilTimerBean.push(...)) and poping (UtilTimerBean.pop(...)) * in a try ... finally ... block. - * - * @version $Date$ $Id$ - * + * * @param + * @version $Date$ $Id$ */ public static interface ProfilingBlock { - - /** - * Method that execute the code subjected to profiling. - * - * @return profiles Type - * @throws Exception - */ - T doProfiling() throws Exception; + + /** + * Method that execute the code subjected to profiling. + * + * @return profiles Type + * @throws Exception + */ + T doProfiling() throws Exception; } } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java index 60fd456f9..9de464b26 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java @@ -29,11 +29,14 @@ import java.util.Map; */ public class ReflectionContextState { + private static final String GETTING_BY_KEY_PROPERTY = "xwork.getting.by.key.property"; + private static final String SET_MAP_KEY = "set.map.key"; + public static final String CURRENT_PROPERTY_PATH="current.property.path"; public static final String FULL_PROPERTY_PATH="current.property.path"; - private static final String GETTING_BY_KEY_PROPERTY="xwork.getting.by.key.property"; - - private static final String SET_MAP_KEY="set.map.key"; + public static final String CREATE_NULL_OBJECTS = "xwork.NullHandler.createNullObjects"; + public static final String DENY_METHOD_EXECUTION = "xwork.MethodAccessor.denyMethodExecution"; + public static final String DENY_INDEXED_ACCESS_EXECUTION = "xwork.IndexedPropertyAccessor.denyMethodExecution"; public static boolean isCreatingNullObjects(Map context) { //TODO @@ -126,7 +129,7 @@ public class ReflectionContextState { public static void setSetMap(Map context, Map setMap, String path) { Map> mapOfSetMaps=(Map)context.get(SET_MAP_KEY); if (mapOfSetMaps==null) { - mapOfSetMaps=new HashMap>(); + mapOfSetMaps = new HashMap<>(); context.put(SET_MAP_KEY, mapOfSetMaps); } mapOfSetMaps.put(path, setMap); @@ -157,7 +160,6 @@ public class ReflectionContextState { } - public static void clear(Map context) { if (context != null) { context.put(XWorkConverter.LAST_BEAN_CLASS_ACCESSED,null); @@ -168,12 +170,4 @@ public class ReflectionContextState { } } - - - public static final String CREATE_NULL_OBJECTS = "xwork.NullHandler.createNullObjects"; - public static final String DENY_METHOD_EXECUTION = "xwork.MethodAccessor.denyMethodExecution"; - public static final String DENY_INDEXED_ACCESS_EXECUTION = "xwork.IndexedPropertyAccessor.denyMethodExecution"; - - - } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java index b1c475d8b..e98f8ee66 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java @@ -16,32 +16,19 @@ package com.opensymphony.xwork2.validator; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.ActionInvocation; -import com.opensymphony.xwork2.ActionProxy; -import com.opensymphony.xwork2.FileManager; -import com.opensymphony.xwork2.FileManagerFactory; -import com.opensymphony.xwork2.XWorkConstants; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.entities.ActionConfig; 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 com.opensymphony.xwork2.validator.validators.VisitorFieldValidator; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; /** * AnnotationActionValidatorManager is the entry point into XWork's annotations-based validator framework. @@ -108,7 +95,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager ValueStack stack = ActionContext.getContext().getValueStack(); // create clean instances of the validators for the caller's use - ArrayList validators = new ArrayList(cfgs.size()); + ArrayList validators = new ArrayList<>(cfgs.size()); for (ValidatorConfig cfg : cfgs) { if (method == null || method.equals(cfg.getParams().get("methodName"))) { Validator validator = validatorFactory.getValidator( @@ -145,9 +132,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager try { validator.setValidatorContext(validatorContext); - if (LOG.isDebugEnabled()) { - LOG.debug("Running validator: " + validator + " for object " + object + " and method " + method); - } + LOG.debug("Running validator: {} for object {} and method {}", validator, object, method); FieldValidator fValidator = null; String fullFieldName = null; @@ -157,10 +142,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager fullFieldName = fValidator.getValidatorContext().getFullFieldName(fValidator.getFieldName()); if ((shortcircuitedFields != null) && shortcircuitedFields.contains(fullFieldName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuited, skipping"); - } - + LOG.debug("Short-circuited, skipping"); continue; } } @@ -174,14 +156,14 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager Collection fieldErrors = validatorContext.getFieldErrors().get(fullFieldName); if (fieldErrors != null) { - errs = new ArrayList(fieldErrors); + errs = new ArrayList<>(fieldErrors); } } } else if (validatorContext.hasActionErrors()) { Collection actionErrors = validatorContext.getActionErrors(); if (actionErrors != null) { - errs = new ArrayList(actionErrors); + errs = new ArrayList<>(actionErrors); } } @@ -192,9 +174,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager Collection errCol = validatorContext.getFieldErrors().get(fullFieldName); if ((errCol != null) && !errCol.equals(errs)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuiting on field validation"); - } + LOG.debug("Short-circuiting on field validation"); if (shortcircuitedFields == null) { shortcircuitedFields = new TreeSet(); @@ -207,10 +187,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager Collection errCol = validatorContext.getActionErrors(); if ((errCol != null) && !errCol.equals(errs)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuiting"); - } - + LOG.debug("Short-circuiting"); break; } } @@ -276,11 +253,11 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager String fileName = aClass.getName().replace('.', '/') + VALIDATION_CONFIG_SUFFIX; - List result = new ArrayList(loadFile(fileName, aClass, checkFile)); + List result = new ArrayList<>(loadFile(fileName, aClass, checkFile)); AnnotationValidationConfigurationBuilder builder = new AnnotationValidationConfigurationBuilder(validatorFactory); - List annotationResult = new ArrayList(builder.buildAnnotationClassValidatorConfigs(aClass)); + List annotationResult = new ArrayList<>(builder.buildAnnotationClassValidatorConfigs(aClass)); result.addAll(annotationResult); @@ -331,10 +308,10 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager * @return a list of validator configs for the given class and context. */ private List buildValidatorConfigs(Class clazz, String context, boolean checkFile, Set checked) { - List validatorConfigs = new ArrayList(); + List validatorConfigs = new ArrayList<>(); if (checked == null) { - checked = new TreeSet(); + checked = new TreeSet<>(); } else if (checked.contains(clazz.getName())) { return validatorConfigs; } @@ -385,24 +362,12 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager URL fileUrl = ClassLoaderUtil.getResource(fileName, clazz); if ((checkFile && fileManager.fileNeedsReloading(fileUrl)) || !validatorFileCache.containsKey(fileName)) { - InputStream is = null; - - try { - is = fileManager.loadFile(fileUrl); - + try (InputStream is = fileManager.loadFile(fileUrl)) { if (is != null) { - retList = new ArrayList(validatorFileParser.parseActionValidatorConfigs(validatorFactory, is, fileName)); - } - } catch (Exception e) { - LOG.error("Caught exception while loading file " + fileName, e); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - LOG.error("Unable to close input stream for " + fileName, e); - } + retList = new ArrayList<>(validatorFileParser.parseActionValidatorConfigs(validatorFactory, is, fileName)); } + } catch (IOException e) { + LOG.error("Caught exception while loading file {}", fileName, e); } validatorFileCache.put(fileName, retList); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationValidationConfigurationBuilder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationValidationConfigurationBuilder.java index dbd897524..dc8d856e2 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationValidationConfigurationBuilder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationValidationConfigurationBuilder.java @@ -15,25 +15,7 @@ */ package com.opensymphony.xwork2.validator; -import com.opensymphony.xwork2.validator.annotations.ConditionalVisitorFieldValidator; -import com.opensymphony.xwork2.validator.annotations.ConversionErrorFieldValidator; -import com.opensymphony.xwork2.validator.annotations.CustomValidator; -import com.opensymphony.xwork2.validator.annotations.DateRangeFieldValidator; -import com.opensymphony.xwork2.validator.annotations.DoubleRangeFieldValidator; -import com.opensymphony.xwork2.validator.annotations.EmailValidator; -import com.opensymphony.xwork2.validator.annotations.ExpressionValidator; -import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator; -import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator; -import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator; -import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator; -import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator; -import com.opensymphony.xwork2.validator.annotations.ShortRangeFieldValidator; -import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator; -import com.opensymphony.xwork2.validator.annotations.UrlValidator; -import com.opensymphony.xwork2.validator.annotations.Validation; -import com.opensymphony.xwork2.validator.annotations.ValidationParameter; -import com.opensymphony.xwork2.validator.annotations.Validations; -import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator; +import com.opensymphony.xwork2.validator.annotations.*; import org.apache.commons.lang3.StringUtils; import java.lang.annotation.Annotation; @@ -41,12 +23,7 @@ import java.lang.reflect.Method; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -70,7 +47,7 @@ public class AnnotationValidationConfigurationBuilder { private List processAnnotations(Object o) { - List result = new ArrayList(); + List result = new ArrayList<>(); String fieldName = null; String methodName = null; @@ -96,7 +73,6 @@ public class AnnotationValidationConfigurationBuilder { // Process collection of custom validations if (a instanceof Validations) { processValidationAnnotation(a, fieldName, methodName, result); - } // Process single custom validator @@ -377,7 +353,7 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processExpressionValidatorAnnotation(ExpressionValidator v, String fieldName, String methodName) { String validatorType = "expression"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); @@ -398,32 +374,28 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processCustomValidatorAnnotation(CustomValidator v, String fieldName, String methodName) { - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } String validatorType = v.type(); - validatorFactory.lookupRegisteredValidatorType(validatorType); Annotation[] recursedAnnotations = v.parameters(); if (recursedAnnotations != null) { for (Annotation a2 : recursedAnnotations) { - if (a2 instanceof ValidationParameter) { - ValidationParameter parameter = (ValidationParameter) a2; String parameterName = parameter.name(); String parameterValue = parameter.value(); params.put(parameterName, parameterValue); } - } } @@ -440,11 +412,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processRegexFieldValidatorAnnotation(RegexFieldValidator v, String fieldName, String methodName) { String validatorType = "regex"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -469,11 +441,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processConditionalVisitorFieldValidatorAnnotation(ConditionalVisitorFieldValidator v, String fieldName, String methodName) { String validatorType = "conditionalvisitor"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -496,11 +468,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processVisitorFieldValidatorAnnotation(VisitorFieldValidator v, String fieldName, String methodName) { String validatorType = "visitor"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -521,11 +493,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processUrlValidatorAnnotation(UrlValidator v, String fieldName, String methodName) { String validatorType = "url"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } if (StringUtils.isNotEmpty(v.urlRegex())) { @@ -549,7 +521,7 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processStringLengthFieldValidatorAnnotation(StringLengthFieldValidator v, String fieldName, String methodName) { String validatorType = "stringlength"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); @@ -609,11 +581,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processRequiredStringValidatorAnnotation(RequiredStringValidator v, String fieldName, String methodName) { String validatorType = "requiredstring"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -633,11 +605,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processRequiredFieldValidatorAnnotation(RequiredFieldValidator v, String fieldName, String methodName) { String validatorType = "required"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -655,11 +627,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processIntRangeFieldValidatorAnnotation(IntRangeFieldValidator v, String fieldName, String methodName) { String validatorType = "int"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -690,11 +662,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processShortRangeFieldValidatorAnnotation(ShortRangeFieldValidator v, String fieldName, String methodName) { String validatorType = "short"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -725,7 +697,7 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processDoubleRangeFieldValidatorAnnotation(DoubleRangeFieldValidator v, String fieldName, String methodName) { String validatorType = "double"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); @@ -775,11 +747,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processFieldExpressionValidatorAnnotation(FieldExpressionValidator v, String fieldName, String methodName) { String validatorType = "fieldexpression"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -799,11 +771,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processEmailValidatorAnnotation(EmailValidator v, String fieldName, String methodName) { String validatorType = "email"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -821,7 +793,7 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processDateRangeFieldValidatorAnnotation(DateRangeFieldValidator v, String fieldName, String methodName) { String validatorType = "date"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); @@ -858,11 +830,11 @@ public class AnnotationValidationConfigurationBuilder { private ValidatorConfig processConversionErrorFieldValidatorAnnotation(ConversionErrorFieldValidator v, String fieldName, String methodName) { String validatorType = "conversion"; - Map params = new HashMap(); + Map params = new HashMap<>(); if (fieldName != null) { params.put("fieldName", fieldName); - } else if (v.fieldName() != null && v.fieldName().length() > 0) { + } else if (StringUtils.isNotEmpty(v.fieldName())) { params.put("fieldName", v.fieldName()); } @@ -880,7 +852,7 @@ public class AnnotationValidationConfigurationBuilder { public List buildAnnotationClassValidatorConfigs(Class aClass) { - List result = new ArrayList(); + List result = new ArrayList<>(); List temp = processAnnotations(aClass); if (temp != null) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultActionValidatorManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultActionValidatorManager.java index f139401d3..d9d740141 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultActionValidatorManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultActionValidatorManager.java @@ -22,9 +22,8 @@ import com.opensymphony.xwork2.XWorkConstants; 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 com.opensymphony.xwork2.validator.validators.VisitorFieldValidator; +import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; @@ -98,7 +97,7 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { List cfgs = validatorCache.get(validatorKey); // create clean instances of the validators for the caller's use - ArrayList validators = new ArrayList(cfgs.size()); + ArrayList validators = new ArrayList<>(cfgs.size()); for (ValidatorConfig cfg : cfgs) { if (method == null || method.equals(cfg.getParams().get("methodName"))) { Validator validator = validatorFactory.getValidator(cfg); @@ -131,9 +130,7 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { try { validator.setValidatorContext(validatorContext); - if (LOG.isDebugEnabled()) { - LOG.debug("Running validator: " + validator + " for object " + object + " and method " + method); - } + LOG.debug("Running validator: {} for object {} and method {}", validator, object, method); FieldValidator fValidator = null; String fullFieldName = null; @@ -143,10 +140,7 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { fullFieldName = fValidator.getValidatorContext().getFullFieldName(fValidator.getFieldName()); if ((shortcircuitedFields != null) && shortcircuitedFields.contains(fullFieldName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuited, skipping"); - } - + LOG.debug("Short-circuited, skipping"); continue; } } @@ -160,7 +154,7 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { Collection fieldErrors = validatorContext.getFieldErrors().get(fullFieldName); if (fieldErrors != null) { - errs = new ArrayList(fieldErrors); + errs = new ArrayList<>(fieldErrors); } } } else if (validatorContext.hasActionErrors()) { @@ -178,12 +172,10 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { Collection errCol = validatorContext.getFieldErrors().get(fullFieldName); if ((errCol != null) && !errCol.equals(errs)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuiting on field validation"); - } + LOG.debug("Short-circuiting on field validation"); if (shortcircuitedFields == null) { - shortcircuitedFields = new TreeSet(); + shortcircuitedFields = new TreeSet<>(); } shortcircuitedFields.add(fullFieldName); @@ -193,14 +185,10 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { Collection errCol = validatorContext.getActionErrors(); if ((errCol != null) && !errCol.equals(errs)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuiting"); - } - + LOG.debug("Short-circuiting"); break; } } - continue; } @@ -281,7 +269,7 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { * @return a list of validator configs for the given class and context. */ private List buildValidatorConfigs(Class clazz, String context, boolean checkFile, Set checked) { - List validatorConfigs = new ArrayList(); + List validatorConfigs = new ArrayList<>(); if (checked == null) { checked = new TreeSet(); @@ -329,22 +317,12 @@ public class DefaultActionValidatorManager implements ActionValidatorManager { List retList = Collections.emptyList(); URL fileUrl = ClassLoaderUtil.getResource(fileName, clazz); if ((checkFile && fileManager.fileNeedsReloading(fileUrl)) || !validatorFileCache.containsKey(fileName)) { - InputStream is = null; - - try { - is = fileManager.loadFile(fileUrl); - + try (InputStream is = fileManager.loadFile(fileUrl)) { if (is != null) { - retList = new ArrayList(validatorFileParser.parseActionValidatorConfigs(validatorFactory, is, fileName)); - } - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - LOG.error("Unable to close input stream for " + fileName, e); - } + retList = new ArrayList<>(validatorFileParser.parseActionValidatorConfigs(validatorFactory, is, fileName)); } + } catch (IOException e) { + LOG.error("Caught exception while loading file {}", fileName, e); } validatorFileCache.put(fileName, retList); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java index 7c96ae3ad..9f8a1b93b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java @@ -21,8 +21,8 @@ import com.opensymphony.xwork2.XWorkException; import com.opensymphony.xwork2.config.ConfigurationException; import com.opensymphony.xwork2.inject.Inject; 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 java.io.File; import java.io.FilenameFilter; @@ -30,12 +30,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -49,7 +44,7 @@ import java.util.zip.ZipInputStream; */ public class DefaultValidatorFactory implements ValidatorFactory { - protected Map validators = new HashMap(); + protected Map validators = new HashMap<>(); private static Logger LOG = LogManager.getLogger(DefaultValidatorFactory.class); protected ObjectFactory objectFactory; protected ValidatorFileParser validatorFileParser; @@ -88,10 +83,7 @@ public class DefaultValidatorFactory implements ValidatorFactory { } public void registerValidator(String name, String className) { - if (LOG.isDebugEnabled()) { - LOG.debug("Registering validator of class " + className + " with name " + name); - } - + LOG.debug("Registering validator of class {} with name {}", className, name); validators.put(name, className); } @@ -107,11 +99,9 @@ public class DefaultValidatorFactory implements ValidatorFactory { } private void parseValidators() { - if (LOG.isDebugEnabled()) { - LOG.debug("Loading validator definitions."); - } + LOG.debug("Loading validator definitions."); - List files = new ArrayList(); + List files = new ArrayList<>(); try { // Get custom validator configurations via the classpath Iterator urls = ClassLoaderUtil.getResources("", DefaultValidatorFactory.class, false); @@ -137,7 +127,7 @@ public class DefaultValidatorFactory implements ValidatorFactory { files.addAll(Arrays.asList(ff)); } } catch (SecurityException se) { - LOG.error("Security Exception while accessing directory '" + f + "'", se); + LOG.error("Security Exception while accessing directory '{}'", f, se); } } else { @@ -158,9 +148,7 @@ public class DefaultValidatorFactory implements ValidatorFactory { ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { if (zipEntry.getName().endsWith("-validators.xml")) { - if (LOG.isTraceEnabled()) { - LOG.trace("Adding validator " + zipEntry.getName()); - } + LOG.trace("Adding validator {}", zipEntry.getName()); files.add(new File(zipEntry.getName())); } zipEntry = zipInputStream.getNextEntry(); diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DelegatingValidatorContext.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DelegatingValidatorContext.java index c47d27796..5b11921da 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DelegatingValidatorContext.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DelegatingValidatorContext.java @@ -17,8 +17,8 @@ package com.opensymphony.xwork2.validator; import com.opensymphony.xwork2.*; 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.*; @@ -299,15 +299,15 @@ public class DelegatingValidatorContext implements ValidatorContext { } public void addActionError(String anErrorMessage) { - log.error("Validation error: " + anErrorMessage); + log.error("Validation error: {}", anErrorMessage); } public void addActionMessage(String aMessage) { - log.info("Validation Message: " + aMessage); + log.info("Validation Message: {}", aMessage); } public void addFieldError(String fieldName, String errorMessage) { - log.error("Validation error for " + fieldName + ":" + errorMessage); + log.error("Validation error for {}:{}", fieldName, errorMessage); } public boolean hasActionErrors() { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidationInterceptor.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidationInterceptor.java index 84788ca06..bbb25ed88 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidationInterceptor.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidationInterceptor.java @@ -21,8 +21,8 @@ import com.opensymphony.xwork2.Validateable; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; import com.opensymphony.xwork2.interceptor.PrefixMethodInvocationUtil; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * @@ -210,8 +210,7 @@ public class ValidationInterceptor extends MethodFilterInterceptor { String method = proxy.getMethod(); if (log.isDebugEnabled()) { - log.debug("Validating " - + invocation.getProxy().getNamespace() + "/" + invocation.getProxy().getActionName() + " with method "+ method +"."); + log.debug("Validating {}/{} with method {}.", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName(), method); } @@ -228,21 +227,15 @@ public class ValidationInterceptor extends MethodFilterInterceptor { Exception exception = null; Validateable validateable = (Validateable) action; - if (LOG.isDebugEnabled()) { - LOG.debug("Invoking validate() on action "+validateable); - } - + LOG.debug("Invoking validate() on action {}", validateable); + try { - PrefixMethodInvocationUtil.invokePrefixMethod( - invocation, - new String[] { VALIDATE_PREFIX, ALT_VALIDATE_PREFIX }); + PrefixMethodInvocationUtil.invokePrefixMethod(invocation, new String[]{VALIDATE_PREFIX, ALT_VALIDATE_PREFIX}); } catch(Exception e) { // If any exception occurred while doing reflection, we want // validate() to be executed - if (LOG.isWarnEnabled()) { - LOG.warn("an exception occured while executing the prefix method", e); - } + LOG.warn("an exception occured while executing the prefix method", e); exception = e; } @@ -261,7 +254,6 @@ public class ValidationInterceptor extends MethodFilterInterceptor { @Override protected String doIntercept(ActionInvocation invocation) throws Exception { doBeforeInvocation(invocation); - return invocation.invoke(); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidatorConfig.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidatorConfig.java index 085607af7..490f34e1a 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidatorConfig.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/ValidatorConfig.java @@ -45,12 +45,12 @@ public class ValidatorConfig extends Located { */ protected ValidatorConfig(String validatorType) { this.type = validatorType; - params = new LinkedHashMap(); + params = new LinkedHashMap<>(); } protected ValidatorConfig(ValidatorConfig orig) { this.type = orig.type; - this.params = new LinkedHashMap(orig.params); + this.params = new LinkedHashMap<>(orig.params); this.defaultMessage = orig.defaultMessage; this.messageKey = orig.messageKey; this.shortCircuit = orig.shortCircuit; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConditionalVisitorFieldValidator.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConditionalVisitorFieldValidator.java index e62e66c1c..4c83bb68d 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConditionalVisitorFieldValidator.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConditionalVisitorFieldValidator.java @@ -75,7 +75,7 @@ public class ConditionalVisitorFieldValidator extends VisitorFieldValidator { if ((obj != null) && (obj instanceof Boolean)) { answer = (Boolean) obj; } else { - log.warn("Got result of " + obj + " when trying to get Boolean."); + log.warn("Got result of {} when trying to get Boolean.", obj); } return answer; diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConversionErrorFieldValidator.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConversionErrorFieldValidator.java index b1deb5968..4fe0ea3de 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConversionErrorFieldValidator.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ConversionErrorFieldValidator.java @@ -18,13 +18,14 @@ package com.opensymphony.xwork2.validator.validators; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.validator.ValidationException; +import org.apache.commons.lang3.StringUtils; import java.util.Map; /** * - * Field Validator that checks if a conversion error occured for this field. + * Field Validator that checks if a conversion error occurred for this field. * *

* @@ -72,7 +73,7 @@ public class ConversionErrorFieldValidator extends RepopulateConversionErrorFiel Map conversionErrors = context.getConversionErrors(); if (conversionErrors.containsKey(fullFieldName)) { - if ((defaultMessage == null) || ("".equals(defaultMessage.trim()))) { + if (StringUtils.isBlank(defaultMessage)) { defaultMessage = XWorkConverter.getConversionErrorMessage(fullFieldName, context.getValueStack()); } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/FieldExpressionValidator.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/FieldExpressionValidator.java index a9d71165d..197314bde 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/FieldExpressionValidator.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/FieldExpressionValidator.java @@ -87,7 +87,7 @@ public class FieldExpressionValidator extends FieldValidatorSupport { if ((obj != null) && (obj instanceof Boolean)) { answer = (Boolean) obj; } else { - log.warn("Got result of " + obj + " when trying to get Boolean."); + log.warn("Got result of {} when trying to get Boolean.", obj); } if (!answer.booleanValue()) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/RepopulateConversionErrorFieldValidatorSupport.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/RepopulateConversionErrorFieldValidatorSupport.java index b6f7014e7..6dcb60f7b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/RepopulateConversionErrorFieldValidatorSupport.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/RepopulateConversionErrorFieldValidatorSupport.java @@ -19,10 +19,10 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; 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.validator.ValidationException; import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.LinkedHashMap; import java.util.Map; @@ -173,9 +173,7 @@ public abstract class RepopulateConversionErrorFieldValidatorSupport extends Fie doExprOverride = true; fakeParams.put(fullFieldName, escape(tmpValue[0])); } else { - if (LOG.isWarnEnabled()) { - LOG.warn("value is an empty array of String or with first element in it as null [" + value + "], will not repopulate conversion error "); - } + LOG.warn("value is an empty array of String or with first element in it as null [{}], will not repopulate conversion error", value); } } else if (value instanceof String) { String tmpValue = (String) value; @@ -183,9 +181,7 @@ public abstract class RepopulateConversionErrorFieldValidatorSupport extends Fie fakeParams.put(fullFieldName, escape(tmpValue)); } else { // opps... it should be - if (LOG.isWarnEnabled()) { - LOG.warn("conversion error value is not a String or array of String but instead is [" + value + "], will not repopulate conversion error"); - } + LOG.warn("conversion error value is not a String or array of String but instead is [{}], will not repopulate conversion error", value); } if (doExprOverride) { diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/StringLengthFieldValidator.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/StringLengthFieldValidator.java index 5587248d2..47916d025 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/StringLengthFieldValidator.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/StringLengthFieldValidator.java @@ -144,7 +144,7 @@ public class StringLengthFieldValidator extends FieldValidatorSupport { String fieldName = getFieldName(); String val = (String) getFieldValue(fieldName, object); - if (val == null || val.length() <= 0) { + if (StringUtils.isEmpty(val)) { // use a required validator for these return; } diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ValidatorSupport.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ValidatorSupport.java index 9dd3f50b6..1ca43b0ec 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ValidatorSupport.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/validators/ValidatorSupport.java @@ -17,14 +17,10 @@ package com.opensymphony.xwork2.validator.validators; 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 com.opensymphony.xwork2.validator.DelegatingValidatorContext; -import com.opensymphony.xwork2.validator.ShortCircuitableValidator; -import com.opensymphony.xwork2.validator.ValidationException; -import com.opensymphony.xwork2.validator.Validator; -import com.opensymphony.xwork2.validator.ValidatorContext; +import com.opensymphony.xwork2.validator.*; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; @@ -84,7 +80,7 @@ public abstract class ValidatorSupport implements Validator, ShortCircuitableVal } List parsedMessageParameters = null; if (messageParameters != null) { - parsedMessageParameters = new ArrayList(); + parsedMessageParameters = new ArrayList<>(); for (String messageParameter : messageParameters) { if (messageParameter != null) { try { @@ -93,7 +89,7 @@ public abstract class ValidatorSupport implements Validator, ShortCircuitableVal } catch (Exception e) { // if there's an exception in parsing, we'll just treat the expression itself as the // parameter - log.warn("exception while parsing message parameter [" + messageParameter + "]", e); + log.warn("exception while parsing message parameter [{}]", messageParameter, e); parsedMessageParameters.add(messageParameter); } } @@ -101,7 +97,6 @@ public abstract class ValidatorSupport implements Validator, ShortCircuitableVal } message = validatorContext.getText(messageKey, defaultMessage, parsedMessageParameters); - } else { message = defaultMessage; } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionContextTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionContextTest.java index dc7632f90..fb5a538bc 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionContextTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionContextTest.java @@ -40,13 +40,13 @@ public class ActionContextTest extends XWorkTestCase { super.setUp(); ValueStack valueStack = container.getInstance(ValueStackFactory.class).createValueStack(); Map extraContext = valueStack.getContext(); - Map application = new HashMap(); + Map application = new HashMap<>(); application.put(APPLICATION_KEY, APPLICATION_KEY); - Map session = new HashMap(); + Map session = new HashMap<>(); session.put(SESSION_KEY, SESSION_KEY); - Map params = new HashMap(); + Map params = new HashMap<>(); params.put(PARAMETERS_KEY, PARAMETERS_KEY); extraContext.put(ActionContext.APPLICATION, application); extraContext.put(ActionContext.SESSION, session); @@ -76,19 +76,19 @@ public class ActionContextTest extends XWorkTestCase { } public void testApplication() { - Map app = new HashMap(); + Map app = new HashMap<>(); context.setApplication(app); assertEquals(app, context.getApplication()); } public void testContextMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); context.setContextMap(map); assertEquals(map, context.getContextMap()); } public void testParameters() { - Map param = new HashMap(); + Map param = new HashMap<>(); context.setParameters(param); assertEquals(param, context.getParameters()); } @@ -98,7 +98,7 @@ public class ActionContextTest extends XWorkTestCase { assertNotNull(errors); assertEquals(0, errors.size()); - Map errors2 = new HashMap(); + Map errors2 = new HashMap<>(); context.setConversionErrors(errors); assertEquals(errors2, context.getConversionErrors()); } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionInvocationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionInvocationTest.java index 29c40eaaa..58d02ddd3 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionInvocationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionInvocationTest.java @@ -76,10 +76,10 @@ public class ActionInvocationTest extends XWorkTestCase { } public void testSimple() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("blah", "this is blah"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionNestingTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionNestingTest.java index ff8b8ed1b..ee996e548 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionNestingTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionNestingTest.java @@ -87,7 +87,7 @@ public class ActionNestingTest extends XWorkTestCase { ValueStack stack = ActionContext.getContext().getValueStack(); assertEquals(VALUE, stack.findValue(KEY)); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.VALUE_STACK, stack); ActionProxy proxy = actionProxyFactory.createActionProxy(NAMESPACE, STACK_ACTION_NAME, extraContext); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionSupportTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionSupportTest.java index 06e7f0680..98a5dacf5 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/ActionSupportTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/ActionSupportTest.java @@ -223,7 +223,7 @@ public class ActionSupportTest extends XWorkTestCase { ActionContext.getContext().setLocale(new Locale("da")); MyActionSupport mas = new MyActionSupport(); - List args = new ArrayList(); + List args = new ArrayList<>(); args.add("Santa"); args.add("loud"); assertEquals("Hello World", mas.getText("hello", "this is default", args)); // no args in bundle @@ -273,7 +273,7 @@ public class ActionSupportTest extends XWorkTestCase { ValueStack stack = ActionContext.getContext().getValueStack(); - List args = new ArrayList(); + List args = new ArrayList<>(); args.add("Santa"); args.add("loud"); assertEquals("Hello World", mas.getText("hello", "this is default", args, stack)); // no args in bundle diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/ChainResultTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/ChainResultTest.java index 59045f8e5..73d10a83b 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/ChainResultTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/ChainResultTest.java @@ -52,7 +52,7 @@ public class ChainResultTest extends XWorkTestCase { String expectedActionName = "testActionName"; String expectedNamespace = "testNamespace"; - Map values = new HashMap(); + Map values = new HashMap<>(); values.put("actionName", expectedActionName); values.put("namespace", expectedNamespace); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultActionInvocationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultActionInvocationTest.java index 42915381c..23e19040a 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultActionInvocationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultActionInvocationTest.java @@ -27,7 +27,7 @@ public class DefaultActionInvocationTest extends XWorkTestCase { * @throws Exception when action throws exception */ public void testInvoke() throws Exception { - List interceptorMappings = new ArrayList(); + List interceptorMappings = new ArrayList<>(); MockInterceptor mockInterceptor1 = new MockInterceptor(); mockInterceptor1.setFoo("test1"); mockInterceptor1.setExpectedFoo("test1"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultTextProviderTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultTextProviderTest.java index 509a7e755..37d6dcef5 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultTextProviderTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/DefaultTextProviderTest.java @@ -53,7 +53,7 @@ public class DefaultTextProviderTest extends TestCase { } public void testGetTextsWithListArgs() throws Exception { - List args = new ArrayList(); + List args = new ArrayList<>(); args.add("Santa"); args.add("loud"); assertEquals("Hello World", tp.getText("hello", "this is default", args)); // no args in bundle @@ -95,7 +95,7 @@ public class DefaultTextProviderTest extends TestCase { } public void testGetTextsWithListAndStack() throws Exception { - List args = new ArrayList(); + List args = new ArrayList<>(); args.add("Santa"); args.add("loud"); assertEquals("Hello World", tp.getText("hello", "this is default", args, null)); // no args in bundle diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/GenericsBean.java b/xwork-core/src/test/java/com/opensymphony/xwork2/GenericsBean.java index 9ea3f2d8d..b1d432ba3 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/GenericsBean.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/GenericsBean.java @@ -14,8 +14,8 @@ import java.util.Map; public class GenericsBean { private List blubb; private List getterList; - private Map genericMap = new HashMap(); - private Map> extendedMap = new HashMap>(); + private Map genericMap = new HashMap<>(); + private Map> extendedMap = new HashMap<>(); /** * @return Returns the doubles. @@ -41,7 +41,7 @@ public class GenericsBean { public List getGetterList() { if ( getterList == null ) { - getterList = new ArrayList(1); + getterList = new ArrayList<>(1); getterList.add(42.42); } return getterList; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/ProxyInvocationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/ProxyInvocationTest.java index 74935e253..0e7e20806 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/ProxyInvocationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/ProxyInvocationTest.java @@ -32,9 +32,9 @@ public class ProxyInvocationTest extends XWorkTestCase { * Needed for the creation of the action proxy */ private Map createDummyContext() { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("blah", "this is blah"); - Map extraContext = new HashMap(); + Map extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); return extraContext; } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAction.java b/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAction.java index 6a180a1e8..d563ebf8e 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAction.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAction.java @@ -32,7 +32,7 @@ public class SimpleAction extends ActionSupport { public static final String COMMAND_RETURN_CODE = "com.opensymphony.xwork2.SimpleAction.CommandInvoked"; - private ArrayList someList = new ArrayList(); + private ArrayList someList = new ArrayList<>(); private Date date = new Date(); private Properties settings = new Properties(); private String blah; @@ -45,12 +45,12 @@ public class SimpleAction extends ActionSupport { private long longFoo; private short shortFoo; private double percentage; - private Map indexedProps = new HashMap(); + private Map indexedProps = new HashMap<>(); private String aliasSource; private String aliasDest; - private Map protectedMap = new HashMap(); - private Map existingMap = new HashMap(); + private Map protectedMap = new HashMap<>(); + private Map existingMap = new HashMap<>(); public static boolean resultCalled; @@ -122,9 +122,7 @@ public class SimpleAction extends ActionSupport { } public boolean[] getBools() { - boolean[] b = new boolean[]{true, false, false, true}; - - return b; + return new boolean[]{true, false, false, true}; } public void setDate(Date date) { @@ -177,11 +175,11 @@ public class SimpleAction extends ActionSupport { } - public void setSomeList(ArrayList someList) { + public void setSomeList(ArrayList someList) { this.someList = someList; } - public ArrayList getSomeList() { + public ArrayList getSomeList() { return someList; } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAnnotationAction.java b/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAnnotationAction.java index 79df77d5e..35f0f5547 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAnnotationAction.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/SimpleAnnotationAction.java @@ -36,7 +36,7 @@ public class SimpleAnnotationAction extends ActionSupport { //~ Instance fields //////////////////////////////////////////////////////// - private ArrayList someList = new ArrayList(); + private ArrayList someList = new ArrayList<>(); private Date date = new Date(); private Properties settings = new Properties(); private String blah; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/StubValueStack.java b/xwork-core/src/test/java/com/opensymphony/xwork2/StubValueStack.java index 8432f2af8..1856c7c38 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/StubValueStack.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/StubValueStack.java @@ -25,7 +25,7 @@ import java.util.Map; * Stub value stack for testing */ public class StubValueStack implements ValueStack { - Map ctx = new HashMap(); + Map ctx = new HashMap<>(); CompoundRoot root = new CompoundRoot(); public Map getContext() { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java index 2c0b377fc..cb360f776 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java @@ -54,7 +54,7 @@ public class TextProviderSupportTest extends XWorkTestCase { } public void testGetTextsWithListArgs() throws Exception { - List args = new ArrayList(); + List args = new ArrayList<>(); args.add("Santa"); args.add("loud"); assertEquals("Hello World", tp.getText("hello", "this is default", args)); // no args in bundle diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java b/xwork-core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java index b27024a0f..d439eda37 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java @@ -9,7 +9,7 @@ import java.util.ArrayList; public class UnknownHandlerManagerMock extends DefaultUnknownHandlerManager { public void addUnknownHandler(UnknownHandler uh) { if (this.unknownHandlers == null) - this.unknownHandlers = new ArrayList(); + this.unknownHandlers = new ArrayList<>(); this.unknownHandlers.add(uh); } } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/VoidResult.java b/xwork-core/src/test/java/com/opensymphony/xwork2/VoidResult.java index afc3f4f76..ccb9ba413 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/VoidResult.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/VoidResult.java @@ -25,11 +25,7 @@ public class VoidResult implements Result { return true; } - if (!(o instanceof VoidResult)) { - return false; - } - - return true; + return o instanceof VoidResult; } public void execute(ActionInvocation invocation) throws Exception { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java index 5178bea8f..f6b9c1952 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java @@ -61,10 +61,10 @@ public class ConfigurationTest extends XWorkTestCase { } public void testDefaultNamespace() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("blah", "this is blah"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcherTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcherTest.java index 6616413cc..e6de0b915 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcherTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/ActionConfigMatcherTest.java @@ -133,9 +133,9 @@ public class ActionConfigMatcherTest extends XWorkTestCase { } private Map buildActionConfigMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("first", "{1}"); params.put("second", "{2}"); @@ -143,7 +143,7 @@ public class ActionConfigMatcherTest extends XWorkTestCase { .methodName("do{2}") .addParams(params) .addExceptionMapping(new ExceptionMappingConfig.Builder("foo{1}", "java.lang.{2}Exception", "success{1}") - .addParams(new HashMap(params)) + .addParams(new HashMap<>(params)) .build()) .addInterceptor(new InterceptorMapping(null, null)) .addResultConfig(new ResultConfig.Builder("success{1}", "foo.{2}").addParams(params).build()) diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/NamespaceMatcherTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/NamespaceMatcherTest.java index 1616704f6..e70f18daa 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/NamespaceMatcherTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/impl/NamespaceMatcherTest.java @@ -24,7 +24,7 @@ import java.util.Set; public class NamespaceMatcherTest extends TestCase { public void testMatch() { - Set names = new HashSet(); + Set names = new HashSet<>(); names.add("/bar"); names.add("/foo/*/bar"); names.add("/foo/*"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/MockConfigurationProvider.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/MockConfigurationProvider.java index 0d453046f..22d748b2c 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/MockConfigurationProvider.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/MockConfigurationProvider.java @@ -15,19 +15,11 @@ */ package com.opensymphony.xwork2.config.providers; -import com.opensymphony.xwork2.Action; -import com.opensymphony.xwork2.ActionChainResult; -import com.opensymphony.xwork2.ModelDrivenAction; -import com.opensymphony.xwork2.ObjectFactory; -import com.opensymphony.xwork2.SimpleAction; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.Configuration; import com.opensymphony.xwork2.config.ConfigurationException; import com.opensymphony.xwork2.config.ConfigurationProvider; -import com.opensymphony.xwork2.config.entities.ActionConfig; -import com.opensymphony.xwork2.config.entities.InterceptorConfig; -import com.opensymphony.xwork2.config.entities.InterceptorMapping; -import com.opensymphony.xwork2.config.entities.PackageConfig; -import com.opensymphony.xwork2.config.entities.ResultConfig; +import com.opensymphony.xwork2.config.entities.*; import com.opensymphony.xwork2.inject.ContainerBuilder; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor; @@ -37,11 +29,7 @@ import com.opensymphony.xwork2.mock.MockResult; import com.opensymphony.xwork2.util.location.LocatableProperties; import com.opensymphony.xwork2.validator.ValidationInterceptor; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** @@ -90,11 +78,11 @@ public class MockConfigurationProvider implements ConfigurationProvider { public void loadPackages() { PackageConfig.Builder defaultPackageContext = new PackageConfig.Builder("defaultPackage"); - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("bar", "5"); - Map results = new HashMap(); - Map successParams = new HashMap(); + Map results = new HashMap<>(); + Map successParams = new HashMap<>(); successParams.put("actionName", "bar"); results.put("success", new ResultConfig.Builder("success", ActionChainResult.class.getName()).addParams(successParams).build()); @@ -103,12 +91,12 @@ public class MockConfigurationProvider implements ConfigurationProvider { .build(); defaultPackageContext.addActionConfig(FOO_ACTION_NAME, fooActionConfig); - results = new HashMap(); - successParams = new HashMap(); + results = new HashMap<>(); + successParams = new HashMap<>(); successParams.put("actionName", "bar"); results.put("success", new ResultConfig.Builder("success", ActionChainResult.class.getName()).addParams(successParams).build()); - List interceptors = new ArrayList(); + List interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("params", new ParametersInterceptor())); ActionConfig paramInterceptorActionConfig = new ActionConfig.Builder("defaultPackage", PARAM_INTERCEPTOR_ACTION_NAME, SimpleAction.class.getName()) @@ -117,7 +105,7 @@ public class MockConfigurationProvider implements ConfigurationProvider { .build(); defaultPackageContext.addActionConfig(PARAM_INTERCEPTOR_ACTION_NAME, paramInterceptorActionConfig); - interceptors = new ArrayList(); + interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("model", objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ModelDrivenInterceptor.class.getName()).build(), EMPTY_STRING_MAP))); interceptors.add(new InterceptorMapping("params", @@ -132,15 +120,15 @@ public class MockConfigurationProvider implements ConfigurationProvider { //List paramFilterInterceptor=new ArrayList(); //paramFilterInterceptor.add(new ParameterFilterInterC) //ActionConfig modelParamFilterActionConfig = new ActionConfig(null, ModelDrivenAction.class, null, null, interceptors); - - results = new HashMap(); - successParams = new HashMap(); + + results = new HashMap<>(); + successParams = new HashMap<>(); successParams.put("actionName", "bar"); results.put("success", new ResultConfig.Builder("success", ActionChainResult.class.getName()).addParams(successParams).build()); results.put(Action.ERROR, new ResultConfig.Builder(Action.ERROR, MockResult.class.getName()).build()); - interceptors = new ArrayList(); + interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("staticParams", objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", StaticParametersInterceptor.class.getName()).build(), EMPTY_STRING_MAP))); interceptors.add(new InterceptorMapping("model", @@ -151,7 +139,7 @@ public class MockConfigurationProvider implements ConfigurationProvider { objectFactory.buildInterceptor(new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), EMPTY_STRING_MAP))); //Explicitly set an out-of-range date for DateRangeValidatorTest - params = new HashMap(); + params = new HashMap<>(); ActionConfig validationActionConfig = new ActionConfig.Builder("defaultPackage", VALIDATION_ACTION_NAME, SimpleAction.class.getName()) .addInterceptors(interceptors) .addParams(params) @@ -164,7 +152,7 @@ public class MockConfigurationProvider implements ConfigurationProvider { new ActionConfig.Builder(validationActionConfig).name(VALIDATION_SUBPROPERTY_NAME).build()); - params = new HashMap(); + params = new HashMap<>(); ActionConfig percentageActionConfig = new ActionConfig.Builder("defaultPackage", "percentage", SimpleAction.class.getName()) .addParams(params) .addResultConfigs(results) diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderActionsTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderActionsTest.java index 64c005286..218118163 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderActionsTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderActionsTest.java @@ -59,8 +59,8 @@ public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase { .addParams(params).build(); // foo action is a little more complex, two params, a result and an interceptor stack - results = new HashMap(); - params = new HashMap(); + results = new HashMap<>(); + params = new HashMap<>(); params.put("foo", "18"); params.put("bar", "24"); results.put("success", new ResultConfig.Builder("success", MockResult.class.getName()).build()); @@ -75,7 +75,7 @@ public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase { .build(); // wildcard action is simple wildcard example - results = new HashMap(); + results = new HashMap<>(); results.put("*", new ResultConfig.Builder("*", MockResult.class.getName()).build()); ActionConfig wildcardAction = new ActionConfig.Builder("", "WildCard", SimpleAction.class.getName()) @@ -87,7 +87,7 @@ public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase { params = new HashMap(); params.put("foo", "18"); params.put("bar", "24"); - results = new HashMap(); + results = new HashMap<>(); results.put("success", new ResultConfig.Builder("success", MockResult.class.getName()).build()); ExceptionMappingConfig exceptionConfig = new ExceptionMappingConfig.Builder("runtime", "java.lang.RuntimeException", "exception") @@ -102,12 +102,12 @@ public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase { .build(); // TestInterceptorParam action tests that an interceptor worked - HashMap interceptorParams = new HashMap(); + HashMap interceptorParams = new HashMap<>(); interceptorParams.put("expectedFoo", "expectedFooValue"); interceptorParams.put("foo", MockInterceptor.DEFAULT_FOO_VALUE); InterceptorConfig mockInterceptorConfig = new InterceptorConfig.Builder("test", MockInterceptor.class.getName()).build(); - interceptors = new ArrayList(); + interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptorConfig, interceptorParams))); ActionConfig intAction = new ActionConfig.Builder("", "TestInterceptorParam", SimpleAction.class.getName()) @@ -115,10 +115,10 @@ public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase { .build(); // TestInterceptorParamOverride action tests that an interceptor with a param override worked - interceptorParams = new HashMap(); + interceptorParams = new HashMap<>(); interceptorParams.put("expectedFoo", "expectedFooValue"); interceptorParams.put("foo", "foo123"); - interceptors = new ArrayList(); + interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptorConfig, interceptorParams))); ActionConfig intOverAction = new ActionConfig.Builder("", "TestInterceptorParamOverride", SimpleAction.class.getName()) @@ -205,10 +205,10 @@ public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase { @Override protected void setUp() throws Exception { super.setUp(); - params = new HashMap(); - results = new HashMap(); - interceptors = new ArrayList(); - exceptionMappings = new ArrayList(); + params = new HashMap<>(); + results = new HashMap<>(); + interceptors = new ArrayList<>(); + exceptionMappings = new ArrayList<>(); this.objectFactory = container.getInstance(ObjectFactory.class); } } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderAllowedMethodsTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderAllowedMethodsTest.java index af45ac278..6a55e75a8 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderAllowedMethodsTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderAllowedMethodsTest.java @@ -1,18 +1,10 @@ package com.opensymphony.xwork2.config.providers; -import com.opensymphony.xwork2.ActionChainResult; -import com.opensymphony.xwork2.SimpleAction; import com.opensymphony.xwork2.config.ConfigurationException; import com.opensymphony.xwork2.config.ConfigurationProvider; import com.opensymphony.xwork2.config.entities.ActionConfig; -import com.opensymphony.xwork2.config.entities.ExceptionMappingConfig; import com.opensymphony.xwork2.config.entities.PackageConfig; -import com.opensymphony.xwork2.config.entities.ResultConfig; -import com.opensymphony.xwork2.mock.MockResult; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; /** diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderExceptionMappingsTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderExceptionMappingsTest.java index 6f2af5cc5..232efd3db 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderExceptionMappingsTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderExceptionMappingsTest.java @@ -26,16 +26,16 @@ public class XmlConfigurationProviderExceptionMappingsTest extends Configuration final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-exception-mappings.xml"; ConfigurationProvider provider = buildConfigurationProvider(filename); - List exceptionMappings = new ArrayList(); - HashMap parameters = new HashMap(); - HashMap results = new HashMap(); + List exceptionMappings = new ArrayList<>(); + HashMap parameters = new HashMap<>(); + HashMap results = new HashMap<>(); exceptionMappings.add( new ExceptionMappingConfig.Builder("spooky-result", "com.opensymphony.xwork2.SpookyException", "spooky-result") .build()); results.put("spooky-result", new ResultConfig.Builder("spooky-result", MockResult.class.getName()).build()); - Map resultParams = new HashMap(); + Map resultParams = new HashMap<>(); resultParams.put("actionName", "bar.vm"); results.put("specificLocationResult", new ResultConfig.Builder("specificLocationResult", ActionChainResult.class.getName()) diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderInterceptorsTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderInterceptorsTest.java index 0867171d2..4f26b5f8f 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderInterceptorsTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderInterceptorsTest.java @@ -57,7 +57,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB // setup expectations // the test interceptor with a parameter - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("foo", "expectedFoo"); InterceptorConfig paramsInterceptor = new InterceptorConfig.Builder("test", MockInterceptor.class.getName()) @@ -65,15 +65,15 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB // the default interceptor stack InterceptorStackConfig defaultStack = new InterceptorStackConfig.Builder("defaultStack") - .addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap()))) + .addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap()))) .addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, params))) .build(); // the derivative interceptor stack InterceptorStackConfig derivativeStack = new InterceptorStackConfig.Builder("derivativeStack") - .addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap()))) + .addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap()))) .addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, params))) - .addInterceptor(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap()))) + .addInterceptor(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap()))) .build(); // execute the configuration @@ -103,7 +103,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB // expectations - the inherited interceptor stack // default package - ArrayList interceptors = new ArrayList(); + ArrayList interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap()))); ActionConfig actionWithOwnRef = new ActionConfig.Builder("", "ActionWithOwnRef", SimpleAction.class.getName()) @@ -120,7 +120,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB .addInterceptor(new InterceptorMapping("timer", objectFactory.buildInterceptor(timerInterceptor, new HashMap()))) .build(); - interceptors = new ArrayList(); + interceptors = new ArrayList<>(); interceptors.add(new InterceptorMapping("logging", objectFactory.buildInterceptor(loggingInterceptor, new HashMap()))); ActionConfig anotherActionWithOwnRef = new ActionConfig.Builder("", "AnotherActionWithOwnRef", SimpleAction.class.getName()) @@ -170,7 +170,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB public void testInterceptorParamOverriding() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("foo", "expectedFoo"); params.put("expectedFoo", "expectedFooValue"); @@ -179,7 +179,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB .addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, params))) .build(); - ArrayList interceptors = new ArrayList(); + ArrayList interceptors = new ArrayList<>(); interceptors.addAll(defaultStack.getInterceptors()); ActionConfig intAction = new ActionConfig.Builder("", "TestInterceptorParam", SimpleAction.class.getName()) @@ -187,7 +187,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB .build(); // TestInterceptorParamOverride action tests that an interceptor with a param override worked - HashMap interceptorParams = new HashMap(); + HashMap interceptorParams = new HashMap<>(); interceptorParams.put("expectedFoo", "expectedFooValue2"); interceptorParams.put("foo", "foo123"); @@ -196,7 +196,7 @@ public class XmlConfigurationProviderInterceptorsTest extends ConfigurationTestB .addInterceptor(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptor, interceptorParams))) .build(); - interceptors = new ArrayList(); + interceptors = new ArrayList<>(); interceptors.addAll(defaultStack2.getInterceptors()); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderResultsTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderResultsTest.java index 468b8d2de..caa9da0d6 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderResultsTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderResultsTest.java @@ -42,24 +42,24 @@ public class XmlConfigurationProviderResultsTest extends ConfigurationTestBase { final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-results.xml"; ConfigurationProvider provider = buildConfigurationProvider(filename); - HashMap parameters = new HashMap(); - HashMap results = new HashMap(); + HashMap parameters = new HashMap<>(); + HashMap results = new HashMap<>(); results.put("chainDefaultTypedResult", new ResultConfig.Builder("chainDefaultTypedResult", ActionChainResult.class.getName()).build()); results.put("mockTypedResult", new ResultConfig.Builder("mockTypedResult", MockResult.class.getName()).build()); - Map resultParams = new HashMap(); + Map resultParams = new HashMap<>(); resultParams.put("actionName", "bar.vm"); results.put("specificLocationResult", new ResultConfig.Builder("specificLocationResult", ActionChainResult.class.getName()) .addParams(resultParams).build()); - resultParams = new HashMap(); + resultParams = new HashMap<>(); resultParams.put("actionName", "foo.vm"); results.put("defaultLocationResult", new ResultConfig.Builder("defaultLocationResult", ActionChainResult.class.getName()) .addParams(resultParams).build()); - resultParams = new HashMap(); + resultParams = new HashMap<>(); resultParams.put("foo", "bar"); results.put("noDefaultLocationResult", new ResultConfig.Builder("noDefaultLocationResult", ActionChainResult.class.getName()) .addParams(resultParams).build()); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderTest.java index b22045ead..b161d02ab 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderTest.java @@ -43,7 +43,7 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase { XmlConfigurationProvider prov = new XmlConfigurationProvider("xwork-test-load-order.xml", true) { @Override protected Iterator getConfigurationUrls(String fileName) throws IOException { - List urls = new ArrayList(); + List urls = new ArrayList<>(); urls.add(ClassLoaderUtil.getResource("com/opensymphony/xwork2/config/providers/loadorder1/xwork-test-load-order.xml", XmlConfigurationProvider.class)); urls.add(ClassLoaderUtil.getResource("com/opensymphony/xwork2/config/providers/loadorder2/xwork-test-load-order.xml", XmlConfigurationProvider.class)); urls.add(ClassLoaderUtil.getResource("com/opensymphony/xwork2/config/providers/loadorder3/xwork-test-load-order.xml", XmlConfigurationProvider.class)); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/AnnotationXWorkConverterTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/AnnotationXWorkConverterTest.java index 14d9be186..7302359b5 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/AnnotationXWorkConverterTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/AnnotationXWorkConverterTest.java @@ -200,7 +200,7 @@ public class AnnotationXWorkConverterTest extends XWorkTestCase { } public void testStringArrayToCollection() { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add("foo"); list.add("bar"); list.add("baz"); @@ -224,27 +224,25 @@ public class AnnotationXWorkConverterTest extends XWorkTestCase { "123", "456" }, Long[].class); assertNotNull(longs); - assertTrue(Arrays.equals(new Long[]{new Long(123), new Long(456)}, longs)); + assertTrue(Arrays.equals(new Long[]{123L, 456L}, longs)); Integer[] ints = (Integer[]) converter.convertValue(context, null, null, null, new String[]{ "123", "456" }, Integer[].class); assertNotNull(ints); - assertTrue(Arrays.equals(new Integer[]{ - new Integer(123), new Integer(456) - }, ints)); + assertTrue(Arrays.equals(new Integer[]{123, 456}, ints)); Double[] doubles = (Double[]) converter.convertValue(context, null, null, null, new String[]{ "123", "456" }, Double[].class); assertNotNull(doubles); - assertTrue(Arrays.equals(new Double[]{new Double(123), new Double(456)}, doubles)); + assertTrue(Arrays.equals(new Double[]{123D, 456D}, doubles)); Float[] floats = (Float[]) converter.convertValue(context, null, null, null, new String[]{ "123", "456" }, Float[].class); assertNotNull(floats); - assertTrue(Arrays.equals(new Float[]{new Float(123), new Float(456)}, floats)); + assertTrue(Arrays.equals(new Float[]{123F, 456F}, floats)); Boolean[] booleans = (Boolean[]) converter.convertValue(context, null, null, null, new String[]{ "true", "false" @@ -286,7 +284,7 @@ public class AnnotationXWorkConverterTest extends XWorkTestCase { } public void testStringArrayToSet() { - Set list = new HashSet(); + Set list = new HashSet<>(); list.add("foo"); list.add("bar"); list.add("baz"); @@ -330,8 +328,8 @@ public class AnnotationXWorkConverterTest extends XWorkTestCase { assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", Integer.class)); assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", Double.class)); assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class)); - assertEquals(new Boolean(false), converter.convertValue(context, null, null, null, "false", Boolean.class)); - assertEquals(new Boolean(true), converter.convertValue(context, null, null, null, "true", Boolean.class)); + assertEquals(false, converter.convertValue(context, null, null, null, "false", Boolean.class)); + assertEquals(true, converter.convertValue(context, null, null, null, "true", Boolean.class)); } public void testStringToPrimitives() { @@ -339,8 +337,8 @@ public class AnnotationXWorkConverterTest extends XWorkTestCase { assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", int.class)); assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", double.class)); assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class)); - assertEquals(new Boolean(false), converter.convertValue(context, null, null, null, "false", boolean.class)); - assertEquals(new Boolean(true), converter.convertValue(context, null, null, null, "true", boolean.class)); + assertEquals(false, converter.convertValue(context, null, null, null, "false", boolean.class)); + assertEquals(true, converter.convertValue(context, null, null, null, "true", boolean.class)); assertEquals(new BigDecimal(123.5), converter.convertValue(context, null, null, null, "123.5", BigDecimal.class)); assertEquals(new BigInteger("123"), converter.convertValue(context, null, null, null, "123", BigInteger.class)); } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/NumberConverterTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/NumberConverterTest.java index a3c7c94ba..76be6e111 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/NumberConverterTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/NumberConverterTest.java @@ -13,7 +13,7 @@ public class NumberConverterTest extends XWorkTestCase { public void testStringToNumberConversionPL() throws Exception { // given NumberConverter converter = new NumberConverter(); - Map context = new HashMap(); + Map context = new HashMap<>(); context.put(ActionContext.LOCALE, new Locale("pl", "PL")); SimpleFooAction foo = new SimpleFooAction(); @@ -28,7 +28,7 @@ public class NumberConverterTest extends XWorkTestCase { public void testStringToNumberConversionUS() throws Exception { // given NumberConverter converter = new NumberConverter(); - Map context = new HashMap(); + Map context = new HashMap<>(); context.put(ActionContext.LOCALE, new Locale("en", "US")); SimpleFooAction foo = new SimpleFooAction(); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkBasicConverterTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkBasicConverterTest.java index 95fb13f43..7bd49062a 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkBasicConverterTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkBasicConverterTest.java @@ -20,13 +20,8 @@ import com.opensymphony.xwork2.XWorkException; import com.opensymphony.xwork2.XWorkTestCase; import com.opensymphony.xwork2.test.annotations.Person; -import java.lang.reflect.Member; import java.text.DateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; +import java.util.*; /** * Test case for XWorkBasicConverter @@ -60,7 +55,7 @@ public class XWorkBasicConverterTest extends XWorkTestCase { public void testDateWithLocalePoland() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); Locale locale = new Locale("pl", "PL"); map.put(ActionContext.LOCALE, locale); @@ -74,7 +69,7 @@ public class XWorkBasicConverterTest extends XWorkTestCase { public void testDateWithLocaleFrance() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); Locale locale = new Locale("fr", "FR"); map.put(ActionContext.LOCALE, locale); @@ -88,7 +83,7 @@ public class XWorkBasicConverterTest extends XWorkTestCase { public void testDateWithLocaleUK() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); Locale locale = new Locale("en", "US"); map.put(ActionContext.LOCALE, locale); @@ -242,13 +237,12 @@ public class XWorkBasicConverterTest extends XWorkTestCase { public void testConvert() { - Map context = new HashMap(); + Map context = new HashMap<>(); Person o = new Person(); - Member member = null; String s = "names"; Object value = new Person[0]; Class toType = String.class; - basicConverter.convertValue(context, value, member, s, value, toType); + basicConverter.convertValue(context, value, null, s, value, toType); } @Override diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkConverterTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkConverterTest.java index bc0d93238..3d7fc493e 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkConverterTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/conversion/impl/XWorkConverterTest.java @@ -15,11 +15,7 @@ */ package com.opensymphony.xwork2.conversion.impl; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.ModelDrivenAction; -import com.opensymphony.xwork2.SimpleAction; -import com.opensymphony.xwork2.TestBean; -import com.opensymphony.xwork2.XWorkTestCase; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.ognl.OgnlValueStack; import com.opensymphony.xwork2.test.ModelDrivenAction2; import com.opensymphony.xwork2.test.User; @@ -39,16 +35,7 @@ import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; +import java.util.*; /** @@ -223,7 +210,7 @@ public class XWorkConverterTest extends XWorkTestCase { stack.push(action); stack.push(action.getModel()); - Map ognlStackContext = stack.getContext(); + Map ognlStackContext = stack.getContext(); ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE); String value = "asdf:123"; @@ -250,7 +237,7 @@ public class XWorkConverterTest extends XWorkTestCase { stack.push(action); - Map ognlStackContext = stack.getContext(); + Map ognlStackContext = stack.getContext(); ognlStackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE); assertEquals("Conversion should have failed.", OgnlRuntime.NoConversionPossible, converter.convertValue(ognlStackContext, action.getBean(), null, "count", "111.1", int.class)); @@ -262,7 +249,7 @@ public class XWorkConverterTest extends XWorkTestCase { } public void testStringArrayToCollection() { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add("foo"); list.add("bar"); list.add("baz"); @@ -272,7 +259,7 @@ public class XWorkConverterTest extends XWorkTestCase { } public void testStringArrayToList() { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add("foo"); list.add("bar"); list.add("baz"); @@ -286,27 +273,25 @@ public class XWorkConverterTest extends XWorkTestCase { "123", "456" }, Long[].class); assertNotNull(longs); - assertTrue(Arrays.equals(new Long[]{new Long(123), new Long(456)}, longs)); + assertTrue(Arrays.equals(new Long[]{123L, 456L}, longs)); Integer[] ints = (Integer[]) converter.convertValue(context, null, null, null, new String[]{ "123", "456" }, Integer[].class); assertNotNull(ints); - assertTrue(Arrays.equals(new Integer[]{ - new Integer(123), new Integer(456) - }, ints)); + assertTrue(Arrays.equals(new Integer[]{123, 456}, ints)); Double[] doubles = (Double[]) converter.convertValue(context, null, null, null, new String[]{ "123", "456" }, Double[].class); assertNotNull(doubles); - assertTrue(Arrays.equals(new Double[]{new Double(123), new Double(456)}, doubles)); + assertTrue(Arrays.equals(new Double[]{123D, 456D}, doubles)); Float[] floats = (Float[]) converter.convertValue(context, null, null, null, new String[]{ "123", "456" }, Float[].class); assertNotNull(floats); - assertTrue(Arrays.equals(new Float[]{new Float(123), new Float(456)}, floats)); + assertTrue(Arrays.equals(new Float[]{123F, 456F}, floats)); Boolean[] booleans = (Boolean[]) converter.convertValue(context, null, null, null, new String[]{ "true", "false" @@ -348,7 +333,7 @@ public class XWorkConverterTest extends XWorkTestCase { } public void testStringArrayToSet() { - Set list = new HashSet(); + Set list = new HashSet<>(); list.add("foo"); list.add("bar"); list.add("baz"); @@ -358,7 +343,7 @@ public class XWorkConverterTest extends XWorkTestCase { } public void testStringToCollectionConversion() { - Map stackContext = stack.getContext(); + Map stackContext = stack.getContext(); stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE); stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE); stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE); @@ -430,16 +415,16 @@ public class XWorkConverterTest extends XWorkTestCase { assertEquals(new Integer(123), converter.convertValue(context, null, null, null, "123", Integer.class)); assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", Double.class)); assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class)); - assertEquals(new Boolean(false), converter.convertValue(context, null, null, null, "false", Boolean.class)); - assertEquals(new Boolean(true), converter.convertValue(context, null, null, null, "true", Boolean.class)); + assertEquals(false, converter.convertValue(context, null, null, null, "false", Boolean.class)); + assertEquals(true, converter.convertValue(context, null, null, null, "true", Boolean.class)); } public void testStringToPrimitives() { assertEquals(new Long(123), converter.convertValue(context, null, null, null, "123", long.class)); assertEquals(new Double(123.5), converter.convertValue(context, null, null, null, "123.5", double.class)); assertEquals(new Float(123.5), converter.convertValue(context, null, null, null, "123.5", float.class)); - assertEquals(new Boolean(false), converter.convertValue(context, null, null, null, "false", boolean.class)); - assertEquals(new Boolean(true), converter.convertValue(context, null, null, null, "true", boolean.class)); + assertEquals(false, converter.convertValue(context, null, null, null, "false", boolean.class)); + assertEquals(true, converter.convertValue(context, null, null, null, "true", boolean.class)); assertEquals(new BigDecimal(123.5), converter.convertValue(context, null, null, null, "123.5", BigDecimal.class)); assertEquals(new BigInteger("123"), converter.convertValue(context, null, null, null, "123", BigInteger.class)); } @@ -651,7 +636,7 @@ public class XWorkConverterTest extends XWorkTestCase { } public void testConvertSameCollectionToCollection() { - Collection names = new ArrayList(); + Collection names = new ArrayList<>(); names.add("XWork"); names.add("Struts"); @@ -717,7 +702,7 @@ public class XWorkConverterTest extends XWorkTestCase { class ListAction { - private List ints = new ArrayList(); + private List ints = new ArrayList<>(); public List getInts() { return ints; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java index 44ebab5f2..00077bec4 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java @@ -43,7 +43,7 @@ import java.util.Map; public class AliasInterceptorTest extends XWorkTestCase { public void testUsingDefaultInterceptorThatAliasPropertiesAreCopied() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("aliasSource", "source here"); XmlConfigurationProvider provider = new XmlConfigurationProvider("xwork-sample.xml"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java index 3e3dc6127..1b842090f 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java @@ -103,7 +103,7 @@ public class ChainingInterceptorTest extends XWorkTestCase { interceptor.setCopyErrors("true"); interceptor.setCopyMessages("true"); - Collection excludes = new ArrayList(); + Collection excludes = new ArrayList<>(); excludes.add("count"); interceptor.setExcludes(excludes); @@ -125,7 +125,7 @@ public class ChainingInterceptorTest extends XWorkTestCase { stack.push(bean); stack.push(action); - Collection excludes = new ArrayList(); + Collection excludes = new ArrayList<>(); excludes.add("name"); excludes.add("count"); interceptor.setExcludes(excludes); @@ -152,7 +152,7 @@ public class ChainingInterceptorTest extends XWorkTestCase { mockInvocation = new Mock(ActionInvocation.class); mockInvocation.expectAndReturn("getStack", stack); mockInvocation.expectAndReturn("invoke", Action.SUCCESS); - mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(new HashMap())); + mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(new HashMap())); mockInvocation.expectAndReturn("getResult", new ActionChainResult()); invocation = (ActionInvocation) mockInvocation.proxy(); interceptor = new ChainingInterceptor(); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java index 7f505fae2..0e34ae1f9 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java @@ -138,7 +138,7 @@ public class ConversionErrorInterceptorTest extends XWorkTestCase { invocation = (ActionInvocation) mockInvocation.proxy(); stack = ActionContext.getContext().getValueStack(); context = new ActionContext(stack.getContext()); - conversionErrors = new HashMap(); + conversionErrors = new HashMap<>(); context.setConversionErrors(conversionErrors); mockInvocation.matchAndReturn("getInvocationContext", context); mockInvocation.expect("addPreResultListener", C.isA(PreResultListener.class)); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java index 713aaefe1..80ccae258 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java @@ -16,15 +16,14 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.*; -import com.opensymphony.xwork2.config.entities.InterceptorConfig; import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.entities.InterceptorConfig; import com.opensymphony.xwork2.validator.ValidationInterceptor; - -import java.util.HashMap; - import org.easymock.EasyMock; import org.easymock.IAnswer; +import java.util.HashMap; + /** * Unit test for {@link DefaultWorkflowInterceptor}. @@ -191,9 +190,9 @@ public class DefaultWorkflowInterceptorTest extends XWorkTestCase { EasyMock.replay(action); EasyMock.replay(proxy); - ActionContext contex = new ActionContext(new HashMap()); - ActionContext.setContext(contex); - contex.setActionInvocation(invocation); + ActionContext actionContext = new ActionContext(new HashMap()); + ActionContext.setContext(actionContext); + actionContext.setActionInvocation(invocation); } @Override @@ -204,7 +203,7 @@ public class DefaultWorkflowInterceptorTest extends XWorkTestCase { protected ValidationInterceptor create() { ObjectFactory objectFactory = container.getInstance(ObjectFactory.class); return (ValidationInterceptor) objectFactory.buildInterceptor( - new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), new HashMap()); + new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), new HashMap()); } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java index 37bcaae1c..aad0aec05 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java @@ -289,7 +289,7 @@ public class ExceptionMappingInterceptorTest extends XWorkTestCase { stack = ActionContext.getContext().getValueStack(); mockInvocation = new Mock(ActionInvocation.class); mockInvocation.expectAndReturn("getStack", stack); - mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(new HashMap())); + mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(new HashMap())); interceptor = new ExceptionMappingInterceptor(); interceptor.init(); } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/I18nInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/I18nInterceptorTest.java index 1b585ec24..5979e5854 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/I18nInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/I18nInterceptorTest.java @@ -17,15 +17,15 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.SimpleFooAction; import com.opensymphony.xwork2.ActionInvocation; +import com.opensymphony.xwork2.SimpleFooAction; import com.opensymphony.xwork2.mock.MockActionInvocation; import junit.framework.TestCase; +import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import java.util.Map; -import java.io.Serializable; /** * Unit test for I18nInterceptor. @@ -180,10 +180,10 @@ public class I18nInterceptorTest extends TestCase { protected void setUp() throws Exception { interceptor = new I18nInterceptor(); interceptor.init(); - params = new HashMap(); + params = new HashMap<>(); session = new HashMap(); - Map ctx = new HashMap(); + Map ctx = new HashMap<>(); ctx.put(ActionContext.PARAMETERS, params); ctx.put(ActionContext.SESSION, session); ac = new ActionContext(ctx); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtilTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtilTest.java index 98de1ceee..6598050a2 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtilTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/MethodFilterInterceptorUtilTest.java @@ -22,12 +22,12 @@ import java.util.HashSet; public class MethodFilterInterceptorUtilTest extends XWorkTestCase { public void testApplyMethodNoWildcards() { - - HashSet included= new HashSet(); + + HashSet included = new HashSet<>(); included.add("included"); included.add("includedAgain"); - HashSet excluded= new HashSet(); + HashSet excluded = new HashSet<>(); excluded.add("excluded"); excluded.add("excludedAgain"); @@ -43,10 +43,10 @@ public class MethodFilterInterceptorUtilTest extends XWorkTestCase { public void testApplyMethodWithWildcards() { - HashSet included= new HashSet(); + HashSet included = new HashSet<>(); included.add("included*"); - HashSet excluded= new HashSet(); + HashSet excluded = new HashSet<>(); excluded.add("excluded*"); assertTrue(MethodFilterInterceptorUtil.applyMethod(excluded, included, "includedMethod")); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptorTest.java index c1dbb3832..b57cb226f 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterFilterInterceptorTest.java @@ -34,12 +34,12 @@ public class ParameterFilterInterceptorTest extends XWorkTestCase { ParameterFilterInterceptor interceptor; Mock mockInvocation; ValueStack stack; - Map contextMap; + Map contextMap; @Override protected void setUp() throws Exception { super.setUp(); - contextMap=new HashMap(); + contextMap = new HashMap<>(); stack = ActionContext.getContext().getValueStack(); mockInvocation = new Mock(ActionInvocation.class); mockInvocation.expectAndReturn("getStack", stack); @@ -106,7 +106,7 @@ public class ParameterFilterInterceptorTest extends XWorkTestCase { } private void setUpParameters(String [] paramNames) { - Map params=new HashMap(); + Map params = new HashMap<>(); for (String paramName : paramNames) { params.put(paramName, "irrelevant what this is"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptorTest.java index 14bccd03a..e3b4e8fcf 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParameterRemoverInterceptorTest.java @@ -15,14 +15,14 @@ import java.util.Map; */ public class ParameterRemoverInterceptorTest extends TestCase { - protected Map contextMap; + protected Map contextMap; protected ActionContext context; protected MockControl actionInvocationControl; protected ActionInvocation actionInvocation; @Override protected void setUp() throws Exception { - contextMap = new LinkedHashMap(); + contextMap = new LinkedHashMap<>(); context = new ActionContext(contextMap); actionInvocationControl = MockControl.createControl(ActionInvocation.class); @@ -33,7 +33,7 @@ public class ParameterRemoverInterceptorTest extends TestCase { } public void testInterception1() throws Exception { - contextMap.put(ActionContext.PARAMETERS, new LinkedHashMap() { + contextMap.put(ActionContext.PARAMETERS, new LinkedHashMap() { private static final long serialVersionUID = 0L; { put("param1", new String[] { "paramValue1" }); @@ -62,7 +62,7 @@ public class ParameterRemoverInterceptorTest extends TestCase { public void testInterception2() throws Exception { - contextMap.put(ActionContext.PARAMETERS, new LinkedHashMap() { + contextMap.put(ActionContext.PARAMETERS, new LinkedHashMap() { private static final long serialVersionUID = 0L; { put("param1", new String[] { "paramValue2" }); @@ -85,7 +85,7 @@ public class ParameterRemoverInterceptorTest extends TestCase { public void testInterception3() throws Exception { - contextMap.put(ActionContext.PARAMETERS, new LinkedHashMap() { + contextMap.put(ActionContext.PARAMETERS, new LinkedHashMap() { private static final long serialVersionUID = 0L; { put("param1", new String[] { "paramValueOne" }); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParametersInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParametersInterceptorTest.java index f20e1783e..abf0f722b 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParametersInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ParametersInterceptorTest.java @@ -15,15 +15,7 @@ */ package com.opensymphony.xwork2.interceptor; -import com.opensymphony.xwork2.Action; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.ActionProxy; -import com.opensymphony.xwork2.ModelDrivenAction; -import com.opensymphony.xwork2.SimpleAction; -import com.opensymphony.xwork2.TestBean; -import com.opensymphony.xwork2.TextProvider; -import com.opensymphony.xwork2.ValidationAware; -import com.opensymphony.xwork2.XWorkTestCase; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.config.providers.MockConfigurationProvider; import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; @@ -42,14 +34,7 @@ import ognl.OgnlContext; import ognl.PropertyAccessor; import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; /** @@ -131,7 +116,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } }; - final Map excluded = new HashMap(); + final Map excluded = new HashMap<>(); ParametersInterceptor pi = new ParametersInterceptor() { @Override @@ -171,7 +156,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } }; - final Map excluded = new HashMap(); + final Map excluded = new HashMap<>(); ParametersInterceptor pi = new ParametersInterceptor() { @Override @@ -207,10 +192,10 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testDoesNotAllowMethodInvocations() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("@java.lang.System@exit(1).dummy", "dumb value"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.MODEL_DRIVEN_PARAM_TEST, null, extraContext); @@ -221,7 +206,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testModelDrivenParameters() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); final String fooVal = "com.opensymphony.xwork2.interceptor.ParametersInterceptorTest.foo"; params.put("foo", fooVal); @@ -229,7 +214,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { params.put("name", nameVal); params.put("count", "15"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.MODEL_DRIVEN_PARAM_TEST, null, extraContext); @@ -243,7 +228,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testParametersDoesNotAffectSession() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("blah", "This is blah"); params.put("#session.foo", "Foo"); params.put("\u0023session[\'user\']", "0wn3d"); @@ -255,12 +240,12 @@ public class ParametersInterceptorTest extends XWorkTestCase { params.put("('\u0023'%2b'session[\'user5\']')(unused)", "0wn3d"); params.put("('\\u0023'%2b'session[\'user5\']')(unused)", "0wn3d"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); ValueStack stack = proxy.getInvocation().getStack(); - HashMap session = new HashMap(); + HashMap session = new HashMap<>(); stack.getContext().put("session", session); proxy.execute(); assertEquals("This is blah", ((SimpleAction) proxy.getAction()).getBlah()); @@ -324,13 +309,13 @@ public class ParametersInterceptorTest extends XWorkTestCase { public void testAccessToOgnlInternals() throws Exception { // given - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("blah", "This is blah"); params.put("('\\u0023_memberAccess[\\'allowStaticMethodAccess\\']')(meh)", "true"); params.put("('(aaa)(('\\u0023context[\\'xwork.MethodAccessor.denyMethodExecution\\']\\u003d\\u0023foo')(\\u0023foo\\u003dnew java.lang.Boolean(\"false\")))", ""); params.put("(asdf)(('\\u0023rt.exit(1)')(\\u0023rt\\u003d@java.lang.Runtime@getRuntime()))", "1"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -347,10 +332,10 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testParameters() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("blah", "This is blah"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -359,13 +344,13 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testParametersWithSpacesInTheName() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("theProtectedMap['p0 p1']", "test1"); params.put("theProtectedMap['p0p1 ']", "test2"); params.put("theProtectedMap[' p0p1 ']", "test3"); params.put("theProtectedMap[' p0 p1 ']", "test4"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -375,10 +360,10 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testParametersWithChineseInTheName() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("theProtectedMap['名字']", "test1"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -406,11 +391,11 @@ public class ParametersInterceptorTest extends XWorkTestCase { sb.append("x"); } - Map actual = new LinkedHashMap(); + Map actual = new LinkedHashMap<>(); parametersInterceptor.setValueStackFactory(createValueStackFactory(actual)); ValueStack stack = createStubValueStack(actual); - Map parameters = new HashMap(); + Map parameters = new HashMap<>(); parameters.put(sb.toString(), ""); parameters.put("huuhaa", ""); @@ -434,7 +419,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } }; - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -465,7 +450,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } }; - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -484,11 +469,11 @@ public class ParametersInterceptorTest extends XWorkTestCase { public void testParametersNotAccessPrivateVariables() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("protectedMap.foo", "This is blah"); params.put("theProtectedMap.boo", "This is blah"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -500,11 +485,11 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testParametersNotAccessProtectedMethods() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("theSemiProtectedMap.foo", "This is blah"); params.put("theProtectedMap.boo", "This is blah"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -522,13 +507,13 @@ public class ParametersInterceptorTest extends XWorkTestCase { * @throws Exception */ public void testEvalExpressionAsParameterName() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("blah", "(#context[\"xwork.MethodAccessor.denyMethodExecution\"]= new " + "java.lang.Boolean(false), #_memberAccess[\"allowStaticMethodAccess\"]= new java.lang.Boolean(true), " + "@java.lang.Runtime@getRuntime().exec('mkdir /tmp/PWNAGE'))(meh)"); params.put("top['blah'](0)", "true"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -543,10 +528,10 @@ public class ParametersInterceptorTest extends XWorkTestCase { } public void testParametersOverwriteField() throws Exception { - Map params = new LinkedHashMap(); + Map params = new LinkedHashMap<>(); params.put("existingMap.boo", "This is blah"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, null, extraContext); @@ -562,10 +547,10 @@ public class ParametersInterceptorTest extends XWorkTestCase { container.inject(provider); loadConfigurationProviders(provider, new MockConfigurationProvider(Collections.singletonMap("devMode", "true"))); - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("not_a_property", "There is no action property named like this"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionConfig config = configuration.getRuntimeConfiguration().getActionConfig("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME); @@ -581,10 +566,10 @@ public class ParametersInterceptorTest extends XWorkTestCase { container.inject(provider); loadConfigurationProviders(provider, new MockConfigurationProvider(Collections.singletonMap("devMode", "false"))); - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("not_a_property", "There is no action property named like this"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionConfig config = configuration.getRuntimeConfiguration().getActionConfig("", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME); @@ -608,11 +593,11 @@ public class ParametersInterceptorTest extends XWorkTestCase { public void testNoOrdered() throws Exception { ParametersInterceptor pi = createParametersInterceptor(); - final Map actual = new LinkedHashMap(); + final Map actual = new LinkedHashMap<>(); pi.setValueStackFactory(createValueStackFactory(actual)); ValueStack stack = createStubValueStack(actual); - Map parameters = new HashMap(); + Map parameters = new HashMap<>(); parameters.put("user.address.city", "London"); parameters.put("user.name", "Superman"); @@ -634,11 +619,11 @@ public class ParametersInterceptorTest extends XWorkTestCase { ParametersInterceptor pi = new ParametersInterceptor(); pi.setOrdered(true); container.inject(pi); - final Map actual = new LinkedHashMap(); + final Map actual = new LinkedHashMap<>(); pi.setValueStackFactory(createValueStackFactory(actual)); ValueStack stack = createStubValueStack(actual); - Map parameters = new HashMap(); + Map parameters = new HashMap<>(); parameters.put("user.address.city", "London"); parameters.put("user.address['postal']", "QJR387"); parameters.put("user.name", "Superman"); @@ -728,7 +713,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { } private Map injectValueStackFactory(ParametersInterceptor interceptor) { - final Map actual = new HashMap(); + final Map actual = new HashMap<>(); interceptor.setValueStackFactory(createValueStackFactory(actual)); return actual; } @@ -806,7 +791,7 @@ public class ParametersInterceptorTest extends XWorkTestCase { class ValidateAction implements ValidationAware { - private List messages = new LinkedList(); + private List messages = new LinkedList<>(); private String name; public void setActionErrors(Collection errorMessages) { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/PreResultListenerTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/PreResultListenerTest.java index fce27b861..968274136 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/PreResultListenerTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/PreResultListenerTest.java @@ -41,7 +41,7 @@ public class PreResultListenerTest extends XWorkTestCase { public void testPreResultListenersAreCalled() throws Exception { - ActionProxy proxy = actionProxyFactory.createActionProxy("package", "action", new HashMap(), false, true); + ActionProxy proxy = actionProxyFactory.createActionProxy("package", "action", new HashMap(), false, true); ActionInvocation invocation = proxy.getInvocation(); Mock preResultListenerMock1 = new Mock(PreResultListener.class); preResultListenerMock1.expect("beforeResult", C.args(C.eq(invocation), C.eq(Action.SUCCESS))); @@ -51,7 +51,7 @@ public class PreResultListenerTest extends XWorkTestCase { } public void testPreResultListenersAreCalledInOrder() throws Exception { - ActionProxy proxy = actionProxyFactory.createActionProxy("package", "action", new HashMap(), false, true); + ActionProxy proxy = actionProxyFactory.createActionProxy("package", "action", new HashMap(), false, true); ActionInvocation invocation = proxy.getInvocation(); CountPreResultListener listener1 = new CountPreResultListener(); CountPreResultListener listener2 = new CountPreResultListener(); @@ -60,7 +60,7 @@ public class PreResultListenerTest extends XWorkTestCase { proxy.execute(); assertNotNull(listener1.getMyOrder()); assertNotNull(listener2.getMyOrder()); - assertEquals(listener1.getMyOrder().intValue() + 1, listener2.getMyOrder().intValue()); + assertEquals(listener1.getMyOrder() + 1, listener2.getMyOrder().intValue()); } @Override @@ -113,7 +113,7 @@ public class PreResultListenerTest extends XWorkTestCase { } public void beforeResult(ActionInvocation invocation, String resultCode) { - myOrder = new Integer(count++); + myOrder = count++; } } } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java index 959a768f6..1a5a81e02 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java @@ -41,7 +41,7 @@ public class ScopedModelDrivenInterceptorTest extends XWorkTestCase { public void testResolveModel() throws Exception { ActionContext ctx = ActionContext.getContext(); - ctx.setSession(new HashMap()); + ctx.setSession(new HashMap()); ObjectFactory factory = ObjectFactory.getObjectFactory(); Object obj = inter.resolveModel(factory, ctx, "java.lang.String", "request", "foo"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ValidationInterceptorPrefixMethodInvocationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ValidationInterceptorPrefixMethodInvocationTest.java index f269d90b5..8add1d66a 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ValidationInterceptorPrefixMethodInvocationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/ValidationInterceptorPrefixMethodInvocationTest.java @@ -16,13 +16,11 @@ package com.opensymphony.xwork2.interceptor; import com.opensymphony.xwork2.*; -import com.opensymphony.xwork2.config.entities.InterceptorConfig; import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.entities.InterceptorConfig; import com.opensymphony.xwork2.validator.ValidationInterceptor; -import org.easymock.MockControl; import org.easymock.EasyMock; import org.easymock.IAnswer; -import org.easymock.IMocksControl; import java.util.HashMap; @@ -63,8 +61,8 @@ public class ValidationInterceptorPrefixMethodInvocationTest extends XWorkTestCa protected ValidationInterceptor create() { ObjectFactory objectFactory = container.getInstance(ObjectFactory.class); return (ValidationInterceptor) objectFactory.buildInterceptor( - new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), new HashMap()); - } + new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), new HashMap()); + } private interface ValidateAction extends Action, Validateable, ValidationAware { void validateDoSave(); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AllowingByDefaultModel.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AllowingByDefaultModel.java index a35710163..e31557748 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AllowingByDefaultModel.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AllowingByDefaultModel.java @@ -1,6 +1,5 @@ package com.opensymphony.xwork2.interceptor.annotations; -import com.opensymphony.xwork2.ActionSupport; /** * @author jafl diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterUnitTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterUnitTest.java index abdfd4ecd..d1ea4ca79 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterUnitTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationParameterFilterUnitTest.java @@ -32,9 +32,9 @@ public class AnnotationParameterFilterUnitTest extends TestCase { * @throws Exception */ public void testBlockingByDefault() throws Exception { - - Map contextMap = new HashMap(); - Map parameterMap = new HashMap(); + + Map contextMap = new HashMap<>(); + Map parameterMap = new HashMap<>(); parameterMap.put("job", "Baker"); parameterMap.put("name", "Martin"); @@ -54,8 +54,8 @@ public class AnnotationParameterFilterUnitTest extends TestCase { AnnotationParameterFilterIntereptor intereptor = new AnnotationParameterFilterIntereptor(); intereptor.intercept(invocation); - - assertEquals("Paramter map should contain one entry", 1, parameterMap.size()); + + assertEquals("Parameter map should contain one entry", 1, parameterMap.size()); assertNull(parameterMap.get("job")); assertNotNull(parameterMap.get("name")); @@ -67,9 +67,9 @@ public class AnnotationParameterFilterUnitTest extends TestCase { * @throws Exception */ public void testAllowingByDefault() throws Exception { - - Map contextMap = new HashMap(); - Map parameterMap = new HashMap(); + + Map contextMap = new HashMap<>(); + Map parameterMap = new HashMap<>(); parameterMap.put("job", "Baker"); parameterMap.put("name", "Martin"); @@ -102,9 +102,9 @@ public class AnnotationParameterFilterUnitTest extends TestCase { * @throws Exception */ public void testBlockingByDefaultWithModel() throws Exception { - - Map contextMap = new HashMap(); - Map parameterMap = new HashMap(); + + Map contextMap = new HashMap<>(); + Map parameterMap = new HashMap<>(); parameterMap.put("job", "Baker"); parameterMap.put("name", "Martin"); @@ -139,9 +139,9 @@ public class AnnotationParameterFilterUnitTest extends TestCase { * @throws Exception */ public void testAllowingByDefaultWithModel() throws Exception { - - Map contextMap = new HashMap(); - Map parameterMap = new HashMap(); + + Map contextMap = new HashMap<>(); + Map parameterMap = new HashMap<>(); parameterMap.put("job", "Baker"); parameterMap.put("name", "Martin"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptorTest.java index f5683a83d..e8b8d4f30 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotationWorkflowInterceptorTest.java @@ -28,7 +28,7 @@ import com.opensymphony.xwork2.inject.ContainerBuilder; import com.opensymphony.xwork2.mock.MockResult; import com.opensymphony.xwork2.util.location.LocatableProperties; -import java.util.Arrays; +import java.util.Collections; /** * @author Zsolt Szasz, zsolt at lorecraft dot com @@ -87,11 +87,11 @@ public class AnnotationWorkflowInterceptorTest extends XWorkTestCase { public void loadPackages() throws ConfigurationException { PackageConfig packageConfig = new PackageConfig.Builder("default") .addActionConfig(ANNOTATED_ACTION, new ActionConfig.Builder("defaultPackage", ANNOTATED_ACTION, AnnotatedAction.class.getName()) - .addInterceptors(Arrays.asList(new InterceptorMapping[]{ new InterceptorMapping("annotationWorkflow", annotationWorkflow) })) + .addInterceptors(Collections.singletonList(new InterceptorMapping("annotationWorkflow", annotationWorkflow))) .addResultConfig(new ResultConfig.Builder("success", MockResult.class.getName()).build()) .build()) .addActionConfig(SHORTCIRCUITED_ACTION, new ActionConfig.Builder("defaultPackage", SHORTCIRCUITED_ACTION, ShortcircuitedAction.class.getName()) - .addInterceptors(Arrays.asList(new InterceptorMapping[]{ new InterceptorMapping("annotationWorkflow", annotationWorkflow) })) + .addInterceptors(Collections.singletonList(new InterceptorMapping("annotationWorkflow", annotationWorkflow))) .addResultConfig(new ResultConfig.Builder("shortcircuit", MockResult.class.getName()).build()) .build()) .build(); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsCheckerTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsCheckerTest.java index 22e4a7391..367e1995a 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsCheckerTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/security/DefaultExcludedPatternsCheckerTest.java @@ -67,7 +67,7 @@ public class DefaultExcludedPatternsCheckerTest extends XWorkTestCase { public void testParamWithClassInName() throws Exception { // given - List properParams = new ArrayList(); + List properParams = new ArrayList<>(); properParams.add("eventClass"); properParams.add("form.eventClass"); properParams.add("form[\"eventClass\"]"); @@ -88,7 +88,7 @@ public class DefaultExcludedPatternsCheckerTest extends XWorkTestCase { public void testStrutsTokenIsExcluded() throws Exception { // given - List tokens = new ArrayList(); + List tokens = new ArrayList<>(); tokens.add("struts.token.name"); tokens.add("struts.token"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/spring/SpringObjectFactoryTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/spring/SpringObjectFactoryTest.java index ea39a129e..6aa6f7bef 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/spring/SpringObjectFactoryTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/spring/SpringObjectFactoryTest.java @@ -19,15 +19,7 @@ package com.opensymphony.xwork2.spring; * Created on Mar 8, 2004 */ -import com.opensymphony.xwork2.Action; -import com.opensymphony.xwork2.ActionChainResult; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.ModelDrivenAction; -import com.opensymphony.xwork2.ObjectFactory; -import com.opensymphony.xwork2.Result; -import com.opensymphony.xwork2.SimpleAction; -import com.opensymphony.xwork2.TestBean; -import com.opensymphony.xwork2.XWorkTestCase; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.ConfigurationException; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.config.entities.InterceptorConfig; @@ -115,7 +107,7 @@ public class SpringObjectFactoryTest extends XWorkTestCase { } public void testFallsBackToDefaultObjectFactoryValidatorBuilding() throws Exception { - Map extraContext = new HashMap(); + Map extraContext = new HashMap<>(); Validator validator = objectFactory.buildValidator(RequiredStringValidator.class.getName(), new HashMap(), extraContext); assertEquals(RequiredStringValidator.class, validator.getClass()); @@ -152,7 +144,7 @@ public class SpringObjectFactoryTest extends XWorkTestCase { public void testObtainValidatorBySpringName() throws Exception { sac.registerPrototype("expression-validator", ExpressionValidator.class, new MutablePropertyValues()); - Map extraContext = new HashMap(); + Map extraContext = new HashMap<>(); Validator validator = objectFactory.buildValidator("expression-validator", new HashMap(), extraContext); assertEquals(ExpressionValidator.class, validator.getClass()); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptorTest.java index 1465ad362..b399edf8b 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/spring/interceptor/ActionAutowiringInterceptorTest.java @@ -62,10 +62,10 @@ public class ActionAutowiringInterceptorTest extends XWorkTestCase { } protected void loadSpringApplicationContextIntoApplication(ApplicationContext appContext) { - Map application = new HashMap(); + Map application = new HashMap<>(); application.put(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext); - Map context = new HashMap(); + Map context = new HashMap<>(); context.put(ActionContext.APPLICATION, application); ActionContext actionContext = new ActionContext(context); ActionContext.setContext(actionContext); @@ -90,7 +90,7 @@ public class ActionAutowiringInterceptorTest extends XWorkTestCase { } public void testIfApplicationContextIsNullThenBeanWillNotBeWiredUp() throws Exception { - Map context = new HashMap(); + Map context = new HashMap<>(); context.put(ActionContext.APPLICATION, new HashMap()); ActionContext actionContext = new ActionContext(context); ActionContext.setContext(actionContext); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/ClassLoaderUtilTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/ClassLoaderUtilTest.java index a179da9c2..2439bf354 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/ClassLoaderUtilTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/ClassLoaderUtilTest.java @@ -19,9 +19,9 @@ import junit.framework.TestCase; import java.io.IOException; import java.net.URL; -import java.util.Iterator; import java.util.Arrays; import java.util.Enumeration; +import java.util.Iterator; public class ClassLoaderUtilTest extends TestCase { @@ -79,26 +79,26 @@ public class ClassLoaderUtilTest extends TestCase { } public void testAggregateIterator() { - ClassLoaderUtil.AggregateIterator aggr = new ClassLoaderUtil.AggregateIterator(); + ClassLoaderUtil.AggregateIterator aggr = new ClassLoaderUtil.AggregateIterator<>(); - Enumeration en1 = new Enumeration() { - private Iterator itt = Arrays.asList("str1", "str1", "str3", "str1").iterator(); + Enumeration en1 = new Enumeration() { + private Iterator itt = Arrays.asList("str1", "str1", "str3", "str1").iterator(); public boolean hasMoreElements() { return itt.hasNext(); } - public Object nextElement() { + public String nextElement() { return itt.next(); } }; - Enumeration en2 = new Enumeration() { - private Iterator itt = Arrays.asList("str4", "str5").iterator(); + Enumeration en2 = new Enumeration() { + private Iterator itt = Arrays.asList("str4", "str5").iterator(); public boolean hasMoreElements() { return itt.hasNext(); } - public Object nextElement() { + public String nextElement() { return itt.next(); } }; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/Indexed.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/Indexed.java index 70b2492b0..15c61937d 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/Indexed.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/Indexed.java @@ -10,7 +10,7 @@ import java.util.Map; public class Indexed { public Object[] values = new Object[3]; - public Map map = new HashMap(); + public Map map = new HashMap<>(); public void setSimple(int i, Object v) { values[i] = v; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/MyBeanActionTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/MyBeanActionTest.java index 955223680..9289de61b 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/MyBeanActionTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/MyBeanActionTest.java @@ -31,11 +31,11 @@ import java.util.Map; public class MyBeanActionTest extends XWorkTestCase { public void testIndexedList() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("beanList(1234567890).name", "This is the bla bean"); params.put("beanList(1234567891).name", "This is the 2nd bla bean"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { @@ -56,14 +56,14 @@ public class MyBeanActionTest extends XWorkTestCase { } public void testIndexedMap() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("beanMap[1234567890].id", "1234567890"); params.put("beanMap[1234567891].id", "1234567891"); params.put("beanMap[1234567890].name", "This is the bla bean"); params.put("beanMap[1234567891].name", "This is the 2nd bla bean"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { @@ -74,8 +74,8 @@ public class MyBeanActionTest extends XWorkTestCase { assertEquals(2, Integer.parseInt(proxy.getInvocation().getStack().findValue("beanMap.size").toString())); Map map = (Map) proxy.getInvocation().getStack().findValue("beanMap"); - assertEquals(true, action.getBeanMap().containsKey(new Long(1234567890))); - assertEquals(true, action.getBeanMap().containsKey(new Long(1234567891))); + assertEquals(true, action.getBeanMap().containsKey(1234567890L)); + assertEquals(true, action.getBeanMap().containsKey(1234567891L)); assertEquals(MyBean.class.getName(), proxy.getInvocation().getStack().findValue("beanMap.get(1234567890L)").getClass().getName()); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcherTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcherTest.java index 3e284e5b8..b6597318c 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcherTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/NamedVariablePatternMatcherTest.java @@ -15,19 +15,15 @@ */ package com.opensymphony.xwork2.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import com.opensymphony.xwork2.util.NamedVariablePatternMatcher.CompiledPattern; +import org.junit.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; -import org.junit.Test; - -import com.opensymphony.xwork2.util.NamedVariablePatternMatcher.CompiledPattern; +import static org.junit.Assert.*; public class NamedVariablePatternMatcherTest { @@ -64,7 +60,7 @@ public class NamedVariablePatternMatcherTest { public void testMatch() { NamedVariablePatternMatcher matcher = new NamedVariablePatternMatcher(); - Map vars = new HashMap(); + Map vars = new HashMap<>(); CompiledPattern pattern = new CompiledPattern(Pattern.compile("foo([^/]+)"), Arrays.asList("bar")); assertTrue(matcher.match(vars, "foobaz", pattern)); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/ResolverUtilTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/ResolverUtilTest.java index be9774ffa..791abe703 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/ResolverUtilTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/ResolverUtilTest.java @@ -25,7 +25,7 @@ import java.util.Set; public class ResolverUtilTest extends TestCase { public void testSimpleFind() throws Exception { - ResolverUtil resolver = new ResolverUtil(); + ResolverUtil resolver = new ResolverUtil<>(); resolver.findImplementations(ObjectFactory.class, "com"); Set> impls = resolver.getClasses(); @@ -34,7 +34,7 @@ public class ResolverUtilTest extends TestCase { } public void testMissingSomeFind() throws Exception { - ResolverUtil resolver = new ResolverUtil(); + ResolverUtil resolver = new ResolverUtil<>(); resolver.findImplementations(ObjectFactory.class, "com.opensymphony.xwork2.spring"); Set> impls = resolver.getClasses(); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/TextParseUtilTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/TextParseUtilTest.java index a624a10d3..b6f68d487 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/TextParseUtilTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/TextParseUtilTest.java @@ -15,18 +15,11 @@ */ package com.opensymphony.xwork2.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import org.junit.Assert; - import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.XWorkTestCase; +import org.junit.Assert; + +import java.util.*; /** * Unit test of {@link TextParseUtil}. @@ -49,8 +42,8 @@ public class TextParseUtilTest extends XWorkTestCase { TextParseUtil.ParsedValueEvaluator evaluator = new TextParseUtil.ParsedValueEvaluator() { public Object evaluate(String parsedValue) { - return parsedValue.toString()+"Something"; - } + return parsedValue + "Something"; + } }; String result = TextParseUtil.translateVariables("Hello ${myVariable}", stack, evaluator); @@ -125,7 +118,7 @@ public class TextParseUtilTest extends XWorkTestCase { public void testCommaDelimitedStringToSet() { assertEquals(0, TextParseUtil.commaDelimitedStringToSet("").size()); - assertEquals(new HashSet(Arrays.asList("foo", "bar", "tee")), + assertEquals(new HashSet<>(Arrays.asList("foo", "bar", "tee")), TextParseUtil.commaDelimitedStringToSet(" foo, bar,tee")); } diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/URLUtilTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/URLUtilTest.java index e359640d1..e0c009613 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/URLUtilTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/URLUtilTest.java @@ -5,11 +5,7 @@ import com.opensymphony.xwork2.util.fs.DefaultFileManager; import junit.framework.TestCase; import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; +import java.net.*; public class URLUtilTest extends TestCase { @@ -151,6 +147,8 @@ public class URLUtilTest extends TestCase { assertEquals(false, URLUtil.verifyUrl("")); assertEquals(false, URLUtil.verifyUrl(" ")); assertEquals(false, URLUtil.verifyUrl("no url")); + assertEquals(false, URLUtil.verifyUrl("http://no url")); + assertEquals(false, URLUtil.verifyUrl("https://no url")); assertEquals(true, URLUtil.verifyUrl("http://www.opensymphony.com")); assertEquals(true, URLUtil.verifyUrl("https://www.opensymphony.com")); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardHelperTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardHelperTest.java index 16d3a7dab..6cbd6d2e8 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardHelperTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardHelperTest.java @@ -26,7 +26,7 @@ public class WildcardHelperTest extends XWorkTestCase { public void testMatch() { WildcardHelper wild = new WildcardHelper(); - HashMap matchedPatterns = new HashMap(); + HashMap matchedPatterns = new HashMap<>(); int[] pattern = wild.compilePattern("wes-rules"); assertEquals(wild.match(matchedPatterns,"wes-rules", pattern), true); assertEquals(wild.match(matchedPatterns, "rules-wes", pattern), false); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardUtilTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardUtilTest.java index 14fa012d7..79bb92470 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardUtilTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/WildcardUtilTest.java @@ -20,7 +20,6 @@ package com.opensymphony.xwork2.util; import com.opensymphony.xwork2.XWorkTestCase; import java.util.regex.Pattern; -import java.util.regex.Matcher; public class WildcardUtilTest extends XWorkTestCase { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/util/XWorkListTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/util/XWorkListTest.java index d2aea368c..412673fc4 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/XWorkListTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/XWorkListTest.java @@ -32,7 +32,7 @@ public class XWorkListTest extends XWorkTestCase { xworkList.add(new String[]{"a"}); xworkList.add("b"); - ArrayList addList = new ArrayList(); + ArrayList addList = new ArrayList<>(); addList.add(new String[]{"1"}); addList.add(new String[]{"2"}); addList.add(new String[]{"3"}); @@ -52,7 +52,7 @@ public class XWorkListTest extends XWorkTestCase { xworkList.add(new String[]{"a"}); xworkList.add("b"); - addList = new ArrayList(); + addList = new ArrayList<>(); addList.add(new String[]{"1"}); addList.add(new String[]{"2"}); addList.add(new String[]{"3"}); @@ -70,7 +70,7 @@ public class XWorkListTest extends XWorkTestCase { xworkList.add(new String[]{"a"}); xworkList.add("b"); - addList = new ArrayList(); + addList = new ArrayList<>(); addList.add(new String[]{"1"}); addList.add(new String[]{"2"}); addList.add(new String[]{"3"}); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ConversionErrorFieldValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ConversionErrorFieldValidatorTest.java index 9faec48d3..ab22d48e5 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ConversionErrorFieldValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ConversionErrorFieldValidatorTest.java @@ -48,7 +48,7 @@ public class ConversionErrorFieldValidatorTest extends XWorkTestCase { ValueStack stack = ActionContext.getContext().getValueStack(); ActionContext context = new ActionContext(stack.getContext()); - Map conversionErrors = new HashMap(); + Map conversionErrors = new HashMap<>(); conversionErrors.put("foo", "bar"); context.setConversionErrors(conversionErrors); validator = new ConversionErrorFieldValidator(); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DateRangeValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DateRangeValidatorTest.java index 316f4144a..a93729292 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DateRangeValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DateRangeValidatorTest.java @@ -22,12 +22,7 @@ import com.opensymphony.xwork2.XWorkTestCase; import com.opensymphony.xwork2.config.providers.MockConfigurationProvider; import com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; /** @@ -45,8 +40,8 @@ public class DateRangeValidatorTest extends XWorkTestCase { public void testRangeValidation() throws Exception { Calendar date = Calendar.getInstance(); date.set(2002, Calendar.NOVEMBER, 20); - Map context = new HashMap(); - HashMap params = new HashMap(); + Map context = new HashMap<>(); + HashMap params = new HashMap<>(); params.put("date", date.getTime()); context.put(ActionContext.PARAMETERS, params); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DoubleRangeValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DoubleRangeValidatorTest.java index 2a07e0b12..e7045c2c0 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DoubleRangeValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DoubleRangeValidatorTest.java @@ -9,7 +9,6 @@ import com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.Map; /** @@ -24,8 +23,8 @@ public class DoubleRangeValidatorTest extends XWorkTestCase { public void testRangeValidationWithError() throws Exception { //Explicitly set an out-of-range double for DoubleRangeValidatorTest - Map context = new HashMap(); - HashMap params = new HashMap(); + Map context = new HashMap<>(); + HashMap params = new HashMap<>(); params.put("percentage", 100.0123d); context.put(ActionContext.PARAMETERS, params); @@ -45,8 +44,8 @@ public class DoubleRangeValidatorTest extends XWorkTestCase { } public void testRangeValidationNoError() throws Exception { - Map context = new HashMap(); - HashMap params = new HashMap(); + Map context = new HashMap<>(); + HashMap params = new HashMap<>(); params.put("percentage", 1.234567d); context.put(ActionContext.PARAMETERS, params); @@ -182,8 +181,8 @@ public class DoubleRangeValidatorTest extends XWorkTestCase { public void testRangeValidationWithExpressionsFail() throws Exception { //Explicitly set an out-of-range double for DoubleRangeValidatorTest - Map context = new HashMap(); - HashMap params = new HashMap(); + Map context = new HashMap<>(); + HashMap params = new HashMap<>(); params.put("percentage", 100.0123d); context.put(ActionContext.PARAMETERS, params); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ExpressionValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ExpressionValidatorTest.java index 991650e79..572b31668 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ExpressionValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ExpressionValidatorTest.java @@ -18,17 +18,16 @@ package com.opensymphony.xwork2.validator; import com.mockobjects.dynamic.C; import com.mockobjects.dynamic.Mock; import com.opensymphony.xwork2.*; -import com.opensymphony.xwork2.config.providers.MockConfigurationProvider; import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.providers.MockConfigurationProvider; import com.opensymphony.xwork2.validator.validators.ExpressionValidator; +import org.easymock.EasyMock; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.easymock.EasyMock; - /** * Unit test for ExpressionValidator. * @@ -60,12 +59,12 @@ public class ExpressionValidatorTest extends XWorkTestCase { } public void testExpressionValidatorFailure() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("date", "12/23/2002"); params.put("foo", "5"); params.put("bar", "7"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext); @@ -88,7 +87,7 @@ public class ExpressionValidatorTest extends XWorkTestCase { params.put("foo", "10"); params.put("bar", "7"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/GenericValidatorContext.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/GenericValidatorContext.java index 9a98628bd..6273259f8 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/GenericValidatorContext.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/GenericValidatorContext.java @@ -43,7 +43,7 @@ public class GenericValidatorContext extends DelegatingValidatorContext { @Override public synchronized Collection getActionErrors() { - return new ArrayList(internalGetActionErrors()); + return new ArrayList<>(internalGetActionErrors()); } @Override @@ -90,7 +90,7 @@ public class GenericValidatorContext extends DelegatingValidatorContext { List thisFieldErrors = errors.get(fieldName); if (thisFieldErrors == null) { - thisFieldErrors = new ArrayList(); + thisFieldErrors = new ArrayList<>(); errors.put(fieldName, thisFieldErrors); } @@ -119,7 +119,7 @@ public class GenericValidatorContext extends DelegatingValidatorContext { private Collection internalGetActionErrors() { if (actionErrors == null) { - actionErrors = new ArrayList(); + actionErrors = new ArrayList<>(); } return actionErrors; @@ -127,7 +127,7 @@ public class GenericValidatorContext extends DelegatingValidatorContext { private Collection internalGetActionMessages() { if (actionMessages == null) { - actionMessages = new ArrayList(); + actionMessages = new ArrayList<>(); } return actionMessages; @@ -135,7 +135,7 @@ public class GenericValidatorContext extends DelegatingValidatorContext { private Map> internalGetFieldErrors() { if (fieldErrors == null) { - fieldErrors = new HashMap>(); + fieldErrors = new HashMap<>(); } return fieldErrors; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/IntRangeValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/IntRangeValidatorTest.java index 7f4ee22b6..9c0281bec 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/IntRangeValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/IntRangeValidatorTest.java @@ -37,10 +37,10 @@ import java.util.Map; public class IntRangeValidatorTest extends XWorkTestCase { public void testRangeValidation() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("bar", "5"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/LongRangeValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/LongRangeValidatorTest.java index a56c42141..dfed43e9a 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/LongRangeValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/LongRangeValidatorTest.java @@ -35,10 +35,10 @@ import java.util.Map; public class LongRangeValidatorTest extends XWorkTestCase { public void testRangeValidation() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("longFoo", "200"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ModelDrivenValidationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ModelDrivenValidationTest.java index 5ae51806a..1ced1f592 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ModelDrivenValidationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ModelDrivenValidationTest.java @@ -32,10 +32,10 @@ import java.util.Map; public class ModelDrivenValidationTest extends XWorkTestCase { public void testModelDrivenValidation() throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("count", new String[]{"11"}); - Map context = new HashMap(); + Map context = new HashMap<>(); context.put(ActionContext.PARAMETERS, params); XmlConfigurationProvider provider = new XmlConfigurationProvider("xwork-sample.xml"); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ShortRangeValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ShortRangeValidatorTest.java index 945687457..22909dfe4 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ShortRangeValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ShortRangeValidatorTest.java @@ -35,10 +35,10 @@ import java.util.Map; public class ShortRangeValidatorTest extends XWorkTestCase { public void testRangeValidation() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("shortFoo", "200"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/SimpleActionValidationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/SimpleActionValidationTest.java index c511a6421..dc1fad8b7 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/SimpleActionValidationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/SimpleActionValidationTest.java @@ -34,7 +34,7 @@ import java.util.*; public class SimpleActionValidationTest extends XWorkTestCase { public void testAliasValidation() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("baz", "10"); //valid values @@ -81,7 +81,7 @@ public class SimpleActionValidationTest extends XWorkTestCase { } public void testLookingUpFieldNameAsTextKey() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); // should cause a message params.put("baz", "-1"); @@ -89,7 +89,7 @@ public class SimpleActionValidationTest extends XWorkTestCase { //valid values params.put("bar", "7"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { @@ -111,10 +111,10 @@ public class SimpleActionValidationTest extends XWorkTestCase { } public void testMessageKey() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("foo", "200"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { @@ -160,10 +160,10 @@ public class SimpleActionValidationTest extends XWorkTestCase { } public void testParamterizedMessage() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("bar", "42"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { @@ -185,7 +185,7 @@ public class SimpleActionValidationTest extends XWorkTestCase { } public void testSubPropertiesAreValidated() { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("baz", "10"); //valid values @@ -198,7 +198,7 @@ public class SimpleActionValidationTest extends XWorkTestCase { // this should cause a message params.put("bean.count", "100"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); try { diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/URLValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/URLValidatorTest.java index f49555734..2895d801c 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/URLValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/URLValidatorTest.java @@ -17,7 +17,6 @@ package com.opensymphony.xwork2.validator; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.XWorkTestCase; -import com.opensymphony.xwork2.util.URLUtil; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.validator.validators.URLValidator; diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ValidatorAnnotationTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ValidatorAnnotationTest.java index db0e8e644..399128856 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ValidatorAnnotationTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/ValidatorAnnotationTest.java @@ -17,12 +17,12 @@ import java.util.HashMap; public class ValidatorAnnotationTest extends XWorkTestCase { public void testNotAnnotatedMethodSuccess() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); params.put("date", "12/23/2002"); params.put("foo", "5"); params.put("bar", "7"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", "notAnnotatedMethod", extraContext); @@ -34,9 +34,9 @@ public class ValidatorAnnotationTest extends XWorkTestCase { } public void testNotAnnotatedMethodSuccess2() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", "notAnnotatedMethod", extraContext); @@ -48,9 +48,9 @@ public class ValidatorAnnotationTest extends XWorkTestCase { } public void testAnnotatedMethodFailure() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", "annotatedMethod", extraContext); @@ -64,13 +64,13 @@ public class ValidatorAnnotationTest extends XWorkTestCase { } public void testAnnotatedMethodSuccess() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); //make it not fail params.put("param1", "key1"); params.put("param2", "key2"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", "annotatedMethod", extraContext); @@ -79,12 +79,12 @@ public class ValidatorAnnotationTest extends XWorkTestCase { } public void testAnnotatedMethodSuccess2() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); //make it not fail params.put("param2", "key2"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", "annotatedMethod", extraContext); @@ -93,12 +93,12 @@ public class ValidatorAnnotationTest extends XWorkTestCase { } public void testAnnotatedMethodSuccess3() throws Exception { - HashMap params = new HashMap(); + HashMap params = new HashMap<>(); //make it not fail params.put("param1", "key1"); - HashMap extraContext = new HashMap(); + HashMap extraContext = new HashMap<>(); extraContext.put(ActionContext.PARAMETERS, params); ActionProxy proxy = actionProxyFactory.createActionProxy("", "annotatedMethod", extraContext); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorFieldValidatorTest.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorFieldValidatorTest.java index 3073d6a3a..c36f76195 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorFieldValidatorTest.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorFieldValidatorTest.java @@ -17,14 +17,10 @@ package com.opensymphony.xwork2.validator; import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.entities.ActionConfig; -import com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor; +import org.easymock.EasyMock; import java.util.*; -import org.easymock.EasyMock; -import org.easymock.IAnswer; - - /** * VisitorFieldValidatorTest * @@ -178,7 +174,7 @@ public class VisitorFieldValidatorTest extends XWorkTestCase { public void testVisitorChildConversionValidation() throws Exception { //add conversion error - Map conversionErrors = new HashMap(); + Map conversionErrors = new HashMap<>(); conversionErrors.put("bean.child.count", "bar"); ActionContext.getContext().setConversionErrors(conversionErrors); diff --git a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorValidatorTestAction.java b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorValidatorTestAction.java index 2bebe4b63..fad95fb01 100644 --- a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorValidatorTestAction.java +++ b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/VisitorValidatorTestAction.java @@ -30,7 +30,7 @@ import java.util.List; */ public class VisitorValidatorTestAction extends ActionSupport { - private List testBeanList = new ArrayList(); + private List testBeanList = new ArrayList<>(); private String context; private TestBean bean = new TestBean(); private TestBean[] testBeanArray;