No suitable driver found for jdbc:sqlserver - sql-server

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.

Related

Spring Boot connection to SQL Server in Windows Authentication mode

I am trying to connect to SQL Server in Windows Authentication mode and here is my database configuration:
database.name= DatabaseName spring.datasource.url=jdbc:sqlserver://1.2.3.4:11111;DatabaseName=${database.name};integratedSecurity = true;
spring.datasource.username=user
spring.datasource.password=passw
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
and I got these errors:
Negative matches:
AVSSimulatorServerApplication:
Did not match:
- #ConditionalOnProperty (spring.application.name=avs-simulator-service) found different value in property 'spring.application.name' (OnPropertyCondition)
ActiveMQAutoConfiguration:
Did not match:
- #ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
AopAutoConfiguration.JdkDynamicAutoProxyConfiguration:
Did not match:
- #ConditionalOnProperty (spring.aop.proxy-target-class=false) found different value in property 'proxy-target-class' (OnPropertyCondition)
ArtemisAutoConfiguration:
Did not match:
- #ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory' (OnClassCondition)
AsyncCustomAutoConfiguration:
Did not match:
- #ConditionalOnBean (types: org.springframework.scheduling.annotation.AsyncConfigurer; SearchStrategy: all) did not find any beans (OnBeanCondition)
Matched:
- #ConditionalOnProperty (spring.sleuth.async.enabled) matched (OnPropertyCondition)
.......
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'user'. ClientConnectionId:ce912574-1f20-4843-9b43-01820e67cf54
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'user'. ClientConnectionId:ce912574-1f20-4843-9b43-01820e67cf54
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.HashMap]:
................
Does anybody know what should I do in this situation?
I found the solution and it was only to use
integratedSecurity = false;
instead of
integratedSecurity = true;
so in this case connection string will be:
database.name= DatabaseName spring.datasource.url=jdbc:sqlserver://1.2.3.4:11111;DatabaseName=${database.name};**integratedSecurity = false**;.
Why to use integratedSecurity = false?
The reason is here:
Integrated Security When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.

Issues with testing Cloud SQL locally using App Engine

I've been trying to connect to a Cloud SQL instance using HikariCP from App Engine locally so I can make queries. Every time I run App Engine using the ./gradlew appengineRun command, I get a java.net.SocketException: already connected error. This works fine when I deploy it to App Engine, but locally it just won't work. I'm stumped.
Here's the configuration for Hikari:
val config = HikariConfig().apply {
jdbcUrl = "jdbc:postgresql://google/[DB-NAME]"
username = "[USERNAME]"
password = "[PASSWORD]"
addDataSourceProperty("cloudSqlInstance", "[INSTANCE-CONNECTION-NAME")
addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory")
}
private val dataSource = HikariDataSource(config)
private val connection = dataSource.connection
And then to execute the query:
connection.use { connection ->
connection.prepareCall("SELECT EXISTS(SELECT 1 FROM profiles WHERE username = '$username')").use { statement ->
statement.executeQuery().use { resultSet ->
try {
val exists = generateSequence {
if (resultSet.next()) resultSet.getBoolean(1) else null
}.toList()
onComplete(exists.any { it }, null)
} catch (e: Exception) {
onComplete(false, e)
}
}
}
}
I was certain this was the correct configuration to connect to SQL, but I keep getting this stacktrace:
Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: The connection attempt failed.
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:597)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:576)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:81)
at appengine.sql.repository.ProfileRepository.<clinit>(ProfileRepository.kt:34)
... 48 more
Caused by: org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:262)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:67)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:216)
at org.postgresql.Driver.makeConnection(Driver.java:406)
at org.postgresql.Driver.connect(Driver.java:274)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:353)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:562)
... 51 more
Caused by: java.net.SocketException: already connected
at java.net.Socket.connect(Socket.java:569)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668)
at org.postgresql.core.PGStream.<init>(PGStream.java:64)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:133)
... 60 more
Are the connection being properly closed after use? Is it possible the application is attempting to reuse connection after they have been closed by the SQL instance? I'd advise implementing a connection pool within the application for efficient use of connections to the db. Some CloudSQL documentation pages that may help cover these topics [1][2].
[1] https://cloud.google.com/sql/docs/mysql/manage-connections#opening_and_closing_connections
[2] https://cloud.google.com/sql/docs/mysql/diagnose-issues

How to configure IdentityServerAuthenticationOptions.Authority to use wildcards

I successfully setup IdentityServer4 with ASP.NET Core.
As a default config I had this:
IdentityServerAuthenticationOptions options = new IdentityServerAuthenticationOptions()
{
Authority = "http://localhost:5000",
ScopeName = "scope",
ScopeSecret = "ScopeSecret",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false,
};
Now, using this guide I configured to be read from configuration files and so they can be any numbers in production.
For example if I setup API to be running at http://*:5000 then the client can connect to it via the service IP address like http://192.168.1.100:5000.
Once the client obtains the Bearer token and tries to use it, an Internal Server Error occures with this exception:
Unable to obtain configuration from:
'http://*:5000/.well-known/openid-configuration'.
---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://*:5000/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
What is the correct way to configure IdS4 to have dynamic authority?
Update
It seems the problem is with Issuer, any idea on this?
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException:
IDX10205: Issuer validation failed. Issuer: 'http://192.168.1.100:5000'. Did not match: validationParameters.ValidIssuer: 'http://localhost:5000' or validationParameters.ValidIssuers: 'null'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateIssuer(String issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
By a big surprise, all I needed, was to set a value (almost any value) for IssuerUri:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
////...
var identiyBuilder = services.AddIdentityServer(options =>
{
options.RequireSsl = false;
options.IssuerUri = "MyCompany";
});
////...
}
Now, by the above config, I can use the service by any IP address.
I didn't find I could just put in MyCompany
But in my log files I had the following:
Bearer was not authenticated. Failure message: IDX10205: Issuer validation failed. Issuer: 'https://crm.example.com'. Did not match: validationParameters.ValidIssuer: 'MyCompany' or validationParameters.ValidIssuers: 'null'.
I don't quite know what 'issuer' means but I was able to just take 'https://crm.example.com' and get things working with this :
options.IssuerUri = "https://crm.example.com";

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.

Problem with grails web app running in production: "No such property: save for class: JsecRole"

I've got a grails 1.1 web app running great in development but when I try and run it in production with
an sqlserver database it crashes in a weird way.
The relevant part of my datasource.groovy is as follows:
environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
url = "jdbc:hsqldb:mem:devDB"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
endUsername = "sa"
password = "pw4db"
url = "jdbc:sqlserver://localhost:1433;databaseName=ReleasePlanner;selectMethod=cursor"
The error message I receive is:
Message: No such property: save for class: JsecRole
Caused by: groovy.lang.MissingPropertyException: No such property: save for class: JsecRole
Class: ProjectController
At Line: [28]
Code Snippet:
27: println "###about to create project roles"
28: userManagerService.createProjectRoles(project)
29: userManagerService.addUserToProject(session.user.id.toString(), project, 'owner')
}
}
}
The stacktrace is as follows:
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingPropertyException: No such property: save for class: JsecRole
at org.jsecurity.web.servlet.JSecurityFilter.doFilterInternal(JSecurityFilter.java:382)
at org.jsecurity.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:180)
Caused by: groovy.lang.MissingPropertyException: No such property: save for class: JsecRole
at UserManagerService.createProjectRoles(UserManagerService.groovy:9)
at UserManagerService$$FastClassByCGLIB$$6fa73713.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
at UserManagerService$$EnhancerByCGLIB$$fcf60984.createProjectRoles(<generated>)
at UserManagerService$createProjectRoles.call(Unknown Source)
at ProjectController$_closure4.doCall(ProjectController.groovy:28)
at ProjectController$_closure4.doCall(ProjectController.groovy)
... 2 more
Any help is appreciated.
Thanks
Sarah
I fixed my problem by deleting my database and creating a new database. I think some of the fields in my database weren't mapping correctly as I changed my domain objects. The error didn't really point me in this direction though!
Sarah
This problem is discussed in this thread on the Grails mailing list. It is supposed to be fixed in Grails 1.2. A workaround for earlier versions of Grails is to add the following to Bootstrap.groovy
JsecRole.get(-1)

Resources