I am receiving the following exception when trying to use java mail;
java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
at javax.mail.Session.initLogger(Session.java:226)
at javax.mail.Session.<init>(Session.java:210)
at javax.mail.Session.getInstance(Session.java:247)
at com.secondstory.mailsender.MailSender.createSmtpSession(MailSender.java:67)
at com.secondstory.mailsender.MailSender.sendSimpleMessage(MailSender.java:38)
at com.secondstory.mailsender.MailSender.generateLostPasswordEmail(MailSender.java:79)
at com.secondstory.mailsender.MailSenderTest.shouldReturnTrueWithCredentialsSet(MailSenderTest.java:49)
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:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
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: com.sun.mail.util.MailLogger
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)
... 30 more
After searching stack overflow extensively (maybe not extensively enough - lets see!) I have found that we need two jars inside our maven pom for this too work. The two dependancies I have are as follows;
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
Something has changed but I am not entirely sure what it is - as this worked previously. The code i have written where this element fails is as follows;
private static Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.host", "host");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.transport.protocol", "smtp");
//props.setProperty("mail.debug", "true");
return Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"username", "password");
}
});
}
Am I missing some config or should this work with the current setup that I have?
Thanks
Try adding this into Maven POM:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
The problem is that you are trying to use javax.mail-api.jar. That is the wrong library. JavaMail is a Java EE specification, the interfaces of that specification are published in that javax.mail-api-1.6.1.jar, which only works when compiling. It doesn't provide an implementation of the specification, so it doesn't work at runtime.
You need to use an implementation of the JavaMail specification at runtime. You can find the reference implementation on https://javaee.github.io/javamail/ (but there are others, for example Java EE application servers usually include one).
For javax.mail-api.jar, https://javaee.github.io/javamail/ says:
The JavaMail API definitions only, suitable for compiling against; use
only with a Maven “provided” dependency scope
Specifically in your case you need either javax.mail.jar or mailapi.jar + the jars of the specific protocols you want to use. For example mailapi.jar + smtp.jar if you only need smtp(s) support.
With Maven, you can use
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
Related
I created a vanilla Spring Boot App (1.5.9.RELEASE) but when I Run As -> Spring Boot App (in Eclipse Oxygen) I get
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" java.lang.NoClassDefFoundError: ch/qos/logback/classic/Level
at org.springframework.boot.logging.logback.LogbackLoggingSystem.<clinit>(LogbackLoggingSystem.java:66)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:170)
at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:160)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:229)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:209)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:69)
at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:292)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
at demo.spring.boot.app.CourseApiApp.main(CourseApiApp.java:11)
Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.Level
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)
... 19 more
pom.xml
<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>demo.spring.boot</groupId>
<artifactId>boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
App
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CourseApiApp {
public static void main(String[] args)
{
SpringApplication.run(CourseApiApp.class, args);
}
}
Remark
I also tried mvn clean package -> java -jar target/boot-demo.jar which gives me
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: ch/qos/logback/classic/LoggerContext
at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:59)
at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:50)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:155)
at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:132)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:273)
at org.springframework.boot.SpringApplication.<clinit>(SpringApplication.java:179)
at demo.spring.boot.app.CourseApiApp.main(CourseApiApp.java:11)
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:497)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.LoggerContext
at java.net.URLClassLoader$1.run(URLClassLoader.java:370)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:94)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 19 more
Caused by: java.util.zip.ZipException: invalid stored block lengths
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at org.springframework.boot.loader.jar.ZipInflaterInputStream.read(ZipInflaterInputStream.java:52)
at sun.misc.Resource.getBytes(Resource.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:462)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
... 25 more
Exception in thread "main" java.lang.reflect.InvocationTargetException
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:497)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: java.lang.NoClassDefFoundError: ch/qos/logback/classic/LoggerContext
at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:59)
at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:50)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:155)
at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:132)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:273)
at org.springframework.boot.SpringApplication.<clinit>(SpringApplication.java:179)
at demo.spring.boot.app.CourseApiApp.main(CourseApiApp.java:11)
... 8 more
Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.LoggerContext
at java.net.URLClassLoader$1.run(URLClassLoader.java:370)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:94)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 19 more
Caused by: java.util.zip.ZipException: invalid stored block lengths
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at org.springframework.boot.loader.jar.ZipInflaterInputStream.read(ZipInflaterInputStream.java:52)
at sun.misc.Resource.getBytes(Resource.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:462)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
... 25 more
Extending Mark Bramnik answer, It does look like you don't have logback, which is pretty weird because spring-boot-starter-web have a dependency on spring-boot-starter-logging. Just try to add spring-boot-starter-logging to your POM file
It looks like you're trying to use a logback logging implementation but don't have a logback jar in the classpath:
Please try adding something like this (depending on Spring Boot version there can be another actual version of logback dependency)
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
</dependency>
Then you'll probably want to configure loggers, appenders and so forth. For more information about logging in spring boot read a chapter from official Spring Boot documentation.
Apparently I had a broken jar in the classpath, after removing everything from .m2 and updating it worked.
This worked for me, though not very intelligent: Deleted the ch folder from within .m2 folder, and did a Run > 'Maven install' from Eclipse.
Spring boot application is expecting logback classic dependency.Since its unable to find the logback-classic jar in classpath its throwing an error
Caused by: java.lang.NoClassDefFoundError: ch/qos/logback/classic/turbo/TurboFilter.
After adding the below dependency application started without any issues.
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
</dependency>
Removing everything from maven repo and updating project in eclipse worked for me.
Deleting ch folder in .m2 directory and update maven project in eclipse project helps me in fixing this issue.
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<!-- <version>${logback.version}</version> -->
</dependency>
Adding this logback explicitly, solved the issue in my case.
For us java.lang.ClassNotFoundException: ch.qos.logback.classic.joran.JoranConfigurator meant "I had excluded spring-boot-starter-logging but needed to add spring-boot-starter-log4j2" or something like that, apparently.
working pom:
<build>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
<dependency>
...something internal
<exclusions>
<exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion>
</exclusions>
According to https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/howto-logging.html if you want to use log4j instead of logback you're supposed to "exclude" spring-boot-starter-logging so I guess the pattern of having to reject it from every dependency apps isn't too far off. Kind of weird though...
So maybe what happened was if you "just exclude" Maybe they were still bringing in "just logback" (without joran) as a separate dependency, which confused spring boot?
I've written a test Method. In this project I use Morphia for MongoDB. But when I start the Method I get the follow Error:
java.lang.NoSuchMethodError: org.apache.log4j.Logger.log(Ljava/lang/String;Lorg/apache/log4j/Level;Ljava/lang/Object;Ljava/lang/Throwable;)V
at org.slf4j.impl.Log4jLoggerAdapter.info(Log4jLoggerAdapter.java:166)
at com.mongodb.diagnostics.logging.SLF4JLogger.info(SLF4JLogger.java:71)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:45)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:85)
at com.mongodb.Mongo.createCluster(Mongo.java:670)
at com.mongodb.Mongo.createCluster(Mongo.java:656)
at com.mongodb.Mongo.<init>(Mongo.java:278)
at com.mongodb.Mongo.<init>(Mongo.java:274)
at com.mongodb.MongoClient.<init>(MongoClient.java:174)
at com.mongodb.MongoClient.<init>(MongoClient.java:151)
at com.mongodb.MongoClient.<init>(MongoClient.java:141)
at de.meinTellerchen.utils.mongoDB.connection.MongoDBCon.<init>(MongoDBCon.java:65)
at de.meinTellerchen.ingredient.service.IngredientRestService.dataBaseConnection(IngredientRestService.java:34)
at de.meinTellerchen.ingredient.service.IngredientRestService.<init>(IngredientRestService.java:22)
at de.meinTellerchen.ingredient.service.IngredientRestServiceTest.test001_WriteIngredient(IngredientRestServiceTest.java:21)
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:497)
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.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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)
The Method in this Test creates an Object and saves it in a MongoDB with Morphia.
#Test
public void test001_WriteIngredient() {
Ingredient ingredient = generateIngredient();
IngredientRestService ingredientRestService = new IngredientRestService();
assertNotNull(ingredient);
Response response = ingredientRestService.writeIngredient(ingredient);
assertNotNull(response);
}
I don't know why it doesn't work. I don't use Logger.
The issue is with the version of log4j and slf4j.
Add below mentioned jars in your classpath :
log4j
slf4j-simple
jcl-over-slf4j
slf4j-api
slf4j-log4j12 with appropriate versions
or use maven to handle your dependencies.
Example of Compatible versions of jars:
1) log4j-1.2.15.jar
2) slf4j-api-1.7.7.jar
3) commons-logging-1.0.4.jar
4) logback-classic-1.0.0.jar
5) logback-core-1.0.0.jar
The dependent jar of slf4j is missing in your classpath.
Please open the mongodriver jar available in your system and see the meta-inf/MANIFEST.MF file and add the required jars mentioned in Import-Package:section.
Example:
Mongodb java driver 3.2.1 requires following dependent jars.
Import-Package: javax.xml.bind,javax.crypto,javax.crypto.spec,javax.ma
nagement,javax.net,javax.net.ssl,javax.security.sasl,javax.security.a
uth.callback,org.ietf.jgss,io.netty.bootstrap;resolution:=optional;ve
rsion="[4.0,5)",io.netty.buffer;resolution:=optional;version="[4.0,5)
",io.netty.channel;resolution:=optional;version="[4.0,5)",io.netty.ch
annel.nio;resolution:=optional;version="[4.0,5)",io.netty.channel.soc
ket;resolution:=optional;version="[4.0,5)",io.netty.channel.socket.ni
o;resolution:=optional;version="[4.0,5)",io.netty.handler.ssl;resolut
ion:=optional;version="[4.0,5)",io.netty.handler.timeout;resolution:=
optional;version="[4.0,5)",io.netty.util.concurrent;resolution:=optio
nal;version="[4.0,5)",org.slf4j;resolution:=optional;version="[1.7,2)
"
I am trying to use simple java (minus any framework like Spring or containers like Tomcat etc) to connect to DB2 on mainframe. Here are the steps I took.
Added the db2 drivers to my local maven repository.
mvn install:install-file -Dfile=db2jcc_license_cisuz.jar -DgroupId=com.ibm.db2 -DartifactId=db2jcc -Dversion=1.0 -Dpackaging=jar
mvn install:install-file -Dfile=db2jcc4.jar -DgroupId=com.ibm.db2 -DartifactId=db2jcc4 -Dversion=1.0 -Dpackaging=jar
Created a simple java project using maven archetype. Added the following to the pom.xml
<!-- Connect to DB2 on Mainframe. -->
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>db2jcc </artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>db2jcc4 </artifactId>
<version>1.0</version>
</dependency>
Now created a simple Junit and added the following
Driver driver = (Driver) Class.forName("com.ibm.db2.jcc.DB2Driver")
.newInstance();
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(
"jdbc:db2://server:port/dbname", "username",
"password");
This does not work. It tells me
com.ibm.db2.jcc.am.SqlInvalidAuthorizationSpecException: [jcc][t4][2010][11246][4.13.80] Connection authorization failure occurred. Reason: Local security service non-retryable error. ERRORCODE=-4214, SQLSTATE=28000
I tried changing the driver type as well.
Class.forName("COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver");
But did not work. Still same problem.
I am working off a Windows machine and I have made no configuration for connecting to DB2 at all.
However, from the same Windows machine, using IBM Datastudio, and using the same credentials, I am able to connect to the database and run queries.
The stacktrace
com.ibm.db2.jcc.am.SqlInvalidAuthorizationSpecException: [jcc][t4][2010][11246][3.62.80] Connection authorization failure occurred. Reason: Local security service non-retryable error. ERRORCODE=-4214, SQLSTATE=28000
at com.ibm.db2.jcc.am.fd.a(fd.java:674)
at com.ibm.db2.jcc.am.fd.a(fd.java:60)
at com.ibm.db2.jcc.am.fd.a(fd.java:120)
at com.ibm.db2.jcc.t4.b.q(b.java:2072)
at com.ibm.db2.jcc.t4.b.c(b.java:1669)
at com.ibm.db2.jcc.t4.ab.r(ab.java:809)
at com.ibm.db2.jcc.t4.ab.k(ab.java:363)
at com.ibm.db2.jcc.t4.ab.c(ab.java:136)
at com.ibm.db2.jcc.t4.b.Vc(b.java:1276)
at com.ibm.db2.jcc.t4.b.b(b.java:1195)
at com.ibm.db2.jcc.t4.b.a(b.java:5511)
at com.ibm.db2.jcc.t4.b.c(b.java:760)
at com.ibm.db2.jcc.t4.b.b(b.java:703)
at com.ibm.db2.jcc.t4.b.a(b.java:389)
at com.ibm.db2.jcc.t4.b.<init>(b.java:318)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:214)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:460)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at javahelloworld.poc.DB2ConnectTest.test(DB2ConnectTest.java:38)
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:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
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:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
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)
Please help.
Managed to get this to work. A few things that were wrong with my original attempt.
Both db2jcc_license_cisuz-1.0.jar and db2jcc4-V97FP5.jar are required in the class path. Putting them in your local maven repository and adding them in the pom.xml is fine. However, both of them have to be there. This is how my pom.xml looks now. You could add them both in the classpath by any other method.
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>db2jcc_license</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>db2jcc4</artifactId>
<version>1.0</version>
</dependency>
This driver works fine.
Class.forName("com.ibm.db2.jcc.DB2Driver");
Connection connection1 = DriverManager
.getConnection(
Finally, something that took embarassingly long amount of time for me to figure out. Since we are talking about connection to DB2 on z/OS it might have some additional restrictions of password (those which might not apply to your regular dev environment of windows / linux), that are easy to forget.
Take care of these things and you should be all set. Thanks.
I am aware that there are plenty of information around explaining how to use Swing + Hibernate and Maven in a project, but I think that all this info is way out-dated.
I just tried to follow this and i just ended up having lots of import problems, once apparently the new versions of Hibernate-core dont have some of the classes that it had at the time of this tutorial (I laugh a bit when I saw a code using Vector (-: )
Question is, is it possible to create a project using the latest versions of Hibernate with Swing? Does any one have information on how to do it that is not from 3 years ago?
Issues I had :
1 - Couldnt get HQL Query to work on Netbeans... it complains about
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
Cant find it.. tried other options but no luck (I dont really care about this)
2 - When running code, it complains about
Caused by: java.lang.ClassNotFoundException: org.hibernate.util.DTDEntityResolver
Which is a package from early days of hibernate.
Would appreciate all the help, even pointing me towards a good documentation...
Cheers
UPDATE :
Stack Trace
--- exec-maven-plugin:1.2.1:exec (default-cli) # SwingProject ---
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Apr 01, 2014 4:48:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.4.Final}
Apr 01, 2014 4:48:07 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 01, 2014 4:48:07 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at padaria.util.NewHibernateUtil.<clinit>(NewHibernateUtil.java:30)
at br.com.vaast.main.AdminMain.executeHQLQuery(AdminMain.java:43)
at br.com.vaast.main.AdminMain.runQueryBasedOnFirstName(AdminMain.java:34)
at br.com.vaast.main.AdminMain.jButton1ActionPerformed(AdminMain.java:206)
at br.com.vaast.main.AdminMain.access$200(AdminMain.java:21)
at br.com.vaast.main.AdminMain$3.actionPerformed(AdminMain.java:120)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
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:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.hibernate.cfg.Configuration.reset(Configuration.java:353)
at org.hibernate.cfg.AnnotationConfiguration.reset(AnnotationConfiguration.java:289)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:289)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:293)
at org.hibernate.cfg.AnnotationConfiguration.<init>(AnnotationConfiguration.java:168)
at padaria.util.NewHibernateUtil.<clinit>(NewHibernateUtil.java:26)
... 41 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.util.DTDEntityResolver
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)
... 59 more
Things I’ve tried/checked:
If you download the project that is described in the tutorial and then checking the pom.xml you will see that the libraries used are quite old. I believe that the project is built with an older version of Netbeans. If you check this tutorial: https://netbeans.org/kb/docs/java/hibernate-java-se.html , which is actually the same one but without using maven, it is mentioned that “NetBeans IDE 7.4 and earlier bundled Hibernate 3”.
If you try to follow the tutorial that builds the project without the use of Maven: https://netbeans.org/kb/docs/java/hibernate-java-se.html and you work with NetBeans 8.0 you will get a picture of the Hibernate 4.x libraries needed. That is because the IDE by default comes bundled with Hibernate 4.x libraries.
Going back and building the project with Maven this time I got the following in my pom.xml
<repositories>
<repository>
<id>unknown-jars-temp-repo</id>
<name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
<url>file:${project.basedir}/lib</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpa-2.0-api-1.0.1.Final</artifactId>
<version>SNAPSHOT</version>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>mysql-connector-java-5.1.23-bin</artifactId>
<version>SNAPSHOT</version>
</dependency>
</dependencies>
Solution that worked for me.
The above pom.xml provided some insight but there are some parts that made me unhappy:
<groupId>unknown.binary</groupId> and temporary repository.
So I started searching and finally here: http://hibernate.org/orm/documentation/getting-started/ and here I got what I needed: http://hibernate.org/orm/documentation/getting-started/.
I changed my pom.xml to :
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
Everything is working fine with latest version of Hibernate.
NOTE:
as you can see from the links above you have two options. You can either use <artifactId>hibernate-entitymanager</artifactId> or <artifactId>hibernate-core</artifactId>.
I believe that these references can provide some answers:
Does Hibernate EntityManager include Core?
Any drawbacks of using Hibernate EntityManager (vs. Hibernate Core)?
NOTE 2:
I had some trouble with org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory. In order to build the project I had to use the version without internal. If I did use the internal version then the step Creating Hibernate Mapping Files and POJOs From a Database could not be completed. I had to revert back to classic to complete the step and change it back to internal at the end.
Hope that all the above are useful to you.
Recently ,I decide to use JSR 303 to validate bean In our project,But when i run JUNI test,It got error,The log is as below:
java.lang.AbstractMethodError: org.hibernate.ejb.HibernatePersistence.getProviderUtil()Ljavax/persistence/spi/ProviderUtil;
at javax.persistence.Persistence$1.isLoaded(Persistence.java:78)
at org.hibernate.validator.engine.resolver.JPATraversableResolver.isReachable(JPATraversableResolver.java:61)
at org.hibernate.validator.engine.resolver.DefaultTraversableResolver.isReachable(DefaultTraversableResolver.java:131)
at org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:46)
at org.hibernate.validator.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:1242)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:448)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:397)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:361)
at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:313)
at org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:139)
at com.icil.service.validator.BeanValidator.validate(BeanValidator.java:74)
at com.icil.sofs.booking.model.ValidateTest.test1(ValidateTest.java:48)
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:616)
at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Someone told me this is due to conflicting JAR files. But I don't know which JAR are conflicting. Could anybody could tell me which JAR files are conflicted. Any help is huge for me,Thanks!!!
I was facing similar problem. Actually, HibernatePersistence was not having ProviderUtil() method in entity jars. following combination works well.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.5.Final</version>
</dependency>
without list of JARs its quite hard to help you here.
Do you have maven in your project?
If so, you can use `mvn dependency:tree and see the tree of jars.
It can be that you're using hibernate that doesn't conform the JPA 2.0 Specification ProviderUtil class was introduced in JPA 2.0 as the doc states:
ProviderUtil
Yet another concern:
Are you running standalone or inside some container (app/web server or something)
If you're running a JBoss for example it has its own jars in the lib folder that can also clash with your jars. How exactly you're running your JUnit test?
If it's only a validation problem, consider using your own implementation of TraversableResolver instead of JPATraversableResolver or DefaultTraversableResolver.
Here's how to do it.
JPATraversableResolver might cause an unwished dependency to JPA. Here's a guy with a similar problem.
Of course, if you expect your application to JPA2-compliant, this is not a solution.
public class MyTraversableResolver implements TraversableResolver {
public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class rootBeanType, Path pathToTraversableObject, ElementType elementType) {
return true;
}
public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class rootBeanType, Path pathToTraversableObject, ElementType elementType) {
return true;
}
}