com.mysql.jdbc.Driver not resolved in ApiFest - jdbc

Here is what my pom.xml looks like :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
Code where i am trying to get jdbc connection :
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "dbname” ";
String userName = "userName";
String password = "password";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url + dbName, userName, password);
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
} catch (Exception e) {
System.out.println("Inside exception");
e.printStackTrace();
}
System.out.println("Returning connection >>> " + connection);
return connection;
}
I am running ApiFest server using command :
java -Dproperties.file=apifest-oauth.properties -Dlog4j.configuration=file:log4j.xml -jar target/apifest-oauth20-0.2.0-SNAPSHOT-jar-with-dependencies.jar
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
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 java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:789)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
Also tried downloading com.mysql.jdbc_5.1.5.jar and added it to class path but no help.

Related

Getting BadCredentialsException in password change openldap spring

I have openldap running on my localhost, i am trying to change user account password from my spring application but i am getting below Exception.
Please help.
org.springframework.security.authentication.BadCredentialsException: Authentication for password change failed.
at org.springframework.security.ldap.userdetails.LdapUserDetailsManager$3.executeWithContext(LdapUserDetailsManager.java:204) ~[spring-security-ldap-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.ldap.core.LdapTemplate.executeWithContext(LdapTemplate.java:817) ~[spring-ldap-core-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.ldap.core.LdapTemplate.executeReadWrite(LdapTemplate.java:812) ~[spring-ldap-core-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.security.ldap.userdetails.LdapUserDetailsManager.changePassword(LdapUserDetailsManager.java:191) ~[spring-security-ldap-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at com.atulsia.controller.UserController.getTemplate(UserController.java:417) ~[classes/:na]
at com.atulsia.controller.UserController.getAllUsers(UserController.java:437) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
Code:
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldap://localhost:389");
contextSource.setUserDn("cn=Anil Pawar,cn=mts,ou=mm,dc=example,dc=com");
contextSource.setPassword("123456");
try {
contextSource.afterPropertiesSet();
} catch (Exception ex) {
ex.printStackTrace();
}
LdapTemplate template = new LdapTemplate();
template.setContextSource(contextSource);
LdapUserDetailsManager ldapUserDetailsManager = new LdapUserDetailsManager(template.getContextSource());
ldapUserDetailsManager.changePassword("123456", "111111");

Writing java based JMS Client for WildFly10

I writing java based JMS Client for WildFly10 and I had problem
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, WILDFLY_REMOTING_URL); // NOTICE: "http- remoting" and port "8080"
props.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
props.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
//props.put("jboss.naming.client.ejb.context", true);
context = new InitialContext(props);
i run your client code and i got this error:
Got initial Context: javax.naming.InitialContext#5442a311
Exception in thread “main” org.jboss.naming.remote.protocol.NamingIOException: Failed to lookup [Root exception is java.io.IOException: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory]
at org.jboss.naming.remote.client.ClientUtil.namingException(ClientUtil.java:49)
at org.jboss.naming.remote.protocol.v1.Protocol$1.execute(Protocol.java:104)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1.lookup(RemoteNamingStoreV1.java:95)
at org.jboss.naming.remote.client.HaRemoteNamingStore$1.operation(HaRemoteNamingStore.java:276)
at org.jboss.naming.remote.client.HaRemoteNamingStore.namingOperation(HaRemoteNamingStore.java:137)
at org.jboss.naming.remote.client.HaRemoteNamingStore.lookup(HaRemoteNamingStore.java:272)
at org.jboss.naming.remote.client.RemoteContext.lookup(RemoteContext.java:87)
at org.jboss.naming.remote.client.RemoteContext.lookup(RemoteContext.java:129)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.init(WildFlyJmsQueueSender.java:49)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.main(WildFlyJmsQueueSender.java:43)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.io.IOException: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:159)
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:149)
at org.jboss.naming.remote.protocol.v1.BaseProtocolCommand.readResult(BaseProtocolCommand.java:59)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleClientMessage(Protocol.java:149)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1$MessageReceiver$1.run(RemoteNamingStoreV1.java:232)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at org.jboss.marshalling.AbstractClassResolver.loadClass(AbstractClassResolver.java:131)
at org.jboss.marshalling.AbstractClassResolver.resolveClass(AbstractClassResolver.java:112)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:1002)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1256)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:276)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:209)
at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:156)
… 7 more
Process finished with exit code 1
And I changed code like this and add activemq lib in my project:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.put(Context.PROVIDER_URL, WILDFLY_REMOTING_URL); // NOTICE: "http-remoting" and port "8080"
props.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
props.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
and i got this error :
Got initial Context: javax.naming.InitialContext#6842775d
Exception in thread "main" javax.naming.NameNotFoundException: jms/RemoteConnectionFactory
at org.apache.activemq.jndi.ReadOnlyContext.lookup(ReadOnlyContext.java:225)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.init(WildFlyJmsQueueSender.java:49)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.main(WildFlyJmsQueueSender.java:43)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
and standalone-full.xml config file like this :
<subsystem xmlns="urn:jboss:domain:messaging-activemq:1.0">
<server name="default">
<security-setting name="#">
<role name="guest" send="true" consume="true" create-non-durable-queue="true" delete-non-durable-queue="true"/>
</security-setting>
<address-setting name="#" dead-letter-address="jms.queue.DLQ" expiry-address="jms.queue.ExpiryQueue" max-size-bytes="10485760" page-size-bytes="2097152" message-counter-history-day-limit="10"/>
<http-connector name="http-connector" socket-binding="http" endpoint="http-acceptor"/>
<http-connector name="http-connector-throughput" socket-binding="http" endpoint="http-acceptor-throughput">
<param name="batch-delay" value="50"/>
</http-connector>
<in-vm-connector name="in-vm" server-id="0"/>
<http-acceptor name="http-acceptor" http-listener="default"/>
<http-acceptor name="http-acceptor-throughput" http-listener="default">
<param name="batch-delay" value="50"/>
<param name="direct-deliver" value="false"/>
</http-acceptor>
<in-vm-acceptor name="in-vm" server-id="0"/>
<jms-queue name="ExpiryQueue" entries="java:/jms/queue/ExpiryQueue"/>
<jms-queue name="DLQ" entries="java:/jms/queue/DLQ"/>
<jms-queue name="clickQueue" entries="java:/jms/queue/clickQueue java:/jboss/exported/jms/queue/clickQueue"/>
<jms-queue name="emailQueue" entries="java:/jms/queue/EmailQueue java:/jboss/exported/jms/queue/EmailQueue"/>
<jms-queue name="emailSendQueue" entries="java:/jboss/exported/jms/queue/EmailSendQueue"/>
<connection-factory name="InVmConnectionFactory" entries="java:/ConnectionFactory" connectors="in-vm"/>
<connection-factory name="RemoteConnectionFactory" entries="java:jboss/exported/jms/RemoteConnectionFactory" connectors="http-connector"/>
<pooled-connection-factory name="activemq-ra" entries="java:/JmsXA java:jboss/DefaultJMSConnectionFactory" connectors="in-vm" transaction="xa"/>
</server>
</subsystem>
can you help me about error???
thanks.
Working example:
public class JMSClient {
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "http-remoting://127.0.0.1:8080";
private static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
private static final String DESTINATION = "topic/irisWebBroadcaster";
private static final String USERNAME = "jmsuser";
private static final String PASSWORD = "qqq";
public static void main(String[] args) {
Context namingContext = null;
JMSContext context = null;
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
env.put(Context.SECURITY_PRINCIPAL, USERNAME);
env.put(Context.SECURITY_CREDENTIALS, PASSWORD);
namingContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(CONNECTION_FACTORY);
Destination destination = (Destination) namingContext.lookup(DESTINATION);
context = connectionFactory.createContext(USERNAME, PASSWORD);
JMSProducer producer = context.createProducer();
producer.send(destination, "TEST");
} catch (Exception e) {
// print error messge
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
// print error messge
}
}
if (context != null) {
context.close();
}
}
}
}
Corresponding classpath (maybe excessive):
[WILDFLY10_DIR]/modules/system/layers/base/javax/annotation/api/main/jboss-annotations-api_1.2_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/servlet/api/main/jboss-servlet-api_3.1_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/ejb/api/main/jboss-ejb-api_3.2_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/enterprise/api/main/cdi-api-1.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/log4j/logmanager/main/log4j-jboss-logmanager-1.1.2.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/inject/api/main/javax.inject-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/ws/rs/api/main/jboss-jaxrs-api_2.0_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/jms/api/main/jboss-jms-api_2.0_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/codehaus/jackson/jackson-core-asl/main/jackson-core-asl-1.9.13.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/codehaus/jackson/jackson-mapper-asl/main/jackson-mapper-asl-1.9.13.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/logging/main/jboss-logging-3.3.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.3.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/remote-naming/main/jboss-remote-naming-2.0.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/xnio/main/xnio-api-3.3.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/xnio/nio/main/xnio-nio-3.3.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/remoting/main/jboss-remoting-4.0.18.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/marshalling/main/jboss-marshalling-1.4.10.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/marshalling/river/main/jboss-marshalling-river-1.4.10.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-jms-client-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-core-client-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-commons-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-selector-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/commons/beanutils/main/commons-beanutils-1.9.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/commons/collections/main/commons-collections-3.2.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/jcl-over-slf4j/main/jcl-over-slf4j-1.7.7.jbossorg-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/main/slf4j-api-1.7.7.jbossorg-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/impl/main/slf4j-jboss-logmanager-1.0.3.GA.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/ejb-client/main/jboss-ejb-client-2.1.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/io/netty/main/netty-all-4.0.32.Final.jar
You can add something like this if you have problems with logging:
InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());
PropertyConfigurator.configure("conf/log4j.properties");
I see that Answer given by Rudik is not yet accepted , hence posting my take on this problem.
Test case
#Test
public void sendMessagesToWildfly10() throws IOException, NamingException {
String Message = "Hello, World!";
String connectionFactoryJNDIName = "jms/RemoteConnectionFactory";
String queueName = "jms/queue/TestQueue";
Context namingContext = null;
JMSContext context = null;
try {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "http-remoting://localhost:8470");
// Below May Not be needed if you have turned off the security for Messaging
env.put(Context.SECURITY_PRINCIPAL, "guest");
env.put(Context.SECURITY_CREDENTIALS, "guest");
namingContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(connectionFactoryJNDIName);
Destination destination = (Destination) namingContext.lookup(queueName);
context = connectionFactory.createContext("userName", "password");
JMSProducer producer = context.createProducer();
for (int i = 0; i < 10; i++) {
producer.send(destination, Message+" - "+i);
}
JMSConsumer consumer = context.createConsumer(destination);
for (int i = 0; i < 10; i++) {
String text = consumer.receiveBody(String.class, 5000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (namingContext != null) {
namingContext.close();
}
if (context != null) {
context.close();
}
}
}
You will require below mentioned Jars/dependencies added to your classpath. Most of them you can find in Wildfly/modules
If a JMS client is running within a WildFly application then the org.apache.activemq.artemis module must be added as a dependency on your deployment to avoid the java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory, e.g. as answered here.
Otherwise ( standalone java application) - the jboss-client.jar needs to be included into class-path.
Note: take the jboss-client.jar based on your target WildFly version because it differs between WildFLy 8 and 10.

Closing Connection from WildFly Datasource cause java.net.SocketException

I'm using WildFly 10.0.0 and MySQL 5.5.17 and JDBC Driver 5.1.39
I first set a DataSouce in WildFly as a module
in the folder WILDFLY_HOME\modules\system\layers\base\com\mysql\main there is the driver and the file module.xml :
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mysql">
<resources>
<resource-root path="mysql-connector-java-5.1.39-bin.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
And the config file standalone-full.xml :
<subsystem xmlns="urn:jboss:domain:datasources:4.0">
<datasources>
<datasource jta="false" jndi-name="java:/jdbc/MyDS" pool-name="MyDS" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://www.my-url.com:3306/my_db</connection-url>
<driver>mysql</driver>
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prefill>true</prefill>
</pool>
<security>
<user-name>login</user-name>
<password>password</password>
</security>
</datasource>
<drivers>
<driver name="mysql" module="com.mysql">
<driver-class>com.mysql.jdbc.Driver</driver-class>
<xa-datasource-class>com.mysql.jdbc.Driver</xa-datasource-class>
</driver>
</drivers>
</datasources>
</subsystem>
When I test the connection within the wildfly console I have the message : "Successfully created JDBC connection.
Successfully connected to database MyDS"
When I try to use this DataSource doing :
#Resource(mappedName = "java:/jdbc/MyDS")
private DataSource dataSource;
private Integer selectId(String mail) {
try (Connection connection = dataSource.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(getQuery())) {
statement.setString(1, mail);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
Integer id = resultSet.getInt(1);
return id;
} else {
return null;
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I have this Exception :
The last packet successfully received from the server was 2 621 144 milliseconds ago. The last packet sent successfully to the server was 2 621 171 milliseconds ago.
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:988)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3739)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2508)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:504)
at my.app.mail.service.MailService.selectId(LoginService.java:46)
... 129 more
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3721)
... 136 more
When I do :
#Resource(mappedName = "java:/jdbc/MyDS")
private DataSource dataSource;
private Integer selectId(String mail) {
try {
Connection connection = dataSource.getConnection();
try (PreparedStatement statement = connection.prepareStatement(getQuery())) {
statement.setString(1, mail);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
Integer id = resultSet.getInt(1);
return id;
} else {
return null;
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
It works...
How I have to handle DataSource? Do problems will occurs if I don't close Connection? Maybe it's a problem of DataSource config...

Cassandra CQL JDBC Exception : java.lang.ClassNotFoundException: org.apache.thrift.TEnum

I have tried with the following code to connect CASSANDRA Database on my local system.
package com.prm.cassandra;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class CassandraUserManager {
public static void connectToCassandra(){
DataBaseConnection dbCon = new DataBaseConnection();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
con = dbCon.getConnection();
String query = "SELECT * from users";
pstmt = con.prepareStatement(query);
rs = pstmt.executeQuery();
System.out.println("The Details are printed below.");
ResultSetMetaData rmd = rs.getMetaData();
while(rs.next()){
for(int i=0; i<rmd.getColumnCount(); i++)
System.out.print(" "+rs.getString(i));
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
dbCon.closeResources(con, pstmt, rs);
}
}
}
And used the following lines to get the database connection
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://127.0.0.1:9160/demo");
But got the below runtime exception.
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.
Jul 16, 2013 1:08:39 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet connectCassandra threw exception
java.lang.ClassNotFoundException: org.apache.thrift.TEnum
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1819)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:872)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1327)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
at org.apache.cassandra.cql.jdbc.Utils.<clinit>(Utils.java:62)
at org.apache.cassandra.cql.jdbc.CassandraDriver.connect(CassandraDriver.java:85)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at com.prm.cassandra.DataBaseConnection.getConnection(DataBaseConnection.java:14)
at com.prm.cassandra.CassandraUserManager.connectToCassandra(CassandraUserManager.java:15)
at com.prm.cassandra.CassandraServlet.doGet(CassandraServlet.java:28)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:680)
I have used the below mentioned jars as suggested by CASSANDRA-JDBC Example
apache-cassandra-clientutil-1.2.6.jar
apache-cassandra-thrift-1.2.6.jar
cassandra-jdbc-1.2.5.jar
and the below one for logging
slf4j-api-1.6.1.jar
Please help me out in resolving this. Waiting for an useful answer. Thanks in advance.
Please try using the following code below.... and the procedure given in the site... you will be able to solve the same.
http://www.bigdataplanet.info/2013/08/How-to-use-Cassandra-CQL-in-your-Java-Application.html
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CqlConnection {
public static void main(String[] args) throws Exception{
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con =
DriverManager.getConnection("jdbc:cassandra://localhost:9160/Keyspace");
String query = "SELECT * FROM column_family where gender=f ";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("user_name"));
System.out.println(result.getString("gender"));
System.out.println(result.getString("password"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
}
}
Please add the dependency below in pom.xml......
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>

Not able to load OracleDriver class in simple java class

// DbConnector.java
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DbConnector {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#172.17.119.108:1526:GESSDEV", "username",
"password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I have a jdbc jar with name odbc14.jar
javac -classpath odbc14.jar; DbConnector.java
compilation successfull
java -classpath odbc14.jar; DbConnector
OUTPUT ::
-------- Oracle JDBC Connection Testing ------
Where is your Oracle JDBC Driver?
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at DbConnector.main(DbConnector.java:13)
Please help me out to resolve this
I have sorted out the above problem. Now I'm gettin new exception
-------- Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Connection Failed! Check output console
java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:420)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
The JDBC driver for use with ojdbc14.jar is oracle.jdbc.OracleDriver.
See: Loading JDBC Driver Class - ojdbc14.jar
Put your ojdbc14.jar in <jdk_home>\jre\lib\ext and ADD in CLASSPATH variable then you do not have to specify the classpath while compiling or running
If you are using java6 then oracle.jdbc.driver.OracleDriver is okay but it is deprecated. So it's better to use oracle.jdbc.OracleDriver
Just put the odbc14.jar this JAR in required JRE path like "C:\Program Files\Java\jdk1.7.0_65\jre\lib\ext".
This should solve your issue.
you should
try {
Class.forName("oracle.jdbc.OracleDriver");
}
and place the odbc14.jar in class path (if already not done)
Only you need to put into appsclassloader that is your classpath. I am not sure, why we need to put into jre/lib/ext

Resources