Grails DetachedCriteria using 'where' throw SyntaxErrorException - mysql

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)
}
}
}

Related

Export data from SQL to CSV with modified format

Suppose I have a table in SQL named 'myTable'. It contains 3 columns; 'id', 'lat' and 'lng'
| id | lat | lng |
|------+--------+--------|
| 1 | 1.11 | 1.22 |
| 2 | 2.11 | 2.22 |
| 3 | 3.11 | 3.22 |
| 4 | 4.11 | 4.22 |
| .... | .... | .... |
I want to export it to CSV. I expect the result become like this in the CSV file :
| | A | B | C | D | ....
------+-----+------+--------+------+--------
| 1 | 1.11 | 2.11 | 3.11 | 4.11 | .... //contains 'lat'
| 2 | 1.22 | 2.22 | 3.22 | 4.22 | .... //contains 'lng'
Can you help me? I'm using PHP. Thanks a lot.
This might actually be something which would be best handled in your PHP script, rather than in MySQL. Assuming your are using mysqli, you could try something like this:
$sql = "SELECT id, lat, lng FROM yourTable ORDER BY id";
$result = $conn->query($sql);
$row1 = NULL;
$row2 = NULL;
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($row1 != NULL) {
$row1 .= ",";
$row2 .= ",";
}
$row1 .= $row["lat"];
$row2 .= $row["lng"];
}
}
At the end of the loop in the above script, $row1 and $row2 should contain the first two rows of the output file you expect. The only steps missing might be the header, if you want that, and also the details of how to write a string to a text file.

grails 3.1.1 & json views

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

Jersey Sub-Resource Locators Error

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

"Duplicate entry '' for key" in Grails Database Migration using hasOne

Using Grails Database Migration Plugin 1.4 I want have the following structure of my existing database:
class StickerGroup {
}
Now I added the class Company and updated the class StickerGroup:
class StickerGroup {
static constraints = { company nullable: true, unique: true }
static belongsTo = [company: Company]
}
class Company {
static hasOne = [stickerGroup: StickerGroup]
}
I created the migration file and then I perform grails dbm-update. After that I get the following error log:
2015-01-20 15:03:49,549 [main] ERROR liquibase - Change Set 2015-01-20-update-Company.groovy::1421762562430-2::mg (generated) failed. Error: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id'
Message: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id'
Line | Method
->> 62 | execute in liquibase.executor.jvm.JdbcExecutor
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 104 | execute in ''
| 1091 | execute . . . . . in liquibase.database.AbstractDatabase
| 1075 | executeStatements in ''
| 317 | execute . . . . . in liquibase.changelog.ChangeSet
| 27 | visit in liquibase.changelog.visitor.UpdateVisitor
| 58 | run . . . . . . . in liquibase.changelog.ChangeLogIterator
| 114 | update in liquibase.Liquibase
| 26 | doCall . . . . . in DbmUpdate$_run_closure1_closure2
| 59 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2_closure11
| 133 | executeInSession in grails.plugin.databasemigration.MigrationUtils
| 51 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2
^ 25 | doCall . . . . . in DbmUpdate$_run_closure1
Caused by MySQLIntegrityConstraintViolationException: Duplicate entry '' for key 'company_id'
->> 377 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 360 | getInstance in ''
| 971 | createSQLException in com.mysql.jdbc.SQLError
| 3887 | checkErrorPacket in com.mysql.jdbc.MysqlIO
| 3823 | checkErrorPacket in ''
| 2435 | sendCommand in ''
| 2582 | sqlQueryDirect . in ''
| 2526 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2484 | execSQL . . . . . in ''
| 848 | execute in com.mysql.jdbc.StatementImpl
| 742 | execute . . . . . in ''
| 92 | doInStatement in liquibase.executor.jvm.JdbcExecutor$1ExecuteStatementCallback
| 55 | execute . . . . . in liquibase.executor.jvm.JdbcExecutor
| 104 | execute in ''
| 1091 | execute . . . . . in liquibase.database.AbstractDatabase
| 1075 | executeStatements in ''
| 317 | execute . . . . . in liquibase.changelog.ChangeSet
| 27 | visit in liquibase.changelog.visitor.UpdateVisitor
| 58 | run . . . . . . . in liquibase.changelog.ChangeLogIterator
| 114 | update in liquibase.Liquibase
| 26 | doCall . . . . . in DbmUpdate$_run_closure1_closure2
| 59 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2_closure11
| 133 | executeInSession in grails.plugin.databasemigration.MigrationUtils
| 51 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2
^ 25 | doCall . . . . . in DbmUpdate$_run_closure1
liquibase.exception.MigrationFailedException: Migration failed for change set 2015-01-20-update-Company.groovy::1421762562430-2::mg (generated):
Reason: liquibase.exception.DatabaseException: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id':
Caused By: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id':
Caused By: Duplicate entry '' for key 'company_id'
at liquibase.changelog.ChangeSet.execute(ChangeSet.java:347)
at liquibase.changelog.visitor.UpdateVisitor.visit(UpdateVisitor.java:27)
at liquibase.changelog.ChangeLogIterator.run(ChangeLogIterator.java:58)
at liquibase.Liquibase.update(Liquibase.java:114)
at DbmUpdate$_run_closure1_closure2.doCall(DbmUpdate:26)
at _DatabaseMigrationCommon_groovy$_run_closure2_closure11.doCall(_DatabaseMigrationCommon_groovy:59)
at grails.plugin.databasemigration.MigrationUtils.executeInSession(MigrationUtils.groovy:133)
at _DatabaseMigrationCommon_groovy$_run_closure2.doCall(_DatabaseMigrationCommon_groovy:51)
at DbmUpdate$_run_closure1.doCall(DbmUpdate:25)
Caused by: liquibase.exception.DatabaseException: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id'
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:62)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:104)
at liquibase.database.AbstractDatabase.execute(AbstractDatabase.java:1091)
at liquibase.database.AbstractDatabase.executeStatements(AbstractDatabase.java:1075)
at liquibase.changelog.ChangeSet.execute(ChangeSet.java:317)
... 8 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '' for key 'company_id'
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:971)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:848)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:742)
at liquibase.executor.jvm.JdbcExecutor$1ExecuteStatementCallback.doInStatement(JdbcExecutor.java:92)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:55)
... 12 more
How can I fix this error?

How to tell Grails to render JSONNull as null?

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