Grails upgrade from 2 to 4 ,unable to fetch data from DB - grails

i am upgrading my grails 2 app to grails 4. versions are
Hibernate 5 , Grails 4.0.10 , JVM 8
my problem is i am unable to fetch data from db by using User.findByName(....) or any other findBy or get() .
it always says
org.springframework.dao.DataAccessResourceFailureException: Could not obtain current Hibernate Session; nested exception is org.hibernate.HibernateException: No Session found for current thread
at org.grails.orm.hibernate.GrailsHibernateTemplate.getSession(GrailsHibernateTemplate.java:335)
my hibernate config has
> hibernate :
> cache:
> use_second_level_cache : true
> use_query_cache : true
> provider_class : "net.sf.ehcache.hibernate.EhCacheProvider"
> region:
> factory_class : 'org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory'
> format_sql : false
> generate_statistics : false
>
> allow_update_outside_transaction: true
if I use #Transactional to the method ,then i'm able to fetch the data otherwise it fails.
is there any other way to fetch the data like in previous versions?

Related

Grails 3.3 execute H2 script command

I'm running a small, trivial Grails 3.3.0 application using a H2 file based database. For simple backup reasons I would like to dump the current database state to a file using the H2 specific SCRIPT command:
SCRIPT TO /path/to/backup/dir/tempoDb.sql;
Currently I am trying to execute the native SQL command like this.
User.withSession { session ->
NativeSQLQuerySpecification nativeSQLQuerySpecification = new NativeSQLQuerySpecification("SCRIPT TO /path/to/backup/dir/tempoDb.sql;", null, null)
session.executeNativeUpdate(nativeSQLQuerySpecification, new QueryParameters())
}
but this does not work.
You can autowire the dataSource and try to run your sql query using the connection obtained from datasource Without going through Hibernate. The dataSource bean is registered in the Grails Spring context and it is an instance of javax.sql.DataSource.
Here is an example of a Grails service that backup the current H2 database to the file system.
#ReadOnly
class BackupService {
DataSource dataSource
def backup() {
def sql = "SCRIPT DROP TO '${System.properties['java.io.tmpdir']}/backup.sql'"
Statement statement = dataSource.connection.createStatement()
boolean result = statement.execute(sql)
}
}

Grails 2.4 upgrade issues from 2.2 test event called at app startup

At application startup the eventTestPhasesStart event code in _events script is being called. The test classes referenced in the event code are not available when executing runapp which leads to classes not resolved errors at startup.
unable to resolve class org.codehaus.groovy.grails.test.spock.GrailsSpecTestType
unable to resolve class - org.codehaus.groovy.grails.test.junit4.JUnit4GrailsTestType
unable to resolve class org.codehaus.groovy.grails.test.runner.phase.IntegrationTestPhaseConfigurer
This code also fails to run in forked mode which has forced us to turn forked mode off to run the integration tests which means we cannot use the debugger to debug tests as Grails 2.4 now requires.
The following is the event code:
eventTestPhasesStart = {phasesToRun ->
println "setting inmem phase"
phasesToRun << "inmem"
def inmemPhaseConfigurer = new IntegrationTestPhaseConfigurer(projectTestRunner.projectTestCompiler, projectLoader)
projectTestRunner.testFeatureDiscovery.configurers.inmem = inmemPhaseConfigurer
def inmemtestTypeName = "inmem"
def inmemtestDirectory = "inmem"
def inmemtestMode = new GrailsTestMode(autowire: true, wrapInTransaction: true, wrapInRequestEnvironment: true)
inmemTestTypes = []
inmemTestTypes << (new GrailsSpecTestType(inmemtestTypeName+"Spock", inmemtestDirectory, inmemtestMode))
inmemTestTypes << (new JUnit4GrailsTestType(inmemtestTypeName+"JUnit", inmemtestDirectory, inmemtestMode))
projectTestRunner.testFeatureDiscovery.testExecutionContext.inmemTests = inmemTestTypes
}
When running in forked mode this event is again called when/where it shouldn't resulting in the dynamic properties such as projectTestRunner not being found.
Is there a way to prevent this script from being executed when it shouldn't?
thank you

404 error with scaffolding in Grails

I was trying to follow the step-by-step instructions in Grails In Action (http://www.manning.com/gsmith2/GiA2E_meap_ch01.pdf), and the scaffolding explained in section 1.5.1, Pg. 21-23 does not seem to be working for me.
I added the static scaffold = true in the QuoteController.groovy as suggested. Then did grails run-app, and when I head to localhost:8080/qotd/quote/list I get a 404 error (instead of the Figure 1.11 in the pdf) as follows:
HTTP Status 404 - /qotd/quote/list
type Status report
message /qotd/quote/list
description The requested resource is not available.
Apache Tomcat/7.0.42
Here is the QuoteController.groovy:
package qotd
class QuoteController {
static scaffold = true
def index() {
redirect(action: "home")
}
def home() {
render "Real Programmers do not eat Quiche"
}
def random() {
def allQuotes = Quote.list()
def randomQuote
def n = allQuotes.size()
if (n > 0){
def randomIdx = new Random().nextInt(n)
randomQuote = allQuotes[randomIdx]
} else{
String str = "Real Programmers Don't Eat Quiche" + n
randomQuote = new Quote(author: "Anonymous",
content: str)
}
[quote: randomQuote]
}
}
However, going to localhost:8080/qotd/quote/create works fine (matches with Figure 1.12 in the pdf), and I am able to create a new quote.
The versions I am using are:
App version: 0.1
Grails version: 2.3.1
Groovy version: 2.1.8
JVM version: 1.7.0_45
Is this a bug in Grails or I am missing something?
I am new to Groovy and Grails, and any help would be highly appreciated.
Thank you!
The list action has been removed for some reason. Use index instead.
There are more changes now with version 2.4.2.
The following url explains how scaffolding has been moved to the plugin model:
http://grails.org/doc/latest/guide/scaffolding.html
"As of Grails 2.3, the scaffolding feature has been moved to a plugin. By default this is configured for installation in new applications, but if you are upgrading from a previous version of Grails you will need to add the following configuration to your BuildConfig.groovy file..."
So, inside the plugins { } section add this line:
compile ":scaffolding:2.0.0"
Also, use the action 'create' to force data into your database if it's still empty.
For example:
localhost:8080/myapp/mycont/create
Then try to see if you can load it with:
localhost:8080/myapp/mycont/show/1
Replace:
myapp --> with your application name (used in 'grails create-app')
mycont --> your controller name (used in 'grails create-controller')

Grails + CXF + secureServiceFactory

When I try run this script to secure my web services on Grails / CXF client I get
"Cannot invoke method getInInterceptors() on null object" on secureServiceFactory
Does secureServiceFactory need to be set somewhere else?
Any ideas:
Code :
class BootStrap {
def secureServiceFactory
def init = { servletContext ->
Map<String, Object> inProps = [:]
inProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
inProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
Map<QName, Validator> validatorMap = new HashMap<QName, Validator>();
validatorMap.put(WSSecurityEngine.USERNAME_TOKEN, new UsernameTokenValidator() {
#Override
protected void verifyPlaintextPassword(org.apache.ws.security.message.token.UsernameToken usernameToken, org.apache.ws.security.handler.RequestData data)
throws org.apache.ws.security.WSSecurityException {
if(data.username == "wsuser" && usernameToken.password == "secret") {
println "username and password are correct!"
} else {
println "username and password are NOT correct..."
throw new WSSecurityException("user and/or password mismatch")
}
}
});
inProps.put(WSS4JInInterceptor.VALIDATOR_MAP, validatorMap);
secureServiceFactory.getInInterceptors().add(new WSS4JInInterceptor(inProps))
}
Not sure this is a total answer, but, I receive the same errors and I understand that the cxf plugin is meant to wire up service factories that will match the name of your exposed service. I have verified that out of the box, running the grails-cxf plugin using grails run-app the application works. however, by executing grails war on the project creates a war that when deployed to tc server [vfabric-tc-server-developer-2.9.4.RELEASE] tomcat 7 [tomcat-7.0.47.A.RELEASE], this error occurs.
It is also useful to note that out of the box, as the plugin author has noted in other references [http://www.christianoestreich.com/2012/04/grails-cxf-interceptor-injection/] the generated war won't work unless you change test('org.apache.ws.security:wss4j:1.6.7') to compile('org.apache.ws.security:wss4j:1.6.7') and I note that I was unable to make that work, I had to use compile('org.apache.ws.security:wss4j:1.6.9')
Unfortunately, after surpassing this, I run into a third error when deploying the war that doesn't occur in grails run-app:
22-Aug-2014 11:46:05.062 SEVERE [tomcat-http--1] org.apache.catalina.core.StandardWrapperValve.invoke Allocate exception for servlet CxfServlet
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cxf' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:273)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:979)
at org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:75)
I'll continue looking at it, but perhaps this war isn't meant to really deploy, but is more meant just for development of the plugin itself. however, if that is the case, it would still be better to work in TC because then we can leverage the code in our own projects with confidence.

Grails Data Migration Rollback

Hi I'm trying something very simple with Grails domain class. I am adding to my class a field and I want to use data migration plugin to rollback once so that the field I added gets removed.
First I created the initial change log as followed:
grails dbm-generate-changelog changelog.groovy
Then I added the following to the Config.groovy file:
grails.plugin.databasemigration.updateOnStart = true
grails.plugin.databasemigration.updateOnStartFileNames = ['changelog.groovy']
Then I added an extra field to my domain class and performed the following:
grails dbm-gorm-diff added-new-field.groovy --add
I ran the app (grails run-app), after which I perform a:
grails dbm-rollback-count 1
After which I run the app again using: grails run-app
but the field is still there.
I am using MySQL for db. Here's how I have it configured in DataSource.groovy:
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = 'update'
url = "jdbc:mysql://localhost/dashboard?useUnicode=yes&characterEncoding=UTF-8"
username ="foo"
password = "bar"
}
}
..... and on.....
Can someone guide me to how the rollback is performed?
I am using:
Grails 2.2.2
database-migration:1.3.2
When grails dbm-rollback-count 1 is performed It makes changes only to the database using the groovy changelog filed by taking the very last change set in the log and undoing that. If you run your app again the following lines in Groovy.config will put those fields back into the tables:
grails.plugin.databasemigration.updateOnStart = true grails.plugin.databasemigration.updateOnStartFileNames = ['changelog.groovy']
I'm not really sure what purpose dbm-rollback-count servers in my case but that it what it did.
I was thinking that performing a rollback will not only remove the last changeset (added field) in the database but also remove that field variable from the domain class as well.

Resources