I'm trying to get the JSR-311 plugin working with Grails 2.3.7. I'm using version 0.10, because I think 0.11 requires Grails 2.4.
I've used the generate-resource command to create an end point for my domain class Product. Two resource classes are created, ProductCollectionResource and ProductResource. I've tweaked them a bit, but essentially they look like this:
ProductCollectionResource
#Path('/api/products')
#Consumes(['application/json'])
#Produces(['application/json'])
class ProductCollectionResource {
def productResourceService
#Path('{id}')
#GET
ProductResource getResource(#PathParam('id') Long id) {
new ProductResource(productResourceService: productResourceService, id:id)
}
#GET
Response readAll(#QueryParam("max") Integer max, #QueryParam("offset") Integer offset) {
ok productResourceService.readAll(max, offset)
}
}
ProductResource
#Consumes(['application/json'])
#Produces(['application/json'])
class ProductResource {
def productResourceService
def id
#GET
Response read() {
ok productResourceService.read(id)
}
}
The readAll method in ProductCollectionResource works fine - when I hit it, I get back a list of products, however when I try to access a specific product by id (on /api/products/123), I get the following error:
Caused by MessageException: A message body writer for Java class com.myapp.ProductResource, and Java type class com.myapp.ProductResource, and MIME media type application/json was not found
->> 285 | write in com.sun.jersey.spi.container.ContainerResponse
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1479 | _handleRequest in com.sun.jersey.server.impl.application.WebApplicationImpl
| 1391 | handleRequest . . in ''
| 1381 | handleRequest in ''
| 416 | service . . . . . in com.sun.jersey.spi.container.servlet.WebComponent
| 538 | service in com.sun.jersey.spi.container.servlet.ServletContainer
| 716 | service . . . . . in ''
| 193 | process in org.grails.jaxrs.web.JaxrsContext$JaxrsServiceImpl
| 45 | handle . . . . . . in org.grails.jaxrs.JaxrsController
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter . . . . . in grails.plugin.cache.web.filter.AbstractFilter
| 150 | invoke in net.bull.javamelody.JspWrapper
| 285 | invoke . . . . . . in net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler
| 198 | doFilter in net.bull.javamelody.MonitoringFilter
| 176 | doFilter . . . . . in ''
| 67 | doFilter . . . . . in ''
| 53 | doFilter in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
| 82 | doFilter in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 63 | doFilter . . . . . in com.odobo.grails.plugin.springsecurity.rest.RestLogoutFilter
| 46 | doFilterInternal in org.grails.jaxrs.web.JaxrsFilter
| 82 | doFilter . . . . . in com.brandseye.cors.CorsFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
So it looks like it's trying to marshall my ProductResource class to JSON, which I think isn't really what I want. I think it should be invoking the ProductResource.read() method, and marshalling the returned value from that method to JSON.
I have no experience in Grails whatsoever, but from a pure Jersey standpoint, look at what you got here
#Path('{id}')
#GET
ProductResource getResource(#PathParam('id') Long id) {
This is resource method (endpoint). So the ProductsResource will be treated as the response body, just like any other resource method.
You seem to be trying to use the sub-resource locator functionality, forwarding to the ProductsResource class. For that to work, the sub-resource locator (getResource) should not have an #HttpMethod annotation. That's one of the factors that differentiates a resource method from a sub-resource locator.
So just remove the #GET from the getResource method. The #GET is already established by the read() method in the ProductsResource, which is what will be called.
For more information, see the documentation for Sub-Resource Locators
Related
I've been playing around with Grails-3.1.1 and creating restful services but when I use them to generate from a collection and responding using templates I get the following error:
URI /api/buildings
Class java.lang.IllegalStateException
Message
Error rendering view: Error rendering view: Cannot write a name when a name has just been written. Write a value first!
Caused by
Cannot write a name when a name has just been written. Write a value first!
I followed the example on the json-views github page
https://github.com/grails/grails-views
My index.gson file looks like this
model {
List<Building> buildingList
}
json tmpl.building(buildingList)
And my _building.gson template file like this
model {
Building building
}
json g.render(building)
If I don't use the templates all works well but then I get too little info - I want to expand on some of the object relationships instead of just returning the id. Using a show.gson template accessing the same _building.gson file does seem to work OK. The controller in question extends from RestfulController and only implements the contructor as shown below
#Transactional(readOnly = true)
class BuildingRestController extends RestfulController {
static responseFormats = ['json', 'xml']
BuildingRestController() {
super(Building)
}
}
Any ideas what is going wrong and do others have it working?
Stack trace:
Line | Method
->> 8 | writeTo in C:\Users\Colin\code\biztool\grails-app\views\buildingRest\index.gson
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caused by ViewRenderException: Error rendering view: Cannot write a name when a name has just been written. Write a value first!
->> 8 | writeTo in C:\Users\Colin\code\biztool\grails-app\views\buildingRest\_building.gson
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caused by IllegalStateException: Cannot write a name when a name has just been written. Write a value first!
->> 624 | writeName in grails.plugin.json.builder.StreamingJsonBuilder$StreamingJsonDelegate
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 563 | call in ''
| 149 | process . . . . . . . . in grails.plugin.json.view.api.internal.JsonGrailsViewHelper
| 74 | doCall in grails.plugin.json.view.api.internal.JsonGrailsViewHelper$_render_closure1
| 689 | cloneDelegateAndGetContent in grails.plugin.json.builder.StreamingJsonBuilder$StreamingJsonDelegate
| 681 | cloneDelegateAndGetContent in ''
| 199 | call . . . . . . . . . in grails.plugin.json.builder.StreamingJsonBuilder
| 72 | render in grails.plugin.json.view.api.internal.JsonGrailsViewHelper
| 58 | render . . . . . . . . in ''
| 8 | run in _info_app_name__buildingRest__building_gson
| 32 | doWrite . . . . . . . . in grails.plugin.json.view.JsonViewTemplate
| 30 | writeTo in grails.views.AbstractWritableScript
| 280 | render . . . . . . . . in grails.plugin.json.view.api.internal.JsonGrailsViewHelper
| 30 | invokeMethod in grails.plugin.json.view.api.internal.TemplateRenderer
| 8 | run . . . . . . . . . . in _info_app_name__buildingRest_index_gson
| 32 | doWrite in grails.plugin.json.view.JsonViewTemplate
| 30 | writeTo . . . . . . . . in grails.views.AbstractWritableScript
| 64 | renderMergedOutputModel in grails.views.mvc.GenericGroovyTemplateView
| 94 | render . . . . . . . . in grails.views.mvc.renderer.DefaultViewRenderer
| 188 | internalRespond in grails.artefact.controller.RestResponder$Trait$Helper
| 62 | respond . . . . . . . . in ''
| 64 | index in grails.rest.RestfulController
| 96 | doInTransaction . . . . in grails.transaction.GrailsTransactionTemplate$2
| 93 | execute in grails.transaction.GrailsTransactionTemplate
| 80 | doFilter . . . . . . . in grails.plugin.springsecurity.rest.RestLogoutFilter
| 53 | doFilter in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
| 143 | doFilter . . . . . . . in grails.plugin.springsecurity.rest.RestAuthenticationFilter
| 62 | doFilter in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 58 | doFilter . . . . . . . in grails.plugin.springsecurity.web.SecurityRequestHolderFilter
| 35 | doFilterInternal in CorsFilter.java
| 1142 | runWorker . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 617 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . . . . . . in java.lang.Thread
When I run my Grails app and I get the following error
| Loading Grails 2.3.5
| Configuring classpath
| Configuring classpath.
| Environment set to development
| Environment set to development.
| Environment set to development..
| Environment set to development...
| Environment set to development....
| Environment set to development.....
| Packaging Grails application
| Packaging Grails application.
| Packaging Grails application..
| Packaging Grails application...
| Packaging Grails application....
| Packaging Grails application.....
| Compiling 1 source files
| Compiling 1 source files.
| Compiling 1 source files..
| Compiling 1 source files...
| Compiling 1 source files....
| Compiling 1 source files.....
| Running Grails application
| Error 2015-04-21 11:54:24,947 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initial connections of pool .
Message: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Line | Method
->> 411 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1121 | createCommunicationsException in com.mysql.jdbc.SQLError
| 676 | readPacket . . . . . . . . . in com.mysql.jdbc.MysqlIO
| 1088 | doHandshake in ''
| 2493 | coreConnect . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly in ''
| 2311 | createNewIO . . . . . . . . . in ''
| 834 | <init> in ''
| 47 | <init> . . . . . . . . . . . in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance in com.mysql.jdbc.Util
| 416 | getInstance . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
| 347 | connect in com.mysql.jdbc.NonRegisteringDriver
| 262 | run . . . . . . . . . . . . . in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpecte dly>
>->> 3166 | readFully in com.mysql.jdbc.MysqlIO>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >| 600 | readPacket in ''
| 1088 | doHandshake . . . . . . . . . in ''
| 2493 | coreConnect in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly . . . . . . in ''
| 2311 | createNewIO in ''
| 834 | <init> . . . . . . . . . . . in ''
| 47 | <init> in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance . . . . . . in com.mysql.jdbc.Util
| 416 | getInstance in com.mysql.jdbc.ConnectionImpl
| 347 | connect . . . . . . . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . . . . . . . . . in java.lang.Thread
| Error 2015-04-21 11:54:25,051 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initial connections of pool .
Message: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Line | Method
->> 411 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1121 | createCommunicationsException in com.mysql.jdbc.SQLError
| 676 | readPacket . . . . . . . . . in com.mysql.jdbc.MysqlIO
| 1088 | doHandshake in ''
| 2493 | coreConnect . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly in ''
| 2311 | createNewIO . . . . . . . . . in ''
| 834 | <init> in ''
| 47 | <init> . . . . . . . . . . . in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance in com.mysql.jdbc.Util
| 416 | getInstance . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
| 347 | connect in com.mysql.jdbc.NonRegisteringDriver
| 262 | run . . . . . . . . . . . . . in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpecte dly>
>->> 3166 | readFully in com.mysql.jdbc.MysqlIO>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >| 600 | readPacket in ''
| 1088 | doHandshake . . . . . . . . . in ''
| 2493 | coreConnect in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly . . . . . . in ''
| 2311 | createNewIO in ''
| 834 | <init> . . . . . . . . . . . in ''
| 47 | <init> in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance . . . . . . in com.mysql.jdbc.Util
| 416 | getInstance in com.mysql.jdbc.ConnectionImpl
| 347 | connect . . . . . . . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . . . . . . . . . in java.lang.Thread
| Error 2015-04-21 11:54:25,139 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initial connections of pool .
Message: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Line | Method
->> 411 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1121 | createCommunicationsException in com.mysql.jdbc.SQLError
| 676 | readPacket . . . . . . . . . in com.mysql.jdbc.MysqlIO
| 1088 | doHandshake in ''
| 2493 | coreConnect . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly in ''
| 2311 | createNewIO . . . . . . . . . in ''
| 834 | <init> in ''
| 47 | <init> . . . . . . . . . . . in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance in com.mysql.jdbc.Util
| 416 | getInstance . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
| 347 | connect in com.mysql.jdbc.NonRegisteringDriver
| 262 | run . . . . . . . . . . . . . in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpecte dly>
>->> 3166 | readFully in com.mysql.jdbc.MysqlIO>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >| 600 | readPacket in ''
| 1088 | doHandshake . . . . . . . . . in ''
| 2493 | coreConnect in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly . . . . . . in ''
| 2311 | createNewIO in ''
| 834 | <init> . . . . . . . . . . . in ''
| 47 | <init> in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance . . . . . . in com.mysql.jdbc.Util
| 416 | getInstance in com.mysql.jdbc.ConnectionImpl
| 347 | connect . . . . . . . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . . . . . . . . . in java.lang.Thread
| Error 2015-04-21 11:54:25,169 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Err>
>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. >Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org .spr
>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. > Line | Method>->> 262 | run in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFac tor>
>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. >->> 262 | run in java.util.concurrent.FutureTask>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'lobHandlerDete cto>
>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. >->> 262 | run in java.util.concurrent.FutureTask>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'lobHandlerDetector': Invocation of init method failed; nested exc ept>
>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. >->> 262 | run in java.util.concurrent.FutureTask>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.C omm>
>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. >->> 262 | run in java.util.concurrent.FutureTask>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->> 411 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1121 | createCommunicationsException in com.mysql.jdbc.SQLError
| 676 | readPacket in com.mysql.jdbc.MysqlIO
| 1088 | doHandshake in ''
| 2493 | coreConnect in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly in ''
| 2311 | createNewIO in ''
| 834 | <init> in ''
| 47 | <init> . in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance in com.mysql.jdbc.Util
| 416 | getInstance in com.mysql.jdbc.ConnectionImpl
| 347 | connect in com.mysql.jdbc.NonRegisteringDriver
| 262 | run . . . in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Caused by EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpecte dly>
>->> 3166 | readFully in com.mysql.jdbc.MysqlIO>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 600 | readPacket in ''
| 1088 | doHandshake in ''
| 2493 | coreConnect in com.mysql.jdbc.ConnectionImpl
| 2526 | connectOneTryOnly in ''
| 2311 | createNewIO in ''
| 834 | <init> . in ''
| 47 | <init> in com.mysql.jdbc.JDBC4Connection
| 411 | handleNewInstance in com.mysql.jdbc.Util
| 416 | getInstance in com.mysql.jdbc.ConnectionImpl
| 347 | connect . in com.mysql.jdbc.NonRegisteringDriver
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
| Error Forked Grails VM exited with error
| Server running. Browse to http://localhost:8080/TestDebug
and my code is the following:
dataSource {
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
// cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "update"
url = "jdbc:mysql://localhost/nuage_v3"
driverClassName = "com.mysql.jdbc.Driver"
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = "root"
password = "root"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
properties {
maxActive = -1
minEvictableIdleTimeMillis=1800000
timeBetweenEvictionRunsMillis=1800000
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=false
validationQuery="SELECT 1"
jdbcInterceptors="ConnectionState"
}
}
}
}
The user and password are both correct, I tried reinstalling MySQL.
I've given up on trying to solve the problem.
I reinstalled grails and mysql on a diffenrent machine and it seems to work.
sorry to have bothered you all.
Thank you.
Problem is Mysql is not running.First run apache and Mysql then run grails app.Hope it will works .Also check 80 port is free or not if not then free your 80 port.
The same problem.. All of a sudden..
MySQLWorkbench works well, but grails "Unable to create initial connections of pool"
I've been spend half a day trying to fix this, searching answers. But nothing work for me..
I am trying to do the next select:
ArrayList<Personal> personalAuxList = new ArrayList<Personal>()
def campaigns = Campaign.findAllByEntidad(entidadInstance,[sort: "fechaFin", order: "desc"])
//Here a declare a DetachedCriteria using where method of domain class
def notificacionesQuery = Notificacion.where {
orden.linea.propuesta.campaign in campaigns
}
//For each persona from a search result done before
for(Personal person : result.results){
if(!personalAuxList.contains(person)){
//I add a condition to query creating new one
def notisOfPersonalQuery = notificacionesQuery.where {
personal == person
}
//Fail in this line when i list the result
def notificaciones = notisOfPersonalQuery.list()
notificaciones = notificaciones.sort{it.orden.linea.fin}.reverse()
notisOfPersonal.put(person.id, notificaciones.empty ? null : notificaciones.first())
personalAuxList.add(person)
}
}
That works fine on local, but when i upload the war, start failing in the server:
Class: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
Message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') and this_.personal_id=6616' at line 1
Trace:
Line | Method
->> 411 | handleNewInstance in com.mysql.jdbc.Util
| 386 | getInstance in ''
| 1052 | createSQLException . in com.mysql.jdbc.SQLError
| 4098 | checkErrorPacket in com.mysql.jdbc.MysqlIO
| 4030 | checkErrorPacket . . in ''
| 2490 | sendCommand in ''
| 2651 | sqlQueryDirect . . . in ''
| 2677 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2134 | executeInternal . . in com.mysql.jdbc.PreparedStatement
| 2300 | executeQuery in ''
| 97 | executeQuery . . . . in org.apache.commons.dbcp.DelegatingPreparedStatement
| 671 | doCall in grails.gorm.DetachedCriteria$_list_closure2
| 934 | doCall . . . . . . . in grails.gorm.DetachedCriteria$_withPopulatedQuery_closure9
| 669 | doCall in org.grails.datastore.gorm.GormStaticApi$_withDatastoreSession_closure20
| 302 | execute . . . . . . in org.grails.datastore.mapping.core.DatastoreUtils
| 34 | execute in org.grails.datastore.gorm.AbstractDatastoreApi
| 668 | withDatastoreSession in org.grails.datastore.gorm.GormStaticApi
| 916 | withPopulatedQuery in grails.gorm.DetachedCriteria
| 667 | list . . . . . . . . in ''
| 666 | list in ''
| 301 | search . . . . . . . in com.publidirecta.PersonalController
^ 722 | run in java.lang.Thread
I solve it finally, on local i got campaigns in the DDBB but on real server no, so i change the code to add a condition if there's no campaigns:
ArrayList<Personal> personalAuxList = new ArrayList<Personal>()
def campaigns = Campaign.findAllByEntidad(entidadInstance,[sort: "fechaFin", order: "desc"])
if (campaigns != null && campaigns.size() > 0) {
def notificacionesQuery = Notificacion.where {
orden.linea.propuesta.campaign in campaigns
}
for(Personal person : result.results){
if(!personalAuxList.contains(person)){
def notisOfPersonalQuery = notificacionesQuery.where {
personal == person
}
def notificaciones = notisOfPersonalQuery.list()
notificaciones = notificaciones.sort{it.orden.linea.fin}.reverse()
notisOfPersonal.put(person.id, notificaciones.empty ? null : notificaciones.first())
personalAuxList.add(person)
}
}
}
I have a JSON object returned from Groovy's HTTPBuilder. THE JSON contains some null values represented as JSONNull objects. The problem is that when I try to render the JSON back in a response, I get an error when it tries to render the JSONNull. I get a response that is only partially rendered. I want it to render as "null". How do I do this?
Code:
render(contentType: "text/json") {
listOfJSONObjectsThatIncludeJSONNulls
}
Error:
| Error 2013-09-17 11:33:56,965 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver - JSONException occurred when processing request: [GET] /my/action
Object is null. Stacktrace follows:
Message: Object is null
Line | Method
->> 69 | isEmpty in net.sf.json.JSONNull
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 199 | value in grails.converters.JSON
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 134 | render . . . . in ''
| 150 | render in ''
| 63 | doCall . . . . in myproject.MyController$_index_closure1_closure2_closure4$$EOHirVeS
| 477 | doRequest in groovyx.net.http.HTTPBuilder
| 417 | doRequest . . in ''
| 349 | request in ''
| 43 | doCall . . . . in myproject.MyController$_index_closure1$$EOHirVeS
| 477 | doRequest in groovyx.net.http.HTTPBuilder
| 268 | get . . . . . in ''
| 31 | index in myproject.MyController$$EOHirVeS
| 895 | runTask . . . in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run in ''
^ 680 | run . . . . . in java.lang.Thread
Partially Rendered Output:
[{"keyWithNullValue":{"array":false,"class":"net.sf.json.JSONNull"
I used the following code to render JSONNull as an empty string.
grails.converters.JSON.registerObjectMarshaller(JSONNull, { return "" })
I think you can fix it by specifying the below one in BootStrap
JSONObject.NULL.metaClass.asBoolean = {-> false}
Have a look at: how to get a real null value instead of a JSONObject.NULL value when parsing JSON in grails
I have mysql table named anto2. Which has only one column name of varchar 100. I tried to map this table in grails domain class :
class Anto {
String grailsName
static constraints = {
}
static mapping = {
table 'anto2'
grailsName column: 'name'
}
}
After I did run-app I can see my table have been added with two more columns :
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| name | varchar(100) | YES | | NULL | |
| id | bigint(20) | NO | | NULL | |
| version | bigint(20) | NO | | NULL | |
+---------+--------------+------+-----+---------+-------+
I generated static view and controller for this Domain class and when I tried to save it , I get an error in my save() method (which is generated using generate-all command). The error is as follows :
2012-07-09 23:05:26,391 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - SQLException occurred when processing request: [POST] /mysql/anto/save - parameters:
create: Create
Field 'id' doesn't have a default value. Stacktrace follows:
Message: Field 'id' doesn't have a default value
Line | Method
->> 1073 | createSQLException in com.mysql.jdbc.SQLError
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 3597 | checkErrorPacket in com.mysql.jdbc.MysqlIO
| 3529 | checkErrorPacket . in ''
| 1990 | sendCommand in ''
| 2151 | sqlQueryDirect . . in ''
| 2625 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2119 | executeInternal . in com.mysql.jdbc.PreparedStatement
| 2415 | executeUpdate in ''
| 2333 | executeUpdate . . in ''
| 2318 | executeUpdate in ''
| 105 | executeUpdate . . in org.apache.commons.dbcp.DelegatingPreparedStatement
| 25 | save in mnm.AntoController
| 1110 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . in java.lang.Thread
Why does this happen? Where I went wrong?
If you don't specify your kind of id generator, GORM will use the native strategy of your database.If you're using mysql as db, it will create your ids using IDENTITY strategy to generate them. This strategy requires to have an auto increment on your id column.
Although I think defining a strategy is better. You can use the SEQUENCE strategy:
id column:'id_anto2', generator:'sequence', params:[sequence:'tab_anto2_seq']
and then create a sequence with that same name in your database (so you don't have to use the one Hibernate creates for you automatically). It's very easy and works like a charm.
Also, to discard the version field, insert version false in your mapping block. So, it would be like:
static mapping = {
table 'anto2'
id column: 'id_anto2', generator: 'sequence', params: [sequence:'tab_anto2_seq']
grailsName column: 'name'
version false
}
It looks like you are missing id mapping. Try adding an id reference to your static mapping closure. Also, if this is an existing database you might want to set the version to false or grails might try to alter the table with a version column, depending on how you have datasource.groovy set up.
table 'anto2'
version false
id column:'anto2_ID'
grailsName column: 'name'