You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@struts.apache.org by jo...@apache.org on 2015/06/15 19:38:09 UTC
[8/9] struts git commit: Minor code improvements's in the xwork-core
module
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProvider.java
----------------------------------------------------------------------
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 fe84e09..0cf7059 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<String> loadedFileUrls = new HashSet<String>();
+ private Set<String> loadedFileUrls = new HashSet<>();
private boolean errorIfMissing;
private Map<String, String> dtdMappings;
private Configuration configuration;
private boolean throwExceptionOnDuplicateBeans = true;
- private Map<String, Element> declaredPackages = new HashMap<String, Element>();
+ private Map<String, Element> declaredPackages = new HashMap<>();
private FileManager fileManager;
@@ -92,7 +89,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider {
this.configFileName = filename;
this.errorIfMissing = errorIfMissing;
- Map<String, String> mappings = new HashMap<String, String>();
+ Map<String, String> 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<String, Node> loadedBeans = new HashMap<String, Node>();
+ LOG.info("Parsing configuration file [{}]", configFileName);
+ Map<String, Node> 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<String> graph = new DirectedGraph<String>();
+ DirectedGraph<String> graph = new DirectedGraph<>();
for (Document doc : documents) {
Element rootElement = doc.getDocumentElement();
@@ -343,7 +336,7 @@ public class XmlConfigurationProvider implements ConfigurationProvider {
}
}
- CycleDetector<String> detector = new CycleDetector<String>(graph);
+ CycleDetector<String> 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<Element> reloads) {
if (reloads.size() > 0) {
- List<Element> result = new ArrayList<Element>();
+ List<Element> 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<PackageConfig> 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 <action/> then try to
+ // if there isn't a class name specified for an <action/> then try to
// use the default-class-ref from the <package/>
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<InterceptorMapping> buildInterceptorList(Element element, PackageConfig.Builder context) throws ConfigurationException {
- List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>();
+ List<InterceptorMapping> 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<PackageConfig> parents = new ArrayList<PackageConfig>();
+ List<PackageConfig> 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<String, ResultConfig> buildResults(Element element, PackageConfig.Builder packageContext) {
NodeList resultEls = element.getElementsByTagName("result");
- Map<String, ResultConfig> results = new LinkedHashMap<String, ResultConfig>();
+ Map<String, ResultConfig> 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<ExceptionMappingConfig> buildExceptionMappings(Element element, PackageConfig.Builder packageContext) {
NodeList exceptionMappingEls = element.getElementsByTagName("exception-mapping");
- List<ExceptionMappingConfig> exceptionMappings = new ArrayList<ExceptionMappingConfig>();
+ List<ExceptionMappingConfig> 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<String> allowedMethods = null;
if (allowedMethodsEls.getLength() > 0) {
- allowedMethods = new HashSet<String>();
+ 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<String>();
+ 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<Document> loadConfigurationFiles(String fileName, Element includeElement) {
- List<Document> docs = new ArrayList<Document>();
- List<Document> finalDocs = new ArrayList<Document>();
+ List<Document> docs = new ArrayList<>();
+ List<Document> 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;
}
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/config/providers/XmlHelper.java
----------------------------------------------------------------------
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 e8b2d1f..84e09d3 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<String, String> getParams(Element paramsElement) {
- LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
+ LinkedHashMap<String, String> 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());
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionAnnotationProcessor.java
----------------------------------------------------------------------
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 2f64dbc..c3faae3 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<String, Object> 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
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultConversionFileProcessor.java
----------------------------------------------------------------------
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 5fd0d07..488d9ce8 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);
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultObjectTypeDeterminer.java
----------------------------------------------------------------------
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 3df9f94..3b35102 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
}
}
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverter.java
----------------------------------------------------------------------
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 0394122..47bcd1b 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<Class, Object> map = new HashMap<Class, Object>();
+ Map<Class, Object> 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<Enum>)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));
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/DefaultTypeConverterHolder.java
----------------------------------------------------------------------
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 b547f05..2acaf96 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
* </pre>
*/
- private HashMap<String, TypeConverter> defaultMappings = new HashMap<String, TypeConverter>(); // non-action (eg. returned value)
+ private HashMap<String, TypeConverter> 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
* </pre>
*/
- private HashMap<Class, Map<String, Object>> mappings = new HashMap<Class, Map<String, Object>>(); // action
+ private HashMap<Class, Map<String, Object>> mappings = new HashMap<>(); // action
/**
* Unavailable target class conversion mappings, serves as a simple cache.
*/
- private HashSet<Class> noMapping = new HashSet<Class>(); // action
+ private HashSet<Class> 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
* </pre>
*/
- protected HashSet<String> unknownMappings = new HashSet<String>(); // non-action (eg. returned value)
+ protected HashSet<String> unknownMappings = new HashSet<>(); // non-action (eg. returned value)
public void addDefaultMapping(String className, TypeConverter typeConverter) {
defaultMappings.put(className, typeConverter);
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/InstantiatingNullHandler.java
----------------------------------------------------------------------
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 da49d66..386d070 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<String, Object> context, Object target, String methodName, Object[] args) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Entering nullMethodResult ");
- }
-
+ LOG.debug("Entering nullMethodResult");
return null;
}
public Object nullPropertyValue(Map<String, Object> 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;
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/StringConverter.java
----------------------------------------------------------------------
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 e9c1417..9c6cc8f 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<Integer> intArray = new ArrayList<Integer>(x.length);
+ List<Integer> 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<Long> longArray = new ArrayList<Long>(x.length);
+ List<Long> 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<Double> doubleArray = new ArrayList<Double>(x.length);
+ List<Double> 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<Boolean> booleanArray = new ArrayList<Boolean>(x.length);
+ List<Boolean> booleanArray = new ArrayList<>(x.length);
for (boolean aX : x) {
booleanArray.add(new Boolean(aX));
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/conversion/impl/XWorkConverter.java
----------------------------------------------------------------------
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 eaae007..c0086ee 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<String> 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<String> getIndexValues(String propertyName) {
Matcher matcher = messageIndexPattern.matcher(propertyName);
- List<String> indexes = new ArrayList<String>();
+ List<String> 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<String, Object> conversionErrors = (Map<String, Object>) context.get(ActionContext.CONVERSION_ERRORS);
if (conversionErrors == null) {
- conversionErrors = new HashMap<String, Object>();
+ conversionErrors = new HashMap<>();
context.put(ActionContext.CONVERSION_ERRORS, conversionErrors);
}
@@ -530,7 +516,7 @@ public class XWorkConverter extends DefaultTypeConverter {
* @return the converter mappings
*/
protected Map<String, Object> buildConverterMapping(Class clazz) throws Exception {
- Map<String, Object> mapping = new HashMap<String, Object>();
+ Map<String, Object> mapping = new HashMap<>();
// check for conversion mapping associated with super classes and any implemented interfaces
Class curClazz = clazz;
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/factory/DefaultInterceptorFactory.java
----------------------------------------------------------------------
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 d7841e6..9f0195f 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<String, String> interceptorRefParams) throws ConfigurationException {
String interceptorClassName = interceptorConfig.getClassName();
Map<String, String> thisInterceptorClassParams = interceptorConfig.getParams();
- Map<String, String> params = (thisInterceptorClassParams == null) ? new HashMap<String, String>() : new HashMap<String, String>(thisInterceptorClassParams);
+ Map<String, String> params = (thisInterceptorClassParams == null) ? new HashMap<String, String>() : new HashMap<>(thisInterceptorClassParams);
params.putAll(interceptorRefParams);
String message;
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ConstructionContext.java
----------------------------------------------------------------------
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 44a9e20..d75d464 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<T> {
// 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<T>>();
}
- DelegatingInvocationHandler<T> invocationHandler =
- new DelegatingInvocationHandler<T>();
+ DelegatingInvocationHandler<T> invocationHandler = new DelegatingInvocationHandler<>();
invocationHandlers.add(invocationHandler);
return Proxy.newProxyInstance(
@@ -87,8 +85,7 @@ class ConstructionContext<T> {
void setProxyDelegates(T delegate) {
if (invocationHandlers != null) {
- for (DelegatingInvocationHandler<T> invocationHandler
- : invocationHandlers) {
+ for (DelegatingInvocationHandler<T> invocationHandler : invocationHandlers) {
invocationHandler.setDelegate(delegate);
}
}
@@ -108,9 +105,7 @@ class ConstructionContext<T> {
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();
http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/inject/ContainerBuilder.java
----------------------------------------------------------------------
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 7eec820..54f5be6 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.
- *
+ * <p/>
* 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
- *
+ * <p/>
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ * <p/>
* 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<Key<?>, InternalFactory<?>> factories =
- new HashMap<Key<?>, InternalFactory<?>>();
- final List<InternalFactory<?>> singletonFactories =
- new ArrayList<InternalFactory<?>>();
- final List<Class<?>> staticInjections = new ArrayList<Class<?>>();
- boolean created;
- boolean allowDuplicates = false;
-
- private static final InternalFactory<Container> CONTAINER_FACTORY =
- new InternalFactory<Container>() {
- public Container create(InternalContext context) {
- return context.getContainer();
- }
- };
-
- private static final InternalFactory<Logger> LOGGER_FACTORY =
- new InternalFactory<Logger>() {
- public Logger create(InternalContext context) {
- Member member = context.getExternalContext().getMember();
- return member == null ? Logger.getAnonymousLogger()
- : Logger.getLogger(member.getDeclaringClass().getName());
+ final Map<Key<?>, InternalFactory<?>> factories = new HashMap<>();
+ final List<InternalFactory<?>> singletonFactories = new ArrayList<>();
+ final List<Class<?>> staticInjections = new ArrayList<>();
+ boolean created;
+ boolean allowDuplicates = false;
+
+ private static final InternalFactory<Container> CONTAINER_FACTORY =
+ new InternalFactory<Container>() {
+ public Container create(InternalContext context) {
+ return context.getContainer();
+ }
+ };
+
+ private static final InternalFactory<Logger> LOGGER_FACTORY =
+ new InternalFactory<Logger>() {
+ 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 <T> ContainerBuilder factory(final Key<T> key,
+ InternalFactory<? extends T> factory, Scope scope) {
+ ensureNotCreated();
+ checkKey(key);
+ final InternalFactory<? extends T> scopedFactory = scope.scopeFactory(key.getType(), key.getName(), factory);
+ factories.put(key, scopedFactory);
+ if (scope == Scope.SINGLETON) {
+ singletonFactories.add(new InternalFactory<T>() {
+ public T create(InternalContext context) {
+ try {
+ context.setExternalContext(ExternalContext.newInstance(null, key, context.getContainerImpl()));
+ return scopedFactory.create(context);
+ } finally {
+ context.setExternalContext(null);
+ }
+ }
+ });
}
- };
-
- /**
- * 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 <T> ContainerBuilder factory(final Key<T> key,
- InternalFactory<? extends T> factory, Scope scope) {
- ensureNotCreated();
- checkKey(key);
- final InternalFactory<? extends T> scopedFactory =
- scope.scopeFactory(key.getType(), key.getName(), factory);
- factories.put(key, scopedFactory);
- if (scope == Scope.SINGLETON) {
- singletonFactories.add(new InternalFactory<T>() {
- 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.");
}
- });
- }
- 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 <T> ContainerBuilder factory(final Class<T> type, final String name,
- final Factory<? extends T> factory, Scope scope) {
- InternalFactory<T> internalFactory =
- new InternalFactory<T>() {
-
- public T create(InternalContext context) {
- try {
- Context externalContext = context.getExternalContext();
- return factory.create(externalContext);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ }
+
+ /**
+ * 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 <T> ContainerBuilder factory(final Class<T> type, final String name,
+ final Factory<? extends T> factory, Scope scope) {
+ InternalFactory<T> internalFactory = new InternalFactory<T>() {
+
+ 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<String, Object>() {{
+ 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 <T> ContainerBuilder factory(Class<T> type, Factory<? extends T> 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 <T> ContainerBuilder factory(Class<T> type, String name, Factory<? extends T> 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 <T> ContainerBuilder factory(Class<T> type, Factory<? extends T> 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 <T> ContainerBuilder factory(final Class<T> type, final String name,
+ final Class<? extends T> 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<? extends T> factory = new InternalFactory<T>() {
+
+ volatile ContainerImpl.ConstructorInjector<? extends T> 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<String, Object>() {{
+ 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.
+ * <p/>
+ * <p>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 <T> ContainerBuilder factory(final Class<T> type, String name,
+ final Class<? extends T> 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 <T> ContainerBuilder factory(Class<T> type, Class<? extends T> 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 <T> ContainerBuilder factory(Class<T> type) {
+ return factory(type, Container.DEFAULT_NAME, type);
+ }
+
+ /**
+ * Convenience method. Equivalent to {@code factory(type, name, type)}.
+ *
+ * @see #factory(Class, String, Class)
+ */
+ public <T> ContainerBuilder factory(Class<T> 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 <T> ContainerBuilder factory(Class<T> type, Class<? extends T> 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 <T> ContainerBuilder factory(Class<T> 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 <T> ContainerBuilder factory(Class<T> 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 <T> ContainerBuilder alias(Class<T> 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 <T> ContainerBuilder alias(Class<T> 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 <T> ContainerBuilder alias(final Key<T> key,
+ final Key<T> aliasKey) {
+ ensureNotCreated();
+ checkKey(aliasKey);
+
+ final InternalFactory<? extends T> scopedFactory = (InternalFactory<? extends T>) factories.get(key);
+ if (scopedFactory == null) {
+ throw new DependencyException("Dependency mapping for " + key + " doesn't exists.");
}
- }
-
- @Override
- public String toString() {
- return new LinkedHashMap<String, Object>() {{
- 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 <T> ContainerBuilder factory(Class<T> type,
- Factory<? extends T> 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 <T> ContainerBuilder factory(Class<T> type, String name,
- Factory<? extends T> 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 <T> ContainerBuilder factory(Class<T> type,
- Factory<? extends T> 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 <T> ContainerBuilder factory(final Class<T> type, final String name,
- final Class<? extends T> 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<? extends T> factory = new InternalFactory<T>() {
-
- volatile ContainerImpl.ConstructorInjector<? extends T> constructor;
-
- @SuppressWarnings("unchecked")
- public T create(InternalContext context) {
- if (constructor == null) {
- this.constructor =
- context.getContainerImpl().getConstructor(implementation);
+ 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 <E extends Enum<E>> ContainerBuilder constant(String name, E value) {
+ return constant(value.getDeclaringClass(), name, value);
+ }
+
+ /**
+ * Maps a constant value to the given type and name.
+ */
+ private <T> ContainerBuilder constant(final Class<T> type, final String name, final T value) {
+ InternalFactory<T> factory = new InternalFactory<T>() {
+ public T create(InternalContext ignored) {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return new LinkedHashMap<String, Object>() {
+ {
+ 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<Void>() {
+ public Void call(InternalContext context) {
+ for (InternalFactory<?> factory : singletonFactories) {
+ factory.create(context);
+ }
+ return null;
+ }
+ });
}
- return (T) constructor.construct(context, type);
- }
-
- @Override
- public String toString() {
- return new LinkedHashMap<String, Object>() {{
- 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.
- *
- * <p>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 <T> ContainerBuilder factory(final Class<T> type, String name,
- final Class<? extends T> 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 <T> ContainerBuilder factory(Class<T> type,
- Class<? extends T> 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 <T> ContainerBuilder factory(Class<T> type) {
- return factory(type, Container.DEFAULT_NAME, type);
- }
-
- /**
- * Convenience method. Equivalent to {@code factory(type, name, type)}.
- *
- * @see #factory(Class, String, Class)
- */
- public <T> ContainerBuilder factory(Class<T> 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 <T> ContainerBuilder factory(Class<T> type,
- Class<? extends T> 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 <T> ContainerBuilder factory(Class<T> 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 <T> ContainerBuilder factory(Class<T> 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 <T> ContainerBuilder alias(Class<T> 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 <T> ContainerBuilder alias(Class<T> 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 <T> ContainerBuilder alias(final Key<T> key,
- final Key<T> aliasKey) {
- ensureNotCreated();
- checkKey(aliasKey);
-
- final InternalFactory<? extends T> scopedFactory =
- (InternalFactory<? extends T>)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 <E extends Enum<E>> ContainerBuilder constant(String name, E value) {
- return constant(value.getDeclaringClass(), name, value);
- }
-
- /**
- * Maps a constant value to the given type and name.
- */
- private <T> ContainerBuilder constant(final Class<T> type, final String name,
- final T value) {
- InternalFactory<T> factory = new InternalFactory<T>() {
- public T create(InternalContext ignored) {
- return value;
- }
-
- @Override
- public String toString() {
- return new LinkedHashMap<String, Object>() {
- {
- 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<Key<?>, InternalFactory<?>>(factories));
- if (loadSingletons) {
- container.callInContext(new ContainerImpl.ContextualCallable<Void>() {
- 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.");
}
- });
- }
- 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
+ }
+
+ public void setAllowDuplicates(boolean val) {
+ allowDuplicates = val;
+ }
+
+ /**
+ * Implemented by classes which participate in building a container.
*/
- void build(ContainerBuilder builder);
- }
+ public interface Command {
+
+ /**
+ * Contributes factories to the given builder.
+ *
+ * @param builder
+ */
+ void build(ContainerBuilder builder);
+ }
}