Lambda expression intermittently throws ArrayIndexOutOfBoundsException in my Impl.java class.
Stacktrace:
java.lang.ArrayIndexOutOfBoundsException: 1 java.lang.ArrayIndexOutOfBoundsException: 1
at Impl.lambda$retrieve$0(Impl.java:124) ~[classes/:?]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[?:1.8.0_181]
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[?:1.8.0_181]
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[?:1.8.0_181]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[?:1.8.0_181]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[?:1.8.0_181]
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:1.8.0_181]
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[?:1.8.0_181]
at Impl.retrieve(Impl.java:125) ~[classes/:?]
I've written a sample program simulating the scenario. But, in the sample program, it is NOT reproducible. However, can someone figure out any problem with the following code?
I've tried with empty/non-empty input. When I make numberStr to throw ArrayIndexOutOfBoundsException, the stack trace appears different:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at LambdaTest.lambda$0(LambdaTest.java:13)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at LambdaTest.main(LambdaTest.java:14)
Sample program:
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.math3.util.Pair;
import com.google.common.collect.Lists;
public class LambdaTest {
public static void main(String[] args) {
String[] numberStr = { "one", "two", "three" };
List<Pair<String, SampleEnum>> result = getInputPairs().stream()
.map(entry -> new Pair<String, SampleEnum>(numberStr[entry.getFirst()], entry.getSecond()))
.collect(Collectors.toList()); // <=== similar to Impl.java:125
System.out.println("Lambda tested." + result.toString());
}
private static List<Pair<Integer, SampleEnum>> getInputPairs() {
List<Pair<Integer, SampleEnum>> pairs = Lists.newArrayList();
//pairs.add(new Pair<Integer, SampleEnum>(0, SampleEnum.ONE_AND_ONLY));
return pairs;
}
}
enum SampleEnum {
ONE_AND_ONLY
}
In what cases, can the expression fail? and how to fix it?
It looks like numberStr[entry.getFirst()] is throwing the error. In your Impl class, numberStr somehow has too few elements. Either use a debugger or put this before the .stream() line to see what's going on:
System.out.println("numberStr: " + Arrays.toString(numberStr));
On the same line as Sean mentioned
java.lang.ArrayIndexOutOfBoundsException: 1
This exception clearly tells the that while fetching the data from Array for 1st element, it failed.
If you fix this then it should work fine. To see more clearly, setup debugger at numberStr and see how many elements are there and check how many elements you get from stream. If you try to access an index which is not available in your array. You should see this exception
Related
My working project uses kotlin + spring-boot.
I found this issue when I try to run a test case having space like should success WHEN setting key is api updatable on the MacBook apple-m1 machine.
Example
#Test
#Transactional
fun `should success when setting key is api updatable`()
Then JVM throw Exception that contains stack trace looks like this
Caused by: java.lang.ClassFormatError: Illegal method name "should success when setting key is api updatable" in class com/xxx/xxx/web/rest/CompanySettingResourceIntTest$$EnhancerBySpringCGLIB$$f0902682
This happens on my MacBook m1 machine but never happens on the intel machine.
I try to investigate this issue, then I found when using #Transactional on the method in bean, spring-aop will create a proxy class by using method java.lang.ClassLoader.defineClass.
I have a lot of methods that look like this and it's easy to read. Can I use a method name that contains space run in the m1 machine, How do I fix it?
Thank you.
Environment
JDK version 1.8 (AArch64)
Spring boot 1.5.16
JUnit 4
(I try to POC using spring-boot2+JUnit5 test-case name contains space is fine. But a method in beans throws the Illegal method name too.)
JUnit log (Run test)
Could not generate CGLIB subclass of class com.xxx.xxx.web.rest.CompanySettingResourceIntTest: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class com.xxx.xxx.web.rest.CompanySettingResourceIntTest: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:204)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:466)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:349)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1635)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:398)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:485)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:92)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$100(JUnitPlatformTestClassProcessor.java:77)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:73)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:131)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:201)
... 73 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor82.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:459)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
... 86 more
Caused by: java.lang.ClassFormatError: Illegal method name "should success when setting key is api updatable" in class com/xxx/xxx/web/rest/CompanySettingResourceIntTest$$EnhancerBySpringCGLIB$$f0902682
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
... 91 more
You might be hitting Spring issue #21674 which was fixed in Spring 5.1. You might want to upgrade, if that is an option. It seems there is a fix which ignores those kinds of methods. If that is OK for you or not, I do not know.
Some background information: Your target method is transactional, so Spring tries to create a CGLIB proxy for it. I quickly verified in a simple Spock (Groovy) test that CGLIB seems to be unable to handle methods containing spaces correctly -probably because it is simply unaware of languages like Groovy and Kotlin which allow such things. Here is a proof of concept. I used Groovy and Spock, because I am lazy and did not want to set up a Kotlin project. But I am expecting the result to be identical.
Java class under test:
package de.scrum_master.stackoverflow.q70654015;
public class SampleJava {
public String greet(String input) {
return "Hello " + input + "!";
}
}
Groovy class under test:
package de.scrum_master.stackoverflow.q70654015
class SampleGroovy {
String "say hello to"(String input) {
"Hello $input!"
}
}
Spock test creating CGLIB proxies:
package de.scrum_master.stackoverflow.q70654015
import net.sf.cglib.proxy.Enhancer
import net.sf.cglib.proxy.MethodInterceptor
import spock.lang.Specification
class CGLIBProxyTest extends Specification {
def "create CGLIB proxy for Java class"() {
given:
Enhancer enhancer = new Enhancer()
enhancer.superclass = SampleJava
enhancer.callback = { obj, method, args, proxy ->
method.getDeclaringClass() != Object.class && method.getReturnType() == String.class
? "Hello cglib!"
: proxy.invokeSuper(obj, args)
} as MethodInterceptor
when:
SampleJava proxy = enhancer.create()
then:
proxy.greet("world") == "Hello cglib!"
}
def "create CGLIB proxy for Groovy class with spaces in method name"() {
given:
Enhancer enhancer = new Enhancer()
enhancer.superclass = SampleGroovy
enhancer.callback = { obj, method, args, proxy ->
method.getDeclaringClass() != Object.class && method.getReturnType() == String.class
? "Hello cglib!"
: proxy.invokeSuper(obj, args)
} as MethodInterceptor
when:
SampleGroovy proxy = enhancer.create()
then:
proxy."say hello to"("world") == "Hello cglib!"
}
}
The first test passes, the second one fails with:
net.sf.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
at net.sf.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
at net.sf.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at net.sf.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at net.sf.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at net.sf.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at net.sf.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at net.sf.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at net.sf.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:305)
at de.scrum_master.stackoverflow.q70654015.CGLIBProxyTest.create CGLIB proxy for Groovy class with spaces in method name(CGLIBProxyTest.groovy:36)
Caused by: java.lang.reflect.InvocationTargetException
at net.sf.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:459)
at net.sf.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
... 12 more
Caused by: java.lang.ClassFormatError: Illegal method name "say hello to" in class de/scrum_master/stackoverflow/q70654015/SampleGroovy$$EnhancerByCGLIB$$ef703cf1
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
... 14 more
This is the same error you experieced. As soon as you rename the Groovy method to something which is legal in a JVM, the test passes.
With regard to your claim that the behaviour is supposed to be dependent on the hardware or OS platform, I disagree. I think you probably have differences in your runtime environment. How are you building and running your project? Maven, Gradle, something else?
Update: I have good news for you: I had run my test on JDK 8 and 15 and cglib:cglib-nodep:3.2.6. When upgrading to CGLIB 3.3.0, the test started passing. So you might want to version-manage CGLIB in your Maven POM's <dependencyManagement> section (or whatever is Gradle's equivalent) to that version. Maybe it helps. Please note that some tools might also depend on cglib:cglib, so you want to version-manage that one too. I.e., make sure that you use these versions:
cglib:cglib-nodep:3.3.0
cglib:cglib:3.3.0 (if it is used in your application)
Update 2: I am not a regular Spring user, so I forgot that Spring Core (artifact org.springframework:spring-core) includes its own CGLIB version, relocated to base package name org.springframework.cglib. Please note the package name difference from your stack trace to the original net.sf.cglib for my stand-alone example.
I checked for you and found out that since version 5.2.0.RELEASE, Spring Core was upgraded to CGLIB 3.3.0. So if you can use a Spring version 5.2.0 or more recent, chances are that it works for you.
here is my setup below,
#SpringBootApplication
#ComponentScan(basePackages = "com.amazonaws.serverless.sample.springboot.controller")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
public class LambdaHandler implements RequestStreamHandler {
private SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
private static ObjectMapper mapper = new ObjectMapper();
private Logger log = LoggerFactory.getLogger(LambdaHandler.class);
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
if (handler == null) {
try {
handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);
} catch (ContainerInitializationException e) {
e.printStackTrace();
outputStream.close();
return;
}
}
AwsProxyRequest request = mapper.readValue(inputStream, AwsProxyRequest.class);
AwsProxyResponse resp = handler.proxy(request, context);
mapper.writeValue(outputStream, resp);
// just in case it wasn't closed by the mapper
outputStream.close();
}
}
each time when when I am trying invoke my lambda from local console using command - "serverless invoke local -f hello" I am getting below exception,
j
ava.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.serverless.InvokeBridge.invoke(InvokeBridge.java:102)
at com.serverless.InvokeBridge.<init>(InvokeBridge.java:40)
at com.serverless.InvokeBridge.main(InvokeBridge.java:153)
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContainerInitializer
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler.initialize(SpringBootLambdaContainerHandler.java:167)
at com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler.getAwsProxyHandler(SpringBootLambdaContainerHandler.java:77)
at com.techprimers.serverless.services.AWSLambdaHandler.handleRequest(AWSLambdaHandler.java:172)
... 7 more
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContainerInitializer
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 23 more
at line - "handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);"
Please HELP me resolve this, I tried various ways of boot setup with aws lambda but failed every time. Please help me fix this or help me out in setting up in any other way. Thanks.
In your logs we can see :
NoClassDefFoundError: javax/servlet/ServletContainerInitializer
ClassNotFoundException: javax.servlet.ServletContainerInitializer
Could you please check if libs are loaded , there must be something missing and not loaded up correctly
Also, something like this has been done
<dependency>
<groupId>com.amazonaws.serverless</groupId>
<artifactId>aws-serverless-java-container-spring</artifactId>
<version>1.3.2</version>
</dependency>
Also double check steps in :
https://github.com/awslabs/aws-serverless-java-container/wiki/Quick-start---Spring-Boot
I had the same issue. I was using version 0.2 of aws-serverless-java-container-spring and had to switch to version 1.3.2 as the former version didn't have SpringBootLambdaContainerHandler class.
I am having problems with ElasticSearch Client.
I have designed a Java application (to finish my developer studies) that manage different databases MySQL, mongoDb and ElasticSearch.
I was able to read, create and update data from a db to another.
All was designed and coded with local databases and everything works very well.
All the tests have been validated so we decide to make it work on distant servers on the real databases.
And then the problems begin to happened, and especially the one i'm stuck with since two long days and i'm getting really desperate.
With TransportClient it worked on local, but on real server it bring a NoNodeAvailableException saying that none of the configured nodes are available. Have try a lot of things to make it work but it doesn't.
So i decide to try connect and request with REST. Here is my code, and the error i got is not very detailed : it's a ConnectException.
Code :
// Get the connection client from ES database
public static RestHighLevelClient getConnection()
{
// Singleton
if(client == null)
{
try
{
// Set Credz
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("Login", "pwd"));
// Builder
RestClientBuilder builder = RestClient.builder(new HttpHost("ServerIP", 9200, "http")).setHttpClientConfigCallback(new HttpClientConfigCallback()
{
#Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder)
{
System.out.println("Setting taken !");
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
// Create client
client = new RestHighLevelClient (builder);
ClusterHealthRequest healthReq = new ClusterHealthRequest("looppy-cluster");
ClusterHealthResponse response = client.cluster().health(healthReq, RequestOptions.DEFAULT);
int numberOfNodes = response.getNumberOfNodes();
System.out.println("Nodes Nb : " + numberOfNodes);
}
catch(Exception ex)
{
System.out.println("Client connection problem");
ex.printStackTrace();
}
}
return client;
}
And here is the exception i got :
java.net.ConnectException
at org.elasticsearch.client.RestClient$SyncResponseListener.get(RestClient.java:943)
at org.elasticsearch.client.RestClient.performRequest(RestClient.java:227)
at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1256)
at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:1231)
at org.elasticsearch.client.ClusterClient.health(ClusterClient.java:146)
at utils.ElasticSearchMng.getConnection(ElasticSearchMng.java:86)
at utils.ElasticSearchMng.getLoopiesFromES(ElasticSearchMng.java:133)
at program.Program$1.run(Program.java:96)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.net.ConnectException
at org.apache.http.nio.pool.RouteSpecificPool.timeout(RouteSpecificPool.java:168)
at org.apache.http.nio.pool.AbstractNIOConnPool.requestTimeout(AbstractNIOConnPool.java:561)
at org.apache.http.nio.pool.AbstractNIOConnPool$InternalSessionRequestCallback.timeout(AbstractNIOConnPool.java:822)
at org.apache.http.impl.nio.reactor.SessionRequestImpl.timeout(SessionRequestImpl.java:183)
at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processTimeouts(DefaultConnectingIOReactor.java:210)
at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processEvents(DefaultConnectingIOReactor.java:155)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor.execute(AbstractMultiworkerIOReactor.java:348)
at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.execute(PoolingNHttpClientConnectionManager.java:192)
at org.apache.http.impl.nio.client.CloseableHttpAsyncClientBase$1.run(CloseableHttpAsyncClientBase.java:64)
at java.lang.Thread.run(Unknown Source)
I'm getting despered and ireally don't understand what's happening, would appreciate a lot if someone can help !
thx a lot guyz
The problem is finally resolved, the port was not the good one, the peoples who work with the servers have tell me the port because they changed it and it directly worked ;)
I was trying to create a springboot batch job, which has to read data's from a queue, and write into xml format. I am using StaxEventItemWriter for writing , and while running the application I am getting following error. I strongly believe the error is in the itemwriter section, because with the same reader, I am able to write to a flat file using Filefileitemwriter. I am not able to find out what I did wrong. I am really appriciate your help.
[org.springframework.batch.core.step.AbstractStep.execute] Encountered
an error executing step step1 in job importUserJob
org.springframework.batch.item.ItemStreamException: File already
exists: [C:\folder\Sync_0.xml] at
org.springframework.batch.item.util.FileUtils.setUpOutputFile(FileUtils.java:61)
at
org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:428)
at
org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:400)
at
org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96)
at
org.springframework.batch.core.step.tasklet.TaskletStep.open(TaskletStep.java:310)
at
org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:197)
at
org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
at
org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64)
at
org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67)
at
org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169)
at
org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144)
at
org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134)
at
org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306)
at
org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
at
org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at
org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at
org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy40.run(Unknown Source) at
org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:216)
at
org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:233)
at
org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:125)
at
org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:119)
at
org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:806)
at
org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:790)
at
org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:777)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
Code for itemwriter is provided below.
#Bean
public ItemWriter<WorkerXML> staxEventItemWriter() throws XmlMappingException, Exception{
StaxEventItemWriter<WorkerXML> staxEventItemWriter = new StaxEventItemWriter<WorkerXML>();
try{
XStreamMarshaller marshaller = new XStreamMarshaller();
staxEventItemWriter.setName("StaxEventItemWriter");
staxEventItemWriter.setResource("C://folder//Sync_0.xml"));
staxEventItemWriter.setRootTagName("WorkerXML");
staxEventItemWriter.setOverwriteOutput(false);
staxEventItemWriter.setMarshaller(marshaller);
staxEventItemWriter.setEncoding(StandardCharsets.UTF_8.toString());
staxEventItemWriter.setVersion("XML");//
staxEventItemWriter.setSaveState(true); // staxEventItemWriter.open(new ExecutionContext());
ExecutionContext executionContext = new ExecutionContext();
staxEventItemWriter.open(executionContext);
}
catch(Exception e){
System.out.println("staxEventItemWriter " + e);
}
return staxEventItemWriter;
}
#Bean
public Marshaller marshaller()
{
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(QVCWorkerXML.class);
return marshaller;
}
I am facing an issue with junit. I am trying to autowire Datasource in my junit, but while loading context file it is throwing an error stating failed to load Application context. Please find attached files which contains error trace and junit code. Please let me know if you can help me in this.
The issue is with the xml file entries. It would be helpful if anyone could provide sample codes.
Error Message
-----------------------------------------------------------------------
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
**Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 12 in XML document from class path resource [spring-config.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 10; Element type "bean" must be followed by either attribute specifications, ">" or "/>".**
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:233)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:117)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 10; Element type "bean" must be followed by either attribute specifications, ">" or "/>".
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
... 38 more
XML Code
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.jbhunt.apps"/>
<bean id="testDataSource" class="com.jbhunt.apps.freightmanager.test">
<property name="testDataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2://DEVPJES2.jbhunt.com:5031/JBHDB2T" />
<property name="username" value="rcon666" />
<property name="password" value="jb8829" />
</bean>
<context:property-placeholder location="jdbc.properties" />
Junit Class code
package com.jbhunt.apps.freightmanager.test;
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.jbhunt.biz.touring.preplan.dao.DriverOptimizedQuery;
import com.jbhunt.biz.touring.preplan.util.WsOptLdRslHelper;
//#ComponentScan(basePackages = {"com.jbhunt.apps.freightmanager.test"})
#Configuration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/spring-config.xml")
public class DriverViewCursorQueryTest extends JdbcDaoSupport {
#Autowired
private DataSource testDataSource;
#Autowired
public void settestDataSource(#Qualifier ("testDataSource") DataSource testDataSource) {
this.testDataSource = testDataSource;
}
/*#Autowired
public DriverViewCursorQueryTest(#Qualifier ("testDataSource") DataSource dataSource) {
this.setDataSource(dataSource);
}*/
#Before
public void setUp() throws Exception {
}
#Test
public void testGetDriverOptiQuery()
{
List records = null;
String driverAlphaCode = "ALBM0";
try
{
DriverOptimizedQuery drvOptiQry = new DriverOptimizedQuery(testDataSource);
records = (List) drvOptiQry.execute(new Object[] {driverAlphaCode});
}
catch(Exception e)
{
e.printStackTrace();
}
List Actual = WsOptLdRslHelper.getDriverOptimizedQuery(driverAlphaCode);
assertEquals("Objects are equal , Test Successful",records,Actual);
}
}
Looks like the class name is missing (you only have a package name there):
<bean id="testDataSource" class="com.jbhunt.apps.freightmanager.test">
This does not explain the exception you are facing, which is complaining about wrong xml. The xml looks ok at the position lineNumber: 12; columnNumber: 10 . But may be the xml you posted is not the one used by spring ?
Search the whole project for files with name spring-config.xml, may be you have more than one ?
You can also set a breakpoint at DefaultDocumentLoader.java:75, than you can see, which resource is actually used by spring.