EL container integration; support for contextual objects; removal of deprecated Spring 2.0 functionality; Java 5 code style

This commit is contained in:
Juergen Hoeller
2008-11-20 02:10:53 +00:00
parent 369821dd66
commit 347f34c68a
281 changed files with 6120 additions and 9903 deletions

View File

@@ -52,6 +52,18 @@ public interface ConfigurableApplicationContext extends ApplicationContext, Life
*/
String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver";
/**
* Name of the System properties bean in the factory.
* @see java.lang.System#getProperties()
*/
String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";
/**
* Name of the System environment bean in the factory.
* @see java.lang.System#getenv()
*/
String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";
/**
* Set the parent of this application context.

View File

@@ -609,7 +609,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
"] does not carry a WebServiceClient annotation");
}
service = (Service) BeanUtils.instantiateClass(ctor,
new Object[] {new URL(this.wsdlLocation), new QName(clientAnn.targetNamespace(), clientAnn.name())});
new URL(this.wsdlLocation), new QName(clientAnn.targetNamespace(), clientAnn.name()));
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException("JAX-WS Service class [" + this.lookupType.getName() +

View File

@@ -16,14 +16,9 @@
package org.springframework.context.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.JdkVersion;
import org.springframework.util.ClassUtils;
import org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser;
import org.springframework.context.annotation.ComponentScanBeanDefinitionParser;
/**
* {@link org.springframework.beans.factory.xml.NamespaceHandler}
@@ -38,36 +33,12 @@ public class ContextNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
registerJava5DependentParser("annotation-config",
"org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser");
registerJava5DependentParser("component-scan",
"org.springframework.context.annotation.ComponentScanBeanDefinitionParser");
registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser());
registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());
registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());
}
private void registerJava5DependentParser(final String elementName, final String parserClassName) {
BeanDefinitionParser parser = null;
if (JdkVersion.isAtLeastJava15()) {
try {
Class parserClass = ClassUtils.forName(parserClassName, ContextNamespaceHandler.class.getClassLoader());
parser = (BeanDefinitionParser) parserClass.newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException("Unable to create Java 1.5 dependent parser: " + parserClassName, ex);
}
}
else {
parser = new BeanDefinitionParser() {
public BeanDefinition parse(Element element, ParserContext parserContext) {
throw new IllegalStateException("Context namespace element '" + elementName +
"' and its parser class [" + parserClassName + "] are only available on JDK 1.5 and higher");
}
};
}
registerBeanDefinitionParser(elementName, parser);
}
}

View File

@@ -23,7 +23,7 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.JdkVersion;
import org.springframework.jmx.export.annotation.AnnotationMBeanExporter;
import org.springframework.jmx.support.MBeanRegistrationSupport;
import org.springframework.util.StringUtils;
@@ -61,10 +61,7 @@ class MBeanExportBeanDefinitionParser extends AbstractBeanDefinitionParser {
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
String beanClassName = (JdkVersion.isAtLeastJava15() ?
"org.springframework.jmx.export.annotation.AnnotationMBeanExporter" :
"org.springframework.jmx.export.MBeanExporter");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClassName);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AnnotationMBeanExporter.class);
// Mark as infrastructure bean and attach source location.
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
@@ -94,7 +91,7 @@ class MBeanExportBeanDefinitionParser extends AbstractBeanDefinitionParser {
else if (REGISTRATION_REPLACE_EXISTING.equals(registration)) {
registrationBehavior = MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING;
}
builder.addPropertyValue("registrationBehavior", new Integer(registrationBehavior));
builder.addPropertyValue("registrationBehavior", registrationBehavior);
return builder.getBeanDefinition();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,10 +18,10 @@ package org.springframework.context.event;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.core.CollectionFactory;
/**
* Abstract implementation of the {@link ApplicationEventMulticaster} interface,
@@ -46,7 +46,7 @@ import org.springframework.core.CollectionFactory;
public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster {
/** Collection of ApplicationListeners */
private Collection applicationListeners = new LinkedHashSet();
private Collection<ApplicationListener> applicationListeners = new LinkedHashSet<ApplicationListener>();
/**
@@ -56,7 +56,8 @@ public abstract class AbstractApplicationEventMulticaster implements Application
* without synchronization while still making listener updates thread-safe.
*/
public void setConcurrentUpdates(boolean concurrent) {
Collection newColl = (concurrent ? CollectionFactory.createCopyOnWriteSet() : new LinkedHashSet());
Collection<ApplicationListener> newColl = concurrent ?
new CopyOnWriteArraySet<ApplicationListener>() : new LinkedHashSet<ApplicationListener>();
// Add all previously registered listeners (usually none).
newColl.addAll(this.applicationListeners);
this.applicationListeners = newColl;
@@ -70,6 +71,7 @@ public abstract class AbstractApplicationEventMulticaster implements Application
* of the same listener, while a List class will allow for registering
* the same listener multiple times.
*/
@SuppressWarnings("unchecked")
public void setCollectionClass(Class collectionClass) {
if (collectionClass == null) {
throw new IllegalArgumentException("'collectionClass' must not be null");
@@ -78,7 +80,8 @@ public abstract class AbstractApplicationEventMulticaster implements Application
throw new IllegalArgumentException("'collectionClass' must implement [java.util.Collection]");
}
// Create desired collection instance.
Collection newColl = (Collection) BeanUtils.instantiateClass(collectionClass);
Collection<ApplicationListener> newColl =
(Collection<ApplicationListener>) BeanUtils.instantiateClass(collectionClass);
// Add all previously registered listeners (usually none).
newColl.addAll(this.applicationListeners);
this.applicationListeners = newColl;

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.expression;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.util.Assert;
/**
* Abstract implementation of the {@link BeanExpressionResolver} interface.
* Handles the common mixing of expression parts with literal parts.
*
* <p>Subclasses need to implement the {@link #evaluateExpression} template
* method for actual expression evaluation.
*
* @author Juergen Hoeller
* @since 3.0
* @see #setExpressionPrefix
* @see #setExpressionSuffix
*/
public abstract class AbstractBeanExpressionResolver implements BeanExpressionResolver {
/** Default expression prefix: "#{" */
public static final String DEFAULT_EXPRESSION_PREFIX = "#{";
/** Default expression suffix: "}" */
public static final String DEFAULT_EXPRESSION_SUFFIX = "}";
private String expressionPrefix = DEFAULT_EXPRESSION_PREFIX;
private String expressionSuffix = DEFAULT_EXPRESSION_SUFFIX;
/**
* Set the prefix that an expression string starts with.
* The default is "#{".
* @see #DEFAULT_EXPRESSION_PREFIX
*/
public void setExpressionPrefix(String expressionPrefix) {
Assert.hasText(expressionPrefix, "Expression prefix must not be empty");
this.expressionPrefix = expressionPrefix;
}
/**
* Set the suffix that an expression string ends with.
* The default is "}".
* @see #DEFAULT_EXPRESSION_SUFFIX
*/
public void setExpressionSuffix(String expressionSuffix) {
Assert.hasText(expressionSuffix, "Expression suffix must not be empty");
this.expressionSuffix = expressionSuffix;
}
public Object evaluate(String value, BeanExpressionContext evalContext) {
if (value == null) {
return null;
}
Object result = "";
int prefixIndex = value.indexOf(this.expressionPrefix);
int endIndex = 0;
while (prefixIndex != -1) {
int exprStart = prefixIndex + this.expressionPrefix.length();
int suffixIndex = value.indexOf(this.expressionSuffix, exprStart);
if (suffixIndex != -1) {
if (prefixIndex > 0) {
result = result + value.substring(endIndex, prefixIndex);
}
endIndex = suffixIndex + this.expressionSuffix.length();
String expr = value.substring(exprStart, suffixIndex);
Object exprResult = evaluateExpression(expr, evalContext);
if (result != null && !"".equals(result)) {
result = result.toString() + exprResult.toString();
}
else {
result = exprResult;
}
prefixIndex = value.indexOf(this.expressionPrefix, suffixIndex);
}
else {
prefixIndex = -1;
}
}
if (endIndex < value.length()) {
return result + value.substring(endIndex);
}
else {
return result;
}
}
/**
* Evaluate the given expression.
* @param exprString the expression String to evaluate
* @param evalContext the context to evaluate the expression within
* @return the evaluation result
*/
protected abstract Object evaluateExpression(String exprString, BeanExpressionContext evalContext);
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.expression;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.PropertyAccessor;
/**
* EL property accessor that knows how to traverse the beans and contextual objects
* of a Spring {@link org.springframework.beans.factory.config.BeanExpressionContext}.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class BeanExpressionContextAccessor implements PropertyAccessor {
public boolean canRead(EvaluationContext context, Object target, Object name) throws AccessException {
return (((BeanExpressionContext) target).containsObject(name.toString()));
}
public Object read(EvaluationContext context, Object target, Object name) throws AccessException {
return ((BeanExpressionContext) target).getObject(name.toString());
}
public boolean canWrite(EvaluationContext context, Object target, Object name) throws AccessException {
return false;
}
public void write(EvaluationContext context, Object target, Object name, Object newValue) throws AccessException {
throw new AccessException("Beans in a BeanFactory are read-only");
}
public Class[] getSpecificTargetClasses() {
return new Class[] {BeanExpressionContext.class};
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.expression;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.PropertyAccessor;
/**
* EL property accessor that knows how to traverse the beans of a
* Spring {@link org.springframework.beans.factory.BeanFactory}.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class BeanFactoryAccessor implements PropertyAccessor {
public boolean canRead(EvaluationContext context, Object target, Object name) throws AccessException {
return (((BeanFactory) target).containsBean(name.toString()));
}
public Object read(EvaluationContext context, Object target, Object name) throws AccessException {
return ((BeanFactory) target).getBean(name.toString());
}
public boolean canWrite(EvaluationContext context, Object target, Object name) throws AccessException {
return false;
}
public void write(EvaluationContext context, Object target, Object name, Object newValue) throws AccessException {
throw new AccessException("Beans in a BeanFactory are read-only");
}
public Class[] getSpecificTargetClasses() {
return new Class[] {BeanFactory.class};
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.expression;
import java.util.Map;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.PropertyAccessor;
/**
* EL property accessor that knows how to traverse the keys
* of a standard {@link java.util.Map}.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MapAccessor implements PropertyAccessor {
public boolean canRead(EvaluationContext context, Object target, Object name) throws AccessException {
return (((Map) target).containsKey(name));
}
public Object read(EvaluationContext context, Object target, Object name) throws AccessException {
return ((Map) target).get(name);
}
public boolean canWrite(EvaluationContext context, Object target, Object name) throws AccessException {
return true;
}
public void write(EvaluationContext context, Object target, Object name, Object newValue) throws AccessException {
((Map) target).put(name, newValue);
}
public Class[] getSpecificTargetClasses() {
return new Class[] {Map.class};
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.expression;
import org.springframework.beans.factory.BeanExpressionException;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.SpelExpressionParser;
import org.springframework.expression.spel.standard.StandardEvaluationContext;
import org.springframework.util.Assert;
/**
* Standard implementation of the {@link BeanExpressionResolver} interface,
* parsing and evaluating Spring EL using Spring's expression module.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.expression.ExpressionParser
* @see org.springframework.expression.spel.SpelExpressionParser
* @see org.springframework.expression.spel.standard.StandardEvaluationContext
*/
public class StandardBeanExpressionResolver extends AbstractBeanExpressionResolver {
private ExpressionParser expressionParser = new SpelExpressionParser();
/**
* Specify the EL parser to use for expression parsing.
* <p>Default is a {@link org.springframework.expression.spel.SpelExpressionParser},
* compatible with standard Unified EL style expression syntax.
*/
public void setExpressionParser(ExpressionParser expressionParser) {
Assert.notNull(expressionParser, "ExpressionParser must not be null");
this.expressionParser = expressionParser;
}
protected Object evaluateExpression(String exprString, BeanExpressionContext evalContext) {
try {
Expression expr = this.expressionParser.parseExpression(exprString);
StandardEvaluationContext ec = new StandardEvaluationContext(evalContext);
ec.addPropertyAccessor(new BeanExpressionContextAccessor());
ec.addPropertyAccessor(new BeanFactoryAccessor());
ec.addPropertyAccessor(new MapAccessor());
return expr.getValue(ec);
}
catch (Exception ex) {
throw new BeanExpressionException("Expression parsing failed", ex);
}
}
/**
* Template method for customizing the expression evaluation context.
* <p>The default implementation is empty.
*/
protected void customizeEvaluationContext(StandardEvaluationContext evalContext) {
}
}

View File

@@ -0,0 +1,7 @@
<html>
<body>
Expression parsing support within a Spring application context.
</body>
</html>

View File

@@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -30,10 +29,9 @@ import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
@@ -61,7 +59,8 @@ import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.JdkVersion;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
@@ -71,7 +70,6 @@ import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
/**
@@ -151,7 +149,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
private ApplicationContext parent;
/** BeanFactoryPostProcessors to apply on refresh */
private final List beanFactoryPostProcessors = new ArrayList();
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors =
new ArrayList<BeanFactoryPostProcessor>();
/** Display name */
private String displayName;
@@ -181,7 +180,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
private ApplicationEventMulticaster applicationEventMulticaster;
/** Statically specified listeners */
private List applicationListeners = new ArrayList();
private List<ApplicationListener> applicationListeners = new ArrayList<ApplicationListener>();
/**
@@ -324,9 +323,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
/**
* Return the list of BeanFactoryPostProcessors that will get applied
* to the internal BeanFactory.
* @see org.springframework.beans.factory.config.BeanFactoryPostProcessor
*/
public List getBeanFactoryPostProcessors() {
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
@@ -336,9 +334,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
/**
* Return the list of statically specified ApplicationListeners.
* @see org.springframework.context.ApplicationListener
*/
public List getApplicationListeners() {
public List<ApplicationListener> getApplicationListeners() {
return this.applicationListeners;
}
@@ -439,10 +436,9 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader.
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
// Populate the bean factory with context-specific resource editors.
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));
// Configure the bean factory with context callbacks.
@@ -460,22 +456,19 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME) && JdkVersion.isAtLeastJava15()) {
// Register the (JDK 1.5 specific) LoadTimeWeaverAwareProcessor.
try {
Class ltwapClass = ClassUtils.forName(
"org.springframework.context.weaving.LoadTimeWeaverAwareProcessor",
AbstractApplicationContext.class.getClassLoader());
BeanPostProcessor ltwap = (BeanPostProcessor) BeanUtils.instantiateClass(ltwapClass);
((BeanFactoryAware) ltwap).setBeanFactory(beanFactory);
beanFactory.addBeanPostProcessor(ltwap);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Spring's LoadTimeWeaverAwareProcessor class is not available");
}
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
if (!beanFactory.containsBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, System.getProperties());
}
if (!beanFactory.containsBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, System.getenv());
}
}
/**
@@ -495,8 +488,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// Invoke factory processors registered with the context instance.
for (Iterator it = getBeanFactoryPostProcessors().iterator(); it.hasNext();) {
BeanFactoryPostProcessor factoryProcessor = (BeanFactoryPostProcessor) it.next();
for (BeanFactoryPostProcessor factoryProcessor : getBeanFactoryPostProcessors()) {
factoryProcessor.postProcessBeanFactory(beanFactory);
}
@@ -507,18 +499,18 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List priorityOrderedPostProcessors = new ArrayList();
List orderedPostProcessorNames = new ArrayList();
List nonOrderedPostProcessorNames = new ArrayList();
for (int i = 0; i < postProcessorNames.length; i++) {
if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i]));
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (isTypeMatch(postProcessorNames[i], Ordered.class)) {
orderedPostProcessorNames.add(postProcessorNames[i]);
else if (isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(postProcessorNames[i]);
nonOrderedPostProcessorNames.add(ppName);
}
}
@@ -527,19 +519,17 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
invokeBeanFactoryPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List orderedPostProcessors = new ArrayList();
for (Iterator it = orderedPostProcessorNames.iterator(); it.hasNext();) {
String postProcessorName = (String) it.next();
orderedPostProcessors.add(getBean(postProcessorName));
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
Collections.sort(orderedPostProcessors, new OrderComparator());
invokeBeanFactoryPostProcessors(beanFactory, orderedPostProcessors);
// Finally, invoke all other BeanFactoryPostProcessors.
List nonOrderedPostProcessors = new ArrayList();
for (Iterator it = nonOrderedPostProcessorNames.iterator(); it.hasNext();) {
String postProcessorName = (String) it.next();
nonOrderedPostProcessors.add(getBean(postProcessorName));
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(beanFactory, nonOrderedPostProcessors);
}
@@ -547,9 +537,10 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
/**
* Invoke the given BeanFactoryPostProcessor beans.
*/
private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) {
for (Iterator it = postProcessors.iterator(); it.hasNext();) {
BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor) it.next();
private void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> postProcessors) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
@@ -570,18 +561,18 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List priorityOrderedPostProcessors = new ArrayList();
List orderedPostProcessorNames = new ArrayList();
List nonOrderedPostProcessorNames = new ArrayList();
for (int i = 0; i < postProcessorNames.length; i++) {
if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i]));
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanPostProcessor.class));
}
else if (isTypeMatch(postProcessorNames[i], Ordered.class)) {
orderedPostProcessorNames.add(postProcessorNames[i]);
else if (isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(postProcessorNames[i]);
nonOrderedPostProcessorNames.add(ppName);
}
}
@@ -590,19 +581,17 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List orderedPostProcessors = new ArrayList();
for (Iterator it = orderedPostProcessorNames.iterator(); it.hasNext();) {
String postProcessorName = (String) it.next();
orderedPostProcessors.add(getBean(postProcessorName));
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(getBean(postProcessorName, BeanPostProcessor.class));
}
Collections.sort(orderedPostProcessors, new OrderComparator());
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Finally, register all other BeanPostProcessors.
List nonOrderedPostProcessors = new ArrayList();
for (Iterator it = nonOrderedPostProcessorNames.iterator(); it.hasNext();) {
String postProcessorName = (String) it.next();
nonOrderedPostProcessors.add(getBean(postProcessorName));
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(getBean(postProcessorName, BeanPostProcessor.class));
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
}
@@ -610,9 +599,10 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
/**
* Register the given BeanPostProcessor beans.
*/
private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) {
for (Iterator it = postProcessors.iterator(); it.hasNext();) {
BeanPostProcessor postProcessor = (BeanPostProcessor) it.next();
private void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
@@ -624,7 +614,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = (MessageSource) beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
@@ -659,7 +649,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster = (ApplicationEventMulticaster)
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
@@ -693,14 +683,14 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
*/
protected void registerListeners() {
// Register statically specified listeners first.
for (Iterator it = getApplicationListeners().iterator(); it.hasNext();) {
addListener((ApplicationListener) it.next());
for (ApplicationListener listener : getApplicationListeners()) {
addListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
Collection listenerBeans = getBeansOfType(ApplicationListener.class, true, false).values();
for (Iterator it = listenerBeans.iterator(); it.hasNext();) {
addListener((ApplicationListener) it.next());
Collection<ApplicationListener> lisBeans = getBeansOfType(ApplicationListener.class, true, false).values();
for (ApplicationListener lisBean : lisBeans) {
addListener(lisBean);
}
}
@@ -823,9 +813,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
logger.error("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
// Stop all Lifecycle beans, to avoid delays during individual destruction.
Map lifecycleBeans = getLifecycleBeans();
for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) {
String beanName = (String) it.next();
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
for (String beanName : new LinkedHashSet<String>(lifecycleBeans.keySet())) {
doStop(lifecycleBeans, beanName);
}
// Destroy all cached singletons in the context's BeanFactory.
@@ -881,7 +870,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
return getBeanFactory().getBean(name);
}
public Object getBean(String name, Class requiredType) throws BeansException {
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return getBeanFactory().getBean(name, requiredType);
}
@@ -938,11 +927,11 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
return getBeanFactory().getBeanNamesForType(type, includePrototypes, allowEagerInit);
}
public Map getBeansOfType(Class type) throws BeansException {
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
return getBeanFactory().getBeansOfType(type);
}
public Map getBeansOfType(Class type, boolean includePrototypes, boolean allowEagerInit)
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includePrototypes, boolean allowEagerInit)
throws BeansException {
return getBeanFactory().getBeansOfType(type, includePrototypes, allowEagerInit);
@@ -968,7 +957,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
*/
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext) ?
((ConfigurableApplicationContext) getParent()).getBeanFactory() : (BeanFactory) getParent();
((ConfigurableApplicationContext) getParent()).getBeanFactory() : getParent();
}
@@ -1025,27 +1014,23 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
//---------------------------------------------------------------------
public void start() {
Map lifecycleBeans = getLifecycleBeans();
for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) {
String beanName = (String) it.next();
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
for (String beanName : new LinkedHashSet<String>(lifecycleBeans.keySet())) {
doStart(lifecycleBeans, beanName);
}
publishEvent(new ContextStartedEvent(this));
}
public void stop() {
Map lifecycleBeans = getLifecycleBeans();
for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) {
String beanName = (String) it.next();
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
for (String beanName : new LinkedHashSet<String>(lifecycleBeans.keySet())) {
doStop(lifecycleBeans, beanName);
}
publishEvent(new ContextStoppedEvent(this));
}
public boolean isRunning() {
Iterator it = getLifecycleBeans().values().iterator();
while (it.hasNext()) {
Lifecycle lifecycle = (Lifecycle) it.next();
for (Lifecycle lifecycle : getLifecycleBeans().values()) {
if (!lifecycle.isRunning()) {
return false;
}
@@ -1058,14 +1043,14 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
* Lifecycle interface in this context.
* @return Map of Lifecycle beans with bean name as key
*/
private Map getLifecycleBeans() {
private Map<String, Lifecycle> getLifecycleBeans() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
String[] beanNames = beanFactory.getSingletonNames();
Map beans = new LinkedHashMap();
for (int i = 0; i < beanNames.length; i++) {
Object bean = beanFactory.getSingleton(beanNames[i]);
Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>();
for (String beanName : beanNames) {
Object bean = beanFactory.getSingleton(beanName);
if (bean instanceof Lifecycle) {
beans.put(beanNames[i], bean);
beans.put(beanName, (Lifecycle) bean);
}
}
return beans;
@@ -1081,8 +1066,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName);
if (bean != null) {
String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
for (int i = 0; i < dependenciesForBean.length; i++) {
doStart(lifecycleBeans, dependenciesForBean[i]);
for (String dependency : dependenciesForBean) {
doStart(lifecycleBeans, dependency);
}
if (!bean.isRunning()) {
bean.start();
@@ -1101,8 +1086,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName);
if (bean != null) {
String[] dependentBeans = getBeanFactory().getDependentBeans(beanName);
for (int i = 0; i < dependentBeans.length; i++) {
doStop(lifecycleBeans, dependentBeans[i]);
for (String dependentBean : dependentBeans) {
doStop(lifecycleBeans, dependentBean);
}
if (bean.isRunning()) {
bean.stop();
@@ -1156,7 +1141,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getId());
StringBuilder sb = new StringBuilder(getId());
sb.append(": display name [").append(getDisplayName());
sb.append("]; startup date [").append(new Date(getStartupDate()));
sb.append("]; ");

View File

@@ -121,11 +121,11 @@ public class DefaultMessageSourceResolvable implements MessageSourceResolvable,
* including codes, arguments, and default message.
*/
protected final String resolvableToString() {
StringBuffer buf = new StringBuffer();
buf.append("codes [").append(StringUtils.arrayToDelimitedString(this.codes, ","));
buf.append("]; arguments [" + StringUtils.arrayToDelimitedString(this.arguments, ","));
buf.append("]; default message [").append(this.defaultMessage).append(']');
return buf.toString();
StringBuilder result = new StringBuilder();
result.append("codes [").append(StringUtils.arrayToDelimitedString(this.codes, ","));
result.append("]; arguments [" + StringUtils.arrayToDelimitedString(this.arguments, ","));
result.append("]; default message [").append(this.defaultMessage).append(']');
return result.toString();
}
/**

View File

@@ -405,7 +405,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
StringBuffer temp = new StringBuffer(basename);
StringBuilder temp = new StringBuilder(basename);
if (language.length() > 0) {
temp.append('_').append(language);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -64,12 +64,23 @@ public class LoadTimeWeaverAwareProcessor implements BeanPostProcessor, BeanFact
* <code>LoadTimeWeaver</code> will be auto-retrieved from the containing
* {@link BeanFactory}, expecting a bean named
* {@link ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME "loadTimeWeaver"}.
* @param loadTimeWeaver the specific <code>LoadTimeWeaver</code> that is to be used; can be <code>null</code>
* @param loadTimeWeaver the specific <code>LoadTimeWeaver</code> that is to be used
*/
public LoadTimeWeaverAwareProcessor(LoadTimeWeaver loadTimeWeaver) {
this.loadTimeWeaver = loadTimeWeaver;
}
/**
* Create a new <code>LoadTimeWeaverAwareProcessor</code>.
* <p>The <code>LoadTimeWeaver</code> will be auto-retrieved from
* the given {@link BeanFactory}, expecting a bean named
* {@link ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME "loadTimeWeaver"}.
* @param loadTimeWeaver the specific <code>LoadTimeWeaver</code> that is to be used
*/
public LoadTimeWeaverAwareProcessor(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
@@ -82,7 +93,7 @@ public class LoadTimeWeaverAwareProcessor implements BeanPostProcessor, BeanFact
if (ltw == null) {
Assert.state(this.beanFactory != null,
"BeanFactory required if no LoadTimeWeaver explicitly specified");
ltw = (LoadTimeWeaver) this.beanFactory.getBean(
ltw = this.beanFactory.getBean(
ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, LoadTimeWeaver.class);
}
((LoadTimeWeaverAware) bean).setLoadTimeWeaver(ltw);

View File

@@ -66,8 +66,8 @@ public class ShadowingClassLoader extends DecoratingClassLoader {
public ShadowingClassLoader(ClassLoader enclosingClassLoader) {
Assert.notNull(enclosingClassLoader, "Enclosing ClassLoader must not be null");
this.enclosingClassLoader = enclosingClassLoader;
for (int i = 0; i < DEFAULT_EXCLUDED_PACKAGES.length; i++) {
excludePackage(DEFAULT_EXCLUDED_PACKAGES[i]);
for (String excludedPackage : DEFAULT_EXCLUDED_PACKAGES) {
excludePackage(excludedPackage);
}
}
@@ -113,8 +113,8 @@ public class ShadowingClassLoader extends DecoratingClassLoader {
* @return whether the specified class should be shadowed
*/
private boolean shouldShadow(String className) {
return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader")
&& isEligibleForShadowing(className) && !isClassNameExcludedFromShadowing(className));
return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader") &&
isEligibleForShadowing(className));
}
/**
@@ -128,18 +128,6 @@ public class ShadowingClassLoader extends DecoratingClassLoader {
return !isExcluded(className);
}
/**
* Subclasses can override this method to specify whether or not a
* particular class should be excluded from shadowing.
* @param className the class name to test
* @return whether the specified class is excluded
* @deprecated in favor of {@link #isEligibleForShadowing}
*/
@Deprecated
protected boolean isClassNameExcludedFromShadowing(String className) {
return false;
}
private Class doLoadClass(String name) throws ClassNotFoundException {
String internalName = StringUtils.replace(name, ".", "/") + ".class";

View File

@@ -50,7 +50,7 @@ class ConnectorDelegate {
* @param environment the JMX environment for the connector (may be <code>null</code>)
* @param agentId the local JMX MBeanServer's agent id (may be <code>null</code>)
*/
public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map environment, String agentId)
public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map<String, ?> environment, String agentId)
throws MBeanServerNotFoundException {
if (serviceUrl != null) {

View File

@@ -23,7 +23,6 @@ import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.management.Attribute;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
@@ -73,9 +72,6 @@ import org.springframework.util.ReflectionUtils;
* {@link #setConnectOnStartup(boolean) connectOnStartup} property to "false",
* you can defer this process until the first invocation against the proxy.
*
* <p>Requires JMX 1.2's <code>MBeanServerConnection</code> feature.
* As a consequence, this class will not work on JMX 1.0.
*
* <p>This functionality is usually used through {@link MBeanProxyFactoryBean}.
* See the javadoc of that class for more information.
*
@@ -95,7 +91,7 @@ public class MBeanClientInterceptor
private JMXServiceURL serviceUrl;
private Map environment;
private Map<String, ?> environment;
private String agentId;
@@ -117,11 +113,11 @@ public class MBeanClientInterceptor
private MBeanServerInvocationHandler invocationHandler;
private Map allowedAttributes;
private Map<String, MBeanAttributeInfo> allowedAttributes;
private Map allowedOperations;
private Map<MethodCacheKey, MBeanOperationInfo> allowedOperations;
private final Map signatureCache = new HashMap();
private final Map<Method, String[]> signatureCache = new HashMap<Method, String[]>();
private final Object preparationMonitor = new Object();
@@ -145,7 +141,7 @@ public class MBeanClientInterceptor
* Specify the environment for the JMX connector.
* @see javax.management.remote.JMXConnectorFactory#connect(javax.management.remote.JMXServiceURL, java.util.Map)
*/
public void setEnvironment(Map environment) {
public void setEnvironment(Map<String, ?> environment) {
this.environment = environment;
}
@@ -156,7 +152,7 @@ public class MBeanClientInterceptor
* "environment[myKey]". This is particularly useful for
* adding or overriding entries in child bean definitions.
*/
public Map getEnvironment() {
public Map<String, ?> getEnvironment() {
return this.environment;
}
@@ -288,17 +284,16 @@ public class MBeanClientInterceptor
MBeanInfo info = this.serverToUse.getMBeanInfo(this.objectName);
MBeanAttributeInfo[] attributeInfo = info.getAttributes();
this.allowedAttributes = new HashMap(attributeInfo.length);
for (int x = 0; x < attributeInfo.length; x++) {
this.allowedAttributes.put(attributeInfo[x].getName(), attributeInfo[x]);
this.allowedAttributes = new HashMap<String, MBeanAttributeInfo>(attributeInfo.length);
for (MBeanAttributeInfo infoEle : attributeInfo) {
this.allowedAttributes.put(infoEle.getName(), infoEle);
}
MBeanOperationInfo[] operationInfo = info.getOperations();
this.allowedOperations = new HashMap(operationInfo.length);
for (int x = 0; x < operationInfo.length; x++) {
MBeanOperationInfo opInfo = operationInfo[x];
Class[] paramTypes = JmxUtils.parameterInfoToTypes(opInfo.getSignature(), this.beanClassLoader);
this.allowedOperations.put(new MethodCacheKey(opInfo.getName(), paramTypes), opInfo);
this.allowedOperations = new HashMap<MethodCacheKey, MBeanOperationInfo>(operationInfo.length);
for (MBeanOperationInfo infoEle : operationInfo) {
Class[] paramTypes = JmxUtils.parameterInfoToTypes(infoEle.getSignature(), this.beanClassLoader);
this.allowedOperations.put(new MethodCacheKey(infoEle.getName(), paramTypes), infoEle);
}
}
catch (ClassNotFoundException ex) {
@@ -467,7 +462,7 @@ public class MBeanClientInterceptor
throws JMException, IOException {
String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
MBeanAttributeInfo inf = (MBeanAttributeInfo) this.allowedAttributes.get(attributeName);
MBeanAttributeInfo inf = this.allowedAttributes.get(attributeName);
// If no attribute is returned, we know that it is not defined in the
// management interface.
if (inf == null) {
@@ -506,14 +501,14 @@ public class MBeanClientInterceptor
*/
private Object invokeOperation(Method method, Object[] args) throws JMException, IOException {
MethodCacheKey key = new MethodCacheKey(method.getName(), method.getParameterTypes());
MBeanOperationInfo info = (MBeanOperationInfo) this.allowedOperations.get(key);
MBeanOperationInfo info = this.allowedOperations.get(key);
if (info == null) {
throw new InvalidInvocationException("Operation '" + method.getName() +
"' is not exposed on the management interface");
}
String[] signature = null;
synchronized (this.signatureCache) {
signature = (String[]) this.signatureCache.get(method);
signature = this.signatureCache.get(method);
if (signature == null) {
signature = JmxUtils.getMethodSignature(method);
this.signatureCache.put(method, signature);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,9 +39,6 @@ import org.springframework.util.ClassUtils;
* interface that does not correspond to the management interface will lead
* to an <code>InvalidInvocationException</code>.
*
* <p>Requires JMX 1.2's <code>MBeanServerConnection</code> feature.
* As a consequence, this class will not work on JMX 1.0.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2

View File

@@ -40,9 +40,6 @@ import org.springframework.util.CollectionUtils;
* with one or more MBeans in an {@link javax.management.MBeanServer}
* (typically via a {@link javax.management.MBeanServerConnection}).
*
* <p>Requires JMX 1.2's <code>MBeanServerConnection</code> feature.
* As a consequence, this class will not work on JMX 1.0.
*
* @author Juergen Hoeller
* @since 2.5.2
* @see #setServer
@@ -59,7 +56,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder
private JMXServiceURL serviceUrl;
private Map environment;
private Map<String, ?> environment;
private String agentId;
@@ -80,7 +77,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder
* Specify the environment for the JMX connector.
* @see javax.management.remote.JMXConnectorFactory#connect(javax.management.remote.JMXServiceURL, java.util.Map)
*/
public void setEnvironment(Map environment) {
public void setEnvironment(Map<String, ?> environment) {
this.environment = environment;
}
@@ -91,7 +88,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder
* "environment[myKey]". This is particularly useful for
* adding or overriding entries in child bean definitions.
*/
public Map getEnvironment() {
public Map<String, ?> getEnvironment() {
return this.environment;
}
@@ -138,9 +135,9 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder
if (logger.isDebugEnabled()) {
logger.debug("Registering NotificationListener for MBeans " + Arrays.asList(this.actualObjectNames));
}
for (int i = 0; i < this.actualObjectNames.length; i++) {
this.server.addNotificationListener(this.actualObjectNames[i],
getNotificationListener(), getNotificationFilter(), getHandback());
for (ObjectName actualObjectName : this.actualObjectNames) {
this.server.addNotificationListener(
actualObjectName, getNotificationListener(), getNotificationFilter(), getHandback());
}
}
catch (IOException ex) {
@@ -158,10 +155,10 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder
public void destroy() {
try {
if (this.actualObjectNames != null) {
for (int i = 0; i < this.actualObjectNames.length; i++) {
for (ObjectName actualObjectName : this.actualObjectNames) {
try {
this.server.removeNotificationListener(this.actualObjectNames[i],
getNotificationListener(), getNotificationFilter(), getHandback());
this.server.removeNotificationListener(
actualObjectName, getNotificationListener(), getNotificationFilter(), getHandback());
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {

View File

@@ -20,12 +20,10 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.DynamicMBean;
import javax.management.JMException;
import javax.management.MBeanException;
@@ -86,10 +84,8 @@ import org.springframework.util.ObjectUtils;
* allowing application code to be notified of MBean registration and
* unregistration events.
*
* <p>This exporter is compatible with JMX 1.0 or higher for its basic
* functionality. However, for adapting AOP proxies where the target
* bean is a native MBean, JMX 1.2 is required. As of Spring 2.5,
* this class also autodetects and exports JDK 1.6 MXBeans.
* <p>This exporter is compatible with JMX 1.2 on Java 5 and above.
* As of Spring 2.5, it also autodetects and exports Java 6 MXBeans.
*
* @author Rob Harrop
* @author Juergen Hoeller
@@ -145,7 +141,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
private static final Constants constants = new Constants(MBeanExporter.class);
/** The beans to be exposed as JMX managed resources, with JMX names as keys */
private Map beans;
private Map<String, Object> beans;
/** The autodetect mode to use for this MBeanExporter */
private Integer autodetectMode;
@@ -160,7 +156,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
private boolean exposeManagedResourceClassLoader = true;
/** A set of bean names that should be excluded from autodetection */
private Set excludedBeans;
private Set<String> excludedBeans;
/** The MBeanExporterListeners registered with this exporter. */
private MBeanExporterListener[] listeners;
@@ -169,7 +165,8 @@ public class MBeanExporter extends MBeanRegistrationSupport
private NotificationListenerBean[] notificationListeners;
/** Map of actually registered NotificationListeners */
private final Map registeredNotificationListeners = new LinkedHashMap();
private final Map<NotificationListenerBean, ObjectName[]> registeredNotificationListeners =
new LinkedHashMap<NotificationListenerBean, ObjectName[]>();
/** Stores the MBeanInfoAssembler to use for this exporter */
private MBeanInfoAssembler assembler = new SimpleReflectiveMBeanInfoAssembler();
@@ -201,7 +198,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
* @see org.springframework.jmx.export.naming.KeyNamingStrategy
* @see javax.management.ObjectName#ObjectName(String)
*/
public void setBeans(Map beans) {
public void setBeans(Map<String, Object> beans) {
this.beans = beans;
}
@@ -216,7 +213,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
* @see #isMBean
*/
public void setAutodetect(boolean autodetect) {
this.autodetectMode = new Integer(autodetect ? AUTODETECT_ALL : AUTODETECT_NONE);
this.autodetectMode = (autodetect ? AUTODETECT_ALL : AUTODETECT_NONE);
}
/**
@@ -233,7 +230,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
if (!constants.getValues(CONSTANT_PREFIX_AUTODETECT).contains(new Integer(autodetectMode))) {
throw new IllegalArgumentException("Only values of autodetect constants allowed");
}
this.autodetectMode = new Integer(autodetectMode);
this.autodetectMode = autodetectMode;
}
/**
@@ -302,7 +299,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
* Set the list of names for beans that should be excluded from autodetection.
*/
public void setExcludedBeans(String[] excludedBeans) {
this.excludedBeans = (excludedBeans != null ? new HashSet(Arrays.asList(excludedBeans)) : null);
this.excludedBeans = (excludedBeans != null ? new HashSet<String>(Arrays.asList(excludedBeans)) : null);
}
/**
@@ -354,34 +351,25 @@ public class MBeanExporter extends MBeanRegistrationSupport
* advanced options such as registering
* {@link javax.management.NotificationFilter NotificationFilters} and
* handback objects see {@link #setNotificationListeners(NotificationListenerBean[])}.
* @throws IllegalArgumentException if the supplied <code>listeners</code> {@link Map} is <code>null</code>.
*/
public void setNotificationListenerMappings(Map listeners) {
public void setNotificationListenerMappings(Map<?, ? extends NotificationListener> listeners) {
Assert.notNull(listeners, "'listeners' must not be null");
List notificationListeners = new ArrayList(listeners.size());
for (Iterator iterator = listeners.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
List<NotificationListenerBean> notificationListeners =
new ArrayList<NotificationListenerBean>(listeners.size());
for (Map.Entry<?, ? extends NotificationListener> entry : listeners.entrySet()) {
// Get the listener from the map value.
Object value = entry.getValue();
if (!(value instanceof NotificationListener)) {
throw new IllegalArgumentException(
"Map entry value [" + value + "] is not a NotificationListener");
}
NotificationListenerBean bean = new NotificationListenerBean((NotificationListener) value);
NotificationListenerBean bean = new NotificationListenerBean(entry.getValue());
// Get the ObjectName from the map key.
Object key = entry.getKey();
if (key != null && !WILDCARD.equals(key)) {
// This listener is mapped to a specific ObjectName.
bean.setMappedObjectName(entry.getKey());
}
notificationListeners.add(bean);
}
this.notificationListeners = (NotificationListenerBean[])
this.notificationListeners =
notificationListeners.toArray(new NotificationListenerBean[notificationListeners.size()]);
}
@@ -507,15 +495,15 @@ public class MBeanExporter extends MBeanRegistrationSupport
protected void registerBeans() {
// The beans property may be null, for example if we are relying solely on autodetection.
if (this.beans == null) {
this.beans = new HashMap();
this.beans = new HashMap<String, Object>();
// Use AUTODETECT_ALL as default in no beans specified explicitly.
if (this.autodetectMode == null) {
this.autodetectMode = new Integer(AUTODETECT_ALL);
this.autodetectMode = AUTODETECT_ALL;
}
}
// Perform autodetection, if desired.
int mode = (this.autodetectMode != null ? this.autodetectMode.intValue() : AUTODETECT_NONE);
int mode = (this.autodetectMode != null ? this.autodetectMode : AUTODETECT_NONE);
if (mode != AUTODETECT_NONE) {
if (this.beanFactory == null) {
throw new MBeanExportException("Cannot autodetect MBeans if not running in a BeanFactory");
@@ -533,12 +521,8 @@ public class MBeanExporter extends MBeanRegistrationSupport
}
if (!this.beans.isEmpty()) {
for (Iterator it = this.beans.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Assert.notNull(entry.getKey(), "Beans key must not be null");
String beanKey = entry.getKey().toString();
Object value = entry.getValue();
registerBeanNameOrInstance(value, beanKey);
for (Map.Entry<String, Object> entry : this.beans.entrySet()) {
registerBeanNameOrInstance(entry.getValue(), entry.getKey());
}
}
}
@@ -607,11 +591,11 @@ public class MBeanExporter extends MBeanRegistrationSupport
else {
// Plain bean instance -> register it directly.
if (this.beanFactory != null) {
Map beansOfSameType = this.beanFactory.getBeansOfType(mapValue.getClass(), false, false);
for (Iterator iterator = beansOfSameType.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
Map<String, ?> beansOfSameType =
this.beanFactory.getBeansOfType(mapValue.getClass(), false, false);
for (Map.Entry<String, ?> entry : beansOfSameType.entrySet()) {
if (entry.getValue() == mapValue) {
String beanName = (String) entry.getKey();
String beanName = entry.getKey();
ObjectName objectName = registerBeanInstance(mapValue, beanKey);
replaceNotificationListenerBeanNameKeysIfNecessary(beanName, objectName);
return objectName;
@@ -636,8 +620,8 @@ public class MBeanExporter extends MBeanRegistrationSupport
*/
private void replaceNotificationListenerBeanNameKeysIfNecessary(String beanName, ObjectName objectName) {
if (this.notificationListeners != null) {
for (int i = 0; i < this.notificationListeners.length; i++) {
this.notificationListeners[i].replaceObjectName(beanName, objectName);
for (NotificationListenerBean notificationListener : this.notificationListeners) {
notificationListener.replaceObjectName(beanName, objectName);
}
}
}
@@ -889,15 +873,14 @@ public class MBeanExporter extends MBeanRegistrationSupport
*/
private void autodetect(AutodetectCallback callback) {
String[] beanNames = this.beanFactory.getBeanNamesForType(Object.class, true, this.allowEagerInit);
for (int i = 0; i < beanNames.length; i++) {
String beanName = beanNames[i];
for (String beanName : beanNames) {
if (!isExcluded(beanName)) {
Class beanClass = this.beanFactory.getType(beanName);
if (beanClass != null && callback.include(beanClass, beanName)) {
boolean lazyInit = isBeanDefinitionLazyInit(this.beanFactory, beanName);
Object beanInstance = (!lazyInit ? this.beanFactory.getBean(beanName) : null);
if (!this.beans.containsValue(beanName) &&
(beanInstance == null || !CollectionUtils.containsInstance(this.beans.values(), beanInstance))) {
if (!this.beans.containsValue(beanName) && (beanInstance == null ||
!CollectionUtils.containsInstance(this.beans.values(), beanInstance))) {
// Not already registered for JMX exposure.
this.beans.put(beanName, (beanInstance != null ? beanInstance : beanName));
if (logger.isInfoEnabled()) {
@@ -945,8 +928,7 @@ public class MBeanExporter extends MBeanRegistrationSupport
*/
private void registerNotificationListeners() throws MBeanExportException {
if (this.notificationListeners != null) {
for (int i = 0; i < this.notificationListeners.length; i++) {
NotificationListenerBean bean = this.notificationListeners[i];
for (NotificationListenerBean bean : this.notificationListeners) {
try {
ObjectName[] mappedObjectNames = bean.getResolvedObjectNames();
if (mappedObjectNames == null) {
@@ -954,9 +936,9 @@ public class MBeanExporter extends MBeanRegistrationSupport
mappedObjectNames = getRegisteredObjectNames();
}
if (this.registeredNotificationListeners.put(bean, mappedObjectNames) == null) {
for (int j = 0; j < mappedObjectNames.length; j++) {
this.server.addNotificationListener(mappedObjectNames[j],
bean.getNotificationListener(), bean.getNotificationFilter(), bean.getHandback());
for (ObjectName mappedObjectName : mappedObjectNames) {
this.server.addNotificationListener(mappedObjectName, bean.getNotificationListener(),
bean.getNotificationFilter(), bean.getHandback());
}
}
}
@@ -972,14 +954,13 @@ public class MBeanExporter extends MBeanRegistrationSupport
* from the {@link MBeanServer}.
*/
private void unregisterNotificationListeners() {
for (Iterator it = this.registeredNotificationListeners.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
NotificationListenerBean bean = (NotificationListenerBean) entry.getKey();
ObjectName[] mappedObjectNames = (ObjectName[]) entry.getValue();
for (int j = 0; j < mappedObjectNames.length; j++) {
for (Map.Entry<NotificationListenerBean, ObjectName[]> entry : this.registeredNotificationListeners.entrySet()) {
NotificationListenerBean bean = entry.getKey();
ObjectName[] mappedObjectNames = entry.getValue();
for (ObjectName mappedObjectName : mappedObjectNames) {
try {
this.server.removeNotificationListener(mappedObjectNames[j],
bean.getNotificationListener(), bean.getNotificationFilter(), bean.getHandback());
this.server.removeNotificationListener(mappedObjectName, bean.getNotificationListener(),
bean.getNotificationFilter(), bean.getHandback());
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
@@ -1028,8 +1009,8 @@ public class MBeanExporter extends MBeanRegistrationSupport
*/
private void notifyListenersOfRegistration(ObjectName objectName) {
if (this.listeners != null) {
for (int i = 0; i < this.listeners.length; i++) {
this.listeners[i].mbeanRegistered(objectName);
for (MBeanExporterListener listener : this.listeners) {
listener.mbeanRegistered(objectName);
}
}
}
@@ -1040,8 +1021,8 @@ public class MBeanExporter extends MBeanRegistrationSupport
*/
private void notifyListenersOfUnregistration(ObjectName objectName) {
if (this.listeners != null) {
for (int i = 0; i < this.listeners.length; i++) {
this.listeners[i].mbeanUnregistered(objectName);
for (MBeanExporterListener listener : this.listeners) {
listener.mbeanUnregistered(objectName);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,6 @@ import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.management.Descriptor;
import javax.management.JMException;
import javax.management.MBeanOperationInfo;
@@ -31,7 +30,6 @@ import javax.management.modelmbean.ModelMBeanOperationInfo;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.JdkVersion;
import org.springframework.jmx.support.JmxUtils;
/**
@@ -252,10 +250,10 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
@Override
protected ModelMBeanAttributeInfo[] getAttributeInfo(Object managedBean, String beanKey) throws JMException {
PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(getClassToExpose(managedBean));
List infos = new ArrayList();
List<ModelMBeanAttributeInfo> infos = new ArrayList<ModelMBeanAttributeInfo>();
for (int i = 0; i < props.length; i++) {
Method getter = props[i].getReadMethod();
for (PropertyDescriptor prop : props) {
Method getter = prop.getReadMethod();
if (getter != null && getter.getDeclaringClass() == Object.class) {
continue;
}
@@ -263,15 +261,15 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
getter = null;
}
Method setter = props[i].getWriteMethod();
Method setter = prop.getWriteMethod();
if (setter != null && !includeWriteAttribute(setter, beanKey)) {
setter = null;
}
if (getter != null || setter != null) {
// If both getter and setter are null, then this does not need exposing.
String attrName = JmxUtils.getAttributeName(props[i], isUseStrictCasing());
String description = getAttributeDescription(props[i], beanKey);
String attrName = JmxUtils.getAttributeName(prop, isUseStrictCasing());
String description = getAttributeDescription(prop, beanKey);
ModelMBeanAttributeInfo info = new ModelMBeanAttributeInfo(attrName, description, getter, setter);
Descriptor desc = info.getDescriptor();
@@ -288,7 +286,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
}
}
return (ModelMBeanAttributeInfo[]) infos.toArray(new ModelMBeanAttributeInfo[infos.size()]);
return infos.toArray(new ModelMBeanAttributeInfo[infos.size()]);
}
/**
@@ -306,11 +304,10 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
@Override
protected ModelMBeanOperationInfo[] getOperationInfo(Object managedBean, String beanKey) {
Method[] methods = getClassToExpose(managedBean).getMethods();
List infos = new ArrayList();
List<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (JdkVersion.isAtLeastJava15() && method.isSynthetic()) {
for (Method method : methods) {
if (method.isSynthetic()) {
continue;
}
if (method.getDeclaringClass().equals(Object.class)) {
@@ -355,7 +352,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean
}
}
return (ModelMBeanOperationInfo[]) infos.toArray(new ModelMBeanOperationInfo[infos.size()]);
return infos.toArray(new ModelMBeanOperationInfo[infos.size()]);
}
/**

View File

@@ -21,7 +21,6 @@ import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.List;
import javax.management.DynamicMBean;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer;
@@ -33,7 +32,6 @@ import javax.management.ObjectName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.JdkVersion;
import org.springframework.jmx.MBeanServerNotFoundException;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
@@ -114,7 +112,7 @@ public abstract class JmxUtils {
server = (MBeanServer) servers.get(0);
}
if (server == null && agentId == null && JdkVersion.isAtLeastJava15()) {
if (server == null && agentId == null) {
// Attempt to load the PlatformMBeanServer.
try {
server = ManagementFactory.getPlatformMBeanServer();
@@ -221,7 +219,7 @@ public abstract class JmxUtils {
public static ObjectName appendIdentityToObjectName(ObjectName objectName, Object managedResource)
throws MalformedObjectNameException {
Hashtable keyProperties = objectName.getKeyPropertyList();
Hashtable<String, String> keyProperties = objectName.getKeyPropertyList();
keyProperties.put(IDENTITY_OBJECT_NAME_KEY, ObjectUtils.getIdentityHexString(managedResource));
return ObjectNameManager.getInstance(objectName.getDomain(), keyProperties);
}
@@ -282,8 +280,7 @@ public abstract class JmxUtils {
}
String mbeanInterfaceName = clazz.getName() + MBEAN_SUFFIX;
Class[] implementedInterfaces = clazz.getInterfaces();
for (int x = 0; x < implementedInterfaces.length; x++) {
Class iface = implementedInterfaces[x];
for (Class iface : implementedInterfaces) {
if (iface.getName().equals(mbeanInterfaceName)) {
return iface;
}
@@ -303,13 +300,12 @@ public abstract class JmxUtils {
return null;
}
Class[] implementedInterfaces = clazz.getInterfaces();
for (int x = 0; x < implementedInterfaces.length; x++) {
Class iface = implementedInterfaces[x];
for (Class iface : implementedInterfaces) {
boolean isMxBean = iface.getName().endsWith(MXBEAN_SUFFIX);
if (mxBeanAnnotationAvailable) {
Boolean checkResult = MXBeanChecker.hasMXBeanAnnotation(iface);
if (checkResult != null) {
isMxBean = checkResult.booleanValue();
isMxBean = checkResult;
}
}
if (isMxBean) {
@@ -325,14 +321,9 @@ public abstract class JmxUtils {
*/
private static class MXBeanChecker {
public static Boolean hasMXBeanAnnotation(Class iface) {
MXBean mxBean = (MXBean) iface.getAnnotation(MXBean.class);
if (mxBean != null) {
return Boolean.valueOf(mxBean.value());
}
else {
return null;
}
public static Boolean hasMXBeanAnnotation(Class<?> iface) {
MXBean mxBean = iface.getAnnotation(MXBean.class);
return (mxBean != null ? mxBean.value() : null);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,18 +17,12 @@
package org.springframework.jmx.support;
import java.util.Hashtable;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.springframework.util.ClassUtils;
/**
* Helper class for the creation of {@link javax.management.ObjectName} instances.
*
* <p><code>ObjectName</code> instances will be cached on JMX 1.2,
* whereas they will be recreated for each request on JMX 1.0.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2
@@ -36,11 +30,6 @@ import org.springframework.util.ClassUtils;
*/
public class ObjectNameManager {
// Determine whether the JMX 1.2 <code>ObjectName.getInstance</code> method is available.
private static final boolean getInstanceAvailable =
ClassUtils.hasMethod(ObjectName.class, "getInstance", new Class[] {String.class});
/**
* Retrieve the <code>ObjectName</code> instance corresponding to the supplied name.
* @param objectName the <code>ObjectName</code> in <code>ObjectName</code> or
@@ -70,12 +59,7 @@ public class ObjectNameManager {
* @see ObjectName#getInstance(String)
*/
public static ObjectName getInstance(String objectName) throws MalformedObjectNameException {
if (getInstanceAvailable) {
return ObjectName.getInstance(objectName);
}
else {
return new ObjectName(objectName);
}
return ObjectName.getInstance(objectName);
}
/**
@@ -92,12 +76,7 @@ public class ObjectNameManager {
public static ObjectName getInstance(String domainName, String key, String value)
throws MalformedObjectNameException {
if (getInstanceAvailable) {
return ObjectName.getInstance(domainName, key, value);
}
else {
return new ObjectName(domainName, key, value);
}
return ObjectName.getInstance(domainName, key, value);
}
/**
@@ -110,15 +89,10 @@ public class ObjectNameManager {
* @see ObjectName#ObjectName(String, java.util.Hashtable)
* @see ObjectName#getInstance(String, java.util.Hashtable)
*/
public static ObjectName getInstance(String domainName, Hashtable properties)
public static ObjectName getInstance(String domainName, Hashtable<String, String> properties)
throws MalformedObjectNameException {
if (getInstanceAvailable) {
return ObjectName.getInstance(domainName, properties);
}
else {
return new ObjectName(domainName, properties);
}
return ObjectName.getInstance(domainName, properties);
}
}

View File

@@ -1,133 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.support;
import java.lang.reflect.InvocationTargetException;
import javax.management.MBeanServer;
import javax.naming.NamingException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jmx.MBeanServerNotFoundException;
import org.springframework.jndi.JndiLocatorSupport;
/**
* FactoryBean that obtains a specified WebLogic {@link javax.management.MBeanServer}
* reference through a WebLogic <code>MBeanHome</code> obtained via a JNDI lookup.
* By default, the server's local <code>MBeanHome</code> will be obtained.
*
* <p>Exposes the <code>MBeanServer</code> for bean references.
* This FactoryBean is a direct alternative to {@link MBeanServerFactoryBean},
* which uses standard JMX 1.2 API to access the platform's MBeanServer.
*
* <p>Note: There is also a more general {@link WebLogicMBeanServerFactoryBean}
* for accessing any specified WebLogic <code>MBeanServer</code>,
* potentially a remote one.
*
* <p><b>NOTE: This class is only intended for use with WebLogic 8.1.</b>
* On WebLogic 9.x, simply obtain the MBeanServer directly from the JNDI location
* "java:comp/env/jmx/runtime", for example through the following configuration:
*
* <pre>
* &lt;bean class="org.springframework.jndi.JndiObjectFactoryBean"&gt;
* &lt;property name="jndiName" value="java:comp/env/jmx/runtime"/&gt;
* &lt;/bean&gt;</pre>
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2.6
* @see weblogic.management.MBeanHome#LOCAL_JNDI_NAME
* @see weblogic.management.MBeanHome#getMBeanServer()
* @see javax.management.MBeanServer
* @see MBeanServerFactoryBean
* @see WebLogicMBeanServerFactoryBean
*/
public class WebLogicJndiMBeanServerFactoryBean extends JndiLocatorSupport
implements FactoryBean, InitializingBean {
private static final String WEBLOGIC_MBEAN_HOME_CLASS = "weblogic.management.MBeanHome";
private static final String LOCAL_JNDI_NAME_FIELD = "LOCAL_JNDI_NAME";
private static final String GET_MBEAN_SERVER_METHOD = "getMBeanServer";
private String mbeanHomeName;
private MBeanServer mbeanServer;
/**
* Specify the JNDI name of the WebLogic MBeanHome object to use
* for creating the JMX MBeanServer reference.
* <p>Default is <code>MBeanHome.LOCAL_JNDI_NAME</code>
* @see weblogic.management.MBeanHome#LOCAL_JNDI_NAME
*/
public void setMbeanHomeName(String mbeanHomeName) {
this.mbeanHomeName = mbeanHomeName;
}
public void afterPropertiesSet() throws MBeanServerNotFoundException {
try {
String jndiName = this.mbeanHomeName;
if (jndiName == null) {
/*
* jndiName = MBeanHome.LOCAL_JNDI_NAME;
*/
Class mbeanHomeClass = getClass().getClassLoader().loadClass(WEBLOGIC_MBEAN_HOME_CLASS);
jndiName = (String) mbeanHomeClass.getField(LOCAL_JNDI_NAME_FIELD).get(null);
}
Object mbeanHome = lookup(jndiName);
/*
* this.mbeanServer = mbeanHome.getMBeanServer();
*/
this.mbeanServer = (MBeanServer)
mbeanHome.getClass().getMethod(GET_MBEAN_SERVER_METHOD, null).invoke(mbeanHome, null);
}
catch (NamingException ex) {
throw new MBeanServerNotFoundException("Could not find WebLogic's MBeanHome object in JNDI", ex);
}
catch (ClassNotFoundException ex) {
throw new MBeanServerNotFoundException("Could not find WebLogic's MBeanHome class", ex);
}
catch (InvocationTargetException ex) {
throw new MBeanServerNotFoundException(
"WebLogic's MBeanHome.getMBeanServer method failed", ex.getTargetException());
}
catch (Exception ex) {
throw new MBeanServerNotFoundException(
"Could not access WebLogic's MBeanHome/getMBeanServer method", ex);
}
}
public Object getObject() {
return this.mbeanServer;
}
public Class getObjectType() {
return (this.mbeanServer != null ? this.mbeanServer.getClass() : MBeanServer.class);
}
public boolean isSingleton() {
return true;
}
}

View File

@@ -1,153 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.support;
import java.lang.reflect.InvocationTargetException;
import javax.management.MBeanServer;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jmx.MBeanServerNotFoundException;
/**
* FactoryBean that obtains a specified WebLogic {@link javax.management.MBeanServer}
* reference through WebLogic's proprietary <code>Helper</code> /
* <code>MBeanHome</code> API, which is available on WebLogic 6.1 and higher.
*
* <p>Exposes the <code>MBeanServer</code> for bean references.
* This FactoryBean is a direct alternative to {@link MBeanServerFactoryBean},
* which uses standard JMX 1.2 API to access the platform's MBeanServer.
*
* <p>Note: There is also a {@link WebLogicJndiMBeanServerFactoryBean} for
* accessing the WebLogic <code>MBeanServer</code> instance through a WebLogic
* <code>MBeanHome</code> obtained via a JNDI lookup, typical a local one.
*
* <p><b>NOTE: This class is only intended for use with WebLogic up to 8.1.</b>
* On WebLogic 9.x, simply obtain the MBeanServer directly from the JNDI location
* "java:comp/env/jmx/runtime", for example through the following configuration:
*
* <pre>
* &lt;bean class="org.springframework.jndi.JndiObjectFactoryBean"&gt;
* &lt;property name="jndiName" value="java:comp/env/jmx/runtime"/&gt;
* &lt;/bean&gt;</pre>
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2
* @see weblogic.management.Helper#getMBeanHome(String, String, String, String)
* @see weblogic.management.MBeanHome#getMBeanServer()
* @see javax.management.MBeanServer
* @see MBeanServerFactoryBean
* @see WebLogicJndiMBeanServerFactoryBean
*/
public class WebLogicMBeanServerFactoryBean implements FactoryBean, InitializingBean {
private static final String WEBLOGIC_JMX_HELPER_CLASS = "weblogic.management.Helper";
private static final String GET_MBEAN_HOME_METHOD = "getMBeanHome";
private static final String GET_MBEAN_SERVER_METHOD = "getMBeanServer";
private String username = "weblogic";
private String password = "weblogic";
private String serverUrl = "t3://localhost:7001";
private String serverName = "server";
private MBeanServer mbeanServer;
/**
* Set the username to use for retrieving the WebLogic MBeanServer.
* Default is "weblogic".
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Set the password to use for retrieving the WebLogic MBeanServer.
* Default is "weblogic".
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Set the server URL to use for retrieving the WebLogic MBeanServer.
* Default is "t3://localhost:7001".
*/
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
/**
* Set the server name to use for retrieving the WebLogic MBeanServer.
* Default is "server".
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
public void afterPropertiesSet() throws MBeanServerNotFoundException {
try {
/*
* MBeanHome mbeanHome = Helper.getMBeanHome(this.username, this.password, this.serverUrl, this.serverName);
*/
Class helperClass = getClass().getClassLoader().loadClass(WEBLOGIC_JMX_HELPER_CLASS);
Class[] argTypes = new Class[] {String.class, String.class, String.class, String.class};
Object[] args = new Object[] {this.username, this.password, this.serverUrl, this.serverName};
Object mbeanHome = helperClass.getMethod(GET_MBEAN_HOME_METHOD, argTypes).invoke(null, args);
/*
* this.mbeanServer = mbeanHome.getMBeanServer();
*/
this.mbeanServer = (MBeanServer)
mbeanHome.getClass().getMethod(GET_MBEAN_SERVER_METHOD, null).invoke(mbeanHome, null);
}
catch (ClassNotFoundException ex) {
throw new MBeanServerNotFoundException("Could not find WebLogic's JMX Helper class", ex);
}
catch (InvocationTargetException ex) {
throw new MBeanServerNotFoundException(
"WebLogic's JMX Helper.getMBeanHome/getMBeanServer method failed", ex.getTargetException());
}
catch (Exception ex) {
throw new MBeanServerNotFoundException(
"Could not access WebLogic's JMX Helper.getMBeanHome/getMBeanServer method", ex);
}
}
public Object getObject() {
return this.mbeanServer;
}
public Class getObjectType() {
return (this.mbeanServer != null ? this.mbeanServer.getClass() : MBeanServer.class);
}
public boolean isSingleton() {
return true;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,6 @@ import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.JdkVersion;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
@@ -114,11 +113,7 @@ public class TimerFactoryBean implements FactoryBean, BeanNameAware, Initializin
* @see java.util.Timer#Timer(boolean)
*/
protected Timer createTimer(String name, boolean daemon) {
Timer timer = createTimer(daemon);
if (timer != null) {
return timer;
}
if (StringUtils.hasText(name) && JdkVersion.isAtLeastJava15()) {
if (StringUtils.hasText(name)) {
return new Timer(name, daemon);
}
else {
@@ -126,16 +121,6 @@ public class TimerFactoryBean implements FactoryBean, BeanNameAware, Initializin
}
}
/**
* Create a new Timer instance. Called by <code>afterPropertiesSet</code>.
* Can be overridden in subclasses to provide custom Timer subclasses.
* @deprecated as of Spring 2.0.1, in favor of {@link #createTimer(String, boolean)}
*/
@Deprecated
protected Timer createTimer(boolean daemon) {
return null;
}
/**
* Register the specified {@link ScheduledTimerTask ScheduledTimerTasks}
* on the given {@link Timer}.
@@ -143,8 +128,7 @@ public class TimerFactoryBean implements FactoryBean, BeanNameAware, Initializin
* @param timer the Timer to register the tasks on.
*/
protected void registerTasks(ScheduledTimerTask[] tasks, Timer timer) {
for (int i = 0; i < tasks.length; i++) {
ScheduledTimerTask task = tasks[i];
for (ScheduledTimerTask task : tasks) {
if (task.isOneTimeTask()) {
timer.schedule(task.getTimerTask(), task.getDelay());
}

View File

@@ -59,8 +59,8 @@ public class ExtendedModelMap extends ModelMap implements Model {
return this;
}
@SuppressWarnings("unchecked")
public Map<String, Object> asMap() {
return this;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ import org.springframework.util.Assert;
* @see org.springframework.web.servlet.ModelAndView
* @see org.springframework.web.portlet.ModelAndView
*/
public class ModelMap extends LinkedHashMap {
public class ModelMap extends LinkedHashMap<String, Object> {
/**
* Construct a new, empty <code>ModelMap</code>.
@@ -127,8 +127,7 @@ public class ModelMap extends LinkedHashMap {
*/
public ModelMap mergeAttributes(Map<String, ?> attributes) {
if (attributes != null) {
for (Iterator it = attributes.keySet().iterator(); it.hasNext();) {
Object key = it.next();
for (String key : attributes.keySet()) {
if (!containsKey(key)) {
put(key, attributes.get(key));
}

View File

@@ -212,7 +212,7 @@ public abstract class AbstractErrors implements Errors, Serializable {
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append(": ").append(getErrorCount()).append(" errors");
Iterator it = getAllErrors().iterator();
while (it.hasNext()) {

View File

@@ -17,7 +17,6 @@
package org.springframework.validation.support;
import java.util.Map;
import java.util.Set;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.validation.BindingResult;
@@ -32,19 +31,19 @@ import org.springframework.validation.BindingResult;
*
* @author Juergen Hoeller
* @since 2.5.6
* @see
* @see org.springframework.validation.BindingResult
*/
public class BindingAwareModelMap extends ExtendedModelMap {
@Override
public Object put(Object key, Object value) {
public Object put(String key, Object value) {
removeBindingResultIfNecessary(key, value);
return super.put(key, value);
}
@Override
public void putAll(Map map) {
for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
public void putAll(Map<? extends String, ?> map) {
for (Map.Entry entry : map.entrySet()) {
removeBindingResultIfNecessary(entry.getKey(), entry.getValue());
}
super.putAll(map);