Problems connecting to Postgres from Grails - postgresql

I have verified that I can connect to the postgres database using a Java test program. I have also verified that I can connect using a little Grails testDB project. But when I try to run my larger project, which the same BuildConfig.groovy, it fails.
I've tried different jdbc versions (e.g., 4 rather than 41) in the postgres jar, but it didn't help.
I've been searching stackoverflow and anything else I can find to no avail (e.g., "help me stackoverflow, your my only hope").
My BuildConfig.groovy file is shown below:
grails.servlet.version = "3.0" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.work.dir = "target/work"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.project.fork = [
// configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
// compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the test-app JVM, uses the daemon by default
test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the run-app JVM
run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the run-war JVM
war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the Console UI JVM
console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]
grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// specify dependency exclusions here; for example, uncomment this to disable ehcache:
// excludes 'ehcache'
}
log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
mavenLocal()
grailsCentral()
mavenCentral()
// uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
}
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
// runtime 'mysql:mysql-connector-java:5.1.29'
compile 'org.postgresql:postgresql:9.3-1101-jdbc41'
runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
test "org.grails:grails-datastore-test-support:1.0-grails-2.4"
}
plugins {
// plugins for the build system only
build ":tomcat:7.0.55"
// plugins for the compile step
compile ":scaffolding:2.1.2"
compile ':cache:1.1.7'
compile ":asset-pipeline:1.9.6"
compile ":twitter-bootstrap:3.2.1"
// compile ":jquery-dialog:2.0.3"
// plugins needed at runtime but not for compilation
runtime ":hibernate4:4.3.5.5" // or ":hibernate:3.6.10.15"
runtime ":database-migration:1.4.0"
runtime ":jquery:1.11.1"
runtime ":twitter-bootstrap:3.2.1"
}
}
My DataSource.groovy file contains
dataSource {
pooled = true
jmxExport = true
url = "jdbc:postgresql://150.18.178.9:5432/myDB"
driverClassName = "org.postgresql.Driver"
dbCreate = "update"
username = "user"
password = "password"
dialect = net.sf.hibernate.dialect.PostgreSQLDialect
}
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
singleSession = true // configure OSIV singleSession mode
}
// environment specific settings
environments {
development {
dataSource { // database dev
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url="jdbc:postgresql://150.18.178.9:5432/dev"
username = "user"
password = "password"
}
}
test {
dataSource {
dbCreate = "update"
url="jdbc:postgresql://150.18.178.9:5432/test"
username = "user"
password = "password"
}
}
production {
dataSource {
dbCreate = "update"
url="jdbc:postgresql://150.18.178.9:5432/myDB"
username = "user"
password = "password"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}
}
}
When I try to run my application I get:
/usr/java/latest/bin/java -Dgrails.home=/home/iank/software/grails/latest -Dbase.dir=/home/iank/IdeaProjects/nderground -Dtools.jar=/usr/java/latest/lib/tools.jar -Dgroovy.starter.conf=/home/iank/software/grails/latest/conf/groovy-starter.conf -Xmx768M -Xms768M -XX:MaxPermSize=256m -XX:PermSize=256m -javaagent:/home/iank/software/grails/latest/lib/org.springframework/springloaded/jars/springloaded-1.2.0.RELEASE.jar -noverify -Dspringloaded=profile=grails -Didea.launcher.port=7535 -Didea.launcher.bin.path=/home/iank/software/idea-IU-135.909/bin -Dfile.encoding=UTF-8 -classpath /home/iank/software/grails/latest/lib/org.codehaus.groovy/groovy-all/jars/groovy-all-2.3.6.jar:/home/iank/software/grails/latest/dist/grails-bootstrap-2.4.3.jar:/home/iank/software/idea-IU-135.909/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf /home/iank/software/grails/latest/conf/groovy-starter.conf "run-app -plain-output"
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to development
.................................
|Packaging Grails application
...........
|Compiling 1 source files
............................
|Running Grails application
| Error 2014-09-27 17:16:38,021 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
Line | Method
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by IllegalArgumentException: object is not an instance of declaring class
->> 22 | doCall in nderground.User$__clinit__closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
Error |
Forked Grails VM exited with error
|Server running. Browse to http://localhost:8080/nderground
Process finished with exit code 1
Any help would be deeply appreciated. My progress has completely stalled and I'm not sure what to do other than to try rebuilding the project piece by piece.
Many thanks...

By creating a Grails project that worked and slowly adding code I was able to find the problem. I had an improperly specified constraint.
class User {
String handle
String emailAddr
String salt
String password
boolean isAdmin
String toString()
{
String rslt = "$handle"
return rslt
}
static constraints = {
handle blank : false, nullable : false, unique : true
emailAddr blank : false, nullable : false, unique : true, email : true
salt blank: false, nullable: false
password blank: false, nullable: false
isAdmin false <<======= This is the problem!
}
static mapping = {
table 'users'
handle index : 'handle_Ix'
emailAddr index: 'email_ix'
isAdmin defaultValue: false
}
}
This should have been in the static mapping section:
static mapping = {
table 'users'
handle index : 'handle_Ix'
emailAddr index: 'email_ix'
isAdmin defaultValue: false <<== This is the right way to set the default
}
To put it mildly, its annoying that the error shows up as a thread creation error, without any other indication of other errors.

As #EElke points out in the comments, there's no indication at all that Postgres is the problem; the error that you should be looking at says Error creating bean with name 'sessionFactory' ... object is not an instance of declaring class.
My guess is that net.sf.hibernate.dialect.PostgreSQLDialect is the problem - replace that with org.hibernate.dialect.PostgreSQLDialect.
Also, delete this:
runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
since you already have
compile 'org.postgresql:postgresql:9.3-1101-jdbc41'
and runtime scope includes dependencies from compile scope.

Related

Can't install and use Jhipster Registry 7.4.0 because hazelcast and logs properties are left bound

I try to use Jhipster Registry 7.4.0 for my new application. At this time, I just want to start it in default configuration.
In my application and application-dev properties files, I have (in both files):
...
jhipster:
async:
core-pool-size: 2
max-pool-size: 50
queue-capacity: 10000
cache:
hazelcast:
time-to-live-seconds: 3600
backup-count: 1
management-center:
enabled: false
update-interval: 3
url: http://localhost:8180/mancenter
security:
authentication:
jwt:
base64-secret: <MY KEY>
metrics:
logs:
enabled: false
report-frequency: 60
...
When I start my registry, it's failed because logs and hazelcast are left bound :
2022-11-17T11:42:40.901+01:00 INFO 11900 --- [ main] t.jhipster.registry.JHipsterRegistryApp : The following 4 profiles are active: "composite", "dev", "api-docs", "swagger"
2022-11-17T11:42:44.401+01:00 WARN 11900 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webConfigurer' defined in URL [jar:file:/C:/Users/myuser/Desktop/JHIPSTER_REGISTRY-7.4.0/jhipster-registry-7.4.0.jar!/BOOT-INF/classes!/tech/jhipster/registry/config/WebConfigurer.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'jhipster-tech.jhipster.config.JHipsterProperties': Could not bind properties to 'JHipsterProperties' : prefix=jhipster, ignoreInvalidFields=false, ignoreUnknownFields=false; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'jhipster' to tech.jhipster.config.JHipsterProperties
2022-11-17T11:42:44.489+01:00 ERROR 11900 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : ____***************************__APPLICATION FAILED TO START__***************************____Description:____Binding to target [Bindable#9a2ec9b type = tech.jhipster.config.JHipsterProperties, value = 'provided', annotations = array<Annotation>[#org.springframework.boot.context.properties.ConfigurationProperties(ignoreInvalidFields=false, ignoreUnknownFields=false, prefix="jhipster", value="jhipster")]] failed:____ Property: jhipster.metrics.logs.enabled__ Value: "false"__ Origin: URL [file:config/application-dev.yml] - 88:22__ Reason: The elements [jhipster.metrics.logs.enabled,jhipster.metrics.logs.report-frequency] were left unbound.__ Property: jhipster.metrics.logs.report-frequency__ Value: "60"__ Origin: URL [file:config/application-dev.yml] - 89:31__ Reason: The elements [jhipster.metrics.logs.enabled,jhipster.metrics.logs.report-frequency] were left unbound.____Action:____Update your application's configuration__
Do you know why this properties ar not found ? I havec check sample on gitub registry depo ans configuration seems to be identical ...

Deploying Spring Boot App to Google App Engine - issues with connecting to SQL instance (PostgreSQL)

I have a Gradle based Spring Boot app that I'm trying to deploy to the App Engine via the App Engine gradle plugin. The SQL instance (PostgreSQL) is up and running fine, I can connect to it locally through DataGrip and it works fine. Here's my application.properties file:
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
#################### GOOGLE CLOUD SETTINGS
spring.cloud.gcp.sql.enabled=true
spring.cloud.gcp.sql.database-name=db-name
spring.cloud.gcp.sql.instance-connection-name=app-name:europe-west2:db-name
When I try to deploy the app, I'm getting the following error (seems that it can't connect to the SQL instance):
A 2020-05-27T16:12:26.340839Z 2020-05-27 16:12:26.340 INFO 10 --- [ main] o.s.c.g.a.s.GcpCloudSqlAutoConfiguration : Default POSTGRESQL JdbcUrl provider. Connecting to jdbc:postgresql://google/db-name?socketFactory=com.google.cloud.sql.postgres.SocketFactory&cloudSqlInstance=instance-name:europe-west2:db-name with driver org.postgresql.Driver
A 2020-05-27T16:12:26.773138Z 2020-05-27 16:12:26.772 INFO 10 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
A 2020-05-27T16:12:26.977687Z 2020-05-27 16:12:26.977 INFO 10 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
A 2020-05-27T16:12:27.413333Z 2020-05-27 16:12:27.413 INFO 10 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
A 2020-05-27T16:12:27.683594Z 2020-05-27 16:12:27.683 INFO 10 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
A 2020-05-27T16:12:27.760810Z 2020-05-27 16:12:27.760 INFO 10 --- [ main] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [app-name:europe-west2:db-name] via unix socket.
A 2020-05-27T16:12:27.966435Z 2020-05-27 16:12:27.966 WARN 10 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Found interface org.objectweb.asm.ClassVisitor, but class was expected
2020-05-27 17:12:27.970 BST
2020-05-27 16:12:27.970 INFO 10 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
I've researched this issue and it seems that this happens when the runtime classpath is different the compile class path. Problem is that I can't reproduce it locally and I can't figure out if it's a dependency that's causing this.
Full stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Found interface org.objectweb.asm.ClassVisitor, but class was expected
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1796)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0 (AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean (AbstractApplicationContext.java:1108)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh (ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:1215)
at com.turbochargedapps.basketballappinternalrest.BasketballAppInternalRestApplication.main (BasketballAppInternalRestApplication.java:21)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.springframework.boot.loader.MainMethodRunner.run (MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch (Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch (Launcher.java:51)
at org.springframework.boot.loader.JarLauncher.main (JarLauncher.java:52)
Caused by: java.lang.IncompatibleClassChangeError: Found interface org.objectweb.asm.ClassVisitor, but class was expected
at jnr.ffi.provider.jffi.AsmLibraryLoader.generateInterfaceImpl (AsmLibraryLoader.java:104)
at jnr.ffi.provider.jffi.AsmLibraryLoader.loadLibrary (AsmLibraryLoader.java:89)
at jnr.ffi.provider.jffi.NativeLibraryLoader.loadLibrary (NativeLibraryLoader.java:44)
at jnr.ffi.LibraryLoader.load (LibraryLoader.java:325)
at jnr.unixsocket.Native.<clinit> (Native.java:80)
at jnr.unixsocket.UnixSocketChannel.<init> (UnixSocketChannel.java:101)
at jnr.unixsocket.UnixSocketChannel.open (UnixSocketChannel.java:65)
at com.google.cloud.sql.core.CoreSocketFactory.connect (CoreSocketFactory.java:180)
at com.google.cloud.sql.postgres.SocketFactory.createSocket (SocketFactory.java:71)
at org.postgresql.core.PGStream.<init> (PGStream.java:73)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect (ConnectionFactoryImpl.java:93)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl (ConnectionFactoryImpl.java:197)
at org.postgresql.core.ConnectionFactory.openConnection (ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init> (PgConnection.java:211)
at org.postgresql.Driver.makeConnection (Driver.java:459)
at org.postgresql.Driver.connect (Driver.java:261)
at com.zaxxer.hikari.util.DriverDataSource.getConnection (DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection (PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry (PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry (HikariPool.java:477)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast (HikariPool.java:560)
at com.zaxxer.hikari.pool.HikariPool.<init> (HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.getConnection (HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection (DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection (JdbcEnvironmentInitiator.java:180)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService (JdbcEnvironmentInitiator.java:68)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService (JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService (StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService (AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService (AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService (AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices (DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies (AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService (AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService (AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init> (InFlightMetadataCollectorImpl.java:176)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete (MetadataBuildingProcess.java:118)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata (EntityManagerFactoryBuilderImpl.java:1214)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build (EntityManagerFactoryBuilderImpl.java:1245)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory (SpringHibernateJpaPersistenceProvider.java:58)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory (LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory (AbstractEntityManagerFactoryBean.java:391)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet (AbstractEntityManagerFactoryBean.java:378)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet (LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods (AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1792)
build.gradle file:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.cloud.tools:appengine-gradle-plugin:2.2.0'
}
}
plugins {
id 'org.springframework.boot' version '2.2.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
id 'java'
}
apply plugin: 'com.google.cloud.tools.appengine'
appengine {
deploy {
appengine.deploy.version = "GCLOUD_CONFIG"
appengine.deploy.projectId = "GCLOUD_CONFIG"
}
}
group = 'com.group'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
ext {
set('snippetsDir', file("build/generated-snippets"))
set('springCloudVersion', "Hoxton.SR4")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
compile project(':project-core-submodule')
compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.0.0'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
testImplementation 'org.springframework.security:spring-security-test'
testCompile group: 'com.h2database', name: 'h2', version: '1.4.200'
compile 'io.jsonwebtoken:jjwt-api:0.11.1'
runtime 'io.jsonwebtoken:jjwt-impl:0.11.1',
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
//'org.bouncycastle:bcprov-jdk15on:1.60',
'io.jsonwebtoken:jjwt-jackson:0.11.1' // or 'io.jsonwebtoken:jjwt-gson:0.11.1' for gson
// https://mvnrepository.com/artifact/com.google.guava/guava
compile group: 'com.google.guava', name: 'guava', version: '29.0-jre'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-sql-postgresql'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test {
outputs.dir snippetsDir
useJUnitPlatform()
}
asciidoctor {
inputs.dir snippetsDir
dependsOn test
}
Any ideas?
Turns out it was Google Guava that was causing this issue - I simply removed the dependency from my build.gradle file, did gradle clean build and then redeployed!

My execution halts while implemented the Data Driven Approach

I have included few lines of code for data driven, where I will fetch the details from a Excel sheet and it will pass to the script in Run Time. Here my script won't execute and it hangs after returning the message in Eclipse Console:
Returning cached instance of singleton bean 'todoClient1'
Below attached the Code and package com.consol.citrus.integration.Demo.
import java.util.Hashtable;
import org.apache.log4j.helpers.SyslogWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.testng.SkipException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import com.consol.citrus.TestCaseMetaInfo.Status;
import com.consol.citrus.annotations.CitrusTest;
import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;
import com.consol.citrus.http.client.HttpClient;
import com.consol.citrus.message.MessageType;
public class UnSuccessFullLogin extends TestNGCitrusTestDesigner {
#Autowired (required=true)
#Qualifier("todoClient1")
private HttpClient todoClient1;
public Xls_Reader xls=new Xls_Reader(Constants.DATA_XLS_PATH);
String testCaseName="UnSuccessFullLogin";
public String actualResult="";
#CitrusTest
#Test(dataProvider="getData")
public void TestPost(Hashtable<String, String> data) {
echo("i am entered");
variable("Uname", "admin2");
variable("Pwd", "admin");
if(!DataUtil.isTestExecutable(xls, testCaseName) || data.get(Constants.RUNMODE_COL).equals("N")){
throw new SkipException("Skipping the test as Rnumode is N");
}
http()
.client(todoClient1)
.send()
.post("/rest/api/user/login")
.contentType("application/json")
// .payload("{ \"userName\": \"${uN}\", \"password\": \"${pwd}\"}");
.payload("{ \"userName\": \"${Uname}\", \"password\": \"${Pwd}\"}");
http()
.client(todoClient1)
.receive()
.response(HttpStatus.ACCEPTED)
.validate("$.statusCode", "400");
}
#DataProvider
public Object[][] getData()
{
return DataUtil.getData(xls, testCaseName);
}
}
Log Here:
17:37:56,650 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient'
17:37:56,650 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient'
17:37:56,651 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClientConfiguration'
17:37:56,675 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient' to allow for resolving potential circular references
17:37:56,690 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient'
17:37:56,690 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient1Configuration'
17:37:56,690 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient1Configuration'
17:37:56,691 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient1Configuration' to allow for resolving potential circular references
17:37:56,697 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient1Configuration'
17:37:56,697 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient1'
17:37:56,697 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient1'
17:37:56,697 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1Configuration'
17:37:56,699 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient1' to allow for resolving potential circular references
17:37:56,699 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient1'
17:37:56,699 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'globalVariables'
17:37:56,699 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'com.consol.citrus.report.MessageTracingTestListener#1'
17:37:56,700 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:37:56,851 DEBUG icApplicationContext| Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#655a5d9c]
17:37:56,852 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'lifecycleProcessor'
17:37:56,856 DEBUG rcesPropertyResolver| Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
17:37:56,866 DEBUG ontextLoaderDelegate| Storing ApplicationContext in cache under key [[MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:37:56,866 DEBUG context.cache| Spring test ApplicationContext cache statistics: [DefaultContextCache#1a6f2363 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
17:37:56,939 DEBUG on.InjectionMetadata| Processing injected element of bean 'com.consol.citrus.integration.Demo.UnSuccessFullLogin': AutowiredFieldElement for private com.consol.citrus.http.client.HttpClient com.consol.citrus.integration.Demo.UnSuccessFullLogin.todoClient1
17:37:56,942 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1'
17:37:56,942 DEBUG ionBeanPostProcessor| Autowiring by type from bean name 'com.consol.citrus.integration.Demo.UnSuccessFullLogin' to bean named 'todoClient1'
17:37:56,947 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'testSuiteListeners'
17:37:56,947 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'testContextFactory'
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus - .__ __
5876 [main] INFO com.consol.citrus.Citrus - ____ |__|/ |________ __ __ ______
5876 [main] INFO com.consol.citrus.Citrus - _/ ___\| \ __\_ __ \ | \/ ___/
5876 [main] INFO com.consol.citrus.Citrus - \ \___| || | | | \/ | /\___ \
5876 [main] INFO com.consol.citrus.Citrus - \___ >__||__| |__| |____//____ >
5876 [main] INFO com.consol.citrus.Citrus - \/ \/
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - C I T R U S T E S T S 2.7.2
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - BEFORE TEST SUITE: SUCCESS
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus -
17:37:56,974 DEBUG estExecutionListener| Before test class: context [DefaultTestContext#740fb309 testClass = UnSuccessFullLogin, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
17:37:56,975 DEBUG estExecutionListener| Performing dependency injection for test context [[DefaultTestContext#740fb309 testClass = UnSuccessFullLogin, testInstance = com.consol.citrus.integration.Demo.UnSuccessFullLogin#5524cca1, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]].
17:37:56,975 DEBUG ontextLoaderDelegate| Retrieved ApplicationContext from cache with key [[MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:37:56,975 DEBUG context.cache| Spring test ApplicationContext cache statistics: [DefaultContextCache#1a6f2363 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 1, missCount = 1]
17:37:56,976 DEBUG on.InjectionMetadata| Processing injected element of bean 'com.consol.citrus.integration.Demo.UnSuccessFullLogin': AutowiredFieldElement for private com.consol.citrus.http.client.HttpClient com.consol.citrus.integration.Demo.UnSuccessFullLogin.todoClient1
17:37:56,976 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1'
Please see the following working sample how to use TestNG data provider with Citrus:
public class DataProviderJavaIT extends TestNGCitrusTestDesigner {
#CitrusTest
#CitrusParameters( {"message", "delay"} )
#Test(dataProvider = "sampleDataProvider")
public void dataProvider(String message, Long sleep) {
echo(message);
sleep(sleep);
echo("${message}");
echo("${delay}");
}
#DataProvider
public Object[][] sampleDataProvider() {
return new Object[][] {
{ "Hello World!", 300L },
{ "Hallo Welt!", 1000L },
{ "Hallo Citrus!", 500L },
};
}
}
According to the sample you are missing the #CitrusParameters annotation that translates data provider arguments to Citrus test variables.

FactType.getFields return no fields drools KIE

I have created a fact type( CustomerFact ) with two fact fields(age and bonus) . A sample rule is also created using workbench. Now, I want to inject some test values and check whether the rules are getting fired. I used Eclipse IDE.
I am able to retrieve package name and the rule created in workbench in my java code. However, I am enable to get any fact fields. GetFields always returns an empty list whereas it should have returned 2 fields. Is there any alternative to this? I just want to set the field of the fact type and see whether the rules are getting fired. Any help is highly appreciated.
package org.demo.cityproject;
/**
* This class was automatically generated by the data modeler tool.
*/
public class CustomerFact implements java.io.Serializable
{
static final long serialVersionUID = 1L;
#org.kie.api.definition.type.Key
private int age;
#org.kie.api.definition.type.Key
private int bonus;
public CustomerFact()
{
}
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
this.age = age;
}
public int getBonus()
{
return this.bonus;
}
public void setBonus(int bonus)
{
this.bonus = bonus;
}
public CustomerFact(int age, int bonus)
{
this.age = age;
this.bonus = bonus;
}
#Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
org.demo.cityproject.CustomerFact that = (org.demo.cityproject.CustomerFact) o;
if (age != that.age)
return false;
if (bonus != that.bonus)
return false;
return true;
}
#Override
public int hashCode()
{
int result = 17;
result = 31 * result + age;
result = 31 * result + bonus;
return result;
}
}
Test Code
public static void main(String[] args)
{
String url = "http://localhost:8080/kie-drools-wb-distribution-wars-6.2.0.Final-jboss-as7/maven2/Project1/org/demo/CityProject/1.0/CityProject-1.0.jar";
ReleaseIdImpl releaseId = new ReleaseIdImpl("org.demo", "CityProject", "LATEST");
KieServices kieServices = KieServices.Factory.get();
kieServices.getResources().newUrlResource(url);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieScanner kieScanner = kieServices.newKieScanner(kieContainer);
kieScanner.scanNow();
Scanner scanner = new Scanner(System.in);
System.out.println("kieContainer.getKieBaseNames() "+kieContainer.getKieBaseNames());
KieSession newKieSession =kieContainer.newKieSession("session1");
KieBase lKieBase=newKieSession.getKieBase();
System.out.println("lPackage "+lKieBase.getKiePackages());
KiePackage lPackage=lKieBase.getKiePackage("org.demo.cityproject");
System.out.println("lPackage FactTypes: "+lPackage.getFactTypes());
for(FactType lFact:lPackage.getFactTypes())
{
System.out.println("lFacts: "+lFact.getName());
System.out.println("lFacts Fields: "+lFact.getFields());
}
}
Console o/p in eclipse
22:58:28.998 [main] DEBUG o.d.c.k.b.impl.KieRepositoryImpl - KieModule Lookup. ReleaseId org.demo:CityProject:LATEST was not in cache, checking maven repository
22:58:37.430 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:37.743 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:39.455 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:41.744 [main] DEBUG o.e.a.i.i.DefaultDependencyCollector - Dependency collection stats: {ConflictMarker.analyzeTime=0, ConflictMarker.markTime=0, ConflictMarker.nodeCount=1, ConflictIdSorter.graphTime=0, ConflictIdSorter.topsortTime=0, ConflictIdSorter.conflictIdCount=1, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=0, ConflictResolver.conflictItemCount=1, DefaultDependencyCollector.collectTime=32, DefaultDependencyCollector.transformTime=15}
22:58:42.230 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:42.230 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:42.246 [main] DEBUG o.e.a.i.i.DefaultDependencyCollector - Dependency collection stats: {ConflictMarker.analyzeTime=0, ConflictMarker.markTime=0, ConflictMarker.nodeCount=1, ConflictIdSorter.graphTime=0, ConflictIdSorter.topsortTime=0, ConflictIdSorter.conflictIdCount=0, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=0, ConflictResolver.conflictItemCount=0, DefaultDependencyCollector.collectTime=0, DefaultDependencyCollector.transformTime=0}
22:58:47.596 [main] INFO o.d.c.k.b.impl.KieRepositoryImpl - KieModule was added: ZipKieModule[releaseId=org.demo:CityProject:1.0,file=C:\Users\USER\.m2\repository\org\demo\CityProject\1.0\CityProject-1.0.jar]
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.426 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.442 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
kieContainer.getKieBaseNames() [KnowledgeBaseALL]
22:58:50.532 [main] DEBUG o.drools.core.impl.KnowledgeBaseImpl - Starting Engine in PHREAK mode
lPackage [[Package name=org.demo.cityproject]]
lPackage FactTypes: [ClassDefinition{className='org.demo.cityproject.CustomerFact', superClass='java.lang.Object', interfaces=[java.io.Serializable], definedClass=class org.demo.cityproject.CustomerFact, traitable=null, abstract=false, fields={}, annotations=null}]
lFacts: org.demo.cityproject.CustomerFact
**lFacts Fields: []**
As you can see in the output fact field is empty.
The - rather disappointing - situation is that there are two or even three kinds of FactTypes:
Fact types defined by a declare statement in a DRL file
Fact types resulting from Java classes and imported explicitly or implicitly
JDK types used as fact types
Method getFactTypes does not return #3. Method getFields returns an empty list for #2.
Finally I found an answer. Such fields can be invoked by reflection.
Here is how the rules get triggered
for(FactType lFct:lusedpackage.getFactTypes())
{
// System.out.println("Customer class "+lFct.getFactClass());
**Constructor constructor=lFct.getFactClass().getConstructor(String.class,java.math.BigInteger.class);**
**Object s1=constructor.newInstance(lcity,lcustomerID);**
//System.out.println("constructor "+constructor);
//System.out.println("Object "+s1);
**Method lCustID=lFct.getFactClass().getMethod("getCustomerID");**
System.out.println("*************************************************************");
System.out.println("Customer value before firing the rule: "+ lCustID.invoke(s1));
**Method setCity = lFct.getFactClass().getMethod("getCity");**
System.out.println("City value before firing the rule: "+ setCity.invoke(s1));
//System.out.println("method "+lCustID);
System.out.println("*************************************************************");
newKieSession.insert(s1);
newKieSession.fireAllRules();
System.out.println("Customer value after firing the rule: "+ **lCustID.invoke(s1)**);
System.out.println("City value after firing the rule: "+ setCity.invoke(s1));
System.out.println("*************************************************************");
}

How to configure mongodb with grails

I am new on this way.I tried to much still i am getting error to make login application using mongodb with grails.
grails 2.4.0
mongodb 3.0.3
BuildConfig.groovy.
grails.servlet.version = "3.0" // Change depending on target container
compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.work.dir = "target/work"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.project.fork = [
// configure settings for compilation JVM, note that if you alter the
Groovy version forked compilation is required
// compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256,
daemon:true],
// configure settings for the test-app JVM, uses the daemon by default
test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256,
daemon:true],
// configure settings for the run-app JVM
run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256,
forkReserve:false],
// configure settings for the run-war JVM
war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256,
forkReserve:false],
// configure settings for the Console UI JVM
console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]
grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// specify dependency exclusions here; for example, uncomment this to
disable ehcache:
// excludes 'ehcache'
}
log "error" // log level of Ivy resolver, either 'error', 'warn', 'info',
'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin
installation, not advised and here for backwards compatibility
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
mavenLocal()
grailsCentral()
mavenCentral()
// uncomment these (or add new ones) to enable remote dependency
resolution from public Maven repositories
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
}
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'
compile "org.springframework:spring-orm:$springVersion"
compile 'org.grails:grails-datastore-gorm:3.1.4.RELEASE'
compile 'org.grails:grails-datastore-core:3.1.4.RELEASE'
test 'org.grails:grails-datastore-simple:3.1.4.RELEASE'
}
plugins {
// plugins for the build system only
build ":tomcat:7.0.53"
// plugins for the compile step
compile ":scaffolding:2.1.0"
compile ':cache:1.1.6'
compile ":asset-pipeline:1.8.7"
// plugins needed at runtime but not for compilation
// runtime ":hibernate4:4.3.5.3" // or ":hibernate:3.6.10.15"
runtime ":database-migration:1.4.0"
runtime ":jquery:1.11.1"
// Uncomment these to enable additional asset-pipeline capabilities
//compile ":sass-asset-pipeline:1.7.4"
//compile ":less-asset-pipeline:1.7.0"
//compile ":coffee-asset-pipeline:1.7.0"
//compile ":handlebars-asset-pipeline:1.3.0.3"
compile ":mongodb:3.0.3"
}
}
DataSource.groovy
dataSource {
pooled = true
jmxExport = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
grails {
mongo {
host = "localhost"
port = 27017
username = "admin"
password = "admin"
databaseName = "mydb"
}
}
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
singleSession = true // configure OSIV singleSession mode
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop',
'update', 'validate', ''
url =
"jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
}
}
test {
dataSource {
dbCreate = "update"
url =
"jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
}
}
production {
dataSource {
dbCreate = "update"
url =
"jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource
//for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation =
java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}
}
}
Error while run this application i spent more time two solve it but i think it would be version compatibility issue.
Error | 2015-05-09 11:50:58,502 [localhost-startStop-1] ERROR
context.GrailsContextLoaderListener - Error initializing the application:
Error creating bean with name 'transactionManagerPostProcessor':
Initialization of bean failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'transactionManager': Cannot resolve reference to bean
'mongoTransactionManager' while setting constructor argument with key [1];
nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'mongoTransactionManager': Cannot resolve reference to bean
'mongoDatastore' while setting bean property 'datastore'; nested exception
is org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'mongoDatastore': Cannot resolve reference to bean
'mongoBean' while setting bean property 'mongo'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'mongo': Invocation of init method failed; nested exception
is com.mongodb.MongoTimeoutException: Timed out while waiting for a server
that matches AnyServerSelector{} after 10000 ms
Message: Error creating bean with name 'transactionManagerPostProcessor':
Initialization of bean failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'transactionManager': Cannot resolve reference to bean
'mongoTransactionManager' while setting constructor argument with key [1];
nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'mongoTransactionManager': Cannot resolve reference to bean
'mongoDatastore' while setting bean property 'datastore'; nested exception
is org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'mongoDatastore': Cannot resolve reference to bean
'mongoBean' while setting bean property 'mongo'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'mongo': Invocation of init method failed; nested exception
is com.mongodb.MongoTimeoutException: Timed out while waiting for a server
that matches AnyServerSelector{} after 10000 ms
Seems like your MongoDB server is not running into your local machine. Please confirm and start the service.
For Ubuntu:
sudo service mongod start
Or for other operating systems, follow this http://docs.mongodb.org/manual/installation/