Grails Rest Client Builder Throwing OperationNotSupported - spring

I am trying to develop a Grails application to call some REST services ...
I am attempting to use the Grails Rest Client Builder Plugin ...
I have tried on several versions of Grails ... currently on most recent version ... 2.3.7 although I've tried with a few older versions as well ...
Using IntelliJ 13 ... started a Grails project ... threw together a quick domain class ... using create-domain-class ... defined a few fields and constraints ... then did generate-all ...
Defined the Rest plugin in the BuildConfig with
compile ":rest-client-builder:2.0.0"
also tried with 2.0.1
I am defining the rest bean in the spring/resources.groovy
// Place your Spring DSL code here
beans = {
rest(grails.plugins.rest.client.RestBuilder)
}
Generated a service with create-service ... it's pretty bare-bones
package myPackage
import grails.transaction.Transactional
#Transactional
class myService {
def rest
def serviceMethod() {
def resp = rest.get("http://myServer/myContextRoot/allEmployees")
return resp
}
}
And I am calling this service method from the controller....
def search() {
myService.serviceMethod()
// Not really trying to do anything yet other than see
// if the bean gets injected properly and the method gets called.
render("Not yet implemented")
}
However I always get a Bean Instantiation Exception as the app is trying to start up.
| Running Grails application
| Error 2014-03-06 16:11:02,310 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Error creating bean with name 'rest': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [grails.plugins.rest.client.RestBuilder]: Constructor threw exception; nested exception is java.lang.UnsupportedOperationException
Message: Error creating bean with name 'rest': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [grails.plugins.rest.client.RestBuilder]: Constructor threw exception; nested exception is java.lang.UnsupportedOperationException
Line | Method
->> 303 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 138 | run in java.util.concurrent.FutureTask
| 895 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run in ''
^ 680 | run . . in java.lang.Thread
Caused by BeanInstantiationException: Could not instantiate bean class [grails.plugins.rest.client.RestBuilder]: Constructor threw exception; nested exception is java.lang.UnsupportedOperationException
->> 303 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 138 | run in java.util.concurrent.FutureTask
| 895 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run in ''
^ 680 | run . . in java.lang.Thread
Caused by UnsupportedOperationException: null
->> 186 | put in java.util.AbstractMap
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 69 | <init> in grails.plugins.rest.client.RestBuilder
| 57 | <init> . in ''
| 303 | innerRun in java.util.concurrent.FutureTask$Sync
| 138 | run . . in java.util.concurrent.FutureTask
| 895 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run . . in ''
^ 680 | run in java.lang.Thread
Checking the Grails source it seems to be choking on code involved with Proxy intialization, I've attempted to fiddle with the bean instantiation to set proxy settings and it has no affect.
Feel like I must be missing something related to the Plugin configuration, but have been unable to track down the problem. Any constructive input would be most appreciated.
-Jim

The no-arg constructor of RestBuilder creates an immutable map via Collections.emptyMap() on which a put() is later attempted in certain cases (for example, if you have an HTTP proxy defined through your System properties). One workaround is to construct your rest bean using an explicit, mutable Map:
rest(grails.plugins.rest.client.RestBuilder, [:])
I haven't checked to see if this apparent bug has been filed in JIRA. If not, it would probably be worthwhile to create a ticket and attach your sample app.

Related

Grails 2.4.5 Error net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException Invalid character ':' in value part of property

I get this error below when running a Grails 2.4.5 project (full stacktrace)
Error |
2021-11-28 01:27:44,302 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'ehCacheManagementService': Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
Message: Error creating bean with name 'ehCacheManagementService': Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
Line | Method
->> 266 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run in java.lang.Thread
Caused by CacheException: net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
->> 246 | init in net.sf.ehcache.management.ManagementService
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 266 | run in java.util.concurrent.FutureTask
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run . . . in java.lang.Thread
Caused by CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
->> 76 | createObjectName in net.sf.ehcache.management.Cache
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 64 | <init> in ''
| 107 | getCache in net.sf.ehcache.management.CacheManager
| 126 | getCaches in ''
| 237 | init . . in net.sf.ehcache.management.ManagementService
| 266 | run in java.util.concurrent.FutureTask
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run . . . in java.lang.Thread
Caused by MalformedObjectNameException: Invalid character ':' in value part of property
->> 618 | construct in javax.management.ObjectName
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1382 | <init> in ''
| 73 | createObjectName in net.sf.ehcache.management.Cache
| 64 | <init> in ''
| 107 | getCache in net.sf.ehcache.management.CacheManager
| 126 | getCaches in ''
| 237 | init . . in net.sf.ehcache.management.ManagementService
| 266 | run in java.util.concurrent.FutureTask
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run . . . in java.lang.Thread
Error |
2021-11-28 01:27:44,339 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing Grails: Error creating bean with name 'ehCacheManagementService': Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
Message: Error creating bean with name 'ehCacheManagementService': Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
Line | Method
->> 266 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run in java.lang.Thread
Caused by CacheException: net.sf.ehcache.CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
->> 246 | init in net.sf.ehcache.management.ManagementService
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 266 | run in java.util.concurrent.FutureTask
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run . . . in java.lang.Thread
Caused by CacheException: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property
->> 76 | createObjectName in net.sf.ehcache.management.Cache
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 64 | <init> in ''
| 107 | getCache in net.sf.ehcache.management.CacheManager
| 126 | getCaches in ''
| 237 | init . . in net.sf.ehcache.management.ManagementService
| 266 | run in java.util.concurrent.FutureTask
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run . . . in java.lang.Thread
Caused by MalformedObjectNameException: Invalid character ':' in value part of property
->> 618 | construct in javax.management.ObjectName
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1382 | <init> in ''
| 73 | createObjectName in net.sf.ehcache.management.Cache
| 64 | <init> in ''
| 107 | getCache in net.sf.ehcache.management.CacheManager
| 126 | getCaches in ''
| 237 | init . . in net.sf.ehcache.management.ManagementService
| 266 | run in java.util.concurrent.FutureTask
| 1149 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 624 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 748 | run . . . in java.lang.Thread
Error |
2021-11-28 01:27:44,345 [localhost-startStop-1] ERROR core.StandardContext - Error listenerStart
Error |
2021-11-28 01:27:44,347 [localhost-startStop-1] ERROR core.StandardContext - Context [/soctrack-web] startup failed due to previous errors
|Server running. Browse to http://localhost:8080/soctrack-web
I am not sure what's causing the error, I get a successful "maven clean/package/install".
However, doing a "grails compile", I get a deprecated warning (as show below) from the cache-ehcache plugin, I am assuming that might be the reason why I am getting this error, but not sure how to solve it.
Note: C:\Users\kgeoffroy\Documents\dev\soc-track-upgrade\SOCScheduleServiceWEB\target\plugins\cache-ehcache-1.0.5\src\java\grails\plugin\cache\ehcache\G
railsEhCacheManagerFactoryBean.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
I will try to see if there are higher version of that plugin. So far I am constricted to a nexus mirror repository for the most part, so I haven't been able to find a higher version to test.
I have the sample dependencies inside my pom.xml
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>cache-ehcache</artifactId>
<version>1.0.5</version>
<type>zip</type>
</dependency>
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>hibernate4</artifactId>
<version>4.3.8.1</version>
<scope>runtime</scope>
<type>zip</type>
</dependency>
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>tomcat</artifactId>
<version>7.0.55.2</version>
<scope>provided</scope>
<type>zip</type>
</dependency>
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>cache</artifactId>
<version>1.1.8</version>
<scope>compile</scope>
<type>zip</type>
</dependency>
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>cache-headers</artifactId>
<version>1.1.7</version>
<type>zip</type>
</dependency>
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>cached-resources</artifactId>
<version>1.1</version>
<type>zip</type>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
According to an open issue https://github.com/grails-plugins/grails-cache-ehcache/issues/41, it might be a possible bug, but no solution or work around was provided.
I am doing an upgrade from Grails 2.2.0 to 2.4.5, I have updated the Datasource.groovy to point out to the right hibernate4 ehCache class:
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
// cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider' //Outdated class
// http://grails-plugins.github.io/grails-cache-ehcache/guide/usage.html
cache.region.factory_class = 'grails.plugin.cache.ehcache.hibernate.BeanEhcacheRegionFactory' // For Hibernate before 4.0
cache.region.factory_class = 'grails.plugin.cache.ehcache.hibernate.BeanEhcacheRegionFactory4' // For Hibernate before 4.0 and higher
}
config.groovy:
/*https://github.com/grails/grails-core/releases/tag/v2.4.5
* ehcache 2.9.0 is more strict about the configuration.
* ehcache is used in the spring-security-core plugin for caching users.
* There is a problem reported as GRAILS-12120.
* As a workaround to the "net.sf.ehcache.CacheException:
* Another unnamed CacheManager already exists in the same VM.
* " error you can add this config to Config.groovy:*/
beans {
cacheManager {
shared = true
}
}
I am trying to understand where that MalformedObjectNameException: Invalid character ':' in value part of property is coming from since the project didn't configure any ehcache, it just used some classes from the cache plugin. Here is a sample cache service implementation below:
GrailsEhCacheCache not recognized by IntelliJ GrailsCacheManager not recognized by IntelliJ
import grails.plugin.cache.GrailsCacheManager
import grails.plugin.cache.ehcache.GrailsEhcacheCache
import org.springframework.transaction.annotation.Transactional
class ChatCacheService
{
static transactional = false
static final String CHAT_CACHE_NAME = Chat.canonicalName
static final String CHAT_HASHES_CACHE_NAME = "${CHAT_CACHE_NAME}.Hashes"
GrailsCacheManager grailsCacheManager
ChatMessageCacheService chatMessageCacheService
FilterService filterService
GrailsEhcacheCache getChatCache()
{
grailsCacheManager.getCache(CHAT_CACHE_NAME) as GrailsEhcacheCache
}
GrailsEhcacheCache getChatHashesCache()
{
grailsCacheManager.getCache(CHAT_HASHES_CACHE_NAME) as GrailsEhcacheCache
}
void addNewChat(String chatChannelName, Chat chat)
{
chatMessageCacheService.createChatMessageCache(chatChannelName, chatCache)
chat.channelName = chatChannelName
refreshChat(chatCache, chat)
}
void refreshChat(Chat chat)
{
refreshChat(chatCache, chat)
}
void refreshChat(GrailsEhcacheCache chatCache, Chat chat)
{
chat.updateChatTimestamp()
chatCache.put(chat.channelName, chat)
// >>> Chat Cache Event listener will update hash, except during initialization
}
void refreshChatHash(Chat chat)
{
ChatHash chatHash = chat.generateHashCode(chatMessageCacheService.getCacheChatMessages(chat.channelName))
chatHashesCache.put(chat.channelName, chatHash)
}
Chat retrieveChat(String chatChannelName)
{
Chat chat = chatCache.get(chatChannelName)?.get() as Chat
chat
}
synchronized Chat retrieveNonPurgeableChat(String chatChannelName)
{
Chat chat = retrieveChat(chatChannelName)
if (!chat)
{
addNewChat(chatChannelName, new NonPurgeableChat())
chat = retrieveChat(chatChannelName)
}
chat
}
List<ChatChatMessage> getCacheChatMessages(String channelName)
{
chatMessageCacheService.getCacheChatMessages(channelName) //.sort { -it.id }
}
ChatChatMessage addNewChatMessageCache(String channelName, ChatMessage chatMessage)
{
Chat chat = retrieveChat(channelName)
chatMessageCacheService.addNewChatMessageCacheToTop(channelName, chatMessage)
refreshChat(chat) // refresh chat
}
void removeChat(String chatChannelName)
{
GrailsEhcacheCache chatCache = grailsCacheManager.getCache(CHAT_CACHE_NAME) as GrailsEhcacheCache
chatCache.evict(chatChannelName)
chatMessageCacheService.destroy(chatChannelName)
}
#Transactional(readOnly = true)
List<Chat> retrieveAllGeneralAndGroupChats()
{
List<Chat> generalAndGroupChats = []
List<ChatMessageType> generalAndGroupChatTypes = [
ChatMessageType.findByDescription(ChatType.GROUP.name()),
ChatMessageType.findByDescription(ChatType.GENERAL.name())
]
chatCache.allKeys.each { key ->
Chat chat = (Chat) chatCache.get(key).get()
if (generalAndGroupChatTypes.find { it?.description == chat?.chatTypeDescription })
{
generalAndGroupChats.add(chat)
}
}
generalAndGroupChats
}
void purgeOldMessagesFromChats()
{
chatCache.allKeys.findAll { String channelName -> !ChatService.isEventChat(channelName) }.each { String chatChannelName ->
Chat chat = (Chat) chatCache.get(chatChannelName).get()
if (!(chat instanceof NonPurgeableChat))
{
if (chatMessageCacheService.purgeOldMessages(chatChannelName) > 0)
{
refreshChat(chatCache, chat)
}
}
}
}
String getChatCacheHash(String channelName)
{
((ChatHash) chatHashesCache.get(channelName)?.get())?.hash
}
String synchronizeChat(UserProfile userProfile, String chatChannelName, String chatTimestamp, String selectedFilter)
{
String response = null
Chat chatToSynchronize = retrieveChat(chatChannelName)
if (chatToSynchronize && (chatTimestamp != getChatCacheHash(chatToSynchronize.channelName) || filterChanged(userProfile, selectedFilter)))
{
response = chatToJson(chatToSynchronize, filterService.getCurrentFilterForUsername(userProfile?.userId), selectedFilter, userProfile)
}
response
}
Boolean filterChanged(UserProfile userProfile, String selectedFilter) {
Boolean filterChanged = Boolean.FALSE
if (userProfile && userProfile?.groupChatFilterOption != selectedFilter
&& (userProfile?.groupChatFilterOption == SOCTrackConstants.DASHBOARD_FILTER || selectedFilter == SOCTrackConstants.DASHBOARD_FILTER)) {
filterChanged = Boolean.TRUE
}
filterChanged
}
String chatToJson(Chat chat, List<EventFilter> userFilters, String selectedFilter, UserProfile userProfile)
{
List<ChatChatMessage> chatChatMessages = chatMessageCacheService.getCacheChatMessages(chat.channelName)
// Apply dashboard filters
if (selectedFilter == SOCTrackConstants.DASHBOARD_FILTER) {
chatChatMessages = chatChatMessages.findAll{ChatChatMessage chatMessage ->
includeChatMessage(chatMessage, userFilters)
}
}
Map<String, Collection<String>> chatMessagesAndTimestamp = [:]
chatMessagesAndTimestamp['messages'] = chatChatMessages.collect { ChatChatMessage chatMessage ->
chatMessage.messageAsHtml = chatMessage.messageAsHtmlClone
if (! userProfile?.shouldHighlightGroupMessage(chatMessage.id, chatMessage.enteredDate, chatMessage.messageType) ||
chatMessage.enteredBy.equals(userProfile?.userId)) {
chatMessage.messageAsHtml = chatMessage.messageAsHtml.replaceAll("groupChatUnreadHighlight","")
}
if(chatMessage.lastResponseId > 0) {
if (!userProfile?.shouldHighlightGroupMessage(chatMessage.lastResponseId, chatMessage.lastResponseDate, chatMessage.messageType) ||
chatMessage.lastResponseBy.equals(userProfile?.userId)) {
chatMessage.messageAsHtml = chatMessage.messageAsHtml.replaceAll("groupChatResponseUnreadHighlight", "")
}
}
chatMessage.messageAsHtml
}.findAll { it }
chatMessagesAndTimestamp['chatTimestamp'] = getChatCacheHash(chat.channelName) // chat.chatTimestamp
JSON messagesAsJson = new JSON(chatMessagesAndTimestamp)
messagesAsJson.toString()
}
Boolean includeChatMessage (ChatChatMessage chatChatMessage, List<EventFilter> userFilters) {
boolean displayRow = true
if (userFilters) { //at least one filter to satisfy
boolean satisfiedAllAndFilters
boolean satisfiedAnOrFilter
List<EventFilter> andFilters = userFilters.findAll { eventFilter ->
eventFilter.filterOperationType == FilterOperationType.AND
}
List<EventFilter> orFilters = userFilters.findAll { eventFilter ->
eventFilter.filterOperationType == FilterOperationType.OR
}
if (andFilters) {
satisfiedAllAndFilters = andFilters.collect { andFilter ->
andFilter.displayChatBasedOnFilter(chatChatMessage)
}.every{ it } //all 'AND' filters must be satisfied
}
if (orFilters) {
satisfiedAnOrFilter = orFilters.collect { orFilter ->
orFilter.displayChatBasedOnFilter(chatChatMessage)
}.any{ it } //at least one 'OR' filter must be satisfied
}
displayRow = satisfiedAllAndFilters || satisfiedAnOrFilter
}
displayRow
}
}
UPDATE: Custom Utility method used to createEHcache
synchronized static Cache createEhcache(String name, CacheManager cacheManager, CacheConfiguration baseCacheConfiguration, CacheEventListener cacheEventListener = null)
{
Ehcache ehcache
PersistenceConfiguration persistenceConfiguration
if (cacheManager.cacheExists(name))
{
ehcache = cacheManager.getCache(name)
ehcache.cacheConfiguration.overflowToDisk = false //overflowToDisk deprecated
// ehcache.cacheConfiguration.persistence(persistenceConfiguration.strategy("LOCALTEMPSWAP"))
ehcache.cacheConfiguration.diskPersistent = false // diskPersistent deprecated
// ehcache.cacheConfiguration.persistence(persistenceConfiguration.strategy("NONE"))
ehcache.cacheConfiguration.timeToLiveSeconds = 0
ehcache.cacheConfiguration.timeToIdleSeconds = 0
logger.warn "Cache $name already exists, configuration has been reset."
}
else
{
baseCacheConfiguration.name = name
// ehcache = new Cache(baseCacheConfiguration, null, null); //Runtime error (Ambiguous method overloading)
// RegisteredEventListeners registeredEventListeners = new RegisteredEventListeners(null);
// BootstrapCacheLoader bootstrapCacheLoader = new RMIBootstrapCacheLoader()
ehcache = new Cache(baseCacheConfiguration, null as RegisteredEventListeners, null as BootstrapCacheLoader)
cacheManager.addCache(ehcache)
cacheManager.cacheManagerPeerProviders?.get('RMI')?.registerPeer("${getEhcachePeerBaseUrl()}/$baseCacheConfiguration.name")
if (cacheEventListener)
{
ehcache.getCacheEventNotificationService().registerListener(cacheEventListener)
}
}
ehcache
}
Putting that line of code inside the Config.groovy file solved the issue and removed the exception: grails.cache.ehcache.cacheManagerName = 'default_grails_cache'.
Solution comes from https://github.com/grails-plugins/grails-cache-ehcache/issues/41#issuecomment-985049476.

Problem with hibernate.hbm2ddl.auto in a migration

I have migrated a spring-boot project from MySQL to SQL Server. I don't have the necessary roles to use hibernate.hbm2ddl.auto = update.
How can I update without having access to sysadmin?
I need to update because I can't lose the records
2021-07-21 | 13:30:17.660 | INFO | main | o.h.t.h.SchemaUpdate | HHH000228: Running hbm2ddl schema update
2021-07-21 | 13:30:17.692 | WARN | main | .e.j.s.SqlExceptionHelper | SQL Error: 229, SQLState: S0005
2021-07-21 | 13:30:17.692 | ERROR | main | .e.j.s.SqlExceptionHelper | The SELECT permission was denied on the object 'sequences', database 'mssqlsystemresource', schema 'sys'.
2021-07-21 | 13:30:17.692 | WARN | main | ddedWebApplicationContext | Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2021-07-21 | 13:30:17.692 | INFO | main | o.a.c.c.StandardService | Stopping service [Tomcat]
I don't know how you are invoking hbm2ddl but you can specify an output file and then apply these statements manually. You can configure this through the javax.persistence.schema-generation.scripts.create-target parameter. See the documentation for details: https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl

Unable to create initial connections of pool when start up Grails app

I am using Oracle 11g. And have the following error when starting up my Grails app in development mode. My DataSource.Groovy is listed below. Please advise.
Error |
2014-12-25 18:42:11,836 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initia
l connections of pool.
Message: oracle.jdbc.driver.OracleDriver
dataSource {
pooled = true
jmxExport = true
driverClassName = "oracle.jdbc.driver.OracleDriver"
username = "john"
password = "password"
}
Update:
I had the following line in Build.Groovy. But the app failed to start. So I deleted it. Do I still need a plugin? If so, what should it be?
runtime ":com.oracle:ojdbc6:11.2.0.1.0"
Update -2
Afte I run grails compile --refresh-dependencies and start up the app, now I have the following error.
Error |
2014-12-25 19:30:22,069 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error i
nitializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initia
lization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException
: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFacto
ry' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.fact
ory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference
to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframewo
rk.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve r
eference to bean 'dataSourceLazy' while setting constructor argument; nested exception is org.spring
framework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceLazy': Canno
t resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested excepti
on is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSo
urceUnproxied': Error setting property values; nested exception is org.springframework.beans.Propert
yBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean fai
led; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bea
n with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting be
an property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationExce
ption: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'dataSource'
while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.Bea
nCreationException: Error creating bean with name 'dataSource': Cannot resolve reference to bean 'da
taSourceLazy' while setting constructor argument; nested exception is org.springframework.beans.fact
ory.BeanCreationException: Error creating bean with name 'dataSourceLazy': Cannot resolve reference
to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.springfram
ework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Erro
r setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateExceptio
n; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
Line | Method
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve
reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFact
ory': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested
exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'dataSource': Cannot resolve reference to bean 'dataSourceLazy' while setting constructor argument;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean wi
th name 'dataSourceLazy': Cannot resolve reference to bean 'dataSourceUnproxied' while setting const
ructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSourceUnproxied': Error setting property values; nested exception is or
g.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve refe
rence to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springf
ramework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Cannot res
olve reference to bean 'dataSourceLazy' while setting constructor argument; nested exception is org.
springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceLazy':
Cannot resolve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested e
xception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '
dataSourceUnproxied': Error setting property values; nested exception is org.springframework.beans.P
ropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'dataSource': Cannot resolve referenc
e to bean 'dataSourceLazy' while setting constructor argument; nested exception is org.springframewo
rk.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceLazy': Cannot resol
ve reference to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is o
rg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnp
roxied': Error setting property values; nested exception is org.springframework.beans.PropertyBatchU
pdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'dataSourceLazy': Cannot resolve refe
rence to bean 'dataSourceUnproxied' while setting constructor argument; nested exception is org.spri
ngframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceUnproxied'
: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateEx
ception; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'dataSourceUnproxied': Error setting
property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested
PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClas
sName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC dri
ver class [oracle.jdbc.driver.OracleDriver]
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
Caused by PropertyBatchUpdateException: Failed properties: Property 'driverClassName' threw exceptio
n; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [oracle.jdb
c.driver.OracleDriver]
->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
| Error Forked Grails VM exited with error
The Oracle jar with the JDBC driver is not found. Put the file in the lib dir of your grails project.
When you put a jar file in the lib directory, it is not auto-discovered. Run
grails compile --refresh-dependencies
and that will get Grails to find the jar and add it to the dependencies and classpath.

Could not synchronize database state with session Error in Grails Hibernate

I have registered a MySecurityEventListener in my Grails app to set a login count after a user has been logged in.
MySecurityEventListener class:
class MySecurityEventListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent>, LogoutHandler {
/**
* Handler for after login.
*/
#Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
User.withNewSession {
User user = User.get(event.authentication.principal.id)
user.lastLoginDate = new Date() // set the last login date
user.loginCount += 1 // increase the login count
user.isLoggedIn = true
user.save(flush: true)
}
}
/**
* Handler for after logout.
*/
#Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
User.withNewSession {
User user = User.get(authentication.principal.id)
user.isLoggedIn = false
user.save(flush: true)
}
}
}
Sometimes when a user loggs in I get the following error:
| Error 2013-07-03 13:40:56,306 [http-nio-8080-exec-1]
ERROR events.PatchedDefaultFlushEventListener -
Could not synchronize database state with session Message:
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [demo.User#ffd93c5639b54405bf]
Line | Method
->> 38 | doCall in demo.MySecurityEventListener$_onApplicationEvent_closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 33 | onApplicationEvent in demo.MySecurityEventListener
| 1145 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . in java.lang.Thread
2013-07-03 13:40:56,551 [http-nio-8080-exec-1] INFO cpr.SessionSupport - Session created
2013-07-03 13:40:56,554 [http-nio-8080-exec-2] INFO cpr.SessionSupport - Session created
| Error 2013-07-03 13:40:56,554 [http-nio-8080-exec-1] ERROR [/demo].[gsp] - Servlet.service() for servlet [gsp] in context with path [/demo] threw exception
Message: Object of class [demo.User] with identifier [ffd93c5639b54405bf]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [demo.User#ffd93c5639b54405bf]
Line | Method
->> 38 | doCall in demo.MySecurityEventListener$_onApplicationEvent_closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 33 | onApplicationEvent in demo.MySecurityEventListener
| 1145 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . in java.lang.Thread
Caused by StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [demo.User#ffd93c5639b54405bf]
->> 38 | doCall in demo.MySecurityEventListener$_onApplicationEvent_closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 33 | onApplicationEvent in demo.MySecurityEventListener
| 1145 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . in java.lang.Thread
How do I have to fix this error?
withTransaction provides access to the underlying transaction. If needed a control over transaction rollback you can use it.
withSession uses the default session provided by SessionFactory. If needed a control over sesion then use it.
Looking at your example, I would vouch for withTransaction (the simplest one).

Grails 2.0.1 : async messaging: `jmsConnectionFactory` compilation error

I have resource.groovy
beans = {
jmsConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) { brokerURL = 'vm://localhost' }
}
and on run it says
Running Grails application
| Error 2012-02-24 18:02:13,490 [pool-6-thread-1] ERROR spring.GrailsRuntimeConfigurator - [RuntimeConfiguration] Unable to load beans from resources.groovy
Message: No such property: org for class: resources
Line | Method
->> 3 | doCall in resources$_run_closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 736 | invokeBeanDefiningClosure in grails.spring.BeanBuilder
| 569 | beans . . . . . . . . . . in ''
| 736 | invokeBeanDefiningClosure in ''
| 569 | beans . . . . . . . . . . in ''
| 511 | invokeMethod in ''
| 303 | innerRun . . . . . . . . in java.util.concurrent.FutureTask$Sync
| 138 | run in java.util.concurrent.FutureTask
| 886 | runTask . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
| 908 | run in ''
^ 662 | run . . . . . . . . . . . in java.lang.Thread
| Error 2012-02-24 18:02:16,537 [pool-6-thread-1] ERROR context.GrailsContextLoader - Error executing bootstraps: Error creating bean with name 'delayedCreateMessageJmsListenerContainer': Cannot resolve reference to bean 'jmsConnectionFactory' while setting bean property 'connectionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jmsConnectionFactory' is defined
Message: Error creating bean with name 'delayedCreateMessageJmsListenerContainer': Cannot resolve reference to bean 'jmsConnectionFactory' while setting bean property 'connectionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jmsConnectionFactory' is defined
It worked all well before upgrade, after updating to 2.0.1 it failed with this error, I am using groovy compiler 1.8.6
I have always configured ActiveMQ in Grails as follows:
BuildConfig.groovy
dependencies {
compile 'org.apache.activemq:activemq-core:5.5.0'
}
resources.groovy
import org.springframework.jms.connection.SingleConnectionFactory
import org.apache.activemq.ActiveMQConnectionFactory
beans = {
jmsConnectionFactory(SingleConnectionFactory) {
targetConnectionFactory = { ActiveMQConnectionFactory cf ->
brokerURL = 'vm://localhost'
}
}
}
It may be a ClassNotFound error in disguise. Try adding an import statement:
import org.apache.activemq.ActiveMQConnectionFactory
and see if you get a ClassNotFoundError, if so then it's just a matter of tracking down the missing dependency.

Resources