An issue with deploying grails war file - grails

Using grails 2.0.2 I created a war file for my application and placed in the web apps directory of a jetty instance. I get this error. The application works fine in local testing with grails run-app. What am I doing wrong?
2012-03-01 18:12:14.151:WARN::Failed startup of context o.e.j.w.WebAppContext{/pokermetrics,[file:/tmp/jetty-0.0.0.0-8080-pokermetrics.war-_pokermetrics-any-/webinf/, jar:file:/home/j2play/j2play/jetty-hightide-7.2.2.v20101205/webapps/pokermetrics.war!/]},/home/j2play/j2play/jetty-hightide-7.2.2.v20101205/webapps/pokermetrics.war
org.springframework.beans.factory.BeanCreationException: 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': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Unsupported connection setting "SHUTDOWN" [90113-147])
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.codehaus.groovy.grails.commons.spring.ReloadAwareAutowireCapableBeanFactory.doCreateBean(ReloadAwareAutowireCapableBeanFactory.java:126)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:707)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:449)
at org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration.getApplicationContext(DefaultRuntimeSpringConfiguration.java:153)
at org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.configure(GrailsRuntimeConfigurator.java:170)
at org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.configure(GrailsRuntimeConfigurator.java:127)
at org.codehaus.groovy.grails.web.context.GrailsConfigUtils.configureWebApplicationContext(GrailsConfigUtils.java:121)
at org.codehaus.groovy.grails.web.context.GrailsContextLoader.initWebApplicationContext(GrailsContextLoader.java:104)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:641)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:228)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1181)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:584)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:496)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:180)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:481)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:137)
"2012_03_01.stderrout.log" 709L, 79353
Data source.groovy:
dataSource {
pooled = true
driverClassName = "org.h2.Driver"
username = "XXXX"
password = "XXXX"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
url = "jdbc:h2:mem:devDb"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:file:prodDb;shutdown=true"
}
}
}

That looks like an older pre-2.0 application that was using HSQLDB and was upgraded to H2. HSQLDB and H2 configurations are fairly similar, but not all JDBC url parameters are supported in both. Here's the production block that you'd get in a new 2.0.x application:
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:prodDb;MVCC=TRUE"
properties {
maxActive = -1
minEvictableIdleTimeMillis=1800000
timeBetweenEvictionRunsMillis=1800000
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=true
validationQuery="SELECT 1"
}
}
}
But you'll probably want to switch to a more robust database at some point, e.g. MySQL/PostgreSQL/Oracle/etc.

Related

NullPointerException : Initialization of bean failed

I am getting following error when I execute grails run-app, I am trying to run my grails application locally but unable to do so
Following is the error from Stacktrace
Stacktrace
2017-01-25T06:01:32.640+05:00 uptime="38155", level="ERROR", class="org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener", thread="localhost-startStop-1:", message="Error initializing the application: Error creating bean with name 'samlIDPDiscovery': Unsatisfied dependency expressed through method 'setSamlEntryPoint' parameter 0: Error creating bean with name 'samlEntryPoint': Unsatisfied dependency expressed through method 'setContextProvider' parameter 0: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'samlEntryPoint': Unsatisfied dependency expressed through method 'setContextProvider' parameter 0: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException"
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'samlIDPDiscovery': Unsatisfied dependency expressed through method 'setSamlEntryPoint' parameter 0: Error creating bean with name 'samlEntryPoint': Unsatisfied dependency expressed through method 'setContextProvider' parameter 0: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'samlEntryPoint': Unsatisfied dependency expressed through method 'setContextProvider' parameter 0: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'samlEntryPoint': Unsatisfied dependency expressed through method 'setContextProvider' parameter 0: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException
... 4 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextProvider': Cannot resolve reference to bean 'metadataResolver' while setting bean property 'metadataResolver'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException
... 4 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metadataResolver': Initialization of bean failed; nested exception is java.lang.NullPointerException
... 4 more
Caused by: java.lang.NullPointerException
... 4 more
Config.groovy
security {
saml {
userAttributeMappings = ['firstName': 'FirstName', 'lastName': 'LastName', 'email': 'EmailAddress']
userGroupToRoleMapping = [:]
active = true
afterLoginUrl = '/'
afterLogoutUrl = '/'
loginFormUrl = '/saml/login'
userGroupAttribute = "memberOf"
responseSkew = 60
idpSelectionPath = '/'
autoCreate {
active = true
key = 'username'
assignAuthorities = true
}
metadata {
defaultIdp = 'http://idp.ssocircle.com'
url = '/saml/metadata'
//default idp info
idp{
file = 'security/idp.xml'
alias = 'http://idp.ssocircle.com'
}
sp {
file = 'security/sp.xml'
alias = 'jbilling'
defaults{
local = true
alias = 'jbilling'
signingKey = 'ping'
encryptionKey = 'ping'
tlsKey = 'ping'
requireArtifactResolveSigned = false
requireLogoutRequestSigned = false
requireLogoutResponseSigned = false
idpDiscoveryEnabled = true
}
}
}
keyManager {
storeFile = 'classpath:security/keystore.jks'
storePass = 'nalle123'
passwords = [ ping: 'ping123' ]
defaultKey = 'ping'
}
}
}
resources.groovy
def conf = SpringSecurityUtils.securityConfig
if (!conf || !conf.active) { return }
SpringSecurityUtils.loadSecondaryConfig 'SamlSecurityConfig'
conf = SpringSecurityUtils.securityConfig
if (!conf.saml.active) { return }
println 'Configuring Spring Security SAML ...'
//Due to Spring DSL limitations, need to import these beans as XML definitions
def beansFile = "classpath:security/springSecuritySamlBeans.xml"
delegate.importBeans beansFile
xmlns context:"http://www.springframework.org/schema/context"
context.'annotation-config'()
context.'component-scan'('base-package': "org.springframework.security.saml")
SpringSecurityUtils.registerProvider 'samlAuthenticationProvider'
SpringSecurityUtils.registerLogoutHandler 'successLogoutHandler'
SpringSecurityUtils.registerLogoutHandler 'logoutHandler'
successRedirectHandler(SavedRequestAwareAuthenticationSuccessHandler) {
alwaysUseDefaultTargetUrl = conf.saml.alwaysUseAfterLoginUrl ?: false
defaultTargetUrl = conf.saml.afterLoginUrl
}
successLogoutHandler(SimpleUrlLogoutSuccessHandler) {
defaultTargetUrl = conf.saml.afterLogoutUrl
}
samlLogger(SAMLDefaultLogger)
keyManager(JKSKeyManager,
conf.saml.keyManager.storeFile, conf.saml.keyManager.storePass, conf.saml.keyManager.passwords, conf.saml.keyManager.defaultKey)
samlEntryPoint(SAMLEntryPoint) {
println "Entry point process url is ${conf.saml.loginFormUrl}"
filterProcessesUrl = conf.saml.loginFormUrl // '/saml/login'
defaultProfileOptions = ref('webProfileOptions')
}
webProfileOptions(WebSSOProfileOptions) {
includeScoping = false
}
// metadataFilter(MetadataDisplayFilter) {
// println "metadataFilter process url: ${conf.saml.metadata.url }"
// filterProcessesUrl = conf.saml.metadata.url //'/saml/metadata'
// }
//
metadataGenerator(MetadataGenerator) {
includeDiscoveryExtension = true
}
metadataGeneratorFilter(MetadataGeneratorFilter, ref('metadataGenerator'))
log.debug "Defining the default idp metadata provider... "
def idpResource
def idpFile = conf.saml.metadata.idp.file
if(idpFile){
idpResource = new ClassPathResource(idpFile)
defaultIdpMetadata(ExtendedMetadataDelegate) { extMetaDataDelegateBean ->
idpMetadataProvider(FilesystemMetadataProvider) { bean ->
bean.constructorArgs = [idpResource.getFile()]
parserPool = ref('parserPool')
}
extMetaDataDelegateBean.constructorArgs = [ref('idpMetadataProvider')]
}
}
def spFile = conf.saml.metadata.sp.file
if (spFile) {
def spResource = new ClassPathResource(spFile)
spMetadata(ExtendedMetadataDelegate) { spMetadataBean ->
spMetadataProvider(FilesystemMetadataProvider) { spMetadataProviderBean ->
spMetadataProviderBean.constructorArgs = [spResource.getFile()]
parserPool = ref('parserPool')
}
def spDefaults = conf.saml.metadata.sp.defaults
spMetadataDefaults(ExtendedMetadata) { extMetadata ->
local = spDefaults.local
alias = spDefaults.alias
signingKey = spDefaults.signingKey
encryptionKey = spDefaults.encryptionKey
tlsKey = spDefaults.tlsKey
requireArtifactResolveSigned = spDefaults.requireArtifactResolveSigned
requireLogoutRequestSigned = spDefaults.requireLogoutRequestSigned
requireLogoutResponseSigned = spDefaults.requireLogoutResponseSigned
idpDiscoveryEnabled = spDefaults.idpDiscoveryEnabled
}
spMetadataBean.constructorArgs = [ref('spMetadataProvider'), ref('spMetadataDefaults')]
}
}
metadata(CachingMetadataManager,[ref('spMetadata'), ref('defaultIdpMetadata')]){
hostedSPName = conf.saml.metadata.sp?."alias"
defaultIDP = conf.saml.metadata.defaultIdp
}
samlUserDetailsService(SpringSamlUserDetailsService) {
grailsApplication = ref('grailsApplication')
authorityClassName = conf.authority.className
authorityJoinClassName = conf.userLookup.authorityJoinClassName
authorityNameField = conf.authority.nameField
samlAutoCreateActive = conf.saml.autoCreate.active
samlAutoAssignAuthorities = conf.saml.autoCreate.assignAuthorities
samlAutoCreateKey = conf.saml.autoCreate.key
samlUserAttributeMappings = conf.saml.userAttributeMappings
samlUserGroupAttribute = conf.saml.userGroupAttribute
samlUserGroupToRoleMapping = conf.saml.userGroupToRoleMapping
userDomainClassName = conf.userLookup.userDomainClassName
}
samlAuthenticationProvider(GrailsSAMLAuthenticationProvider) {
userDetails = ref('samlUserDetailsService')
hokConsumer = ref('webSSOprofileConsumer')
}
metadataResolver(MetadataCredentialResolver,ref('metadata'),ref('keyManager')) {
useXmlMetadata = true
}
contextProvider(SAMLContextProviderImpl) {
metadataResolver = ref('metadataResolver')
}
samlProcessingFilter(SAMLProcessingFilter) {
authenticationManager = ref('authenticationManager')
authenticationSuccessHandler = ref('successRedirectHandler')
sessionAuthenticationStrategy = ref('sessionFixationProtectionStrategy')
authenticationFailureHandler = ref('authenticationFailureHandler')
}
authenticationFailureHandler(AjaxAwareAuthenticationFailureHandler) {
redirectStrategy = ref('redirectStrategy')
defaultFailureUrl = conf.failureHandler.defaultFailureUrl //'/login/authfail?login_error=1'
useForward = conf.failureHandler.useForward // false
ajaxAuthenticationFailureUrl = conf.failureHandler.ajaxAuthFailUrl // '/login/authfail?ajax=true'
exceptionMappings = conf.failureHandler.exceptionMappings // [:]
}
redirectStrategy(DefaultRedirectStrategy) {
contextRelative = conf.redirectStrategy.contextRelative // false
}
sessionFixationProtectionStrategy(SessionFixationProtectionStrategy)
logoutHandler(SecurityContextLogoutHandler) {
invalidateHttpSession = true
}
samlLogoutFilter(SAMLLogoutFilter,
ref('successLogoutHandler'), ref('logoutHandler'), ref('logoutHandler'))
samlLogoutProcessingFilter(SAMLLogoutProcessingFilter,
ref('successLogoutHandler'), ref('logoutHandler'))
webSSOprofileConsumer(WebSSOProfileConsumerImpl){
responseSkew = conf.saml.responseSkew
}
webSSOprofile(WebSSOProfileImpl)
ecpprofile(WebSSOProfileECPImpl)
logoutprofile(SingleLogoutProfileImpl)
postBinding(HTTPPostBinding, ref('parserPool'), ref('velocityEngine'))
redirectBinding(HTTPRedirectDeflateBinding, ref('parserPool'))
artifactBinding(HTTPArtifactBinding,
ref('parserPool'),
ref('velocityEngine'),
ref('artifactResolutionProfile')
)
artifactResolutionProfile(ArtifactResolutionProfileImpl, ref('httpClient')) {
processor = ref('soapProcessor')
}
httpClient(HttpClient)
soapProcessor(SAMLProcessorImpl, ref('soapBinding'))
soapBinding(HTTPSOAP11Binding, ref('parserPool'))
paosBinding(HTTPPAOS11Binding, ref('parserPool'))
bootStrap(SAMLBootstrap)
velocityEngine(VelocityFactory) { bean ->
bean.factoryMethod = "getEngine"
}
parserPool(BasicParserPool)
securityTagLib(SamlTagLib) {
springSecurityService = ref('samlSpringSecurityService')
webExpressionHandler = ref('webExpressionHandler')
webInvocationPrivilegeEvaluator = ref('webInvocationPrivilegeEvaluator')
}
samlSpringSecurityService(SamlSecurityService) {
config = conf
authenticationTrustResolver = ref('authenticationTrustResolver')
grailsApplication = ref('grailsApplication')
passwordEncoder = ref('passwordEncoder')
objectDefinitionSource = ref('objectDefinitionSource')
userDetailsService = ref('userDetailsService')
userCache = ref('userCache')
}
println '...finished configuring Spring Security SAML'
I have added my full stacktrace here http://pasted.co/97aa6cb4, please review and let me know if you find the problem
I can provide more details if you want, can anyone help why is this happening? and how to solve this?
Try specifying the first argument in the JKSKeyManager's constructor which is a org.springframework.core.io.Resource, the implementation that seems to fit best with your config value is a org.springframework.core.io.ClassPathResource.
cpResource(ClassPathResource, conf.saml.keyManager.storeFile )
keyManager(JKSKeyManager,
ref('cpResource'),
conf.saml.keyManager.storePass,
conf.saml.keyManager.passwords,
conf.saml.keyManager.defaultKey)

Grails IndexOutOfBoundsException

I have the following code in Grails:
public LibraryItem createLibraryItemWithValues(ProjectItem projectItem) {
def libraryitem = new LibraryItem ()
libraryitem.name = projectItem.name
libraryitem.itemtype = projectItem.itemtype.itemtype
libraryitem.description = projectItem.description
List<LibraryCategoryValue> libCatValues = new ArrayList<LibraryCategoryValue>();
for (def pcv : projectItem.categoryvalues) {
libCatValues.add(pcv.librarycategoryvalue);
}
if (libraryitem.id != null && !libraryitem.isAttached()) {
libraryitem.attach()
}
libCatValues.each{
it.addToLibraryitems(libraryitem)
}
return libraryitem.save()
}
The class LibraryCategoryValue
package ch.fhnw.accelerom.project.library
import ch.fhnw.accelerom.project.ItemType
import ch.fhnw.accelerom.project.TranslatableObject
class LibraryCategoryValue extends TranslatableObject {
SortedSet<LibraryItem> libraryitems
static belongsTo = [librarycategory:LibraryCategory]
static hasMany = [libraryitems: LibraryItem]
static constraints = {
}
}
My problem is, that I get the exception "IndexOutOfBoundsException" with the detailMessage "Index:1, Size 0" and suppressedExceptions "Collections$UnmodifiableRandomAccessList" with Value "size = 0" when I run this code in the service but there is no exception, when I run this code in the controller. The exception comes from the command it.addToLibraryitems(libraryitem), respektive, when I comment this line, than no exception occur. Can someone give me a hint, what the problem could be?
Thanks in advance.
Edit:
I now initialized libraryitems in the class with
SortedSet<LibraryItem> libraryitems = []
but now I get the following error when I start the application
ERROR context.GrailsContextLoader - 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 org.hibernate.InstantiationException: could not instantiate test objectch.fhnw.accelerom.project.library.LibraryCategoryValue
org.springframework.beans.factory.BeanCreationException: 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 org.hibernate.InstantiationException: could not instantiate test objectch.fhnw.accelerom.project.library.LibraryCategoryValue
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: 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 org.hibernate.InstantiationException: could not instantiate test objectch.fhnw.accelerom.project.library.LibraryCategoryValue
... 4 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.hibernate.InstantiationException: could not instantiate test objectch.fhnw.accelerom.project.library.LibraryCategoryValue
... 4 more
Caused by: org.hibernate.InstantiationException: could not instantiate test objectch.fhnw.accelerom.project.library.LibraryCategoryValue
... 4 more
Caused by: java.lang.reflect.InvocationTargetException
... 4 more
Caused by: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[]' with class 'java.util.ArrayList' to class 'java.util.SortedSet' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.SortedSet()
at ch.fhnw.accelerom.project.library.LibraryCategoryValue.<init>(LibraryCategoryValue.groovy:7)
... 4 more
Edit 2:
I also tried to initialize libraryitems with
SortedSet<LibraryItem> libraryitems = new TreeSet<LibraryItem>()
But then I'm back on the first exception "IndexOutOfBoundsException". I'm so wondering, why there is no problem, when this code is in the controller. What's the difference between a service and a controller in this case?
Try using a transactional service method:
import grails.transaction.Transactional
class LibraryService {
#Transactional
public LibraryItem createLibraryItemWithValues(ProjectItem projectItem) {
def libraryitem = new LibraryItem()
libraryitem.name = projectItem.name
libraryitem.itemtype = projectItem.itemtype.itemtype
libraryitem.description = projectItem.description
projectItem.categoryvalues*.librarycategoryvalue.each {
it.addToLibraryitems(libraryitem)
}
return libraryitem.save()
}
}
Since you're creating a new LibraryItem it's ID will always be null until you save it. In most cases you don't need to use attach(), so I removed all of that code.

Grails GORM default sort field which is also a field of a composite key

My Grails is version 2.5.0
I have two domain classes:
import org.apache.commons.lang.builder.HashCodeBuilder
class TemplateHeader implements Serializable {
int headerId
int ver
String templateName
String extraDescription
String serviceType
String createdBy
boolean isActive
String updatedBy
Date dateCreated
Date lastUpdated
static hasMany = [templateItems: TemplateItem]
static mapping = {
id composite: ['headerId', 'ver']
ver comment:''
templateName length: 40
serviceType length: 20
extraDescription length: 60
isActive defaultValue:false
templateItems sort:'itemNo', order:'asc'
}
static constraints = {
headerId unique: 'ver'
templateName nullable: false
serviceType nullable: false
}
boolean equals(other) {
if (!(other instanceof TemplateItem)) {
return false
}
other.id == id && other.ver == ver
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append id
builder.append ver
builder.toHashCode()
}
}
=======================================================
import org.apache.commons.lang.builder.HashCodeBuilder
class TemplateItem implements Serializable {
int itemNo
String itemName;
String unitName;
int unitPrice;
double defaultValue
boolean allowChange
String extraComment
String createdBy
String updatedBy
Date dateCreated
Date lastUpdated
static belongsTo = [templateHeader:TemplateHeader]
static mapping = {
id composite: [ 'templateHeader', 'itemNo']
itemNo comment:''
itemName length: 60
unitName length: 4
unitPrice comment:''
extraComment length: 60
defaultValue comment:''
allowChange comment:''
}
static constraints = {
itemName nullable: false
unitName nullable: false
extraComment nullable: true
defaultValue nullable: false
}
boolean equals(other) {
if (!(other instanceof TemplateItem)) {
return false
}
other.itemNo == itemNo && other.templateHeaderId == templateHeaderId
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append templateHeaderId
builder.append itemNo
builder.toHashCode()
}
}
When I run the grails application, it shows the below Exception when build tables:
|Running Grails application
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 org.codehaus.groovy.grails.exceptions.GrailsDomainException: property from sort clause not found: accudata_portal.TemplateItem.itemNo
org.springframework.beans.factory.BeanCreationException: 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 org.codehaus.groovy.grails.exceptions.GrailsDomainException: property from sort clause not found: accudata_portal.TemplateItem.itemNo
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: 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 org.codehaus.groovy.grails.exceptions.GrailsDomainException: property from sort clause not found: accudata_portal.TemplateItem.itemNo
... 4 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.codehaus.groovy.grails.exceptions.GrailsDomainException: property from sort clause not found: accudata_portal.TemplateItem.itemNo
... 4 more
Caused by: org.codehaus.groovy.grails.exceptions.GrailsDomainException: property from sort clause not found: accudata_portal.TemplateItem.itemNo
... 4 more
Error |
Forked Grails VM exited with error
Does somebody tell me how to fix it ? Thank you
I wonder why your'e not getting errors for fields that you are using in mapping closure and for which you have not defined any mappings like itemNo, unitPrice, defaultValue etc.
Also the equals condition in your TemapletHeader domain should be:
if (!(other instanceof TemplateHeader))
Now comming to your question, you are getting this error because the itemNo property is inside TemplateItem domain not in TemplateHeader domain. Also the sort keyword accepts a map.
To sort TemplateItem objects based on the itemNo field, you would have to define the sort property in mapping closure for TemplateItem domain
static mapping = {
.
.
.
sort 'itemNo': 'asc'
}
Now whenever you will make a query to TemplateItem, the default sorting will be on itemNo field.
So if you use
TemplateItem.findAllByTemplateHeader(templateHeaderInstance)
it will give sorted TemplateItems based on itemNo.
By defining the sort property in TemplateItem domain will not sort the templateItems field in TemplateHeader domain. Reason for which is that while fetching an association for a domain object Grails ignores the sort field for that domain. If you look at the sql being generated while fetching the TemplateHeader object and its associations you will see the difference.
Apparently there is no direct way for what you want to achieve, depending upon whether do you want to sort TemapleHeader objects based on templateItems or just sort TemplateItems within a single TemplateHeader object
To sort TemplateHeader objects based on the TemplateItems, add below sort property to mapping closure of TemplateHeader domain:
static mapping = {
.
.
.
sort 'templateItems.itemNo': 'asc'
}
And when you will execute this GORM
TemplateHeader header = TemplateHeader.list()
it generates following sql
select this_.header_id as header_i1_0_1_, this_.ver as ver2_0_1_, .... from template_header this_ inner join template_item templateit1_ on this_.header_id=templateit1_.template_header_header_id and this_.ver=templateit1_.template_header_ver order by templateit1_.item_no asc
Now the problem with this query is that its execution cost is very high. It is using inner join between TemplateHeader and TemplateItem domains. So if you have 2 records in TemplateHeader domain and 10 in TemplateItem domain, it will fetch 10 record while you need only 2. Another issue is that templateItems property will still be fetched lazily. So while you do header.templateItems, it will again make a query to database and the result will not be sorted based on itemNo. sql will look like this:
select templateit0_.template_header_header_id as template1_0_0_, templateit0_.template_header_ver as template2_0_0_, ... from template_item templateit0_ where templateit0_.template_header_header_id=? and templateit0_.template_header_ver=?
So if you want to sort the templateItems for a TemplateHeader object, you can over ride the getter for templateItems and sort the result there:
Set<TemplateItem> getTemplateItems() {
return templateItems?.sort { item_1, item_2 -> item_1?.itemNo <=> item_2?.itemNo }
}
Just in case if you get an error like this while adding TemplateItem object to TemplateHeader object:
No signature of method: TemplateHeader.addToTemplateItems() is applicable for argument types: (TemplateItem)
then try with declaring templateItems as List.

OAuth issue in Grails

I am tyring to configure login using twitter in my grails application
getting this stack trace when i do run-app
Server running. Browse to http://localhost:8080/TestOAuth
Error initializing the application: Error creating bean with name 'uk.co.desirableobjects.oauth.scribe.OauthController': Initialization of bean failed;<br/>
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'oauthService': Invocation of init method failed; nested exception is uk.co.desirableobjects.oauth.scribe.exception.InvalidOauthProviderException: [:] is not a Class <br/>
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'uk.co.desirableobjects.oauth.scribe.OauthController': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'oauthService': Invocation of init method failed; nested exception is uk.co.desirableobjects.oauth.scribe.exception.InvalidOauthProviderException: [:] is not a Class
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722) <br/>
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'oauthService': Invocation of init method failed; nested exception is uk.co.desirableobjects.oauth.scribe.exception.InvalidOauthProviderException: [:] is not a Class
... 5 more <br/>
Caused by: uk.co.desirableobjects.oauth.scribe.exception.InvalidOauthProviderException: [:] is not a Class
at uk.co.desirableobjects.oauth.scribe.OauthService.afterPropertiesSet(OauthService.groovy:48)
... 5 more
| Error Forked Grails VM exited with error
this is what i configured for twitter
oauth {
providers {
twitter {
api = 'TwitterApi'
key = 'i have my key here'
secret = 'i have my secrete key here'
successUri = '/success.gsp'
failureUri = '/fail.gsp'
}
}
debug = true
}
The provider API is a class (from scribe API) instead of String, which has to be referred in the config.
import org.scribe.builder.api.TwitterApi
oauth {
providers {
twitter {
api = TwitterApi
key = 'i have my key here'
secret = 'i have my secrete key here'
successUri = '/success.gsp'
failureUri = '/fail.gsp'
}
}
debug = true
}

Upgrading from Grails 1.3.9 to Grails 2.2.1 produces error in domain class

I am in the process of upgrading an app from Grails 1.3.9 to Grails 2.2.1. When I issue the run-app command, I get a long stacktrace that begins with this error and then more or less repeats it for about 400 lines:
2013-03-07 13:32:11.364 ERROR [ StackTrace] Full Stack Trace:
org.springframework.beans.factory.BeanCreationException: 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 org.hibernate.MappingException: property [sponsoringManager] not found on entity [com.mycompany.myapp.ManagerDelegate]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.codehaus.groovy.grails.commons.spring.ReloadAwareAutowireCapableBeanFactory.doCreateBean(ReloadAwareAutowireCapableBeanFactory.java:118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:713)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:457)
at org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration.getApplicationContext(DefaultRuntimeSpringConfiguration.java:153)
at org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.configure(GrailsRuntimeConfigurator.java:170)
at org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.configure(GrailsRuntimeConfigurator.java:127)
at org.codehaus.groovy.grails.web.context.GrailsConfigUtils.configureWebApplicationContext(GrailsConfigUtils.java:121)
at org.codehaus.groovy.grails.web.context.GrailsContextLoader.initWebApplicationContext(GrailsContextLoader.java:107)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
I think the pertinent part is this:
org.hibernate.MappingException: property [sponsoringManager] not found on entity [com.mycompany.myapp.ManagerDelegate]
Here's the code for the ManagerDelegate domain class, which is a many to many join class:
package com.mycompany.myapp
class ManagerDelegate extends Base implements Serializable {
static belongsTo = [sponsoringManager:User, delegate:User]
boolean equals(other) {
if (!(other instanceof ManagerDelegate)) {
return false
}
other.sponsoringManager.id == sponsoringManager.id && other.delegate.id == delegate.id
}
static mapping = {
id composite: [
'sponsoringManager',
'delegate'
]
version false
}
}
As you can see, ManagerDelegate does contain a sponsoringManager property which is declared in the belongsTo statement. This worked perfectly in Grails 1.3.9.
Here is the User class:
class User {
static hasMany = [sponsoringManagers: ManagerDelegate, delegates: ManagerDelegate]
static mappedBy = [sponsoringManagers: "delegate", delegates: "sponsoringManager"]
static mapping = {
id generator: 'uuid'
sponsoringManagers cascade: 'all-delete-orphan'
delegates cascade: 'all-delete-orphan'
}
...
}
When I try to access the app from my browser, nothing is displayed and no log output is produced.

Resources