Using H2 server mode for Grails integration tests - grails

I want to try user H2 db in server mode for my grails integration tests, but there is a problem: H2GrailsPlugin: Started TCP Server - args: -tcp,-tcpPort,8043
ERROR pool.ConnectionPool - Unable to create initial connections of pool.
Message: Connection is broken: "java.net.ConnectException: Connection refused: localhost:8043"
Now I use grails h2 plugin, for running H2 server with next configuration in my Config.groovy:
plugins {
h2 {
tcpserver {tcpPort = 8043;}
}
}
This is my DataSourse:
test {
dataSource_one {
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
dbCreate = "update"
//url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
url = "jdbc:h2:tcp://localhost:8043/testDb"
}
Also I tried direct run of the Server in my Bootstrap.groovy:
import grails.util.Environment
import org.h2.tools.Server
class BootStrap {
Server server
def init = { servletContext ->
println "INIT"
if(Environment.current == Environment.TEST){
server = Server.createTcpServer('-tcpPort', '8043').start()
}
}
def destroy = {
server.stop()
}
}
but this code wasn't executed cause of exception was thrown before . It would be great, if someone help me with this issue.

Related

No suitable driver found for jdbc:jtds:sqlserver in grails 2.4.3 + groovy 2.3 project

I am facing weird issue in my grail project and after trying a lot i am posting this question here.I have tried all the URL related combination form http://jtds.sourceforge.net/faq.html#noSuitableDriver and other stack over flow answers like Help me create a jTDS connection string.
I am working on grails 2.4.3 project with groovy 2.3 and trying to connect with SQL Server database using jtds 1.3.1 but always getting "No suitable driver found for jdbc:jtds:sqlserver:" But to test this scenario i have written stand alone program as given below for same data base using same jar jtds 1.3.1 and its working fine.
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = "jdbc:jtds:sqlserver://<hostname>:<port>/<database>";
Connection con = DriverManager.getConnection(url,"user","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);}
Below I have provided the grails project code snippet for connection class
class SQLServerConnection implements DBConnection {
#Override
public Connection getConnection(String serverName, String databaseName) {
// TODO Auto-generated method stub
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = "jdbc:jtds:sqlserver://<host>:<port>/<database>";
Connection con = DriverManager.getConnection(url,"user","password");
return con
}
Action form where i am calling this method
def dataFaucetColumn (){
def currentApp = RawDataApp.get(params.int('id'))
String query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='"+currentApp?.tableName +"'"
Connection con = new SQLServerConnection().getConnection(currentApp?.servers,currentApp?.databaseName)
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query); }
waiting for your answers.
Here's how you can use SQL Server with Grails, while taking advantage of Hibernate:
Open grails-app/conf/BuildConfig.groovy
In the dependencies section add the JTDS dependency. Then save the file.
Example:
dependencies {
runtime 'net.sourceforge.jtds:jtds:1.3.1'
}
Open grails-app/conf/DataSource.groovy
In the environments section, set up the data source and save the file. In the following example I'll set up SQL Server for the production environment
Example:
environments {
production {
dataSource {
dbCreate = "update"
url = "jdbc:jtds:sqlserver://<hostname>:<port>/<database>"
username = "X"
password = "X"
driverClassName = "net.sourceforge.jtds.jdbc.Driver"
dialect = org.hibernate.dialect.SQLServerDialect
properties {
maxActive = 8
minEvictableIdleTimeMillis = 1800000
timeBetweenEvictionRunsMillis = 1800000
numTestsPerEvictionRun = 3
testOnBorrow = true
testWhileIdle = true
testOnReturn = true
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}
}
}
That's it. Now you can use GORM to query the database. Plus, Hibernate will manage the database connection(s) :)

Render from controller is working fine in development but not in test

I have the following code in my grails app:
def list () {
def roles = principal.authorities*.authority
def page = roles.contains("ROLE_ADMIN")? "allcolors": "usercolors"
if (params.sort == "latest" || params.sort == null) {
logger.debug("came in if");
render view: page, model: [colorlist: colorService.colorList()]
}
else
render view: page, model: [colorlist: colorService.colorListForUser()]
}
When I run my application with grails run-app the above code works fine. However, when I deploy the war file created by grails test war target/myapp.war the above code does not work and errors with "Page not found" even though the debug statement came in if still gets printed.
I've tried to run this app in development with grails test run-app as well but even then the above does not work. Interestingly, when I run the app in prod mode (grails prod run-app) everything works fine as well. So it is certainly something to do with the test environment
Also, to ensure there aren't any data discrepancies I've changed dev test and prod to point at the same development database.
Could it be that my app has some special setting for test environment that I'm failing to see ...which would cause "render" to not work?
My environment looks like this:
environments {
development {
grails.logging.jul.usebridge = true
}
test {
grails.logging.jul.usebridge = true
}
production {
grails.logging.jul.usebridge = false
}
}
And DB config looks like this:
environments {
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:mysql://localhost/myapp?useUnicode=yes&zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8"
username = "root"
password = ""
}
hibernate {
}
}
test {
dataSource {
dbCreate =
url = "jdbc:mysql://localhost/myapp?useUnicode=yes&zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8"
username = "root"
password = ""
properties {
}
hibernate {
}
}
}
production {
dataSource {
dbCreate = "create-drop"
url = "jdbc:mysql://localhost/myapp?useUnicode=yes&zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8"
username = "root"
password = ""
}
}
}
How can I resolve this or troubleshoot it further??
run-app runs with the default "development" data source, which is not to be confused with the "test" environment. Check your Config.groovy (edit: and DataSource.groovy) and make sure you have test { } configured within your environments.
More info can be found in the grails documentation here:
http://www.grails.org/Environments

Grails mysql connection time out in production mode

I have deployed a grails application in tomcat 7. Database connection works fine during normal time, but in the night the connection is getting closed. Next day I have to restart the tomcat to make it work.
Here is my connection string in the config file.
production {
dataSource {
dbCreate = "update"
pooled = true
logSql = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
url =
properties {
maxActive = -1
minEvictableIdleTimeMillis=1800000
timeBetweenEvictionRunsMillis=1800000
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=true
validationQuery="SELECT 1"
}
}
error log:
Broken pipe. Stacktrace follows:
java.net.SocketException: Broken pipe
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:3832)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2471)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2728)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2678)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1612)
also I see this message in the log file.
appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
How can I fix the connection time out issue.
You have to add autoReconnect=true to the connection url, it will help with such conection issues.
Like:
production {
dataSource {
...
url = 'jdbc:mysql://localhost/dbname?autoReconnect=true'
...
}
}

Grails JMS Plugin - Not receiving messages

I installed the Grails JMS pluign into my application, but am not receiving any messages. My config is as follows:
In resources.groovy
jmsConnectionFactory(package.OracleAqFactoryBean) {
dataSource = ref("dataSource")
}
In config.groovy
jms {
containers {
standard {
autoStartup = true
connectionFactoryBean = "jmsConnectionFactory"
}
}
}
In my Grails Service:
class MyService {
static exposes = ["jms"]
static destination = "queuename"
static listenerCount = 5
void onMessage(msg) {
// handle message
println "WE GOT A MESSAGE...."
}
}
In Datasource.groovy
dataSource {
driverClassName = "oracle.jdbc.pool.OracleDataSource"
url = "jdbc:oracle:thin:#restofurl"
username = "xxx"
password = "xxxx"
}
We have a connection to the queue working using standard Spring config in a standard Java app, but that spring config does not work if imported in the Grails app, which is why we are trying to use the jms plugin.

how can i dynamic update Datasource.groovy file

in a grails project, there will a file named DataSource.groovy. Such as follows:
dataSource {
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
mongodb {
host = 127.0.0.1// adjust this according to your settings
port = 27017
databaseName = 'test'
username = 'user' // database user and password, if server requires authentication
password = 's3cret'
}
My question is that how can I set for example mongodb.host dynamically at run time.
If you have different MongoDB Hosts, you can set up different environments for development, test, and production using the environments closure in your DataSource.groovy.
In your example above, let's say that you are using localhost 127.0.0.1 for development and mongo-prodserver for production
environments {
development {
grails {
mongo {
host = "127.0.0.1"
port = 27017
username = "user"
password= "s3cret"
databaseName = "test"
}
}
}
production {
grails {
mongo {
host = "mongo-prodserver"
port = 27017
username = "user"
password= "s3cret"
databaseName = "prod"
}
}
}
...
}
Here is the link to Grails Doc on DataSources and Environments.

Resources