INT-1727 refactored Groovy support to use ScriptVariableSource

This commit is contained in:
Oleg Zhurakousky
2011-01-27 11:19:05 -05:00
parent 1857d5b6c0
commit f80df192c8
10 changed files with 136 additions and 218 deletions

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2011 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.integration.groovy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
/**
* @author Oleg Zhurakousky
*
*/
public abstract class BeanFactoryAwareScriptVariableSource implements BeanFactoryAware, ScriptVariableSource {
protected volatile BeanFactory beanFactory;
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2002-2011 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.integration.groovy;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.Lifecycle;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.integration.Message;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.CustomizableThreadCreator;
/**
* @author Oleg Zhurakousky
* @since 2.0.2
*/
public class DefaultScriptVariableSource implements BeanFactoryAware, ScriptVariableSource {
protected volatile ListableBeanFactory beanFactory;
private volatile Map<String, Object> variableMap;
public DefaultScriptVariableSource(){
this(null);
}
public DefaultScriptVariableSource(Map<String, Object> variableMap){
this.variableMap = variableMap;
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (beanFactory instanceof ListableBeanFactory) ? (ListableBeanFactory) beanFactory : null;
}
public Map<String, Object> resolveScriptVariables(Message<?> message){
Map<String, Object> scriptVariables = new HashMap<String, Object>();
// Ad Message attributes
if (message != null) {
scriptVariables.put("payload", message.getPayload());
scriptVariables.put("headers", message.getHeaders());
}
// Add contents of 'variableMap'
if (!CollectionUtils.isEmpty(variableMap)){
scriptVariables.putAll(variableMap);
}
// Add contents of 'beanFactory'
if (this.beanFactory != null){
for (String name : this.beanFactory.getBeanDefinitionNames()) {
Object bean = this.beanFactory.getBean(name);
if (bean instanceof Lifecycle || bean instanceof CustomizableThreadCreator
|| (AnnotationUtils.findAnnotation(bean.getClass(), ManagedResource.class) != null)) {
scriptVariables.put(name, bean);
}
}
}
this.doResolveScriptVariables(scriptVariables);
return scriptVariables;
}
/**
* Will allow further customization to the map of script variables
* that will be accessible to script executing engine
*
* @param variables
*/
protected void doResolveScriptVariables(Map<String, Object> variables){
}
}

View File

@@ -13,41 +13,27 @@
package org.springframework.integration.groovy;
import groovy.lang.GString;
import java.util.Map;
import org.springframework.integration.Message;
import org.springframework.integration.handler.AbstractScriptExecutingMessageProcessor;
import org.springframework.scripting.ScriptSource;
import org.springframework.scripting.groovy.GroovyObjectCustomizer;
import org.springframework.scripting.groovy.GroovyScriptFactory;
import org.springframework.scripting.support.StaticScriptSource;
import org.springframework.util.Assert;
/**
* @author Dave Syer
* @author Mark Fisher
* @author Oleg Zhurakousky
* @since 2.0
*/
public class GroovyCommandMessageProcessor extends AbstractScriptExecutingMessageProcessor<Object> {
private final GroovyObjectCustomizer customizer;
public class GroovyCommandMessageProcessor extends GroovyScriptExecutingMessageProcessor {
public GroovyCommandMessageProcessor() {
this((GroovyObjectCustomizer) null);
super(null);
}
public GroovyCommandMessageProcessor(Map<String, ?> map) {
this(new MapContextBindingCustomizer(map));
public GroovyCommandMessageProcessor(ScriptVariableSource scriptVariableSource) {
super(null, scriptVariableSource);
}
public GroovyCommandMessageProcessor(GroovyObjectCustomizer customizer) {
this.customizer = customizer;
}
@Override
protected ScriptSource getScriptSource(Message<?> message) {
Object payload = message.getPayload();
@@ -56,19 +42,8 @@ public class GroovyCommandMessageProcessor extends AbstractScriptExecutingMessag
return new StaticScriptSource((String) payload, className);
}
@Override
protected Object executeScript(ScriptSource scriptSource, Message<?> message) throws Exception {
// Keeping everything local prevents PermGen (class instances) leaks...
MessageContextBindingCustomizer bindingCustomizer = new MessageContextBindingCustomizer(this.customizer);
bindingCustomizer.setMessage(message);
GroovyScriptFactory scriptFactory = new GroovyScriptFactory(this.getClass().getSimpleName(), bindingCustomizer);
Object result = scriptFactory.getScriptedObject(scriptSource, null);
return (result instanceof GString) ? result.toString() : result;
}
protected String generateScriptName(Message<?> message) {
// Don't use the same script (class) name for all invocations by default
return getClass().getSimpleName() + message.getHeaders().getId().toString().replaceAll("-", "");
}
}

View File

@@ -27,15 +27,16 @@ import org.springframework.util.Assert;
/**
* @author Dave Syer
* @author Mark Fisher
* @author Oleg Zhurakousky
* @since 2.0
*/
public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecutingMessageProcessor<Object> {
private final GroovyScriptFactory scriptFactory;
private final MessageContextBindingCustomizer customizer = new MessageContextBindingCustomizer();
private final MapResolvingBindingCustomizer customizer = new MapResolvingBindingCustomizer();
private final ScriptSource scriptSource;
private volatile ScriptSource scriptSource;
private final ScriptVariableSource scriptVariableSource;
@@ -43,17 +44,15 @@ public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecuti
* Create a processor for the given {@link ScriptSource}.
*/
public GroovyScriptExecutingMessageProcessor(ScriptSource scriptSource) {
this(scriptSource, null);
this(scriptSource, new DefaultScriptVariableSource());
}
public GroovyScriptExecutingMessageProcessor(ScriptSource scriptSource, ScriptVariableSource scriptVariableSource) {
Assert.notNull(scriptSource, "scriptSource must not be null");
this.scriptSource = scriptSource;
this.scriptVariableSource = scriptVariableSource;
this.scriptFactory = new GroovyScriptFactory(this.getClass().getSimpleName(), this.customizer);
}
@Override
protected ScriptSource getScriptSource(Message<?> message) {
return this.scriptSource;
@@ -61,8 +60,8 @@ public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecuti
@Override
protected Object executeScript(ScriptSource scriptSource, Message<?> message) throws Exception {
Assert.notNull(scriptSource, "scriptSource must not be null");
synchronized (this) {
this.customizer.setMessage(message);
if (this.scriptVariableSource != null){
this.customizer.setResolvedScriptVariables(this.scriptVariableSource.resolveScriptVariables(message));
}

View File

@@ -24,26 +24,26 @@ import org.springframework.util.Assert;
/**
* @author Dave Syer
* @author Oleg Zhurakousky
* @since 2.0
*/
public class MapContextBindingCustomizer implements GroovyObjectCustomizer {
public class MapResolvingBindingCustomizer implements GroovyObjectCustomizer {
private final Map<String, ?> map;
private volatile Map<String, ?> resolvedScriptVariables;
public MapContextBindingCustomizer(Map<String, ?> map) {
this.map = map;
public void setResolvedScriptVariables(Map<String, ?> resolvedScriptVariables) {
this.resolvedScriptVariables = resolvedScriptVariables;
}
public void customize(GroovyObject goo) {
Assert.state(goo instanceof Script, "Expected a Script");
if (this.map != null) {
if (this.resolvedScriptVariables != null) {
Binding binding = ((Script) goo).getBinding();
for (String key : this.map.keySet()) {
binding.setVariable(key, this.map.get(key));
for (String key : this.resolvedScriptVariables.keySet()) {
binding.setVariable(key, this.resolvedScriptVariables.get(key));
}
}
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright 2002-2010 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.integration.groovy;
import groovy.lang.Binding;
import groovy.lang.GroovyObject;
import groovy.lang.Script;
import java.util.Map;
import org.springframework.integration.Message;
import org.springframework.scripting.groovy.GroovyObjectCustomizer;
import org.springframework.util.Assert;
/**
* A groovy object customizer used internally by the groovy message processors.
* Not public because the customizer is not the best API for groovy context binding,
* but it's what we have in Spring right now.
*
* @author Dave Syer
* @since 2.0
*/
class MessageContextBindingCustomizer implements GroovyObjectCustomizer {
private volatile Message<?> message;
private final GroovyObjectCustomizer customizer;
private volatile Map<String, ?> resolvedScriptVariables;
public MessageContextBindingCustomizer() {
this((GroovyObjectCustomizer) null);
}
public MessageContextBindingCustomizer(Map<String, ?> context) {
this(new MapContextBindingCustomizer(context));
}
public MessageContextBindingCustomizer(GroovyObjectCustomizer customizer) {
this.customizer = customizer;
}
public void setResolvedScriptVariables(Map<String, ?> resolvedScriptVariables) {
this.resolvedScriptVariables = resolvedScriptVariables;
}
public void setMessage(Message<?> message) {
this.message = message;
}
public void customize(GroovyObject goo) {
Assert.state(goo instanceof Script, "Expected a Script");
Binding binding = ((Script) goo).getBinding();
if (resolvedScriptVariables != null){
for (String key : resolvedScriptVariables.keySet()) {
binding.setVariable(key, this.resolvedScriptVariables.get(key));
}
}
if (this.message != null) {
binding.setVariable("payload", this.message.getPayload());
binding.setVariable("headers", this.message.getHeaders());
}
if (this.customizer != null){
this.customizer.customize(goo);
}
}
}

View File

@@ -13,41 +13,32 @@
package org.springframework.integration.groovy.config;
import groovy.lang.Binding;
import groovy.lang.GroovyObject;
import groovy.lang.Script;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.Lifecycle;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean;
import org.springframework.integration.core.MessageHandler;
import org.springframework.integration.groovy.DefaultScriptVariableSource;
import org.springframework.integration.groovy.GroovyCommandMessageProcessor;
import org.springframework.integration.handler.ServiceActivatingHandler;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.scripting.groovy.GroovyObjectCustomizer;
import org.springframework.util.CustomizableThreadCreator;
/**
* FactoryBean for creating {@link MessageHandler} instances to handle a message as a Groovy Script.
*
* @author Dave Syer
* @author Oleg Zhurakousky
* @since 2.0
*/
public class GroovyControlBusFactoryBean extends AbstractSimpleMessageHandlerFactoryBean {
private volatile Long sendTimeout;
public void setSendTimeout(Long sendTimeout) {
this.sendTimeout = sendTimeout;
}
@Override
protected MessageHandler createHandler() {
ControlBusContextBindingCustomizer customizer = new ControlBusContextBindingCustomizer(this.getBeanFactory());
GroovyCommandMessageProcessor processor = new GroovyCommandMessageProcessor(customizer);
DefaultScriptVariableSource scriptVariableSource = new DefaultScriptVariableSource();
scriptVariableSource.setBeanFactory(this.getBeanFactory());
GroovyCommandMessageProcessor processor = new GroovyCommandMessageProcessor(scriptVariableSource);
return this.configureHandler(new ServiceActivatingHandler(processor));
}
@@ -57,32 +48,4 @@ public class GroovyControlBusFactoryBean extends AbstractSimpleMessageHandlerFac
}
return handler;
}
/**
* Adds any @ManagedResource, Lifecycle, or CustomizableThreadCreator instances from
* the application context to the Script variable bindings.
*/
private static class ControlBusContextBindingCustomizer implements GroovyObjectCustomizer {
private final ListableBeanFactory beanFactory;
public ControlBusContextBindingCustomizer(BeanFactory beanFactory) {
this.beanFactory = (beanFactory instanceof ListableBeanFactory) ? (ListableBeanFactory) beanFactory : null;
}
public void customize(GroovyObject goo) {
if (this.beanFactory != null) {
Binding binding = ((Script) goo).getBinding();
for (String name : this.beanFactory.getBeanDefinitionNames()) {
Object bean = this.beanFactory.getBean(name);
if (bean instanceof Lifecycle || bean instanceof CustomizableThreadCreator
|| (AnnotationUtils.findAnnotation(bean.getClass(), ManagedResource.class) != null)) {
binding.setVariable(name, bean);
}
}
}
}
}
}

View File

@@ -19,6 +19,7 @@ package org.springframework.integration.groovy.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlReaderContext;
@@ -45,6 +46,11 @@ public class GroovyScriptParser extends AbstractSingleBeanDefinitionParser {
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
builder.addConstructorArgValue(this.resolveScriptSource(element, parserContext.getReaderContext()));
BeanDefinitionBuilder scriptVariableSource =
BeanDefinitionBuilder.genericBeanDefinition("org.springframework.integration.groovy.DefaultScriptVariableSource");
String name =
BeanDefinitionReaderUtils.registerWithGeneratedName(scriptVariableSource.getBeanDefinition(), parserContext.getRegistry());
builder.addConstructorArgReference(name);
}
private Object resolveScriptSource(Element element, XmlReaderContext readerContext) {

View File

@@ -22,7 +22,6 @@ import static org.junit.Assert.assertFalse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@@ -59,7 +58,7 @@ public class GroovyScriptExecutingMessageProcessorTests {
Message<?> message = MessageBuilder.withPayload("foo").setHeader("testHeader", "bar"+count).build();
TestResource resource = new TestResource(script, "simpleTest");
ScriptSource scriptSource = new ResourceScriptSource(resource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, new DefaultScriptVariableSource());
Object result = processor.processMessage(message);
assertEquals("payload is foo, header is bar"+count, result.toString());
}
@@ -72,14 +71,13 @@ public class GroovyScriptExecutingMessageProcessorTests {
TestResource resource = new TestResource(script, "simpleTest");
ScriptSource scriptSource = new ResourceScriptSource(resource);
Object result = null;
class CustomScriptVariableSource extends DefaultScriptVariableSource{
protected void doResolveScriptVariables(Map<String, Object> variables){
variables.put("date", System.nanoTime());
}
}
for (int i = 0; i < 5; i++) {
ScriptVariableSource scriptVariableSource = new ScriptVariableSource() {
public Map<String, Object> resolveScriptVariables(Message<?> message) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", System.nanoTime());
return map;
}
};
ScriptVariableSource scriptVariableSource = new CustomScriptVariableSource();
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, scriptVariableSource);
Object newResult = processor.processMessage(message);
assertFalse(newResult.equals(result)); // make sure that we get different nanotime verifying that resolveScriptVariables() is invoked
@@ -103,7 +101,7 @@ public class GroovyScriptExecutingMessageProcessorTests {
Message<?> message = MessageBuilder.withPayload("foo").setHeader("testHeader", "bar").build();
TestResource resource = new TestResource(script, "simpleTest");
ScriptSource scriptSource = new ResourceScriptSource(resource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, new DefaultScriptVariableSource());
Thread.sleep(20L);
resource.setScript("return \"payload is $payload\"");
Object result = processor.processMessage(message);
@@ -116,7 +114,7 @@ public class GroovyScriptExecutingMessageProcessorTests {
Message<?> message = MessageBuilder.withPayload("foo").setHeader("testHeader", "bar").build();
TestResource resource = new TestResource(script, "simpleTest");
ScriptSource scriptSource = new RefreshableResourceScriptSource(resource, 1000L);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, new DefaultScriptVariableSource());
// should be the original script
Object result = processor.processMessage(message);
assertEquals("payload is foo, header is bar", result.toString());
@@ -140,7 +138,7 @@ public class GroovyScriptExecutingMessageProcessorTests {
Message<?> message = MessageBuilder.withPayload("foo").setHeader("testHeader", "bar").build();
TestResource resource = new TestResource(script, "simpleTest");
ScriptSource scriptSource = new RefreshableResourceScriptSource(resource, -1L);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, new DefaultScriptVariableSource());
// process with the first script
Object result = processor.processMessage(message);
assertEquals("payload is foo, header is bar", result.toString());
@@ -157,7 +155,7 @@ public class GroovyScriptExecutingMessageProcessorTests {
Message<?> message = MessageBuilder.withPayload("foo").setHeader("testHeader", "bar").build();
TestResource resource = new TestResource(script, "simpleTest");
ScriptSource scriptSource = new RefreshableResourceScriptSource(resource, 0);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource);
MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, new DefaultScriptVariableSource());
// process with the first script
Object result = processor.processMessage(message);
assertEquals("payload is foo, header is bar", result.toString());

View File

@@ -20,6 +20,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.integration.Message;
import org.springframework.integration.handler.MessageProcessor;
import org.springframework.integration.support.MessageBuilder;
@@ -61,8 +62,9 @@ public class GroovyScriptPayloadMessageProcessorTests {
public void testSimpleExecutionWithContext() throws Exception {
Message<?> message = MessageBuilder.withPayload("\"spam is $spam foo is $headers.foo\"")
.setHeader("foo", "bar").build();
MessageProcessor<Object> processor = new GroovyCommandMessageProcessor(Collections.singletonMap("spam",
"bucket"));
ScriptVariableSource scriptVariableSource =
new DefaultScriptVariableSource(Collections.singletonMap("spam",(Object)"bucket"));
MessageProcessor<Object> processor = new GroovyCommandMessageProcessor(scriptVariableSource);
Object result = processor.processMessage(message);
assertEquals("spam is bucket foo is bar", result.toString());
}