JUnit, JPA, Hibernate and Postgres: How to test? - java

I've been stuck for a while now. I have searched a lot and I can't find the easiest way to test entity classes or JPA operations against a postgres database. I've found how to using Spring, Mockito and other things, but I can't find the simplest way using pure Java.
I have the following JUnit test:
public class ModelConverterTest {
private static EntityManagerFactory emf;
private static EntityManager em;
public ModelConverterTest() {
}
#BeforeClass
public static void setUpClass() throws Exception {
emf = Persistence.createEntityManagerFactory("PU");
em = emf.createEntityManager(); // Retrieve an application managed entity manager
}
#AfterClass
public static void tearDownClass() throws Exception {
em.close();
emf.close(); //close at application end
}
#Before
public void setUp() {
...
}
#After
public void tearDown() {
}
/**
* Test of SIMModelToModel method, of class ModelConverter.
*/
#Test
public void testSIMModelToModel() {
System.out.println("SIMModelToModel");
SIMModel simModel = new PESMModel();
simModel.addState(testState);
Model expResult = null;
Model result = ModelConverter.SIMModelToModel(em, simModel);
assertTrue(expResult!=null);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
}
and when running it, I get the following error:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/PersistenceContextType
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:787)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:447)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getDeclaredMethods(Class.java:1808)
at sun.reflect.annotation.AnnotationType$1.run(AnnotationType.java:104)
at sun.reflect.annotation.AnnotationType$1.run(AnnotationType.java:101)
at java.security.AccessController.doPrivileged(Native Method)
at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:100)
at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:84)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:221)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70)
at java.lang.reflect.Field.declaredAnnotations(Field.java:1033)
at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1026)
at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:196)
at org.junit.runners.model.FrameworkField.getAnnotations(FrameworkField.java:26)
at org.junit.runners.model.TestClass.addToAnnotationLists(TestClass.java:52)
at org.junit.runners.model.TestClass.<init>(TestClass.java:45)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:51)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
My persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="PU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/modelsystemdb</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
What should I do to make the test run?

Quoting Trouble With Crippled Java EE 6 APIs in Maven Repository And The Solution by Adam Bien:
Instead of using
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
You should use alternative (geronimo, jboss etc.) dependencies:
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-ejb_3.1_spec</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jpa_2.0_spec</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>

Had a similar issue. i.e Even though the Hibernate JPA jar was available through transitive dependencies and javaee 6.0 dependency was provided, the JUNIT Test case was failing. I just moved the javaee dependency at the end of the dependencies definition on the pom file so that the hibernate JPA api jar appeared before the Javaee jar during classpath resolution. That seemed to do the trick and I was able to run the test case. Hope this helps.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
javaee appears after hibernate dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>

If you want to use JPA in your tests, then you will need to have a JPA provider on the classpath when you run them. You can compile against javaee-api, but you must have a real, live provider at runtime.
You mention that you're using GlassFish; that uses EclipseLink as its provider, so it would make sense for you to do the same for your tests. There's information about using EclipseLink via Maven on their wiki.

We a very similar issue: Junit tests were successfully executing during maven build, however trying to run them from Eclipse directly showed this awful "Absent Code" error. The solution is not in pom.xml-s (they must be right since your build runs, right?) but the configuration of Junit execution in eclipse. In our case, when the maven dependencies were moved on top of the project itself, the correct implementation (eclipselink 2.0.4) persistence classes were loaded. So in eclipse try to check "Run Configurations...", select the Junit configuration in question and on the "Classpath" tab, change the order of libraries in the "User Entries" section: move Maven dependencies on top.
Best regards,
Joe Public

In my case under Run Configurations/ClassPath on the the project, click Edit and check "Only include exported entries" that did the trick.

Related

org.openqa.selenium.remote.service.DriverService$Builder.createArgs()Lcom/google/common/collect/ImmutableList; with Selenium 3.5.3 Chrome 76

I'm writing Selenium Junit tests with IntelliJ. The tests run ok if I trigger from test directly. However, if I trigger tests from TestRunnerSuite with JunitCore, I encountered following weird error that I did not find a solution after researching on google. Similar questions on DriverService$builder, but not my error type.
[main] ERROR sire.responseOrg.TestIncidents - java.lang.AbstractMethodError: org.openqa.selenium.remote.service.DriverService$Builder.createArgs()Lcom/google/common/collect/ImmutableList;
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:332)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
at sire.responseOrg.WebDrivers.getInstance(WebDrivers.java:15)
at sire.responseOrg.util.util1.setupChromeDriver(util1.java:51)
at sire.responseOrg.Test1.setUp(Test1.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at ......Omitted
at org.junit.runner.JUnitCore.run(JUnitCore.java:127)
at org.junit.runner.JUnitCore.runClasses(JUnitCore.java:76)
at sire.responseOrg.TestSuiteRunner.main(TestSuiteRunner.java:24)
I'm using Selenium 3.5.3 and chrome 76.---> Updated to Selenium 3.141.59,and with main scope.
Now getting error
java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials
at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:63)
at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:36)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
at sire.responseOrg.WebDrivers.getInstance(WebDrivers.java:15)
at sire.responseOrg.util.SeleniumUtil.setupChromeDriver(SeleniumUtil.java:62)
at sire.responseOrg.TestIncidents.setUp(TestIncidents.java:29)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.junit.runner.JUnitCore.run(JUnitCore.java:127)
at org.junit.runner.JUnitCore.runClasses(JUnitCore.java:76)
at sire.responseOrg.TestSuiteRunner.main(TestSuiteRunner.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.http.auth.Credentials
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
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)
... 33 more
Full pom.xml dependencies
<?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>myGroupId</groupId>
<artifactId>myArtifactId</artifactId>
<version>1.0-SNAPSHOT</version>
<description>My description</description>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>main</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.141.59</version>
<scope>main</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
<scope>main</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.6</version>
<scope>main</scope>
</dependency>
<dependency>
<groupId>com.salesforce.seti</groupId>
<artifactId>selenium-dependencies</artifactId>
<version>1.0.3</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<packaging>pom</packaging>
</project>
My project folder structure is
.src
...main
.....java
.......projectname
.........constantsFolder
.........utilFolder
...........util1.java
...........util2.java
.........Test1.java
.........TestRunnerSuite.java
.........WebDrivers.java
If I start test from Test1.java, the test runs regularly though with warnings
[main] INFO projectname.util.util1 - Set up chrome driver.
Starting ChromeDriver 75.0.3770.90 (a6dcaf7e3ec6f70a194cc25e8149475c6590e025-refs/branch-heads/3770#{#1003}) on port 28755
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1566609934.853][WARNING]: This version of ChromeDriver has not been tested with Chrome version 76.
Aug 23, 2019 6:25:34 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
[main] INFO projectname.util.util1 - Navigating to https://mytest.com/
However, after adding a testSuiteRunner as below.
#RunWith(Suite.class)
#Suite.SuiteClasses({ Test1.class })
public class TestSuiteRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(Test1.class);
// print erros, exit etc omitted
}
}
Now I get the weird error and cannot fire the chromedriver.
The webdriver I have is singleton
public class WebDrivers {
private static WebDriver driver = null;
public static WebDriver getInstance(){
if (driver == null) {
driver = new ChromeDriver();
}
return driver;
}
}
It's my first time to work on setting everything up from grounds. I'm not sure if it's pom dependency issue, singleton webdriver issue, or something else. Could anyone share an eyesight on this and give some clues? Much appreciated.
This error message...
java.lang.AbstractMethodError: org.openqa.selenium.remote.service.DriverService$Builder.createArgs()Lcom/google/common/collect/ImmutableList;
...implies that there is some incompatibility between the version of the binaries you are using specifically with the guava dependency.
You are using chrome= 76.0
You are using the following:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.5.3</version>
<scope>test</scope>
</dependency>
Your Selenium Client version is 3.5.3 which is more then 2 years older.
Your JDK version is unknown to us.
So there is a clear mismatch between the Selenium Client v3.5.3 and Chrome Browser v76.0
However as per the discussions in:
java.lang.NoSuchMethodError: com.google.common.collect.ImmutableList.builderWithExpectedSize
NoSuchMethodError: com.google.common.collect.ImmutableList.toImmutableList()Ljava/util/stream/Collector; after upgrade to 2.0.16
These issues crop up due to incompatibile Guava dependency.
The current guava version used within selenium-java-3.141.59 is guava-25.0-jre
Solution
Ensure that:
JDK is upgraded to current levels JDK 8u222.
Selenium is upgraded to current levels Version 3.141.59.
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
Take a System Reboot.
Execute your #Test as non-root user.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.
Update
So presumably your main question with respect to the error:
java.lang.AbstractMethodError: org.openqa.selenium.remote.service.DriverService$Builder.createArgs()Lcom/google/common/collect/ImmutableList;
is solved. Congratulations.
Now, as per your question update as you are seeing the error:
java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials
There are two aspects.
NoClassDefFoundError: NoClassDefFoundError in Java occurs when Java Virtual Machine is not able to find a particular class at runtime which was available at compile time. You can find a detailed discussion in Exception in thread “main” java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
http/auth: Traces of http/auth implies http client is still in use where as the CHANGELOG reflects:
The HttpClient implementation details were out of HttpCommandExecutor right from Selenium v2.45.0.
With the availability of Selenium v3.11, Selenium Grid was switched to use OkHttp rather than the Apache HttpClient.
Further with the release of Selenium v3.141.0, Apache HttpClient was removed from selenium-server-standalone which drastically
reduced the size of selenium server distribution package.
Even the apache-backed httpclient was also removed.
You can find a detailed discussion in org.openqa.selenium.remote.internal.ApacheHttpClient is deprecated in selenium 3.14.0 - What should be used instead?
Remove scope from your POM.
test
or main
Isn't needed for your tests to run
used this gauva jar with latest testng 7.3. Resolved this error also dont configure any testNG seperately. Please remove configuration if we add it in pom.xml
I was facing the same issue. The following steps helped resolve it:
Go to your POM file and comment out/ remove the following dependency:
--> org.seleniumhq.selenium
--> selenium-java
--> 2.48.2
Check what version you have.
Then copy the latest mvn dependency which is 4.1.1 as of now
Perform mvn clean install (till this point it will be sufficient)
Perform reload all maven projects
Perform download sources
Build your project again
Play/ perform mvn clean install again
FYI: as per my knowledge, this issue occurs at compile time when you execute the code. Or the time when you execute a code in a new project which was compiled with different dependencies and versions earlier.

How to specify dependency as transitive, so it includes all inner dependencies automatically?

I'm currently in the process of adding the Jasper API to our project, and I've made a JUnit-test to test the connection. Our Maven project architecture is one parent project, with a few inner projects.
I've added the dependencies I need for jasper to the parent pom:
<dependencyManagement>
<dependencies>
...
<dependency>
<groupId>com.jaspersoft.jasperserver</groupId>
<artifactId>jasperserver-common-ws</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.jaspersoft.jasperserver</groupId>
<artifactId>jasperserver-ireport-plugin</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
</dependencyManagement>
And I've added it to the inner project that requires the jasper dependencies for its unit test:
<dependencies>
...
<dependency>
<groupId>com.jaspersoft.jasperserver</groupId>
<artifactId>jasperserver-common-ws</artifactId>
</dependency>
<dependency>
<groupId>com.jaspersoft.jasperserver</groupId>
<artifactId>jasperserver-ireport-plugin</artifactId>
</dependency>
</dependencies>
After I've done a Maven Update; Maven clean install; and Project built & refresh, I try to execute the UnitTest:
package jasper;
import org.junit.Assert;
import org.junit.Test;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import com.jaspersoft.jasperserver.irplugin.JServer;
import junit.framework.TestCase;
public class JasperApiTest extends TestCase{
private JServer jasperServer;
public ResourceDescriptor get(String uri) throws Exception{
ResourceDescriptor rd = new ResourceDescriptor();
rd.setUriString(uri);
return this.jasperServer.getWSClient().get(rd, null, null);
}
#Override
protected void setUp(){
this.jasperServer = new JServer();
this.jasperServer.setName("__ourName__");
this.jasperServer.setPassword("__ourPassword__");
this.jasperServer.setUrl("__ourServer__/jasperserver-pro/services/repository");
}
#Test
public void testJasperApi(){
try{
ResourceDescriptor rd = get("/test");
Assert.assertNotNull(rd);
} catch(Exception ex){
Assert.fail("Failed: " + ex);
}
}
}
Now the problem is that it gives a java.lang.ClassNotFoundException. Initially for the org.apache.axis.EngineConfiguration. When I explicitly add this to the pom it goes to the next ClassNotFoundException, but this time for org.apache.commons.logging.LogFactory. And if I add this one as well, it continues with the next inner dependency.
Since I don't use these dependencies myself, only Jasper is, I don't need to add them, but just let Maven add them for me automatically. So, I've read about Transitive_Dependencies, which is just what I need, but this link didn't really gave an example of how to configure this.
I've also tried the following small 'tutorial', but the inner dependencies aren't added..
How can I add all the inner dependency jars through Maven without adding them all manually to the pom? I thought this was done automatically when the scope is compile (which is the default, although I've also tried setting it explicitly just in case - without any difference).
EDIT: When I build the project with the mvn dependency:tree goal, it shows the following two lines for the Jasper jars:
[INFO] | +- com.jaspersoft.jasperserver:jasperserver-common-ws:jar:5.5.0:compile
[INFO] | \- com.jaspersoft.jasperserver:jasperserver-ireport-plugin:jar:3.0.0:compile
But no inner dependencies, which is why they aren't being added.
But, when I debug the UnitTest it goes to the .getWSClient() line, and the actual error occurs in junit.framework.TestCase#runTest(), with the following Stacktrace:
java.lang.NoClassDefFoundError: org/apache/axis/EngineConfiguration
at com.jaspersoft.jasperserver.irplugin.JServer.getWSClient(JServer.java:102)
at jasper.JasperApiTest.get(JasperApiTest.java:20)
at jasper.JasperApiTest.testJasperApi(JasperApiTest.java:34)
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 junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
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: java.lang.ClassNotFoundException: org.apache.axis.EngineConfiguration
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 22 more
Is this some kind of UnitTest (TestCase-class) reflection problem which causes the ClassNotFoundException. So the classes it gives these errors aren't inner dependencies of the two Jasper API jars, so I am forced to add them all manually even though I don't use them directly in my own code? Or can I still use transitivity somehow?

Way Too Many Maven Dependencies

I've been trying to setup the simplest of simple hibernate applications and for reasons beyond my mediocre way of thinking I cannot get it running. Maven is easy enough - adding dependencies to the build path, updating the project, blah blah blah yadda yadda yadda
It started off as a single ClassNotFoundException which required a missing dependency. I would import the missing jar and run the app again, only to get another ClassNotFoundException. Next thing I know I HAVE A TON OF JARS AND NO WORKING APPLICATION
*Directories have been masked to protect the unfortunate
I've used both Maven and Hibernate in my last project in Eclipse Kepler and it was almost too easy, ha! Updating to Luna was a real pain trying to get Maven to run correctly - disabling the Java Compilier Compliance Level just to be able to update the Dynamic Web Module, not to mention manually creating the missing src/main/java and src/test/java folders that are standard with a maven-archetype-webapp, the list goes on. I've spent tooooo much time just to get the thing to not fail.
In my last project all I needed to import was:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
That' was it! I was swimming in Session Factories and Updating database tables like it was my job (it is).
This leads me to believe some core functionality is missing from this new project. Perhaps I've overlooked something in the IDE Upgrade. Could almost guarantee its my Build Path. Please Help!
About my project - I'm using:
Eclipse Luna (Kepler was 100x easier to setup with Maven)
Maven Webapp Archetype
JDK-1.7
Hibernate Core 4-3.6
My latest Exception was
Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
at org.hibernate.cfg.AnnotationBinder.bindDefaults(AnnotationBinder.java:276)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1402)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at com.boa.ecris.test.Main.main(Main.java:22)
Caused by: java.lang.ClassNotFoundException: javax.persistence.NamedStoredProcedureQuery
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 4 more
If this is specific to the javax persistence-api.jar, it's already in there!!!
Java APIs change over time. You need to find the correct version of your dependency (namely the one which contains the version of the API which you want/need to use). Since you told Maven to use version 1.0.2 of persistance-api, that's what Maven will do - you might know better.
If the error doesn't go away, then your next step should be the Maven central repo, specifically the "find class for me" search dialog: http://search.maven.org/#search%7Cga%7C1%7Cfc%3Ajavax.persistence.NamedStoredProcedureQuery
Next, you need to understand which dependencies you want in your project and select the correct one from the list. Since Maven doesn't know about your constraints, that is something you have to figure out yourself.
A word of wisdom: A computer doesn't have a brain, bring your own.
When you have ClassNotFoundException, first of all you have to look at your repository site. You can get maven repository url from settings file in .m2 folder. Then you can search your dependency at that site with your artifact id and version. If your version is not there, you can see some other version and put it instead yours. So you can provide stability at your project without manual adding.
Luna can create the maven project hierarchy too. On the New maven project dialog check the Create a simple project (skip archetype selection) checkbox.

Java build path errors on Eclipse

Recently, I've been playing a little bit with depency injections in Java. I'm a complete newbie in this field, and I don't really get, why in this simple example I keep receiving an error.
package michal.dependency;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Injector injector = Guice.createInjector(new ProjectModule());
Person person = injector.getInstance(Person.class);
person.greetFriend();
}
}
The error message I receive is as follows:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableList
at com.google.inject.internal.Errors.<clinit>(Errors.java:656)
at com.google.inject.internal.InternalInjectorCreator.<init>(InternalInjectorCreator.java:62)
at com.google.inject.Guice.createInjector(Guice.java:96)
at com.google.inject.Guice.createInjector(Guice.java:73)
at com.google.inject.Guice.createInjector(Guice.java:62)
at michal.dependency.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.ImmutableList
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)
... 6 more
I'm pretty sure by the way the necessary .jar file is included in the classpath.
Here comes the requested Person class, as requested:
package michal.dependency;
import com.google.inject.Inject;
public class Person {
private MessageService messageService;
#Inject
public Person (MessageService messageService)
{
this.messageService = messageService;
}
public void greetFriend ()
{
messageService.sendMessage("Hey!", "How are you?");
}
}
Thanks in advance.
I think you are missing Google collections, now known as Guava.
See Google Guice Wiki
JSR 330
Guice 4.0 requires JSR 330 on your classpath. This is the javax.inject.jar included in the guice download.
com.google.inject.internal
Many things inside com.google.inject.internal changed and/or moved. This is especially true for repackaged Guava (formerly Google Collections), cglib, and asm classes. All these classes are now hidden from IDE auto-import suggestions and are in new locations. You will have to update your code if you relied on any of these classes.
As other have suggested, it seems that something is missing from your classpath.
Maybe you could try using some sort of dependency management tool, for example Apache Maven?
It's a great tool for handling dependencies, used extensively in the java world. Depending on your IDE you will have lots of supportfor using it (my personal favourite is Intellij Idea with really great maven support, though Netbeans also does it pretty well).
I tried to prepare a maven pom.xml file it should look something like this. I tested the project with this and there are no compilation errors:
<?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>groupId</groupId>
<artifactId>test-project</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
</project>

NullPointerException in JAXBContext.newInstance()

Java developer here. I am using JAXB to create bind objects. When I attempt to create a JAXBContext like this:
JAXBContext.newInstance("com.mycompany.jaxb.pkg1:com.mycompany.jaxb.pkg2");
I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at com.sun.xml.bind.v2.model.impl.PropertyInfoImpl.calcXmlName(PropertyInfoImpl.java:287)
at com.sun.xml.bind.v2.model.impl.PropertyInfoImpl.calcXmlName(PropertyInfoImpl.java:260)
at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl.getTypes(ElementPropertyInfoImpl.java:100)
at com.sun.xml.bind.v2.model.impl.RuntimeElementPropertyInfoImpl.getTypes(RuntimeElementPropertyInfoImpl.java:50)
at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.size(ElementPropertyInfoImpl.java:42)
at java.util.AbstractList$Itr.hasNext(AbstractList.java:416)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:139)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
at com.sun.xml.bind.v2.model.impl.RegistryInfoImpl.<init>(RegistryInfoImpl.java:63)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.addRegistry(ModelBuilder.java:232)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:201)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:357)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:351)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:350)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:216)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:76)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:55)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:592)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:286)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:244)
at com.mycompany.jaxb.JAXBContextFactory.initIfNeeded(JAXBContextFactory.java:66)
Googling for the relevant keywords led me to several discussion threads saying that this is a known bug and I should upgrade to version 2.0.3. But here is my maven POM file:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
...as you can see, I am already beyond version 2.0.3. (And yes, I tried rolling back to the old version; it didn't help.)
Has anyone seen this for a reason OTHER than version 2.0.2 or older, or does anyone have pointers for how to go about tracking down the problem?
Okay, for the record: I found the solution.
As several threads had suggested, the source of this bug was using a version of JAXB which was older than 2.0.2. My error was that my maven POM file was being overridden by another POM file which was importing an older version of the library.
Thanks to skaffman, and everyone else who took a look.

Categories

Resources