multiple times triggering of Datasource.groovy in grails application ( throwing exception when called second time) - spring

Work Around for creating the application :
creating a Grails Application using Postgres database.
Needs to create Database when the application is executed (i.e database is to be created from the project itself instead of creating the database manually).
For creating the database I am calling a groovy service CreateDatabaseService in datasource.groovy as follows :
import demo.grails.CreateDatabaseService
CreateDatabaseService.serviceMethod()
dataSource {
pooled = true
jmxExport = true
driverClassName = "org.postgresql.Driver"
dialect = "org.hibernate.dialect.PostgreSQLDialect"
username = "postgres"
password = "password"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
singleSession = true // configure OSIV singleSession mode
flush.mode = 'manual'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "create-drop"
url = "jdbc:postgresql://localhost:5432/SampleAppDb"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:postgresql://localhost:5432/SampleAppDb"
}
} .....
Full code for CreateDatabaseService :
package demo.grails
import groovy.sql.Sql
import java.sql.DriverManager
import java.sql.Connection
import java.sql.SQLException
import java.sql.*
class CreateDatabaseService {
public static flag =0
def static serviceMethod() {
Connection conn = null;
Statement stmt = null;
try{
if(flag == 0) {
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432", "postgres", "password");
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String isDatabase = "select datname from pg_catalog.pg_database where lower(datname) = lower('SampleAppDb')"
ResultSet rs = stmt.executeQuery(isDatabase);
String idr
while(rs.next()){
//Retrieve by column name
idr = rs.getString("datname");
}
if(!idr.equals("SampleAppDb")) {
String sql = "create database SampleAppDb";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
flag =1
}
else {
flag =1
}
}
}catch(Exception e){
e.printStackTrace();
}
finally{
stmt.close();
conn.close();
}
}
}
On running the grails app following is the full stack trace that shows datasource.groovy is called multiple times, though the database is created from the application but complains about no suitable driver found when datasource.groovy is called second time.
|Loading Grails 2.4.5
|Configuring classpath
.
|Environment set to development
.................................
|Packaging Grails application
................Connecting to database...
Creating database...
Database created successfully...
....................
|Running Grails application
Connecting to database...
Error |
java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432
Error |
at java.sql.DriverManager.getConnection(DriverManager.java:689)
Error |
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Error |
at java_sql_DriverManager$getConnection.call(Unknown Source)
Error |
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
Error |
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
Error |
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
Error |
at demo.grails.CreateDatabaseService.serviceMethod(CreateDatabaseService.groovy:23)
Error |
at demo.grails.CreateDatabaseService$serviceMethod.call(Unknown Source)
Error |.......
Please suggest how to overcome this error.
BuildConfig.groovy
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
// runtime 'mysql:mysql-connector-java:5.1.29'
// runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
runtime 'postgresql:postgresql:9.0-801.jdbc4'
test "org.grails:grails-datastore-test-support:1.0.2-grails-2.4"
}
plugins {
// plugins for the build system only
build ":tomcat:7.0.55.2" // or ":tomcat:8.0.20"
// plugins for the compile step
compile ":scaffolding:2.1.2"
compile ':cache:1.1.8'
compile ":asset-pipeline:2.1.5"
// plugins needed at runtime but not for compilation
runtime ":hibernate4:4.3.8.1" // or ":hibernate:3.6.10.18"
runtime ":database-migration:1.4.0"
runtime ":jquery:1.11.1"
// Uncomment these to enable additional asset-pipeline capabilities
//compile ":sass-asset-pipeline:1.9.0"
//compile ":less-asset-pipeline:1.10.0"
//compile ":coffee-asset-pipeline:1.8.0"
//compile ":handlebars-asset-pipeline:1.3.0.3"
}
}

Validate that you have the following configuration in your BuildConfig
dependencies {
...
compile 'org.grails.plugins:hibernate:4.3.10.4'
provided 'org.postgresql:postgresql:9.4-1203-jdbc4'
...
}

Related

Error executing query in Java code to connect to Presto

We are trying to connect to Presto using Java code and execute some queries. Catalog we are using is MySQL.
Presto is installed on the Linux server. Presto CLI is working fine on Linux. Started Presto in Linux.
MySQL is also installed on the Linux machine. We are able to access MySQL in windows using DbVisualizer.
I created a MySQL connector catalog for Presto. I'm successful in querying data of MySQL using Presto CLI as presto --server localhost:8080 --catalog mysql --schema tutorials.
Executing the Java code on the Windows machine, I'm able to access MySQL and execute queries, but we are unable to query data. When we try to run a query from Presto, it is giving us Error Executing Query. In the below example, I have used a jar from Trinosql
package testdbPresto;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class PrestoJdbc {
public static void main(String args[]) throws SQLException, ClassNotFoundException {
try{
//connect mysql server tutorials database here
Class.forName("com.facebook.presto.jdbc.PrestoDriver");
String url = "jdbc:trino://35.173.241.37:8080/mysql/tutorials";
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "Redcar88!");
properties.setProperty("SSL", "true");
Connection connection = DriverManager.getConnection(url, properties);
Statement statement = null;
statement = connection.createStatement();
//select mysql table author table two columns
String sql;
sql = "select auth_id, auth_name from mysql.tutorials.author";
ResultSet resultSet = statement.executeQuery(sql);
//Extract data from result set
while (resultSet.next()) {
//Retrieve by column name
String name = resultSet.getString("auth_name");
//Display values
System.out.println("name : " + name);
}
//Clean-up environment
resultSet.close();
statement.close();
connection.close();
}catch(Exception e){ e.printStackTrace();}
}
}
Output:
java.sql.SQLException: Error executing query
at io.trino.jdbc.TrinoStatement.internalExecute(TrinoStatement.java:274)
at io.trino.jdbc.TrinoStatement.execute(TrinoStatement.java:227)
at io.trino.jdbc.TrinoStatement.executeQuery(TrinoStatement.java:76)
at testdbPresto.PrestoJdbc.main(PrestoJdbc.java:29)
Caused by: java.io.UncheckedIOException: javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
at io.trino.jdbc.$internal.client.JsonResponse.execute(JsonResponse.java:154)
at io.trino.jdbc.$internal.client.StatementClientV1.<init>(StatementClientV1.java:110)
at io.trino.jdbc.$internal.client.StatementClientFactory.newStatementClient(StatementClientFactory.java:24)
at io.trino.jdbc.QueryExecutor.startQuery(QueryExecutor.java:46)
at io.trino.jdbc.TrinoConnection.startQuery(TrinoConnection.java:728)
at io.trino.jdbc.TrinoStatement.internalExecute(TrinoStatement.java:239)
... 3 more
Caused by: javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
at sun.security.ssl.SSLSocketInputRecord.handleUnknownRecord(SSLSocketInputRecord.java:448)
at sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:174)
at sun.security.ssl.SSLTransport.decode(SSLTransport.java:110)
at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1279)
at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1188)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:401)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:373)
at io.trino.jdbc.$internal.okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:299)
at io.trino.jdbc.$internal.okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:268)
at io.trino.jdbc.$internal.okhttp3.internal.connection.RealConnection.connect(RealConnection.java:160)
at io.trino.jdbc.$internal.okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:256)
at io.trino.jdbc.$internal.okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
at io.trino.jdbc.$internal.okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
at io.trino.jdbc.$internal.okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at io.trino.jdbc.$internal.okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at io.trino.jdbc.$internal.okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at io.trino.jdbc.$internal.okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at io.trino.jdbc.$internal.client.OkHttpUtil.lambda$basicAuth$1(OkHttpUtil.java:85)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at io.trino.jdbc.$internal.client.OkHttpUtil.lambda$userAgent$0(OkHttpUtil.java:71)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at io.trino.jdbc.$internal.okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at io.trino.jdbc.$internal.okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at io.trino.jdbc.$internal.okhttp3.RealCall.execute(RealCall.java:77)
at io.trino.jdbc.$internal.client.JsonResponse.execute(JsonResponse.java:131)
... 8 more
It is quite old question but it might be still relevant.
You are trying connect to trino with presto jdbc driver. PrestoSQL was rebranded as Trino . So in order to access trino via jdb, you should use trino jdbc driver.
Add trino dependency in your classpath.
If you use maven, add this dependency in the pom.
<dependency>
<groupId>io.trino</groupId>
<artifactId>trino-jdbc</artifactId>
<version>${trino-jdbc.version}</version>
</dependency>
Then use the following driver
Class.forName("io.trino.jdbc.TrinoDriver");
Here is a code that works with Trino.
fun main() {
val trinoUrl = "jdbc:trino://myDomain:443"
val properties = Properties()
properties.setProperty("user", "noUserS")
// properties.setProperty("password", "noPass")
properties.setProperty("SSL", "true")
DriverManager.getConnection(trinoUrl, properties).use { trinoConn ->
trinoConn.createStatement().use { statement ->
statement.connection.catalog = "catalog1"
statement.connection.schema = "default"
println("Executing query...")
statement.executeQuery("""
select
restaurantId,
type,
time
from table1
where time > CURRENT_TIMESTAMP - INTERVAL '1' hour
""".trimIndent()
).use { resultSet ->
val list = mutableListOf<Map<String, String>>()
while (resultSet.next()) {
val data = mapOf(
"restaurantId" to resultSet.getString("restaurantId"),
"type" to resultSet.getString("type"),
"time" to resultSet.getString("time")
)
list.add(data)
}
println("Records returned: ${list.size}")
println(list)
}
}
}
exitProcess(0)
}
It is Kotlin, but it's easy to understand.
The .use {..} it's try-with-resources in Java.
Hope this helps.

Connection not established after database backup

Deployed web application in weblogic 12c server and it has data source configure to make use of connection pool.
Database is Oracle 12,
Usecase: when application is alive up and running, for a min database backup script has been run(stop db, backup, start db), after that when trying to access application(session got established) then got SQL error (connection already closed). What could be an issue?
Temporary solution: after restarting application it was working fine with out any issue. Still wondering how it got worked?
Datasource configuration :
**dataSource {
configClass = GrailsAnnotationConfiguration.class
dialect = "org.hibernate.dialect.Oracle10gDialect"
loggingSql = false
jmxExport = false
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
hbm2ddl.auto = null
show_sql = false
// naming_strategy = "org.hibernate.cfg.ImprovedNamingStrategy"
dialect = "org.hibernate.dialect.Oracle10gDialect"
config.location = [
"classpath:hibernate-core.cfg.xml",
"classpath:hibernate-utility.cfg.xml"
]
}
// environment specific settings
environments {
development {
dataSource {
}
}
test {
dataSource {
}
}
production {
dataSource {
}
}
}**

Exception when Implementing RPC Security Management in corda using spring webserver

Spring Web server not started when we specify RPC Security Management configuration in node.conf file.
Getting error as Unresolved reference: proxy, while running PartyAServer.
Below is my server configuration for PartyA node :-
task runPartyAServer(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'com.example.server.Server'
environment "server.port", "10022"
environment "config.rpc.host", "localhost"
environment "config.rpc.port", "10006"
}
I am able to start the node with following node A configuration, but facing error while running PartyA server.
node {
name "O=PartyA,L=London,C=GB"
advertisedServices = ["com.example"]
p2pPort 10005
rpcPort 10006
cordapps = ["$corda_release_group:corda-finance:$corda_release_version",
"com.example:java-source:$version",
"com.example:base:$version"]
}
Below is my node.conf for PartyA node :-
extraAdvertisedServiceIds=[
"com.example"
]
myLegalName="O=PartyA,L=London,C=GB"
networkMapService {
address="localhost:10002"
legalName="O=Controller,L=London,C=GB"
}
p2pAddress="localhost:10005"
rpcAddress="localhost:10006"
rpcUsers=[]
security = {
authService = {
dataSource = {
type = "DB",
passwordEncryption = "SHIRO_1_CRYPT",
connection = {
jdbcUrl = "jdbc:oracle:thin:#172.16.105.21:1521:SFMS"
username = "abinay"
password = "abinay"
driverClassName = "oracle.jdbc.OracleDriver"
}
}
options = {
cache = {
expireAfterSecs = 120
maxEntries = 10000
}
}
}
}
Without having username and password how nodeRPCConnection(proxy) will be established with following code,
#PostConstruct
public void initialiseNodeRPCConnection() {
NetworkHostAndPort rpcAddress = new NetworkHostAndPort(host,rpcPort);
CordaRPCClient rpcClient = new CordaRPCClient(rpcAddress);
rpcConnection = rpcClient.start(username, password);
proxy = rpcConnection.getProxy();
staticMap.put("proxy",proxy);
}
This strikes me as more likely to be an oracle connection issue.
I'd start by writing some java code just to ensure that you can connect to the oracle DB, and then focus on getting that to work in the cordapp environment.
There's a good developer example on this (in both java and kotlin: https://github.com/corda/samples-java/tree/master/Basic/flow-database-access ; https://github.com/corda/samples-kotlin/tree/master/Basic/flow-database-access)
Best of luck on this!

Spocking the JDBC

I have some Groovy 2.4.x code that uses some JDBC:
class WidgetPersistor {
#Inject // Gets injected correctly by Guice, don't worry about it!
DataSource dataSource
Fizz getFizzByWidgetName(String name) {
Connection conn
PreparedStatement ps
ResultSet rs
try {
// JDBC code here
} catch(SQLException sqlExc) {
if(conn) {
try {
// NOTE: At the end of the day, I just want to verify
// that, given the 'name' arg to this method, the rollback
// doesn't fire!
conn.rollback()
} catch(SQLException rollBackExc) {
throw rollBackExc
}
}
throw sqlExc
} finally {
if(conn) {
try {
rs.close()
ps.close()
conn.close()
} catch(SQLException closingExc) {
throw closingExc
}
}
}
}
}
I am trying to write a Spock test that will execute this getFizzByWidgetName method and verify that the conn.rollback() method never executed (meaning we never tried to rollback).
Here's my best attempt:
def "getFizzByWidgetName succeeds without rollback"() {
given: "data client with db connections"
// Don't worry about how I get this for my test, but its a legit JDBC connection
DataSource ds = provideDataSource()
Connection mockConn = Mock(Connection)
PreparedStatement mockPS = Mock(PreparedStatement)
ResultSet mockRS = Mock(ResultSet)
mockPS.executeQuery() >> mockRS
mockConn.prepareStatement(_) >> mockPS
ds.connection >> mockConn // ??? Its like I want the DataSource half-mocked...
WidgetPersistor client = new WidgetPersistor(mockDS)
when: "we try to query something"
client.getFizzByWidgetName('fizzbuzz')
then: "we dont get any errors"
0 * mockConn.rollback()
}
Any ideas where I'm going awry?
If you are using a DataSource from a real database, and your code under test is written in Groovy (which looks like the case), you can use the metaclass to test this kind of things:
DataSource ds = provideDataSource()
def connection = ds.connection
connection.metaClass.rollback = { throw new AssertionError("rollback called") }
ds.metaClass.connection = connection
But it's not really pretty. You should probably call your method without using mocks, and test the state of the database (ie, data have been committed, not rollbacked)

Geb Firefox Driver: why my test runs twice?

Sorry for all this code, but I don't have a clue what's making my issue, so here it goes.
I configured the geb plugin to run functional tests with JUnit. So I have in my buildConfig.groovy:
def seleniumVersion = "2.29.0"
def gebVersion = "0.7.0"
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
// runtime 'mysql:mysql-connector-java:5.1.5'
provided('com.oracle:oracle:11.1.0.7.0')
provided('com.oracle:i18n:10.2.0.5')
test ("org.seleniumhq.selenium:selenium-chrome-driver:$seleniumVersion") {
export = false
}
test("org.seleniumhq.selenium:selenium-firefox-driver:$seleniumVersion"){
excludes "commons-io"
export = false
}
test ("org.seleniumhq.selenium:selenium-ie-driver:$seleniumVersion") {
export = false
}
test ("org.seleniumhq.selenium:selenium-support:$seleniumVersion") {
export = false
}
test ("org.seleniumhq.selenium:selenium-remote-driver:$seleniumVersion") {
export = false
}
test ("org.codehaus.geb:geb-junit4:$gebVersion") {
export = false
}
}
plugins {
build(":tomcat:$grailsVersion") {
export = false
excludes 'svn'
}
compile (":hibernate:$grailsVersion") {
export = false
excludes 'svn'
}
build (":release:2.0.0") {
excludes 'commons-io','http-builder'
export = false
}
compile(":spring-security-core:1.2.7.3") { excludes 'svn' }
compile(":spring-security-ldap:1.0.6")
compile (":remote-control:1.3") {
export = false
}
test(":geb:$gebVersion") {
export = false
}
}
And I have a GebConfig.groovy in my conf folder:
driver = {
//def driver = new HtmlUnitDriver()
//driver.javascriptEnabled = true
//driver
def driver = new FirefoxDriver()
driver
}
environments {
// run as “grails -Dgeb.env=chrome test-app”
// See: http://code.google.com/p/selenium/wiki/ChromeDriver
chrome {
driver = { new ChromeDriver() }
}
// run as “grails -Dgeb.env=firefox test-app”
// See: http://code.google.com/p/selenium/wiki/FirefoxDriver
firefox {
driver = { new FirefoxDriver() }
}
}
I have a functional test for the login:
class LoginTests extends GebReportingTest {
#Test
void login() {
to LoginPage
at LoginPage
username = "SERGIO"
password = "SERGIO"
loginButton.click()
assert at(IndexPage)
link.click()
}
}
And this are my two pages:
class LoginPage extends Page {
static url = "login/auth"
static at = {
title ==~ /Efetuar Login/
}
static content = {
loginForm { $("form", id: "loginForm") }
username { $("input", type:"text", id:"username") }
password { $("input", type:"password", id:"password") }
loginButton{ $("input", type:"submit", id:"submit") }
}
}
class IndexPage extends Page {
static at = {
title ==~ /Security Service Index View/
}
static content = {
description { $('h1') }
link { $('a') }
}
}
For some reason my functional test run twice and don't matter how I start this:
grails test-app :functional
grails test-app -functional
It looks like the Geb plugin isn't fully compatible with Grails 2.3.x . For some reason tests get executed twice after upgrading to Geb plugin 0.9.2 .
I believe this problem is related to https://jira.grails.org/browse/GRAILS-10552 and changes made as part of https://jira.grails.org/browse/GRAILS-6352 .
In Grails 2.3.x+, the GrailsSpecTestType takes care of both Junit and Spock tests:
https://github.com/grails/grails-core/blob/bce298f0/grails-test/src/main/groovy/org/codehaus/groovy/grails/test/spock/GrailsSpecTestType.groovy#L33
It looks like the Geb plugin is adding the deprecated JUnit4GrailsTestType to execution:
https://github.com/geb/geb/blob/584738cb/integration/geb-grails/scripts/_Events.groovy#L60-L67
This is why functional tests get executed twice.
This is how I got around the problem in Geb 0.9.2 / 0.9.3 versions.
grails test-app functional:spock
It looks like Geb version 0.9.1 didn't execute the tests twice.
The difference seems to be caused by this commit:
https://github.com/geb/geb/commit/9c71e820
You should also be aware that you shouldn't have the Spock plugin installed in Grails 2.3.x/2.4.x .
Hi Not Much of a Selenium WebDriver on Ruby but It seems to be that you are starting Firefox twice as such the test runs in two instances

Resources