Neo4j database for Grails app without using Neo4j GORM plugin - grails

I want to make a web-app using Grails framework for the server part and Neo4j database for storage. I found the Neo4j GORM plugin on Grails site, but unfortunately after numerous attempts I could not make it work properly. If i solve one error I get more, i can't even set a basic app to work. So I would like to write my own code for handling CRUD operations. I would like to override the default CRUD operations for domain classes. For example when I save a Person entity, i would use the REST API offered by Neo4j database to store the entity there etc. Would this be an acceptable solution? If yes, then how should I proceed about overriding the CRUD methods for domain classes?
Problem i had with GORM plugin: I followed the steps described in the documentation : http://projects.spring.io/grails-data-mapping/neo4j/manual/guide/gettingStarted.html . I created a simple Grails web-app, included the Neo4j-GORM plugin dependency. The application started.
If I try to access 'org.grails.datastore.gorm.neo4j.Neo4jController' I get some strange errors:
Here are the errors I get in the console:
015-01-04 14:11:22,460 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - NullPointerException occurred when processing request: [GET] /ANewHope/neo4j/node
Cannot invoke method getNodeById() on null object. Stacktrace follows:
Message: Cannot invoke method getNodeById() on null object
Line | Method
->> 30 | doCall in org.grails.datastore.gorm.neo4j.Neo4jController$_closure2
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Here is my 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/"
mavenRepo 'http://m2.neo4j.org/releases'
}
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'
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"
// plugins for the compile step
compile ":neo4j:2.0.0-M02"
compile ":scaffolding:2.1.2"
compile ':cache:1.1.8'
compile ":asset-pipeline:1.9.9"
// plugins needed at runtime but not for compilation
// runtime ":hibernate4:4.3.6.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"
}
}
Here is DataSource.groovy:
dataSource {
pooled = true
jmxExport = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
//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
// flush.mode = 'manual' // OSIV session flush mode outside of transactional context
//}
//grails {
// neo4j {
// type = "embedded"
// location = "C:\\data\\neo4j"
// params = []
// }
//}
// 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
}
}
}
}
After this I tried to specify the location as suggested in the documentation and added the following to DataSource.groovy:
grails {
neo4j {
type = "embedded"
location = "C:\\data\\neo4j"
params = []
}
}
The result was the same. After failed attempts I decided to try some other solution.
I want to use Neo4j for my Bachelor Thesis project, and my professor suggested me to use it with Grails. I like both Neo4j and Grails, but unfortunately I got into this problem when I tried to use them together.

If you don't want to use the GORM plugin, you could for instance use the Neo4j-JDBC driver from Grails to send parameterized Cypher Statements to the server. Much like you would do with a relational database.
There is also a new ORM in the works but it is still very much work in progress. You can find it here: https://github.com/neo4j/neo4j-ogm

As powerful as the GORM is, it isn't right for every project. I often elect to use something else, however, grails expects that anything in the domain directory is going to be using the GORM. If you want to use a different API you should just put your classes in src/groovy. If you still want to be able to use constraints for validation, you can apply the #Validatable annotation to the class. Details on that can be found in the Validation Grails docs. I would then just put all of your code to interface with the Neo4j REST API into a Grails Service.

Related

How to configure a custom maven repository in Grails 2.2?

I am trying to get dependency resolution to work in Grails 2.2 from a custom repository which has username password.
I have tried adding the following in my BuildConfig.groovy
grails.project.dependency.resolver = "maven"
grails.project.ivy.authentication = {
repositories {
mavenRepo('https://maven.companyname.com/repository/repository-name') {
auth([
username: 'myusername',
password: 'mypassword'
])
}
}
}
But I get error like
Caused by: groovy.lang.MissingMethodException: No signature of method: groovy.util.ConfigSlurper$_parse_closure5.auth() is applicable for argument types: (java.util.LinkedHashMap) values:
I tried looking at https://grails.github.io/grails2-doc/2.2.0/guide/single.html#dependencyRepositories but it does not tell me more information. It does say that I need to put the credentials in settings.groovy but is that absolutely necessary? I tried putting the credentials inside mavenRepo closure but that did not work. Any ideas?
Grails 2 - quite some time ago…
This way it is working here.
BuildConfig.groovy:
…
grails.project.dependency.resolver = "ivy"
grails.project.dependency.resolution = {
repositories {
mavenRepo "https://repo.example.com/myrepo"
}
…
~/.grails/settings.groovy:
…
grails.project.ivy.authentication = {
credentials {
realm = "My Realm"
host = "repo.example.com"
username = "user"
password = "secret"
}
}
…

Configuring log4j grails

I'm new in grails and I need to configuring loggind for my application. I started to configure log4j in my grails application and I got this error described below and I don't know what makes this:
log4j:ERROR Property missing when configuring log4j: Environment
Someone know what causes it? Below is my code!
def myappLogLevel = "DEBUG"
def myappLogPattern = "%d{yyyy-MM-dd/HH:mm:ss.SSS} [%t] %x %-5p %c{2} -
%m%n"
def log4jFileName = System.properties.getProperty('catalina.base', '.') +
"/logs/myapp.log"
environments {
development {
log4jFileName = "logs/myapp.log"
}
test {
log4jFileName = "logs/myapp.log"
}
log4j = {
def logLayoutPattern = new PatternLayout(myappLogPattern)
appenders {
appender new DailyRollingFileAppender(name: "myappLog",
threshold: Level.toLevel(myappLogLevel),
file: log4jFileName,
datePattern: "'.'yyyy-MM-dd", //Rollover at midnight each day.
layout: logLayoutPattern
)
if (Environment.current == Environment.DEVELOPMENT ||
Environment.current == Environment.TEST) {
appender new ConsoleAppender(name: "console",
threshold: Level.toLevel(myappLogLevel),
layout: logLayoutPattern
)
}
}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate
'org.springframework',
'org.hibernate.cache',
'org.hibernate',
'net.sf.ehcache.hibernate'
'grails'
'groovyx.net.http'
warn 'org.springframework',
'org.hibernate',
'grails.plugins.springsecurity',
'groovyx.net.http'
debug 'grails.plugins.springsecurity',
'grails.plugin.springcache',
'com.myapp',
'org.codehaus.groovy.grails.plugins.springsecurity',
'org.apache.http.headers',
'grails.app.services',
'grails.app.domain',
'grails.app.controllers',
'grails.plugin.databasemigration',
'liquibase'
List<String> loggers = []
loggers.add('myappLog')
if (Environment.current.name == "development" ||
Environment.current.name == "test") {
loggers.add('console')
}
root {
error loggers as String[]
additivity = true
}
}
You may be able to use the log config DSL construction to branch on environment without explicitly accessing Environment.
environments {
development { loggers.add('console') }
test { loggers.add('console') }
}
That said, I am not sure what you are trying to accomplish with the rest of the configuration, so there may be a more elegant way to handle things.

Debug statements aren't showing src/groovy classes

I have the following in my config.groovy
// default for all environments
log4j = { root ->
appenders {
rollingFile name:'stacktrace', file:"${logDirectory}/app_stack.log".toString(), maxFileSize:'100KB'
}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework', 'org.hibernate'
debug 'com.my.code'
root.level = org.apache.log4j.Level.INFO
}
I get debug statements printed to the logs for all classes except for my groovy files placed in package com.my.code I don't get the debug statements printed. Only the info statements are being printed to the log.
Here is an example for one of the groovy classes in src/groovy
#Log4j
class SomeTest {
def someMethod() {
log.info("This will print")
log.debug("This will not print")
println log.isDebugEnabled() //prints false
print log.isInfoEnabled() //prints true
}
}
Question
How can I turn on debugging for all class under package com.my.code ? I'm on grails 2.3.5. When I change root.level to org.apache.log4j.Level.DEBUG then the debug statements do show up but that turns on DEBUG for ALL other classes as well
Here's a configuration that will log all code in packages com.my.code at the DEBUG level, and all other packages at the ERROR level.
The logs will be sent to the console and a file named appLog.txt.
log4j = {
appenders {
def logPattern = '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{2} - %m%n'
console name: 'consoleAppender', layout: pattern(conversionPattern: logPattern)
file name: "fileAppender", file: "appLog.txt"
}
root {
// define the root logger's level and appenders, these will be inherited by all other loggers
error 'consoleAppender', 'fileAppender'
}
def appNamespaces = [
'com.my.code',
'grails.app.conf.com.my.code',
'grails.app.filters.com.my.code',
'grails.app.taglib.com.my.code',
'grails.app.services.com.my.code',
'grails.app.controllers.com.my.code',
'grails.app.domain.com.my.code'
]
appNamespaces.each { debug it }
}
In grails 2.x apps I used next format (with regards to your config):
debug rollingFile 'com.my.code'
Furthermore, if you need to set different log level for a bunch of packages:
debug rollingFile: ['com.example','com.otherpackage']

Grails Hibernate - how to keep data in hibernate cache still my grails application restarted

I created a new simple project.
I created a Book domain and mentioned cache=true in mapping.
I am setting some data by BootStrap.groovy configuration.
I added some print statements in BootStrap.groovy to check the data is added or not.
I put Hibernate second level cache is true.
I run application, it printed in console that "added this many records".
But the date not showing in my grid.
I tried with postgresSQL, with same data. My grid showing records. Just change in DataSource.groovy only.
Please help me, what I am missing
My Default hibernate configuration in DataSource.groovy
dataSource {
pooled = true
jmxExport = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
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
}
In other words, how to keep data in hibernate cache still my grails application restarted.
**
**

Grails logging all to one file

I have an issue when i war my grails project to deploy on my production server there is a limitation that i only log to /var/log/tomcat5/catalina.out. This means that i have to make every log including stacktrace write to that one file. I've tried following other examples and it just doesn't seem to work i still get the error "permission denied on stacktrace.log"
This is my log4j config
log4j = {
// Example of changing the log pattern for the default console
// appender:
//
appender.stacktractLog = "org.apache.log4j.FileAppender"
appender.'stacktraceLog.File'="/var/log/tomcat5/catalina.out"
appenders {
rollingFile name:'catalinaOut', maxFileSize:1024, fileName:"/var/log/tomcat5/catalina.out"
}
root {
error 'catalinaOut'
additivity = true
}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate'
warn 'org.mortbay.log'
}
Just modify your configuration:
log4j = {
// Example of changing the log pattern for the default console
// appender:
//
appenders {
rollingFile name:'catalinaOut', maxFileSize:1024, fileName:"/var/log/tomcat5/catalina.out"
file name: 'stacktrace', file: "/var/log/tomcat5/catalina.out", layout: pattern(conversionPattern: '%c{2} %m%n')
}
root {
error 'catalinaOut'
additivity = true
}
error stacktrace: "StackTrace"
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate'
warn 'org.mortbay.log'
}
Can't help with your current problem but I suggest you change the rollingFile properties. Current setting will only give a 1kb file that over writes it's self.
try:
rollingFile name:'catalinaOut', maxFileSize:${10*1024*1024},maxBackupIndex:100,fileName:"/var/log/tomcat5/catalina.out"
This will give you 100 10MB files or about a gig worth of logs.

Resources