grails incompatible with neo4j - grails

I am trying to develop a sample application using grails and neo4j. I am using grails 3.0.8. I have installed the neo4j plugin and have followed the instructions as mentioned in the documentation. I have updated application.yml to include neo4j credentials. My application.yml looks something like this.
---
grails:
profile: web
codegen:
defaultPackage: sftwitter
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
groovy:
template:
check-template-location: false
---
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
types:
all: '*/*'
atom: application/atom+xml
css: text/css
csv: text/csv
form: application/x-www-form-urlencoded
html:
- text/html
- application/xhtml+xml
js: text/javascript
json:
- application/json
- text/json
multipartForm: multipart/form-data
pdf: application/pdf
rss: application/rss+xml
text: text/plain
hal:
- application/hal+json
- application/hal+xml
xml:
- text/xml
- application/xml
urlmapping:
cache:
maxsize: 1000
controllers:
defaultScope: singleton
converters:
encoding: UTF-8
views:
default:
codec: html
gsp:
encoding: UTF-8
htmlcodec: xml
codecs:
expression: html
scriptlets: html
taglib: none
staticparts: none
---
grails:
neo4j:
type: rest
location: http://localhost:7474/db/data/
username: neo4j
password: welcome123
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
endpoints:
jmx:
unique-names: true
dataSource:
pooled: true
jmxExport: true
driverClassName: org.h2.Driver
username: sa
password:
environments:
development:
dataSource:
username: neo4j
password: welcome123
dbCreate: create-drop
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:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
The code executes fine, but when I try to create the instance of a domain I get an error like this.
ERROR org.grails.web.errors.GrailsExceptionResolver - IllegalStateException occurred when processing request: [GET] /person/index
Method on class [neo4j.Person] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.. Stacktrace follows:
java.lang.reflect.InvocationTargetException: null
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_60]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_60]
Caused by: java.lang.IllegalStateException: Method on class [neo4j.Person] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
at neo4j.PersonController.index(PersonController.groovy:13) ~[main/:na]
at grails.transaction.GrailsTransactionTemplate$2.doInTransaction(GrailsTransactionTemplate.groovy:93) ~[grails-core-3.0.8.jar:3.0.8]
at grails.transaction.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:90) ~[grails-core-3.0.8.jar:3.0.8]
... 3 common frames omitted
I have done this configuration completely as per the documentation, then why am I getting this error. Is it that the newer versions of grails are having compatibility issues with neo4j or is it that I have made some mistake in the configuration.

Related

Set Request Validator of API Gateway by serverless

I want to set Request Validator of API Gateway by serverless. I tried two different settings for the Request Validator. But, both methods have failed. I have summarized what I did, so please let me know if there is something wrong.
I write the API specification in swagger(OAS3.0). Therefore I tried to realize the setting of Request Validator using OAS extension. After I did sls deploy using below swagger.yaml and serverless.yml, None of the validate patterns described in x-amazon-apigateway-request-validators were added to the Request Validator options.
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-request-validator.html
swagger.yaml is below:
openapi: 3.0.0
info:
description: xxx
version: '0.1'
title: xxx API
x-amazon-apigateway-request-validators:
body-only:
validateRequestBody: true,
validateRequestParameters: false
except-body:
validateRequestBody: false,
validateRequestParameters: true
all:
validateRequestBody: true,
validateRequestParameters: true
tags:
- name: auth
description: xxx
paths:
/login:
post:
tags:
- auth
summary: xxx
description: ''
x-amazon-apigateway-request-validator: all
responses:
'200':
description: success
content:
application/json:
schema:
$ref: '#/components/schemas/AuthResponse'
'400':
description: fail
content:
application/json
'401':
description: fail
content:
application/json
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/AuthRequest'
required: true
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
uri: "arn:aws:apigateway:ap-northeast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxx:function:xxx-api-dev-login/invocations"
passthroughBehavior: "when_no_match"
httpMethod: "POST"
contentHandling: "CONVERT_TO_TEXT"
type: "aws_proxy"
My serverless.yml is below:
resources:
Resources:
RestApi :
Type : AWS::ApiGateway::RestApi
Properties :
Body : ${file(./swagger.yaml)}
LoginApiToInvokeLambda:
Type: AWS::Lambda::Permission
DependsOn: LoginLambdaFunction
Properties:
FunctionName: xxx-ext-api-dev-login
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
I tried to realize the setting of Request Validator using AWS::ApiGateway::RequestValidator. After I did sls deploy using above swagger.yaml and below serverless.yml, the all described in RequestValidatorAll in severless.yml were added to the Request Validator options. But the default value of Request Validator was still NONE.
resources:
Resources:
RestApi :
Type : AWS::ApiGateway::RestApi
Properties :
Body : ${file(./swagger.yaml)}
LoginApiToInvokeLambda:
Type: AWS::Lambda::Permission
DependsOn: LoginLambdaFunction
Properties:
FunctionName: xxx-ext-api-dev-login
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
RequestValidatorAll:
Type: AWS::ApiGateway::RequestValidator
Properties:
Name: all
RestApiId:
Ref: RestApi
ValidateRequestBody: true
ValidateRequestParameters: true
You need to remove the commas in your YAML.
i.e
x-amazon-apigateway-request-validators:
body-only:
validateRequestBody: true,
validateRequestParameters: false
except-body:
validateRequestBody: false,
validateRequestParameters: true
all:
validateRequestBody: true,
validateRequestParameters: true
should be
x-amazon-apigateway-request-validators:
body-only:
validateRequestBody: true
validateRequestParameters: false
except-body:
validateRequestBody: false
validateRequestParameters: true
all:
validateRequestBody: true
validateRequestParameters: true
Once you do this the YAML will be valid and it should work.

Grails 3.2.6 with spring security. In memory h2 database is not created when saving users

I didn't find a solution from other postings although this seems a problems that others have encountered.
This is my application.yml
---
grails:
profile: web-plugin
codegen:
defaultPackage: bioprofile
spring:
transactionManagement:
proxies: false
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
main:
banner-mode: "off"
groovy:
template:
check-template-location: false
# Spring Actuator Endpoints are Disabled by Default
endpoints:
enabled: false
jmx:
enabled: true
---
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
types:
all: '*/*'
atom: application/atom+xml
css: text/css
csv: text/csv
form: application/x-www-form-urlencoded
html:
- text/html
- application/xhtml+xml
js: text/javascript
json:
- application/json
- text/json
multipartForm: multipart/form-data
pdf: application/pdf
rss: application/rss+xml
text: text/plain
hal:
- application/hal+json
- application/hal+xml
xml:
- text/xml
- application/xml
urlmapping:
cache:
maxsize: 1000
controllers:
defaultScope: singleton
converters:
encoding: UTF-8
views:
default:
codec: html
gsp:
encoding: UTF-8
htmlcodec: xml
codecs:
expression: html
scriptlets: html
taglib: none
staticparts: none
endpoints:
jmx:
unique-names: true
---
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
dataSources:
dataSource:
pooled: true
jmxExport: true
driverClassName: org.h2.Driver
username: sa
password:
dbCreate: create-drop
dialect : com.hp.opr.hibernate.dialect.H2Dialect
url: jdbc:h2:mem:blogDB;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
master:
pooled: true
jmxExport: true
driverClassName: org.h2.Driver
username: sa
password:
dbCreate: create-drop
url: jdbc:h2:mem:masterDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
but when the application starts and in the bootstrap I try to add some users:
User admin = new User(username: 'admin', password: 'password')
admin.save(flush: true)
User user = new User(username: 'user', password: 'user')
user.save(flsuh:true)
Role adminRole = new Role(authority: Role.ROLE_ADMIN)
adminRole.save(flush:true)
Role userRole = new Role(authority: Role.ROLE_USER)
userRole.save(flush:true)
UserRole.create(admin, adminRole)
UserRole.create(admin, userRole)
UserRole.create(user, userRole)
no database is created.
However if I open the console from the url: http://localhost:8080/dbconsole than a database is created.
Any idea why ?
You are using the in-memory configuration of H2 in your grails config, so no database file is created. But when you open the dbconsole, there problably is a connection string with a file instead of in-memory configuration, so a db file is created. Change the config in the dbconsole configuration.

Grails multiple datasource, not working when trying to save a new Instance into selected datasource

I'm having this issue with a simple configuration when working with multiple datasources and I'm trying to save a new instance into a specific datasource
my datasources:
dataSources:
dataSource:
pooled: true
jmxExport: true
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
driverClassName: com.mysql.jdbc.Driver
username: root
password: Choice2016
dominio1:
pooled: true
jmxExport: true
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
driverClassName: com.mysql.jdbc.Driver
username: root
password: Choice2016
dominio2:
pooled: true
jmxExport: true
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
driverClassName: com.mysql.jdbc.Driver
username: root
password: Choice2016
my domain
class Nxtt_reports {
Boolean favorite
static hasMany = [nxtt_report_histories: Nxtt_report_history, nxtt_user_reports: Nxtt_user_reports, nxtt_report_snapshots: Nxtt_report_snapshot]
static constraints = {
}
static mapping = {
datasource 'ALL'
}
}
when I do this,
def nxtt = Nxtt_reports.class
println(nxtt.dominio1.list())
I can list data in the domain I want, but if I do this
def nxtt = Nxtt_reports.class.newInstance()
nxtt.favorite = 0
nxtt.dominio2.save()
I'm getting this
No such property: dominio2 for class: nexttreport.server.Nxtt_reports. Stacktrace follows:
groovy.lang.MissingPropertyException: No such property: dominio2 for class: nexttreport.server.Nxtt_reports
using:
| Grails Version: 3.1.1
| Groovy Version: 2.4.5
| JVM Version: 1.8.0_65
edit
environments:
development:
dataSources:
dataSource:
dbCreate: update
url: jdbc:mysql://192.168.1.24:3306/nexttreport?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
dominio1:
dbCreate: update
url: jdbc:mysql://192.168.1.24:3306/dominio1?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
dominio2:
dbCreate: update
url: jdbc:mysql://192.168.1.24:3306/dominio2?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
I have a bit of trouble reading a and understanding your code, because you are not following normal Java/Groovy conventions.
Firstly I would recommend using normal CamelCase and no underscores in your class names, so use NxxtReports.
Secondly, why not do NxxtReports.domino1.list() ?
list() is a static method on the NxxtReports, so call it like that.
Thirdly and I think most importantly, use the normal Java/Groovy way of instantiating an Object, so do
def nxxt = new NxxtReport()
nxxt.favorite = 0
nxxt.domino2.save()
I suspect that the extra Grails methods on a DomainClass instance are not correctly added by calling newInstance() on the class variable.
I don't have a real computer at hand (on mobile now) so I can't check my code, but I think using normal Java/Groovy conventions will help a lot.

Grails returns server error after creating domain class

I am a newbie to Grails and I am stuck with the GORM part. I tried to follow tutorial on this site http://grails.asia/grails-tutorial-for-beginners-introduction-to-gorm about GORM and the first thing to do is create a domain class. However, after following the instructions there, I always received the error showed below.
My controller for inserting record
package nba
class PlayerController {
def index() {
//render "It's game time! NBA Game time"
Player p = new Player()
p.fname = "Lebron"
p.lname = "James"
p.position = "Small Forward"
p.age = 30
}
}
. What is the problem with this. What am I lacking? Please help.
---
grails:
profile: web
codegen:
defaultPackage: myapp
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
groovy:
template:
check-template-location: false
---
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
types:
all: '*/*'
atom: application/atom+xml
css: text/css
csv: text/csv
form: application/x-www-form-urlencoded
html:
- text/html
- application/xhtml+xml
js: text/javascript
json:
- application/json
- text/json
multipartForm: multipart/form-data
pdf: application/pdf
rss: application/rss+xml
text: text/plain
hal:
- application/hal+json
- application/hal+xml
xml:
- text/xml
- application/xml
urlmapping:
cache:
maxsize: 1000
controllers:
defaultScope: singleton
converters:
encoding: UTF-8
views:
default:
codec: html
gsp:
encoding: UTF-8
htmlcodec: xml
codecs:
expression: html
scriptlets: html
taglib: none
staticparts: none
---
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
endpoints:
jmx:
unique-names: true
dataSource:
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
environments:
development:
dataSource:
dbCreate: create-drop
url: jdbc:mysql://localhost/grails_db
username: root
password:
test:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost/grails_db
production:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost/grails_db
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
Sorry I didn't see your comment:
Firstly to expand on my comment above and explain grails controller behaviour better. I will stick with render you have other choices.
When declaring an action in your controller:
so lets say we have
class TestController {
def hello() { }
}
You may or may not have a domainClass bound to this example TestController, if you did the domain class would be {package}/Test.groovy {matching the naming construct of controller}.
In this example we have no domain controller and above action will show something as long as you create a folder under views called
test/hello.gsp
So in that test folder you create hello.gsp and put in there some html..
If you didn't have
test/hello.gsp
Then in your controller you would have to define what to render.
class TestController {
def hello() {
// render 'some text'
//render template: '/path/to/template', model: [params:params]
render view: '/path/to/gsp', model: [params:params]
}
}
You then state:
This is how I got the error, when I created a domain class player and
then put the field names (fname, lname, position, age), it was
successful, the table player is created in the database together with
field names but when I restarted running the server, the table was
deleted automatically and the running back the server returns error.
What is the problem with that?
Firstly you need to then ask yourself, did you configure/install some DB in order to see it working initially?
Grails provides you with an inbuilt DB that resides in your memory as part of its default app creation.In short a fresh DB is triggered on each run app.
E2A
Pay attention to dbCreate line:
create-drop : Creates tables on application startup and drops then when shutdown
create : Creates all tables at app start up
update : Updates existing tables (will not attempt to create any. that's down to you)
http://grails.github.io/grails-doc/3.0.x/guide/conf.html
In development mode dbCreate is by default set to "create-drop", but
at some point in development (and certainly once you go to production)
you'll need to stop dropping and re-creating the database every time
you start up your server.

Multiple databases support in Symfony

I am using Propel as my DAL for my Symfony project. I can't seem to get my application to work across two or more databases.
Here's my schema.yml:
db1:
lkp_User:
pk_User: { type: integer, required: true, primaryKey: true, autoIncrement: true }
UserName: { type: varchar(45), required: true }
Password: longvarchar
_uniques:
Unique: [ UserName ]
db2:
tesco:
Id: { type: integer, required: true, primaryKey: true, autoIncrement: true }
Name: { type: varchar(45), required: true }
Description: longvarchar
And here's the databases.yml:
dev:
db1:
param:
classname: DebugPDO
test:
db1:
param:
classname: DebugPDO
all:
db1:
class: sfPropelDatabase
param:
classname: PropelPDO
dsn: 'mysql:dbname=bpodb;host=localhost' #where the db is located
username: root
password: #pass
encoding: utf8
persistent: true
pooling: true
db2:
class: sfPropelDatabase
param:
classname: PropelPDO
dsn: 'mysql:dbname=mystore2;host=localhost' #where the db is located
username: root
password: #pass
encoding: utf8
persistent: true
pooling: true
When I call php symfony propel-build-model, only db1 is generated, db2 is not.
Any idea how to fix this problem?
I got this issue working! The most important thing is you must name your schema according to %dbname%.schema.yml. In this way Symfony will be able to assign the ymls to the correct database.
Also when running the task you should specify the connection for example:
symfony propel:build-all-load --connection=my_connection
This worked for me, hope it helps.
You can also use Propel::getConnection('db2') to manually retrieve a connection.
Just have in mind that what you call "db1", "db2" are the connection names. You can have several connections to a same database with various login/permissions (like read only etc.).
It's very good for testing purpose: you can do it with the same connection name with a different database. No way to crash your production database with that :)

Resources