Installing a JNDI datasource for Oracle 11g in Tomcat - database

I'm on Windows XP, using Tomcat 6 ( I can't upgrade to 7 until the end of the month ).
I've been trying to implement a JNDI database resource to Oracle 11g without success.
A number of other applications on my computer connect just fine with the same database credentials. I made a test JSP using straight up JDBC and put it into Tomcat. It connects just fine too.
I modified a section of my conf/server.xml like this:
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
factory="oracle.jdbc.pool.OracleDataSourceFactory"
url="jdbc:oracle:thin:#apollo.abc.acme.com:2222:mydatabase"
user="joe"
password="blow"
maxActive="20"
maxIdle="30"
maxWait="-1"/>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml"/>
</GlobalNamingResources>
My conf/context.xml:
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<ResourceLink global="jdbc/mydb" name="jdbc/mydb" type="javax.sql.DataSource"/>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
My conf/web.xml:
<resource-ref>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
This is an excerpt from test JSP, it is crapping out with a nullpointer exception right where it goes to get the JNDI resource:
Connection conn = null;
ResultSet result = null;
Statement stmt = null;
String nsdtestcount = null;
InitialContext ctx = null;
Context envContext = null;
javax.sql.DataSource ds = null;
try
{
ctx = new InitialContext();
envContext = (Context)ctx.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/mydb");
conn = ds.getConnection();
}
catch (Exception e)
{
System.out.println(nameJSP + "Failed to connect to the database: " +
"\n ctx = " + ctx +
"\n envContext = " + envContext +
"\n ds = " + ds +
"\n conn = " + conn );
e.printStackTrace();
}
An excerpt from my log::
INFO: Server startup in 675 ms
testJNDI2.jsp: Failed to connect to the database:
ctx = javax.naming.InitialContext#15356d5
envContext = org.apache.naming.NamingContext#69d02b
ds = null
conn = null
java.lang.NullPointerException
at org.apache.jsp.testJNDI_jsp._jspService(testJNDI_jsp.java:114)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
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:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
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:291)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:877)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675)
at java.lang.Thread.run(Thread.java:595)
The code at the line in the stack trace:
at org.apache.jsp.testJNDI_jsp._jspService(testJNDI_jsp.java:114)
ctx = new InitialContext();
envContext = (Context)ctx.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/mydb");
conn = ds.getConnection();
conn = ds.getConnection(); is line 114
From my catalina log:
May 1, 2012 4:17:48 PM org.apache.tomcat.util.modeler.Registry registerComponent
SEVERE: Null component Catalina:type=DataSource,class=javax.sql.DataSource,name="jdbc/mydb"
The contents of my CATALINA_HOME/lib:
C:\tomcat\lib>ls -l
annotations-api.jar
catalina-ant.jar
catalina-ha.jar
catalina-tribes.jar
catalina.jar
ecj-3.3.1.jar
el-api.jar
jasper-el.jar
jasper.jar
jsp-api.jar
log4j-1.2.16.jar
ojdbc14.jar
servlet-api.jar
tomcat-coyote.jar
tomcat-dbcp.jar
tomcat-i18n-es.jar
tomcat-i18n-fr.jar
tomcat-i18n-ja.jar
tomcat-juli-adapters.jar
tomcat-juli.jar
C:\tomcat\lib>
The contents of my JAVA/JDK jre/lib/ext:
C:\Program Files\Java\jdk1.5.0_22\jre\lib\ext>ls -l
activation.jar
dnsns.jar
localedata.jar
log4j-1.2.16.jar
mail.jar
nls_charset12.jar
sunjce_provider.jar
sunmscapi.jar
sunpkcs11.jar
C:\Program Files\Java\jdk1.5.0_22\jre\lib\ext>
Any ideas of what I can try? I would like to make the database resource available to everything running in Tomcat ( it is my dev environment )
Thanks in advance.

There may well be multiple issues but the first is that you have multiple copies of multiple versions of the Oracle JDBC driver in $CATALINA_HOME/lib and $JAVA_HOME/jre/lib/ext.
Step 1 is to remove all instance of the following JARs apart from $CATALINA_HOME/lib/ojdbc14.jar
ojdbc14.jar
ojdbc14_g.jar
ojdbc14dms.jar
ojdbc14dms_g.jar
classes12.jar
classes12.zip
classes12dms.jar
While you are at it, remove $JAVA_HOME/jre/lib/ext/servlet-api.jar as well.
Step 2 is that maxIdle > maxActive does not make any sense. You want maxActive >= maxIdle.

As shown in this example on the tomcat site, I believe "user" should be "username" in your Resource definition.

Related

How to perform EJB DB RBAC with WildFly?

I'm trying to create a rich client that performs EJB RMI to interact with a server/DB. Previously, I had communications working with the remoting system to authenticate a user. Then I tacked on HTTPS communications using a keystore and clustering to the environment. Everything worked at that point.
The file-based authentication was an interim step in moving towards database authentication & authorization. I may still have configurations from that lingering and effecting this new step, I'm not certain.
Below is the failure message when trying to authenticate via the client:
Jan 19, 2017 12:51:52 PM org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 2.1.4.Final
Jan 19, 2017 12:51:52 PM org.xnio.Xnio <clinit>
INFO: XNIO version 3.4.0.Final
Jan 19, 2017 12:51:52 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.4.0.Final
Jan 19, 2017 12:51:52 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 4.0.21.Final
Jan 19, 2017 12:51:53 PM org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector setupEJBReceivers
WARN: Could not register a EJB receiver for connection to 10.0.0.1:8443
javax.security.sasl.SaslException: Authentication failed: all available authentication mechanisms failed:
JBOSS-LOCAL-USER: javax.security.sasl.SaslException: Failed to read server challenge [Caused by java.io.FileNotFoundException: /home/appsrv/wildfly-10.1.0.Final/domain/tmp/auth/local4807198060994958453.challenge (No such file or directory)]
DIGEST-MD5: Server rejected authentication
at org.jboss.remoting3.remote.ClientConnectionOpenListener.allMechanismsFailed(ClientConnectionOpenListener.java:114)
at org.jboss.remoting3.remote.ClientConnectionOpenListener$Capabilities.handleEvent(ClientConnectionOpenListener.java:389)
at org.jboss.remoting3.remote.ClientConnectionOpenListener$Capabilities.handleEvent(ClientConnectionOpenListener.java:241)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.channels.TranslatingSuspendableChannel.handleReadable(TranslatingSuspendableChannel.java:198)
at org.xnio.channels.TranslatingSuspendableChannel$1.handleEvent(TranslatingSuspendableChannel.java:112)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.ChannelListeners$DelegatingChannelListener.handleEvent(ChannelListeners.java:1092)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
at org.xnio.ssl.JsseStreamConduit.run(JsseStreamConduit.java:446)
at org.xnio.ssl.JsseStreamConduit.readReady(JsseStreamConduit.java:547)
at org.xnio.ssl.JsseStreamConduit$2.readReady(JsseStreamConduit.java:319)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:89)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:567)
at ...asynchronous invocation...(Unknown Source)
at org.jboss.remoting3.EndpointImpl.doConnect(EndpointImpl.java:294)
at org.jboss.remoting3.EndpointImpl.connect(EndpointImpl.java:430)
at org.jboss.ejb.client.remoting.EndpointPool$PooledEndpoint.connect(EndpointPool.java:192)
at org.jboss.ejb.client.remoting.NetworkUtil.connect(NetworkUtil.java:153)
at org.jboss.ejb.client.remoting.NetworkUtil.connect(NetworkUtil.java:133)
at org.jboss.ejb.client.remoting.ConnectionPool.getConnection(ConnectionPool.java:78)
at org.jboss.ejb.client.remoting.RemotingConnectionManager.getConnection(RemotingConnectionManager.java:51)
at org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector.setupEJBReceivers(ConfigBasedEJBClientContextSelector.java:161)
at org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector.getCurrent(ConfigBasedEJBClientContextSelector.java:118)
at org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector.getCurrent(ConfigBasedEJBClientContextSelector.java:47)
at org.jboss.ejb.client.EJBClientContext.getCurrent(EJBClientContext.java:281)
at org.jboss.ejb.client.EJBClientContext.requireCurrent(EJBClientContext.java:291)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:178)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:146)
at com.sun.proxy.$Proxy6.getVer(Unknown Source)
at com.test.clientapp.TestClient.authenticate(TestClient.java:208)
at com.test.clientapp.BackgroundServiceEngine.run(BackgroundServiceEngine.java:136)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
In my WildFly domain configuration, I added the following authentication module to the "ha" profile (the one assigned to my host controllers) in -> Security -> MySecurityDomain via the GUI:
name: testds01
code: Database
flag: required
module options:
dsJndiName = java:/TestDS01
principalsQuery = SELECT password FROM users WHERE username=?
password-stacking = useFirstPass
hashAlgorithm = MD5
hashEncoding = BASE64
hashCharset = utf-8
I also added the following authorization module to the same area:
name: testds01
code: Delegating
flag: required
module options:
dsJndiName = java:/TestDS01
rolesQuery = SELECT role, 'Roles' FROM roles INNER JOIN users ON users.role_id = roles.role_id WHERE users.username =?
Honestly, I don't know what the flag "required" means. Nor the code "Delegating". I just found these in a book I read.
My WildFly setup includes: 1x Domain Controller, 2x Host Controllers w/1 server each, 2x SQL databases. All 5 of these are separate VMs. So, In addition to the testds01 modules added above, I have testds02 modules added pointing to "java:/TestDS02".
Let me know if additional information is needed. I'm not sure I covered everything.
Update: It's probably useful to have the client properties I'm using to setup & perform RMI:
// Set TLS Properties
System.setProperty("javax.net.ssl.keyStore", "test.keystore");
System.setProperty("javax.net.ssl.trustStore", "test.truststore");
System.setProperty("javax.net.ssl.keyStorePassword", "testpass1");
System.setProperty("javax.net.ssl.trustStorePassword", "testpass2");
// Set Application Server Properties
properties = new Properties();
properties.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "true");
properties.put("remote.connections", "hcl01,hcl02");
// Host Controller
properties.put("remote.connection.hcl01.port", "8443");
properties.put("remote.connection.hcl01.host", "10.0.0.1");
properties.put("remote.connection.hcl01.protocol", "https-remoting");
properties.put("remote.connection.hcl01.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
properties.put("remote.connection.hrl01.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
properties.put("remote.connection.hcl01.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS", "true");
properties.put("remote.connection.hrl01.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS", "JBOSS-LOCAL-USER");
properties.put("remote.connection.hcl02.port", "8443");
properties.put("remote.connection.hcl02.host", "10.0.0.2");
properties.put("remote.connection.hcl02.protocol", "https-remoting");
properties.put("remote.connection.hcl02.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
properties.put("remote.connection.hrl02.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
properties.put("remote.connection.hcl02.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS", "true");
properties.put("remote.connection.hrl02.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS", "JBOSS-LOCAL-USER");
// Build SLSB Lookup String
String appName = "/"; //name of ear containg ejb
String moduleName = "testapp/"; //name of ejb jar w/o extension
String distinctName = "/"; //any distinct name set within jboss for this deployment
String beanName = Login.class.getSimpleName(); //name of the bean we're looking up
String viewClassName = LoginRemote.class.getName(); //name of the bean interface
System.out.println("beanName=" + beanName + " viewClassName=" + viewClassName);
lookupSLSB = "ejb:" + appName + moduleName + distinctName + beanName + "!" + viewClassName;
// Configure EJB Lookup
Properties props = new Properties();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
context = new InitialContext(props);
properties.put("remote.connection.hcl01.username", au.getUsername());
properties.put("remote.connection.hcl01.password", au.getPassword());
properties.put("remote.connection.hcl02.username", au.getUsername());
properties.put("remote.connection.hcl02.password", au.getPassword());
// JBoss Cluster Setup (using properties above)
EJBClientConfiguration cc = new PropertiesBasedEJBClientConfiguration(properties);
ContextSelector<EJBClientContext> selector = new ConfigBasedEJBClientContextSelector(cc);
EJBClientContext.setSelector(selector);
LoginRemote bean = (LoginRemote)context.lookup(lookupSLSB);
System.out.println("NIC [From bean]: Class=\"" + bean.getStr() + "\"");
I resolved this issue. After dumping traffic it appeared that the queries were being sent to the database. I enabled query logging on the database and found that they were being received, but there was a permission issue with the database user. After granting privileges to the tables being queried, the communication was successful.

javax.naming.NameNotFoundException: env/jdbc/DataSource on JBOSS with SQL Server

The JNDI name in my domain.xml is
The Context.lookup has been defined as follows:
dsName = "java:comp/env";
Context ctx = (Context) new javax.naming.InitialContext();
Context envCtx = (Context)ctx.lookup(dsName);
DataSource ds = (DataSource)envCtx.lookup("jdbc/DataSource");
conn = ds.getConnection();
I'm getting the following exception when connected to SQLserver with the following configuration where as it is working fine with Oracle.The lookup name somehow is not validated properly and connection object is getting null.
javax.naming.NameNotFoundException: env/jdbc/DataSource
ERROR [stderr] (ServerService Thread Pool -- 78) at
org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:104)
ERROR [stderr] (ServerService Thread Pool -- 78) at
org.jboss.as.naming.NamingContext.lookup(NamingContext.java:197)
java.lang.NullPointerException
Even Tried with something like
DataSource ds = (DataSource)envCtx.lookup("java:comp/env/jdbc/DataSource");
Could anyone suggest on this.
Thanks
Check the logs and/or the JNDI tree in the administration console.
Try these:
"java:DataSource"
"java:jboss/datasources/DataSource"
If not, please paste here the data source config section in the config file (e.g. standalone.xml)

No suitable driver found for jdbc:sqlserver

I realize this is what would be considered a duplicate topic, but I have followed the recommended steps in the other topics of this same nature with no success.
I am using GGTS 3.6.4 with
Grails 2.3.0
jdk1.7.0_80
Groovy compiler level 2.3
Microsoft SQL Server 2012
I have a grails-app which authenticates users logging in against an LDAP server with Apache Shiro and I have the following code (in the Shiro generated AuthController.groovy) to try and store some information from an external database in the session. (Note: With regards to usernames, passwords, and database names, I've changed all of them here for privacy reasons)
def signIn = {
Subject subject = SecurityUtils.getSubject();
String lowerCaseUserName=params.username.toLowerCase();
def authToken = new UsernamePasswordToken(lowerCaseUserName, params.password)
// Support for "remember me"
if (params.rememberMe) {
authToken.rememberMe = true
}
try{
subject.login(authToken)
if (subject.isAuthenticated())
{
session.username = lowerCaseUserName
// Attempting to get employee id from MS SQL
Sql Database = Sql.newInstance(
'jdbc:sqlserver://myserver;DatabaseName=mydatabase',
'user',
'password',
'com.microsoft.sqlserver.jdbc.SQLServerDriver'
);
Database.eachRow('select empid from table_name where username=${session.username}') { row ->
session.empid = row.empid
}
Database.close();
def targetUri = params.targetUri ?: "/home"
log.info "Redirecting to '${targetUri}'."
redirect(uri: targetUri)
}
}
...
}
However, I get the following error
SQLException occurred when processing request: [POST] /app/auth/signIn - parameters:
username: user
_rememberMe:
targetUri:
password: ***
No suitable driver found for jdbc:sqlserver://myserver;DatabaseName=mydatabase. Stacktrace follows:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://myserver;DatabaseName=mydatabase
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at app.AuthController$_closure3.doCall(AuthController.groovy:45)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I have tried the following with no success:
Added sqljdbc4.jar to /app/lib/
Manually added /app/lib/ to classpath (via .classpath)
Added sqljdbc4.jar to the classpath via the Properties > Java Build Path > Add JARs
I've tried these variations with sqljdbc4.jar, sqljdbc.jar, and sqlserverjdbc.jar and every combo thereof.
I'm basically stuck. None of the fixes I've read on here, or elsewhere, solve my error. Any help would be greatly appreciated!
Edit 1: Adding Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") above the newInstance call produces the following errors:
ClassNotFoundException occurred when processing request: [POST] /app/auth/signIn - parameters:
username: user
_rememberMe:
targetUri:
password: ***
com.microsoft.sqlserver.jdbc.SQLServerDriver. Stacktrace follows:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName(Class.java:195)
at isec.AuthController$_closure3.doCall(AuthController.groovy:45)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Is this a step forward, backward, or are we running in place?
Edit 2: What I ended up having to do was change my DataSource.groovy to this
dataSource {
pooled = true
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
//cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "validate"
url = "jdbc:sqlserver://myserver:1433;databaseName=mydatabase;"
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
username = "myusername"
password = "mypassword"
}
}
....
}
and changed my AuthController.groovy data access to
try{
subject.login(authToken)
if (subject.isAuthenticated())
{
ShiroUser currentUser = new ShiroUser()
def targetUri = params.targetUri ?: "/home"
log.info "Redirecting to '${targetUri}'."
redirect(uri: targetUri)
}
}
and I have successfully accessed my DB with a modified ShiroUser.groovy file
class ShiroUser {
static hasMany = [ roles: ShiroRole, permissions: String ]
User_Data userData;
static constraints = {
}
def getUsername() {
return userData.username
}
}
where User_Data.groovy is a new domain class containing
class User_Data {
static mapping = {
table "mytablename"
}
...
}
So now I'm onto messing with methods! Not sure why JDBC stuff didn't work out, but GORM is the path I'm taking now.
you definitely need to add sqljdbc4.jar to /app/lib/ which you have already done.
have you tried adding database connection to the BuildConfig.groovy
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
dialect = "org.hibernate.dialect.SQLServerDialect"
url = "jdbc:sqlserver://localhost:1433;databaseName=dbName"
username = "sa"
password = ""
}
Also make sure the SQL server is configured to accept connection on port 1433. It is disabled by default.

using Hibernate and MS SQL with intelliJ IDEA

I am using Hibernate/JPA 2.0 with SQL Server and IntelliJ IDEA here's a sample code I made to test the connection:
public class App {
public static final String SELECT_QUERY = "select u from UsersEntity as u where u.userId = :userId";
public static void main(String[] args)
{
String userId = "1";
PersistenceProvider persistenceProvider = new HibernatePersistence();
EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("newPersistenceUnit", new HashMap());
EntityManager entityManager = entityManagerFactory.createEntityManager();
List<UsersEntity> users = entityManager.createQuery(SELECT_QUERY, UsersEntity.class).setParameter("userId", userId).getResultList();
System.out.println(users);
entityManager.close();
}
}
And here's what I receive in the console:
"C:\Program Files\Java\jdk1.6.0_29\bin\java" -Didea.launcher.port=7539 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 12.0.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.6.0_29\jre\lib\alt-rt.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\alt-string.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\jce.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\resources.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunpkcs11.jar;D:\mobitrack\out\production\web;D:\mobitrack\lib\javax.persistence.jar;D:\mobitrack\lib\hibernate-entitymanager-4.2.0.Final.jar;D:\mobitrack\lib\jboss-logging-3.1.0.GA.jar;D:\mobitrack\lib\hibernate-core-4.2.0.Final.jar;D:\mobitrack\lib\antlr-2.7.7.jar;D:\mobitrack\lib\jboss-transaction-api_1.1_spec-1.0.0.Final.jar;D:\mobitrack\lib\dom4j-1.6.1.jar;D:\mobitrack\lib\hibernate-jpa-2.0-api-1.0.1.Final.jar;D:\mobitrack\lib\javassist-3.15.0-GA.jar;D:\mobitrack\lib\hibernate-commons-annotations-4.0.1.Final.jar;D:\mobitrack\lib\tools.jar;D:\mobitrack\lib\sqljdbc4-4.0.2206.100.jar;C:\Program Files\JetBrains\IntelliJ IDEA 12.0.4\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.mobitrack.services.App
26 mars 2013 17:44:18 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
26 mars 2013 17:44:18 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
26 mars 2013 17:44:18 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
26 mars 2013 17:44:18 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://localhost:1433;databaseName=MOBITRACKDB]
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=sa, password=****, autocommit=true, release_mode=auto}
When debugging I found that it stops at:
EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("newPersistenceUnit", new HashMap());
Knowing that "newPersistenceUnit" is the name of my persistence unit.
Edit:
Yes it works outside IDEA. And when I use the console in IDEA to query the data it works.
I tried using the next code:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I receive the same as above and the debugging stops at :
sessionFactory = new Configuration().configure().buildSessionFactory();
Edit2:
I used an EntityManager:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("newPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
List<AdminsEntity> result = entityManager.createQuery( "from AdminsEntity", AdminsEntity.class ).getResultList();
for ( AdminsEntity event : result ) {
logged = event;
}
entityManager.getTransaction().commit();
entityManager.close();
return logged;
It stops at:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("newPersistenceUnit");
here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="newPersistenceUnit">
<class>com.mobitrack.entities.GroupsEntity</class>
<class>com.mobitrack.entities.ZonesEntity</class>
<class>com.mobitrack.entities.AdminsEntity</class>
<class>com.mobitrack.entities.AlarmsEntity</class>
<class>com.mobitrack.entities.LocationsEntity</class>
<class>com.mobitrack.entities.UsersEntity</class>
<class>com.mobitrack.entities.UserGroupsEntity</class>
<class>com.mobitrack.entities.UserZonesEntity</class>
<class>com.mobitrack.entities.SettingsEntity</class>
<class>com.mobitrack.entities.MessagesEntity</class>
<class>com.mobitrack.entities.ProfilesEntity</class>
<class>com.mobitrack.entities.ProfileZonesEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:sqlserver://localhost:1433;databaseName=MOBITRACKDB"/>
<property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.connection.username" value="admin"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.query.factory_class"
value="org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory"/>
</properties>
</persistence-unit>
Any ideas?
This problem can be caused by the method breakpoints that slow down debugger.
Please double check that you don't have any method breakpoints set. Disabling toString() evaluation and alternate collections view options in Settings | Debugger may also improve its performance.

How to use MSSQL DSN as URL in DataSource.groovy

I have been trying this code in DataSource.groovy but its showing an error of "No suitable driver"
dataSource
{
pooled = true
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
String url="jdbc:microsoft:sqlserver:DSNname";
}
I have already included two jdbc SQLserver drivers sqljdbc, sqljdbc4 (*.jar files).
I also tried this code but went futile.
DataSource
{
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
//url="jdbc:sqlserver://localhost:1433;database=DBNAME" its working
url="jdbc:odbc:myDSN"
username="sa"
password=""
}
Thanks a ton in advance.

Resources