Deploying embedded tomcat enabled spring-boot app using IntelliJ - maven

I have a spring-boot based application, using embedded tomcat. I have no problem when deploying via mvn spring-boot:run goal, but I have a problems when I try to deploy using intelliJ spring-boot plugins. Important note, we have modified the default pom, turning our app into a war that could be deployed into a full tomcatTraditional Deployment, but this in development mode will be better to just deploy the app using the embedded tomcat. The problem is that basically we ended with this message when trying to run the spring boot app from intelliJ
Caused by: java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.web.support.SpringBootServletInitializer
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:163) ~[spring-core-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.retrieveBeanMethodMetadata(ConfigurationClassParser.java:380) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:314) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:245) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:198) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 17 common frames omitted
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContext
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_144]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_144]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_144]
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:152) ~[spring-core-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 22 common frames omitted
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContext
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
... 26 common frames omitted
Do you have any ideas of why is this happening ? and how can we solve it ?
EDIT:
I am using IntelliJ IDEA 2017.2 (just in case the build is idea-IU-172.3317.76), and as a SSCCE, lets use the getting-started example of spring-boot, and lets apply the changes proposed for Traditional Deployment (the first link) we will have the following files
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-spring-boot</artifactId>
<version>0.1.0</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Then we will have the Application.java
package hello;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
And I didn' modify the HelloController.java but just for completeness:
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
This example runs without problem using mvn spring-boot:run but doesn't run when using the spring-boot intelliJ's plug-in

Note - this answer references Spring documentation for v 1.5.6.RELEASE (current release)
Analyses:
Running the main class from IJ is like executing your app from command line. As such, the classpath will include only compile and runtime scoped dependencies. Provided means that it'll be needed during compilation, but you expect the JDK or the container to provide it for your app at runtime:
provided
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
On the other hand, the spring-boot-maven-plugin uses a different classpath to execute the run goal:
By default, both the repackage and the run goals will include any provided dependencies that are defined in the project. A boot-based project should consider provided dependencies as container dependencies that are required to run the application.
Conclusion and solutions:
So it's a classpath configuration issue. As you mentioned, for war packaging or traditional deployment, you should exclude the embedded servlet container. However, to be able to run the app during development, you want the embedded container.
As a solution or work around, you have at least the following 2 options:
1) Remove the <scope>provided</scope> from the spring-boot-starter-tomcat dependency declaration. If you wanted to, you could remove that dependency altogether, as Tomcat is the default container used by spring-boot-starter-web, but perhaps it's best to leave it and add a comment, so you won't forget about it when releasing
2) A neat trick that works with IJ and would make it easier to not forget to uncomment provided before production release, is to leave the dependency as it is now, and add a maven dev profile which you can activate from IJ. This way, by default it will be provided and it can be safely packaged into a war, and only when developing and manually activating the profile it will be included. After adding the profile, reimport your maven project so you can select the profile:
<profiles>
<profile>
<id>dev</id>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>

if you are using maven project then you need to add javax.servlet-api dependency.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
you can also download jar from http://central.maven.org/maven2/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar

Related

Spring boot 2 with apache camel application start error

I have a requirement where I need to listen to a active mq and call rest post api for the data I have recieved as body, for this I have created simple spring boot 2.x application and trying to start a router, but application is failing to start.
My understanding about registering a Router is to anottate a class with #Component and it should implement camel RouteBuilder
#Component
public class Router extends RouteBuilder{
#Override
public void configure() throws Exception {
from("timer:foo").to("log:bar");
}
}
JDK 1.8
Spring boot version 2.2.6.RELEASE
Camel version 2.24.0
Pom xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>2.24.0</version>
</dependency>
</dependencies>
The error I am getting is
Caused by: java.lang.ClassNotFoundException: org.apache.camel.spring.spi.XmlCamelContextConfigurer
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
Try removing the camel-spring dependency. This should be pulled transitively through camel-spring-boot-starter.
The error message could be a problem with different Camel versions. For example if ${camel.version} in your POM is not defined or not equal to 2.24.0 you could have mixed Camel versions for camel-spring and camel-core.
If there will be any resource can't able to downloaded in your system so for this you have to uninstall the application and delete all the files from c/program-file/ and then install it again. Hope it will help you out from this issue.

Mockito cannot mock this class: interface

I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
#BeforeMethod
public void setup() throws Exception {
mockStatic(ResourceBundle.class);
mockStatic(WebObjectsFactory.class);
WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
WebIServerSession webIServerSession = mock(WebIServerSession.class);
PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);
MockitoAnnotations.initMocks(this);
}
#Test
public void shouldBeTrue() {
assertTrue(true);
}
Maven dependencies:
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
</dependencies>
Stacktrace:
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 1.8
JVM vendor name : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name : Java HotSpot(TM) 64-Bit Server VM
JVM version : 1.8.0_191-b12
JVM info : mixed mode
OS name : Mac OS X
OS version : 10.14.1
Underlying exception : java.lang.IllegalArgumentException: Could not create type
at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
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.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 63 more
Test ignored.
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================
Process finished with exit code 0
The exception is most likely to occur due to the version of Mockito used.
Try by replacing the current version of mockito-core with below dependency.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.22.0</version>
<scope>test</scope>
</dependency>
Ignore the warning of overriding managed version in pom.xml
Make sure your interface visibility is public.
I am not sure that it will be the solution in your case. I got the same issue when I was testing in Android Studio.
My solution was replace core-mockito with
androidTestImplementation "org.mockito:mockito-android:2.25.0"
Then it started working perfect.
It may be solution for those who are testing for Android Studio and having the same issue.
add
#RunWith(MockitoJUnitRunner.class)
I also experienced this problem when trying to mock a non-public interface, and the error message didn't make sense, as all my tests in another suite passed correctly while mocking the same interface.
In my case I had to downgrade the Mockito Core library and revert it again to make it work. Here are the steps I took:
Find the Mockito Core dependency in the module level build.gradle file entry:
testImplementation 'org.mockito:mockito-core:2.25.0'
Downgrade to another valid version, in my example 2.23.0:
testImplementation 'org.mockito:mockito-core:2.23.0'
Do a Gradle sync and wait for completion
Revert the Mockito Core dependency to the same version you had before (or newer):
testImplementation 'org.mockito:mockito-core:2.25.0'
Sync the project again
Run the tests again
I had a similar issue. I was surprisingly having:
Mockito cannot mock this class: interface javax.servlet.ServletContext.
This was only when I ran my test in my IDE (IntelliJ Idea). If I tried to run it via maven command - it passed.
To make the test work in IntelliJ Idea I just changed the configurations:
Set Shorten command line to JAR manifest.
It's Strange but after adding below line in build.gradle file it work for me
androidTestImplementation "org.mockito:mockito-android:$mockitoAndroid"
I also have this problem by using IDEA, finally choose Shorten command line: "JAR manifest" solved
annotate your test class like this
#RunWith(PowerMockRunner.class)
#PrepareForTest({ResourceBundle.class, WebObjectsFactory.class, AnyOtherClassThatContainsStaticMethod.class, . . .})
ref: https://github.com/powermock/powermock/wiki/mockstatic

Selenium-TestNG-Maven - Getting "java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver"

This is my first selenium script using TestNG and Maven.
Created a simple "Hello World" code and a selenium test code which just checks the title of google page.
Selenium Code Below with TestNG:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class HelloTest {
#Test
public void testOne() {
//WebDriver d=new FirefoxDriver();
System.setProperty("webdriver.gecko.driver","D:\\Firefox Driver\\geckodriver-v0.17.0-win64\\geckodriver.exe");
WebDriver d=new FirefoxDriver();
d.get("https://www.google.com");
System.out.println("This is first TestNG");
}
}
This is working absolutely fine when run through eclipse - Run As - Test NG test.
But when ran through Maven - mvn clean install from cmd prompt, i am getting below error
T E S T S
-------------------------------------------------------
Running HelloTest
Configuring TestNG with: TestNG652Configurator
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.94 sec <<< FAILURE! - in HelloTest
testOne(HelloTest) Time elapsed: 0.032 sec <<< FAILURE!
java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver
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 HelloTest.testOne(HelloTest.java:11)
It is showing error at WebDriver d=new FirefoxDriver();. Not sure where the issue is. Added all jar files , checked the build path and all the jar were there. Below is my POM file.
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.micky</groupId>
<artifactId>MavenDemoTwo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<type>jar</type>
<version>15.0</version>
</dependency>
</dependencies>
</project>
Any help is deeply appreciated.
What is NoClassDefFoundError
NoClassDefFoundError in Java occurs when JVM is not able to find a particular class at runtime which was available at compile time. For example, if we have resolved a method call from a Class or accessing any static member of a Class and that Class is not available during runtime then JVM will throw NoClassDefFoundError.
The error you are seeing is :
java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver
This clearly indicates that Selenium is trying to resolve the particular FirefoxDriver Class at runtime from org/openqa/selenium/firefox/FirefoxDriver which is not available.
What went wrong :
This situation occurs if there are presence of multiple sources to resolve the Classes and Methods through JDK/Maven/Gradle.
From the pom.xml it is pretty clear that you have added multiple dependencies for FirefoxDriver Class as follows:
<artifactId>selenium-java</artifactId>:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
<scope>test</scope>
</dependency>
<artifactId>selenium-firefox-driver</artifactId>:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.12.0</version>
</dependency>
<artifactId>selenium-server</artifactId>:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.12.0</version>
</dependency>
Additionally you have also added all jar files.
From all the above mentioned points it's clear that the related Class or Methods were resolved from one source at Compile Time which was not available during Run Time.
Solution :
Here are a few steps to solve NoClassDefFoundError :
While using a Build Tool e.g. Maven or Gradle, remove all the External JARs from the Java Build Path. Maven or Gradle will download all the dependencies mentioned in the configuration file (e.g. pom.xml) to resolve the Classes and Methods.
If using Selenium JARs within a Java Project add only required External JARs within the Java Build Path and remove the unused and duplicate External JARs.
If you are using FirefoxDriver use either of the <artifactId>selenium-java</artifactId> or <artifactId>selenium-server</artifactId>. Avoid using both at the same time.
Remove the unwanted and duplicated from pom.xml
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
Use CCleaner tool to wipe off all the OS chores before and after the execution of your Test Suite.
If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.
Take a System Reboot.
While you execute a Maven Project always perform the folling in sequence:
maven clean
maven install
maven test
You can find related discussions in:
Exception in thread “main” java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
How to solve java.lang.NoClassDefFoundError? Selenium
java.lang.NoClassDefFoundError: com/google/common/base/Function
I was using eclipse 09-2019 which is the latest one with latest JDK installed 13, and latest selenium jar files 3.141.59, I installed other JDKs to work around to solve this issue after trying all answers on similar question. Then after 4 days trying, installed eclipse neon version(https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/neon/3/eclipse-java-neon-3-win32-x86_64.zip&mirror_id=105) and used Selenium-Java 3.5.2 jar files (https://jar-download.com/artifacts/org.seleniumhq.selenium/selenium-java/3.5.2/source-code) and now it is working perfectly Alhamdullilah.
Also I don't know what was the errors root cause exactly or at all, but now it is solved.
Wish if that help You

Elasticsearch Java API from web application-error: java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.threadpool.ThreadPool

I couldn't use elasticsearch Java API through JSP. In the following, I have tried to explain what I have done. :|
I have installed elasticseach 2.3.3 on my system by following the elastic instruction and run it from command prompt. everything is working perfectly. It may be useful to say, I have changed below parameters from elasticsearch.yml.
cluster.name: cluster_233
node.name: node_233
bootstrap.mlockall: true
network.host: 127.0.0.1
Then with Netbeans, I have created a Maven project -> Web application project and set the below dependency in pom.xml :
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
<type>jar</type>
</dependency>
Also I have added the Guava version 18 dependency into project and then download all the project dependencies by right clicking on Dependencies and select Download Declared Dependencies . Then created a java class and write below code:
package com.mycompany.esmaven;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
public class aClass {
public String test() throws Exception {
String str = tryToIndex();
String dfd = "";
return str;
}
public String tryToIndex() throws Exception {
Node node = NodeBuilder.nodeBuilder().settings(
Settings.builder()
.put("path.home", "d:/elasticsearch-2.3.3")
.put("cluster.home", "cluster_233")
).node();
Client client = node.client();
client.prepareIndex("kodcucom", "article", "1")
.setSource(putJsonDocument("ElasticSearch: Java API",
"ElasticSearch provides the Java API, all operations "
+ "can be executed asynchronously using a client object.",
new Date(),
new String[]{"elasticsearch"},
"Hüseyin Akdoğan")).execute().actionGet();
node.close();
return "Done";
}
public static Map<String, Object> putJsonDocument(String title,
String content, Date postDate, String[] tags, String author) {
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put("conten", content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("tags", tags);
jsonDocument.put("author", author);
return jsonDocument;
}
}
And through a jsp page tried to call the test() function (I'm going to integrate elasticsearch with a web application). Always after building the project at the first load the below error will appear:
java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
and after refreshing the page the context of error will change to:
java.lang.NoClassDefFoundError: Could not initialize class org.elasticsearch.threadpool.ThreadPool
This is the POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ISTEX</groupId>
<artifactId>mvnESwebapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mvnESwebapp</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Also, I would like to mention, with this POM I can index my JSON from the main function. But the problem is I did not know how to run the application through JSP pages.
I really appreciate you for sharing your knowledge.
Regards,
Amin
FWIW, I ran into the same issue as described above -- that is, the error message I saw was the threadpool initialization error the author describes. The solution described in the link below solved the problem for me:
https://discuss.elastic.co/t/could-not-initialize-class-org-elasticsearch-threadpool-threadpool/47575
UPDATED per comment suggestion:
In my case, the fix was to add a guava dependency entry in my POM file. I used the dependency given in the webpage at the link above:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
That, at least in my case, solved the problem.
With Java applications, errors like
java.lang.NoSuchMethodError
java.lang.NoClassDefFoundError
generally indicate that you are missing a dependency or you have conflicting dependency. For example, Guava 18.0 and Guava 19.0 are completely different as far as Java is concerned, but they share a lot of code. As the jars are loaded, one will naturally be loaded first, so any attempted usage of the second will cause misleading errors like those above.
Also I have added the Guava version 18 dependency into project and then download all the project dependencies by right clicking on Dependencies and select Download Declared Dependencies
Elasticsearch 2.3.3 already depends on Guava 18.0. As such, it's a transitive dependency of the Elasticsearch project.
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
<type>jar</type>
</dependency>
Your Maven dependency is probably creating a collision with one of your other dependencies. Take a look at your Netbeans dependencies, or more appropriately ask Maven to do it directly:
mvn dependency:tree -Dverbose
This will print out the dependency tree for you to find conflicts. Look for jars that are duplicated with different versions and stop the mismatch from happening.
As a side note, at the time of this answer, Guava 19 is the latest version. So even though ES 2.3.3 wants Guava 18, some other dependency of yours could easily and reasonably want a different version of Guava.

JMS connection to WebsphereMQ

I am trying to connect to WebsphereMQ using JMS.
The following configuration is defined:
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
properties.put(Context.URL_PKG_PREFIXES, "com.ibm.ws.naming");
properties.put(Context.PROVIDER_URL, "iiop://localhost:2809");
properties.put(Context.SECURITY_PRINCIPAL, "user")
properties.put(Context.SECURITY_CREDENTIALS, "password")
The following dependencies are included in the Maven POM file:
<dependency>
<groupId>com.ibm</groupId>
<artifactId>com.ibm.mqjms</artifactId>
<version>7.0.1.4</version>
</dependency>
<dependency>
<groupId>com.ibm</groupId>
<artifactId>com.ibm.mq.jmqi</artifactId>
<version>7.0.1.4</version>
</dependency>
<dependency>
<groupId>com.ibm</groupId>
<artifactId>com.ibm.dhbcore</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>com.ibm.mq</groupId>
<artifactId>com.ibm.mq.jar</artifactId>
<version>7.0.1.4</version>
<scope>runtime</scope>
</dependency>
When trying to instantiate the context (new InitialContext(properties)), the following exception is thrown:
javax.naming.NoInitialContextException: Cannot instantiate class: com.ibm.websphere.naming.WsnInitialContextFactory [Root exception is java.lang.ClassNotFoundException: com.ibm.websphere.naming.WsnInitialContextFactory]
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:674)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.init(InitialContext.java:242)
at javax.naming.InitialContext.<init>(InitialContext.java:216)
Is there a maven dependency missing?
Thanks
Not sure what the maven coordinates are, since I don't think these libraries are in any public repos, so coordinates will be repo specific, but according to this post, the jar files required are:
wssec.jar
naming.jar
namingclient.jar
lmproxy.jar
sas.jar
ecutils.jar
Nicholas' answer is correct. (Moving this from comment to allow for formatting)
IBM does not distribute their jars into Maven repositories. Someone in your organization deployed them manually (which is a common practice).
You either:
Are not pointing your maven settings.xml or project pom.xml to your organization's internal Maven Repository
Need to deploy the MQ jars to the repository manually.
mvn deploy:deploy-file -DgroupId=com.ibm.mq -DartifactId=mqjms -Dversion=7.5.0.2 -Dfile=mqjms.jar
See: https://maven.apache.org/guides/mini/guide-3rd-party-jars-remote.html

Resources