How to cast a JSONObjectMap into Map? - json

The following example I derived from
http://mrhaki.blogspot.de/2013/12/grails-goodness-rendering-partial.html
Domain
class Book {
String title
Map details
}
Controller
#Transactional
class BookApiController extends RestfulController {
static responseFormats = ['json', 'xml']
BookApiController() {
super(Book)
}
#Override
#Transactional
def save(Book bookInstance) {
println "details: " + bookInstance.details.getClass().name
bookInstance.save flush:true
respond bookInstance
}
}
URLMappings
"/api/book"(resources: "bookApi")
When I'm using this curl invocation:
curl -i -X POST -H "Content-Type: application/json" -d '{"title":"Grails in Action","details":{"isbn":"123456789"}}' http://localhost:8080/restpoint/api/book
Grails throws the following exception:
details: org.codehaus.groovy.grails.web.binding.bindingsource.JsonDataBindingSourceCreator$JsonObjectMap
| Error 2014-06-09 13:45:52,057 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver - ClassCastException occurred when processing request: [POST] /restpoint/api/book
com.google.gson.JsonPrimitive cannot be cast to java.lang.String. Stacktrace follows:
Message: com.google.gson.JsonPrimitive cannot be cast to java.lang.String
Line | Method
->> 23 | $tt__save in sample.core.BookApiController
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 724 | run in java.lang.Thread
I need the map property (here called 'details') in my Book domain this is precondition.
A we can see it above the map is an instance of org.codehaus.groovy.grails.web.binding.bindingsource.JsonDataBindingSourceCreator$JsonObjectMap
How can I cast it into a map?
Any idea?
Thanks in advance.
-markus

This seems like a bug, please report a JIRA issue at http://jira.grails.org/browse/GRAILS

Related

Save JSON as Domain Class with Restfull Controller in Deep

I've two domain class:
class A {
String foo
static hasMany = [children: B]
}
class B {
String bar
static belongsTo = [a: A]
}
I want to save A from JSON like:
{
foo: "Hello world!",
children: [
{bar: "First child!", _ref: "../.."},
{bar: "Second child!", _ref: "../.."}
]
}
(Note: If I don't put _ref, B objects are saved but without reference to A, ie, null values.)
And I have a Restfull Controller like:
class AController extends RestfullController {
static responseFormats = ['json', 'xml']
AController() {
super(A)
}
}
But, when I try to save my object, I got:
ERROR errors.GrailsExceptionResolver - TransientObjectException occurred when processing request: [POST] /example/a/save.json
object references an unsaved transient instance - save the transient instance before flushing: mx.gob.morelos.ppi.Proyecto. Stacktrace follows:
Message: object references an unsaved transient instance - save the transient instance before flushing: A
Line | Method
->> 99 | $tt__save in grails.rest.RestfulController
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
What I need to do to save my JSON with their relations?
Regards.

REST/json Angular/Grails HTTP PUT (update) "Internal Server Error" 500

I had tested a sample app with REST/json/Grails on one end & Angular on one end to proof test the flow. It was working perfectly fine. All of HTTP GET, POST, PUT, & DELETE was fine.
Now I am making JSON requests via REST in a full-blown app for Project Management. It has basic class structure for the app: classes on Project, Contract, Contacts, Projects Roles etc.
While updating any & every record in the database (MySql 5.6 Community, Grails 2.4.3) via HTTP PUT (with PUT only, POSt with identical arguments works perfectly fine) REST/JSON, I am getting the following error (on the client side):
===================================================
Error 500: Internal Server Error URI/apaNew/api/v1/projectTasks/3Classjava.lang.NullPointerExceptionMessagenull
Around line 198 of PageFragmentCachingFilter.java 195: if (CollectionUtils.isEmpty(cacheOperations)) {196: log.debug("No cacheable annotation found for {}:{} {}",197: new Object[] { request.getMethod(), request.getRequestURI(), getContext() });198: chain.doFilter(request, response);199: return;200: }201:
Around line 63 of AbstractFilter.java 60: try {61: // NO_FILTER set for RequestDispatcher forwards to avoid double gzipping62: if (filterNotDisabled(request)) {63: doFilter(request, response, chain);64: }65: else {66: chain.doFilter(req, res);
Around line 82 of CorsFilter.java 79: }80: }81: }82: filterChain.doFilter(request, response);83: }84:85: private boolean checkOrigin(HttpServletRequest req, HttpServletResponse resp) {
Trace
Line | Method ->> 198 | doFilter in PageFragmentCachingFilter.java
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 63 | doFilter in AbstractFilter.java
| 82 | doFilter in CorsFilter.java
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker ^ 745 | run in java.lang.Thread
==============================================
The application is a very simple project management app. It has a Project class whose records I am trying to modify.
It was working absolutely fine in a sample app I had written before to test everything. Only after converting it into a full-blown app the problem has surfaced.
The HTTP POST/GET/DELETE request is working perfectly fine. An HTTP POST request with similar parameters is working perfectly fine.

Saving of nested list of objects fails with JSON post in Grails

Example application: https://github.com/Hi-Fi/writetable-example-with-grails
In example application, controllers work fine when used through GSP pages or posting with CURL the form. Command with curl:
curl "http://localhost:8080/junk/team/save" --data "name=team&players"%"5B0"%"5D.firstName=first&players"%"5B0"%"5D.lastName=last&players"%"5B0"%"5D.position=position&create=Create" --compressed.
Problem is with identical request using JSON, which creates identical (according dump()) object, but can't save the nested values.
When making following POST with SOAPUI (localhost:8080/junk/api/rest):
{
name: "Team name",
players: [
{
firstName: "Player first name",
lastName: "Player last name",
position: "Player position"
}
]
}
I just get error:
| Error 2014-12-20 21:02:47,050 [http-bio-8080-exec-1] ERROR hibernate.AssertionFailure - an assertion failure occured
(this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
Message: null id in junk.Player entry (don't flush the Session after an exception occurs)
Line | Method
->> 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . in java.lang.Thread
Parent object (Team) is still saved even there's this error. With Hibernate4 whole save fails, so updating to it wasn't helping.
One way to solve this is explicitly connect "Team" with each "Player" like
team.players.each {it.team = team}
With form posting, this step is made automatically, but for some reason not with JSON. Player object at after Team object creation in JSON:
<junk.Player#76f8539e firstName=first lastName=last position=position deleted=false errors=grails.validation.ValidationErrors: 0 errors $changedProperties=null id=null version=null team=null>
And with form POST:
<junk.Player#1ba14c1b firstName=first lastName=last position=position deleted=false errors=grails.validation.ValidationErrors: 0 errors $changedProperties=null id=null version=null team=junk.Team : (unsaved)>
This might not be the "right" solution, so I'm still happy to hear if there's better solution for nested one-to-many -lists.

GRAILS: Using Domain subclasses

Using Grails with the following versions:
APPLICATION STATUS
App version: 0.1
Grails version: 2.3.5
Groovy version: 2.1.9
JVM version: 1.7.0_51
Reloading active: true
Controllers: 15
Domains: 18
Services: 2
Tag Libraries: 13
I have a domain model that I am trying to follow. I built the tables in MySQL prior to programming.
In the model, I have Insertion_orders that are bound to people (Persons) in a Many-to-Many relationship. This relationship is defined by Insertion_orders_persons, with the person_id & location_id defining an entry in Insertion_orders_persons. In addition there is a type value that is ENUMed either Trafficker, Advertiser, Agency, (or) Salesperson. One (or more) trafficker will always appear, but the rest may, may not or have many of these associations. I am trying to bind them according to type to the Insertion_orders model:
package cms
class Insertion_orders {
String insertion_order_name
String po_number
String notes
String toString() {
"${insertion_order_name} - ${id}"
}
static hasMany = [trafficker: Insertion_orders_traffickers, salesperson: Insertion_orders_salespersons]
static constraints = {
insertion_order_name(blank:false)
po_number()
notes(widget: 'textarea', nullable:true)
}
static mapping ={
version false
id column: 'insertion_order_id'
notes sqlType: 'text'
}
}
I am trying to use inheritance and a discrimiator value to accomplish this.
package cms
class Insertion_orders_persons {
Persons person
Insertion_orders insertion_order
Type type
String toString() {
"${person}: ${type}"
}
enum Type {
Trafficker, Salesperson, Advertiser, Agency
}
static constraints = {
}
static mapping = {
version false
id column: 'insertion_order_person_id'
discriminator column: "type"
}
}
class Insertion_orders_traffickers extends Insertion_orders_persons {
static mapping ={
discriminator value: "Traffickers"
}
}
class Insertion_orders_salespersons extends Insertion_orders_persons {
static mapping ={
discriminator value: "Salesperson"
}
}
The problem is that when I try to join to the extended classes (as in the hasMany in the Insertion_orders class), the Grails fails to start and generates the following:
|Loading Grails 2.3.5
|Configuring classpath
.
|Environment set to development
.................................
|Packaging Grails application
..........................................
|Running Grails application
Error |
2014-04-16 11:33:58,693 [localhost-startStop-1] 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.MappingException: Association references unmapped class: cms.Insertion_orders_salespersons
Message: 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: Association references unmapped class: cms.Insertion_orders_salespersons
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 'sessionFactory': Invocation of init method failed; nested exception is org.hibernate.MappingException: Association references unmapped class: cms.Insertion_orders_salespersons
->> 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': Invocation of init method failed; nested exception is org.hibernate.MappingException: Association references unmapped class: cms.Insertion_orders_salespersons
->> 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 MappingException: Association references unmapped class: cms.Insertion_orders_salespersons
->> 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
As additional information, regardless of how I try to access the subclasses, or the subclass composition, I get the same error.
This seems like a very fundamental functionality. Can someone please tell me what I am missing or doing incorrectly?
If you remove discriminator column: “type” from Insertion_orders_persons and define Insertion_orders_persons, Insertion_orders_traffickers and Insertion_orders_salespersons each in their own source files, I think you code will work.

java.lang.ClassCastException in Grails app

I am following the free online book "Getting Started with Grails" (http://www.infoq.com/minibooks/grails-getting-started) and I am getting a java.lang.ClassCastException when trying to list any domain class. Can anyone decipher this?
URI: /RaceTrack/runner/list
Class: java.lang.ClassCastException
Message: sun.proxy.$Proxy26 cannot be cast to org.springframework.orm.hibernate3.HibernateCallback
Stack trace:
Line | Method
->> 15 | list in RunnerController.groovy
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 186 | doFilter in PageFragmentCachingFilter.java
| 63 | doFilter in AbstractFilter.java
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Additional info (around line 186 of PageFragmentCachingFilter.java)
183: if(method == null) {
184: log.debug("No cacheable method found for {}:{} {}",
185: new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
186: chain.doFilter(request, response);
187: return;
188: }
189: Collection<CacheOperation> cacheOperations = cacheOperationSource.getCacheOperations(
Additional info (around line 63 of AbstractFilter.java):
60: try {
61: // NO_FILTER set for RequestDispatcher forwards to avoid double gzipping
62: if (filterNotDisabled(request)) {
63: doFilter(request, response, chain);
64: }
65: else {
66: chain.doFilter(req, res);
I've had the same issue happening all of a sudden couple days back. Deleting ~/.grails/2.0.4/.slcache/ directory fixes it for me.
Delete .slcache in both the top of the .grails subdirectory and also the .slcache, if it exists, for the particular version of grails being used. For example, ~/.grails/2.1.3/.slcache.
This worked when using IntelliJ IDEA to launch the app.
Does the app start up with reloading (spring-loaded agent) disabled?
grails -noreloading run-app
A similar problem has been reported to Grails Jira as GRAILS-9952. It would help fixing the problem if you can provide an test app that reproduces the problem. Please attach that to the jira issue.