Drop deprecated dependencies on Log4j, JRuby, JExcel, Burlap, Commons Pool/DBCP

This commit also removes outdated support classes for Oracle, GlassFish, JBoss.

Issue: SPR-14429
This commit is contained in:
Juergen Hoeller
2016-07-05 15:46:53 +02:00
parent fb5a096ca2
commit 0fc0ce78ae
46 changed files with 24 additions and 4916 deletions

View File

@@ -42,7 +42,6 @@ public class LangNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerScriptBeanDefinitionParser("groovy", "org.springframework.scripting.groovy.GroovyScriptFactory");
registerScriptBeanDefinitionParser("jruby", "org.springframework.scripting.jruby.JRubyScriptFactory");
registerScriptBeanDefinitionParser("bsh", "org.springframework.scripting.bsh.BshScriptFactory");
registerScriptBeanDefinitionParser("std", "org.springframework.scripting.support.StandardScriptFactory");
registerBeanDefinitionParser("defaults", new ScriptingDefaultsParser());

View File

@@ -1,141 +0,0 @@
/*
* Copyright 2002-2015 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.scripting.jruby;
import java.io.IOException;
import org.jruby.RubyException;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.RaiseException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.scripting.ScriptCompilationException;
import org.springframework.scripting.ScriptFactory;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* {@link org.springframework.scripting.ScriptFactory} implementation
* for a JRuby script.
*
* <p>Typically used in combination with a
* {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};
* see the latter's javadoc for a configuration example.
*
* <p>Note: Spring 4.0 supports JRuby 1.5 and higher.
* As of Spring 4.2, JRuby 9.0.0.0 is supported but only through
* {@link org.springframework.scripting.support.StandardScriptFactory}.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 2.0
* @see JRubyScriptUtils
* @see org.springframework.scripting.support.ScriptFactoryPostProcessor
* @deprecated in favor of JRuby support via the JSR-223 abstraction
* ({@link org.springframework.scripting.support.StandardScriptFactory})
*/
@Deprecated
public class JRubyScriptFactory implements ScriptFactory, BeanClassLoaderAware {
private final String scriptSourceLocator;
private final Class<?>[] scriptInterfaces;
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
/**
* Create a new JRubyScriptFactory for the given script source.
* @param scriptSourceLocator a locator that points to the source of the script.
* Interpreted by the post-processor that actually creates the script.
* @param scriptInterfaces the Java interfaces that the scripted object
* is supposed to implement
*/
public JRubyScriptFactory(String scriptSourceLocator, Class<?>... scriptInterfaces) {
Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty");
Assert.notEmpty(scriptInterfaces, "'scriptInterfaces' must not be empty");
this.scriptSourceLocator = scriptSourceLocator;
this.scriptInterfaces = scriptInterfaces;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
@Override
public String getScriptSourceLocator() {
return this.scriptSourceLocator;
}
@Override
public Class<?>[] getScriptInterfaces() {
return this.scriptInterfaces;
}
/**
* JRuby scripts do require a config interface.
*/
@Override
public boolean requiresConfigInterface() {
return true;
}
/**
* Load and parse the JRuby script via JRubyScriptUtils.
* @see JRubyScriptUtils#createJRubyObject(String, Class[], ClassLoader)
*/
@Override
public Object getScriptedObject(ScriptSource scriptSource, Class<?>... actualInterfaces)
throws IOException, ScriptCompilationException {
try {
return JRubyScriptUtils.createJRubyObject(
scriptSource.getScriptAsString(), actualInterfaces, this.beanClassLoader);
}
catch (RaiseException ex) {
RubyException rubyEx = ex.getException();
String msg = (rubyEx != null && rubyEx.message != null) ?
rubyEx.message.toString() : "Unexpected JRuby error";
throw new ScriptCompilationException(scriptSource, msg, ex);
}
catch (JumpException ex) {
throw new ScriptCompilationException(scriptSource, ex);
}
}
@Override
public Class<?> getScriptedObjectType(ScriptSource scriptSource)
throws IOException, ScriptCompilationException {
return null;
}
@Override
public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {
return scriptSource.isModified();
}
@Override
public String toString() {
return "JRubyScriptFactory: script source locator [" + this.scriptSourceLocator + "]";
}
}

View File

@@ -1,253 +0,0 @@
/*
* Copyright 2002-2015 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.scripting.jruby;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.List;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyNil;
import org.jruby.ast.ClassNode;
import org.jruby.ast.Colon2Node;
import org.jruby.ast.NewlineNode;
import org.jruby.ast.Node;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import org.springframework.core.NestedRuntimeException;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* Utility methods for handling JRuby-scripted objects.
*
* <p>Note: Spring 4.0 supports JRuby 1.5 and higher.
* As of Spring 4.2, JRuby 9.0.0.0 is supported but only through
* {@link org.springframework.scripting.support.StandardScriptFactory}.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Rick Evans
* @since 2.0
* @deprecated in favor of JRuby support via the JSR-223 abstraction
* ({@link org.springframework.scripting.support.StandardScriptFactory})
*/
@Deprecated
public abstract class JRubyScriptUtils {
/**
* Create a new JRuby-scripted object from the given script source,
* using the default {@link ClassLoader}.
* @param scriptSource the script source text
* @param interfaces the interfaces that the scripted Java object is to implement
* @return the scripted Java object
* @throws JumpException in case of JRuby parsing failure
* @see ClassUtils#getDefaultClassLoader()
*/
public static Object createJRubyObject(String scriptSource, Class<?>... interfaces) throws JumpException {
return createJRubyObject(scriptSource, interfaces, ClassUtils.getDefaultClassLoader());
}
/**
* Create a new JRuby-scripted object from the given script source.
* @param scriptSource the script source text
* @param interfaces the interfaces that the scripted Java object is to implement
* @param classLoader the {@link ClassLoader} to create the script proxy with
* @return the scripted Java object
* @throws JumpException in case of JRuby parsing failure
*/
public static Object createJRubyObject(String scriptSource, Class<?>[] interfaces, ClassLoader classLoader) {
Ruby ruby = initializeRuntime();
Node scriptRootNode = ruby.parseEval(scriptSource, "", null, 0);
IRubyObject rubyObject = ruby.runNormally(scriptRootNode);
if (rubyObject instanceof RubyNil) {
String className = findClassName(scriptRootNode);
rubyObject = ruby.evalScriptlet("\n" + className + ".new");
}
// still null?
if (rubyObject instanceof RubyNil) {
throw new IllegalStateException("Compilation of JRuby script returned RubyNil: " + rubyObject);
}
return Proxy.newProxyInstance(classLoader, interfaces, new RubyObjectInvocationHandler(rubyObject, ruby));
}
/**
* Initializes an instance of the {@link org.jruby.Ruby} runtime.
*/
@SuppressWarnings("unchecked")
private static Ruby initializeRuntime() {
return JavaEmbedUtils.initialize(Collections.EMPTY_LIST);
}
/**
* Given the root {@link Node} in a JRuby AST will locate the name of the
* class defined by that AST.
* @throws IllegalArgumentException if no class is defined by the supplied AST
*/
private static String findClassName(Node rootNode) {
ClassNode classNode = findClassNode(rootNode);
if (classNode == null) {
throw new IllegalArgumentException("Unable to determine class name for root node '" + rootNode + "'");
}
Colon2Node node = (Colon2Node) classNode.getCPath();
return node.getName();
}
/**
* Find the first {@link ClassNode} under the supplied {@link Node}.
* @return the corresponding {@code ClassNode}, or {@code null} if none found
*/
private static ClassNode findClassNode(Node node) {
if (node == null) {
return null;
}
if (node instanceof ClassNode) {
return (ClassNode) node;
}
List<Node> children = node.childNodes();
for (Node child : children) {
if (child instanceof ClassNode) {
return (ClassNode) child;
}
else if (child instanceof NewlineNode) {
NewlineNode nn = (NewlineNode) child;
ClassNode found = findClassNode(nn.getNextNode());
if (found != null) {
return found;
}
}
}
for (Node child : children) {
ClassNode found = findClassNode(child);
if (found != null) {
return found;
}
}
return null;
}
/**
* InvocationHandler that invokes a JRuby script method.
*/
private static class RubyObjectInvocationHandler implements InvocationHandler {
private final IRubyObject rubyObject;
private final Ruby ruby;
public RubyObjectInvocationHandler(IRubyObject rubyObject, Ruby ruby) {
this.rubyObject = rubyObject;
this.ruby = ruby;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (ReflectionUtils.isEqualsMethod(method)) {
return (isProxyForSameRubyObject(args[0]));
}
else if (ReflectionUtils.isHashCodeMethod(method)) {
return this.rubyObject.hashCode();
}
else if (ReflectionUtils.isToStringMethod(method)) {
String toStringResult = this.rubyObject.toString();
if (!StringUtils.hasText(toStringResult)) {
toStringResult = ObjectUtils.identityToString(this.rubyObject);
}
return "JRuby object [" + toStringResult + "]";
}
try {
IRubyObject[] rubyArgs = convertToRuby(args);
IRubyObject rubyResult =
this.rubyObject.callMethod(this.ruby.getCurrentContext(), method.getName(), rubyArgs);
return convertFromRuby(rubyResult, method.getReturnType());
}
catch (RaiseException ex) {
throw new JRubyExecutionException(ex);
}
}
private boolean isProxyForSameRubyObject(Object other) {
if (!Proxy.isProxyClass(other.getClass())) {
return false;
}
InvocationHandler ih = Proxy.getInvocationHandler(other);
return (ih instanceof RubyObjectInvocationHandler &&
this.rubyObject.equals(((RubyObjectInvocationHandler) ih).rubyObject));
}
private IRubyObject[] convertToRuby(Object[] javaArgs) {
if (javaArgs == null || javaArgs.length == 0) {
return new IRubyObject[0];
}
IRubyObject[] rubyArgs = new IRubyObject[javaArgs.length];
for (int i = 0; i < javaArgs.length; ++i) {
rubyArgs[i] = JavaEmbedUtils.javaToRuby(this.ruby, javaArgs[i]);
}
return rubyArgs;
}
private Object convertFromRuby(IRubyObject rubyResult, Class<?> returnType) {
Object result = JavaEmbedUtils.rubyToJava(this.ruby, rubyResult, returnType);
if (result instanceof RubyArray && returnType.isArray()) {
result = convertFromRubyArray(((RubyArray) result).toJavaArray(), returnType);
}
return result;
}
private Object convertFromRubyArray(IRubyObject[] rubyArray, Class<?> returnType) {
Class<?> targetType = returnType.getComponentType();
Object javaArray = Array.newInstance(targetType, rubyArray.length);
for (int i = 0; i < rubyArray.length; i++) {
IRubyObject rubyObject = rubyArray[i];
Array.set(javaArray, i, convertFromRuby(rubyObject, targetType));
}
return javaArray;
}
}
/**
* Exception thrown in response to a JRuby {@link RaiseException}
* being thrown from a JRuby method invocation.
*/
@SuppressWarnings("serial")
public static class JRubyExecutionException extends NestedRuntimeException {
/**
* Create a new {@code JRubyException},
* wrapping the given JRuby {@code RaiseException}.
* @param ex the cause (must not be {@code null})
*/
public JRubyExecutionException(RaiseException ex) {
super(ex.getMessage(), ex);
}
}
}

View File

@@ -1,6 +0,0 @@
/**
* Package providing integration of
* <a href="http://jruby.sourceforge.net">JRuby</a>
* into Spring's scripting infrastructure.
*/
package org.springframework.scripting.jruby;

View File

@@ -1,220 +0,0 @@
/*
* Copyright 2002-2013 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.aop.target;
import java.util.NoSuchElementException;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.Person;
import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.tests.sample.beans.SideEffectBean;
import org.springframework.util.SerializationTestUtils;
import static org.junit.Assert.*;
/**
* Tests for pooling invoker interceptor.
* TODO: need to make these tests stronger: it's hard to
* make too many assumptions about a pool.
*
* @author Rod Johnson
* @author Rob Harrop
* @author Chris Beams
*/
@SuppressWarnings("deprecation")
public class CommonsPoolTargetSourceTests {
/**
* Initial count value set in bean factory XML
*/
private static final int INITIAL_COUNT = 10;
private DefaultListableBeanFactory beanFactory;
@Before
public void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(this.beanFactory).loadBeanDefinitions(
new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()));
}
/**
* We must simulate container shutdown, which should clear threads.
*/
@After
public void tearDown() {
// Will call pool.close()
this.beanFactory.destroySingletons();
}
private void testFunctionality(String name) {
SideEffectBean pooled = (SideEffectBean) beanFactory.getBean(name);
assertEquals(INITIAL_COUNT, pooled.getCount());
pooled.doWork();
assertEquals(INITIAL_COUNT + 1, pooled.getCount());
pooled = (SideEffectBean) beanFactory.getBean(name);
// Just check that it works--we can't make assumptions
// about the count
pooled.doWork();
//assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
}
@Test
public void testFunctionality() {
testFunctionality("pooled");
}
@Test
public void testFunctionalityWithNoInterceptors() {
testFunctionality("pooledNoInterceptors");
}
@Test
public void testConfigMixin() {
SideEffectBean pooled = (SideEffectBean) beanFactory.getBean("pooledWithMixin");
assertEquals(INITIAL_COUNT, pooled.getCount());
PoolingConfig conf = (PoolingConfig) beanFactory.getBean("pooledWithMixin");
// TODO one invocation from setup
//assertEquals(1, conf.getInvocations());
pooled.doWork();
// assertEquals("No objects active", 0, conf.getActive());
assertEquals("Correct target source", 25, conf.getMaxSize());
// assertTrue("Some free", conf.getFree() > 0);
//assertEquals(2, conf.getInvocations());
assertEquals(25, conf.getMaxSize());
}
@Test
public void testTargetSourceSerializableWithoutConfigMixin() throws Exception {
CommonsPoolTargetSource cpts = (CommonsPoolTargetSource) beanFactory.getBean("personPoolTargetSource");
SingletonTargetSource serialized = (SingletonTargetSource) SerializationTestUtils.serializeAndDeserialize(cpts);
assertTrue(serialized.getTarget() instanceof Person);
}
@Test
public void testProxySerializableWithoutConfigMixin() throws Exception {
Person pooled = (Person) beanFactory.getBean("pooledPerson");
//System.out.println(((Advised) pooled).toProxyConfigString());
assertTrue(((Advised) pooled).getTargetSource() instanceof CommonsPoolTargetSource);
//((Advised) pooled).setTargetSource(new SingletonTargetSource(new SerializablePerson()));
Person serialized = (Person) SerializationTestUtils.serializeAndDeserialize(pooled);
assertTrue(((Advised) serialized).getTargetSource() instanceof SingletonTargetSource);
serialized.setAge(25);
assertEquals(25, serialized.getAge());
}
@Test
public void testHitMaxSize() throws Exception {
int maxSize = 10;
CommonsPoolTargetSource targetSource = new CommonsPoolTargetSource();
targetSource.setMaxSize(maxSize);
targetSource.setMaxWait(1);
prepareTargetSource(targetSource);
Object[] pooledInstances = new Object[maxSize];
for (int x = 0; x < maxSize; x++) {
Object instance = targetSource.getTarget();
assertNotNull(instance);
pooledInstances[x] = instance;
}
// should be at maximum now
try {
targetSource.getTarget();
fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException ex) {
// desired
}
// lets now release an object and try to accquire a new one
targetSource.releaseTarget(pooledInstances[9]);
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
}
}
@Test
public void testHitMaxSizeLoadedFromContext() throws Exception {
Advised person = (Advised) beanFactory.getBean("maxSizePooledPerson");
CommonsPoolTargetSource targetSource = (CommonsPoolTargetSource) person.getTargetSource();
int maxSize = targetSource.getMaxSize();
Object[] pooledInstances = new Object[maxSize];
for (int x = 0; x < maxSize; x++) {
Object instance = targetSource.getTarget();
assertNotNull(instance);
pooledInstances[x] = instance;
}
// should be at maximum now
try {
targetSource.getTarget();
fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException ex) {
// desired
}
// lets now release an object and try to accquire a new one
targetSource.releaseTarget(pooledInstances[9]);
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
}
}
@Test
public void testSetWhenExhaustedAction() {
CommonsPoolTargetSource targetSource = new CommonsPoolTargetSource();
targetSource.setWhenExhaustedActionName("WHEN_EXHAUSTED_BLOCK");
assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, targetSource.getWhenExhaustedAction());
}
private void prepareTargetSource(CommonsPoolTargetSource targetSource) {
String beanName = "target";
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerPrototype(beanName, SerializablePerson.class);
targetSource.setTargetBeanName(beanName);
targetSource.setBeanFactory(applicationContext);
}
}

View File

@@ -229,7 +229,6 @@ class DerivedConstructorDependenciesBean extends ConstructorDependenciesBean {
/**
*
* @author Rod Johnson
*/
interface DummyBo {
@@ -239,7 +238,6 @@ interface DummyBo {
/**
*
* @author Rod Johnson
*/
class DummyBoImpl implements DummyBo {
@@ -260,12 +258,6 @@ class DummyBoImpl implements DummyBo {
* @author Rod Johnson
*/
class DummyDao {
DataSource ds;
public DummyDao(DataSource ds) {
this.ds = ds;
}
}

View File

@@ -466,7 +466,7 @@ public class GroovyScriptFactoryTests {
@Test // SPR-6268
public void testProxyTargetClassNotAllowedIfNotGroovy() throws Exception {
try {
new ClassPathXmlApplicationContext("jruby-with-xsd-proxy-target-class.xml", getClass());
new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml", getClass());
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("Cannot use proxyTargetClass=true"));

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2002-2013 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.scripting.jruby;
import org.junit.After;
import org.junit.Test;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
import org.springframework.tests.aop.advice.CountingBeforeAdvice;
import org.springframework.util.MBeanTestUtils;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Chris Beams
*/
public final class AdvisedJRubyScriptFactoryTests {
private static final Class<?> CLASS = AdvisedJRubyScriptFactoryTests.class;
private static final String CLASSNAME = CLASS.getSimpleName();
private static final String FACTORYBEAN_CONTEXT = CLASSNAME + "-factoryBean.xml";
private static final String APC_CONTEXT = CLASSNAME + "-beanNameAutoProxyCreator.xml";
@After
public void resetMBeanServers() throws Exception {
MBeanTestUtils.resetMBeanServers();
}
@Test
public void testAdviseWithProxyFactoryBean() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(FACTORYBEAN_CONTEXT, CLASS);
try {
Messenger bean = (Messenger) ctx.getBean("messenger");
assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
assertTrue("Bean is not an Advised object", bean instanceof Advised);
CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
assertEquals(0, advice.getCalls());
bean.getMessage();
assertEquals(1, advice.getCalls());
}
finally {
ctx.close();
}
}
@Test
public void testAdviseWithBeanNameAutoProxyCreator() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(APC_CONTEXT, CLASS);
try {
Messenger bean = (Messenger) ctx.getBean("messenger");
assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
assertTrue("Bean is not an Advised object", bean instanceof Advised);
CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
assertEquals(0, advice.getCalls());
bean.getMessage();
assertEquals(1, advice.getCalls());
}
finally {
ctx.close();
}
}
}

View File

@@ -1,364 +0,0 @@
/*
* Copyright 2002-2015 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.scripting.jruby;
import java.util.Map;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.target.dynamic.Refreshable;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Calculator;
import org.springframework.scripting.ConfigurableMessenger;
import org.springframework.scripting.Messenger;
import org.springframework.scripting.ScriptCompilationException;
import org.springframework.scripting.TestBeanAwareMessenger;
import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class JRubyScriptFactoryTests {
private static final String RUBY_SCRIPT_SOURCE_LOCATOR =
"inline:require 'java'\n" +
"class RubyBar\n" +
"end\n" +
"RubyBar.new";
@Test
public void testStaticScript() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContext.xml", getClass());
Calculator calc = (Calculator) ctx.getBean("calculator");
Messenger messenger = (Messenger) ctx.getBean("messenger");
assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable);
assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable);
assertEquals(calc, calc);
assertEquals(messenger, messenger);
assertTrue(!messenger.equals(calc));
assertNotSame(messenger.hashCode(), calc.hashCode());
assertTrue(!messenger.toString().equals(calc.toString()));
assertEquals(3, calc.add(1, 2));
String desiredMessage = "Hello World!";
assertEquals("Message is incorrect", desiredMessage, messenger.getMessage());
}
@Test
public void testStaticScriptUsingJsr223() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextWithJsr223.xml", getClass());
Calculator calc = (Calculator) ctx.getBean("calculator");
Messenger messenger = (Messenger) ctx.getBean("messenger");
assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable);
assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable);
assertEquals(calc, calc);
assertEquals(messenger, messenger);
assertTrue(!messenger.equals(calc));
assertNotSame(messenger.hashCode(), calc.hashCode());
assertTrue(!messenger.toString().equals(calc.toString()));
assertEquals(3, calc.add(1, 2));
String desiredMessage = "Hello World!";
assertEquals("Message is incorrect", desiredMessage, messenger.getMessage());
}
@Test
public void testNonStaticScript() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyRefreshableContext.xml", getClass());
Messenger messenger = (Messenger) ctx.getBean("messenger");
assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger));
assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable);
String desiredMessage = "Hello World!";
assertEquals("Message is incorrect.", desiredMessage, messenger.getMessage());
Refreshable refreshable = (Refreshable) messenger;
refreshable.refresh();
assertEquals("Message is incorrect after refresh.", desiredMessage, messenger.getMessage());
assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount());
}
@Test
public void testScriptCompilationException() throws Exception {
try {
new ClassPathXmlApplicationContext("jrubyBrokenContext.xml", getClass());
fail("Should throw exception for broken script file");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(ScriptCompilationException.class));
}
}
@Test
public void testCtorWithNullScriptSourceLocator() throws Exception {
try {
new JRubyScriptFactory(null, Messenger.class);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testCtorWithEmptyScriptSourceLocator() throws Exception {
try {
new JRubyScriptFactory("", Messenger.class);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testCtorWithWhitespacedScriptSourceLocator() throws Exception {
try {
new JRubyScriptFactory("\n ", Messenger.class);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testCtorWithNullScriptInterfacesArray() throws Exception {
try {
new JRubyScriptFactory(RUBY_SCRIPT_SOURCE_LOCATOR);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testCtorWithEmptyScriptInterfacesArray() throws Exception {
try {
new JRubyScriptFactory(RUBY_SCRIPT_SOURCE_LOCATOR, new Class<?>[]{});
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testResourceScriptFromTag() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass());
TestBean testBean = (TestBean) ctx.getBean("testBean");
Messenger messenger = (Messenger) ctx.getBean("messenger");
assertEquals("Hello World!", messenger.getMessage());
assertFalse(messenger instanceof Refreshable);
TestBeanAwareMessenger messengerByType = (TestBeanAwareMessenger) ctx.getBean("messengerByType");
assertEquals(testBean, messengerByType.getTestBean());
TestBeanAwareMessenger messengerByName = (TestBeanAwareMessenger) ctx.getBean("messengerByName");
assertEquals(testBean, messengerByName.getTestBean());
}
@Test
public void testResourceScriptFromTagUsingJsr223() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd-jsr223.xml", getClass());
Messenger messenger = (Messenger) ctx.getBean("messenger");
assertEquals("Hello World!", messenger.getMessage());
assertFalse(messenger instanceof Refreshable);
}
@Test
public void testPrototypeScriptFromTag() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass());
ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype");
ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype");
assertNotSame(messenger, messenger2);
assertSame(messenger.getClass(), messenger2.getClass());
assertEquals("Hello World!", messenger.getMessage());
assertEquals("Hello World!", messenger2.getMessage());
messenger.setMessage("Bye World!");
messenger2.setMessage("Byebye World!");
assertEquals("Bye World!", messenger.getMessage());
assertEquals("Byebye World!", messenger2.getMessage());
}
@Test
public void testInlineScriptFromTag() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass());
Calculator calculator = (Calculator) ctx.getBean("calculator");
assertNotNull(calculator);
assertFalse(calculator instanceof Refreshable);
assertEquals(3, calculator.add(1, 2));
}
@Test
public void testInlineScriptFromTagUsingJsr223() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd-jsr223.xml", getClass());
Calculator calculator = (Calculator) ctx.getBean("calculator");
assertNotNull(calculator);
assertFalse(calculator instanceof Refreshable);
assertEquals(3, calculator.add(1, 2));
}
@Test
public void testRefreshableFromTag() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass());
Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");
assertEquals("Hello World!", messenger.getMessage());
assertTrue("Messenger should be Refreshable", messenger instanceof Refreshable);
}
@Test
public void testRefreshableFromTagUsingJsr223() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd-jsr223.xml", getClass());
Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");
assertEquals("Hello World!", messenger.getMessage());
assertTrue("Messenger should be Refreshable", messenger instanceof Refreshable);
}
@Test
public void testThatMultipleScriptInterfacesAreSupported() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass());
Messenger messenger = (Messenger) ctx.getBean("calculatingMessenger");
assertEquals("Hello World!", messenger.getMessage());
// cool, now check that the Calculator interface is also exposed
Calculator calc = (Calculator) messenger;
assertEquals(0, calc.add(2, -2));
}
@Test
public void testWithComplexArg() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContext.xml", getClass());
Printer printer = (Printer) ctx.getBean("printer");
CountingPrintable printable = new CountingPrintable();
printer.print(printable);
assertEquals(1, printable.count);
}
@Test
public void testWithComplexArgUsingJsr223() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextWithJsr223.xml", getClass());
Printer printer = (Printer) ctx.getBean("printer");
CountingPrintable printable = new CountingPrintable();
printer.print(printable);
assertEquals(1, printable.count);
}
@Test
public void testWithPrimitiveArgsInReturnTypeAndParameters() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextForPrimitives.xml", getClass());
PrimitiveAdder adder = (PrimitiveAdder) ctx.getBean("adder");
assertEquals(2, adder.addInts(1, 1));
assertEquals(4, adder.addShorts((short) 1, (short) 3));
assertEquals(5, adder.addLongs(2L, 3L));
assertEquals(5, new Float(adder.addFloats(2.0F, 3.1F)).intValue());
assertEquals(5, new Double(adder.addDoubles(2.0, 3.1)).intValue());
assertFalse(adder.resultIsPositive(-200, 1));
assertEquals("ri", adder.concatenate('r', 'i'));
assertEquals('c', adder.echo('c'));
}
@Test
public void testWithWrapperArgsInReturnTypeAndParameters() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextForWrappers.xml", getClass());
WrapperAdder adder = (WrapperAdder) ctx.getBean("adder");
assertEquals(new Integer(2), adder.addInts(new Integer(1), new Integer(1)));
assertEquals(Integer.class, adder.addInts(new Integer(1), new Integer(1)).getClass());
assertEquals(new Short((short) 4), adder.addShorts(new Short((short) 1), new Short((short) 3)));
assertEquals(Short.class, adder.addShorts(new Short((short) 1), new Short((short) 3)).getClass());
assertEquals(new Long(5L), adder.addLongs(new Long(2L), new Long(3L)));
assertEquals(Long.class, adder.addLongs(new Long(2L), new Long(3L)).getClass());
assertEquals(5, adder.addFloats(new Float(2.0F), new Float(3.1F)).intValue());
assertEquals(Float.class, adder.addFloats(new Float(2.0F), new Float(3.1F)).getClass());
assertEquals(5, new Double(adder.addDoubles(new Double(2.0), new Double(3.1)).intValue()).intValue());
assertEquals(Double.class, adder.addDoubles(new Double(2.0), new Double(3.1)).getClass());
assertFalse(adder.resultIsPositive(new Integer(-200), new Integer(1)).booleanValue());
assertEquals(Boolean.class, adder.resultIsPositive(new Integer(-200), new Integer(1)).getClass());
assertEquals("ri", adder.concatenate(new Character('r'), new Character('i')));
assertEquals(String.class, adder.concatenate(new Character('r'), new Character('i')).getClass());
assertEquals(new Character('c'), adder.echo(new Character('c')));
assertEquals(Character.class, adder.echo(new Character('c')).getClass());
Integer[] numbers = new Integer[]{new Integer(1), new Integer(2), new Integer(3), new Integer(4), new Integer(5)};
assertEquals("12345", adder.concatArrayOfIntegerWrappers(numbers));
assertEquals(String.class, adder.concatArrayOfIntegerWrappers(numbers).getClass());
Short[] shorts = adder.populate(new Short((short) 1), new Short((short) 2));
assertEquals(2, shorts.length);
assertNotNull(shorts[0]);
assertEquals(new Short((short) 1), shorts[0]);
assertNotNull(shorts[1]);
assertEquals(new Short((short) 2), shorts[1]);
String[][] lol = adder.createListOfLists("1", "2", "3");
assertNotNull(lol);
assertEquals(3, lol.length);
assertEquals("1", lol[0][0]);
assertEquals("2", lol[1][0]);
assertEquals("3", lol[2][0]);
Map<?, ?> singleValueMap = adder.toMap("key", "value");
assertNotNull(singleValueMap);
assertEquals(1, singleValueMap.size());
assertEquals("key", singleValueMap.keySet().iterator().next());
assertEquals("value", singleValueMap.values().iterator().next());
String[] expectedStrings = new String[]{"1", "2", "3"};
Map<?, ?> map = adder.toMap("key", expectedStrings);
assertNotNull(map);
assertEquals(1, map.size());
assertEquals("key", map.keySet().iterator().next());
String[] strings = (String[]) map.values().iterator().next();
for (int i = 0; i < expectedStrings.length; ++i) {
assertEquals(expectedStrings[i], strings[i]);
}
}
@Test
public void testAop() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-aop.xml", getClass());
Messenger messenger = (Messenger) ctx.getBean("messenger");
assertEquals(new StringBuffer("Hello World!").reverse().toString(), messenger.getMessage());
}
private static final class CountingPrintable implements Printable {
public int count;
@Override
public String getContent() {
this.count++;
return "Hello World!";
}
}
}

View File

@@ -1,25 +0,0 @@
package org.springframework.scripting.jruby;
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-3026
*
* @author Rick Evans
*/
public interface PrimitiveAdder {
int addInts(int x, int y);
short addShorts(short x, short y);
long addLongs(long x, long y);
float addFloats(float x, float y);
double addDoubles(double x, double y);
boolean resultIsPositive(int x, int y);
String concatenate(char c, char d);
char echo(char c);
}

View File

@@ -1,26 +0,0 @@
/*
* Copyright 2002-2006 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.scripting.jruby;
/**
* @author Rob Harrop
* @since 2.0.2
*/
public interface Printable {
String getContent();
}

View File

@@ -1,26 +0,0 @@
/*
* Copyright 2002-2006 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.scripting.jruby;
/**
* @author Rob Harrop
* @since 2.0.2
*/
public interface Printer {
void print(Printable arg);
}

View File

@@ -1,52 +0,0 @@
/*
* Copyright 2002-2012 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.scripting.jruby;
import java.util.Map;
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-3038
*
* @author Rick Evans
*/
public interface WrapperAdder {
Integer addInts(Integer x, Integer y);
Short addShorts(Short x, Short y);
Long addLongs(Long x, Long y);
Float addFloats(Float x, Float y);
Double addDoubles(Double x, Double y);
Boolean resultIsPositive(Integer x, Integer y);
String concatenate(Character c, Character d);
Character echo(Character c);
String concatArrayOfIntegerWrappers(Integer[] numbers);
Short[] populate(Short one, Short two);
String[][] createListOfLists(String one, String second, String third);
Map<?, ?> toMap(String key, Object value);
}

View File

@@ -3,8 +3,6 @@
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"/>
<bean id="dao" class="org.springframework.beans.factory.xml.DummyDao" autowire="constructor"/>
<bean id="boPrototype" autowire="constructor" class="org.springframework.beans.factory.xml.DummyBoImpl"