Grails 2.3.2: findOrCreate using Enums in Bootstrap - mysql

I am having troubles with using the findOrCreateBy method in the Bootstrap.groovy.
class Guest {
String firstname
String lastname
Gender gender
static constraints = {
firstname blank: false
lastname blank: false
gender nullable: false
}
}
enum Gender {
MALE('male'), FEMALE('female')
final String v
Gender(String s) { v = s }
}
And in the Bootstrap I try to create Guests if they do not exist yet.
Guest guest = Guest.findOrCreateByFirstnameAndLastnameAndGender(firstname, lastname, Gender.MALE)
guest.save()
The first time I run the app against MySQL everything works fine. The apps starts without any error. If I run the app a second time (this time with guest in the database) I get the following failure.
| Error 2013-11-17 14:27:37,621 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Message: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Line | Method
->> 105 | methodMissing in org.grails.datastore.gorm.GormStaticApi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 106 | createGuest in BootStrap
| 102 | createGuest . . . . . . . . . . in ''
| 66 | doCall in BootStrap$_closure1
| 308 | evaluateEnvironmentSpecificBlock in grails.util.Environment
| 301 | executeForEnvironment in ''
| 277 | executeForCurrentEnvironment . . in ''
| 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
It seems the the first time Gorm writes values '0' and '1' to the database. In the second run it fails to convert these 0 and 1 into the corresponding enum value. Can anybody tell me what I am doing wrong?

Try this - Add the parameter generateSimpleParameterMetadata=true to your url connect string,
...
url = "jdbc:mysql://localhost/bootstraptest?generateSimpleParameterMetadata=true"
...
This has something to do with the way the driver interprets the enum meta data (frankly i don't understand it well) see http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
This solution is very db specific, so you don't need any other changes
Note that the actual enum label will now be stored in the database ('NEW', 'WIP', 'DONE' instead of 0, 1, 2)

I think this is related to mysql, I dont have mysql to test it against and never worked with mysql, but try to specifically map the enum, like this:
static mapping = {
...
gender column: 'gender', sqlType: 'enum', name: 'gender'
}
ref
And if you are manually creating your database table , try to create the enum for your columns similar to this:
CREATE TABLE sizes (
name ENUM('small', 'medium', 'large')
);
ref
This is another article that can help here

I suggest to change mapping using IdentityEnumType:
static mapping = {
...
gender column: 'gender', type: IdentityEnumType
}
Modify your Enum, by adding id to it:
public enum Gender {
MALE (1, "male"),
FEMALE (2, "female"),
final Integer id
final String value
Gender (Integer id, String value) {
this.id = id
this.value = value
}
String getValue() {
return value
}
String toString() {
return name()
}
String getKey() {
return name()
}
That should help you.

Related

How can I use Perl's format function?

I'm learning Perl formatting by following the tutorial at Perl - Formats, but when I type their example into my IDE:
format EMPLOYEE =
===================================
#<<<<<<<<<<<<<<<<<<<<<< #<<
$name $age
######.##
$salary
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
#n = ("Ali", "Raza", "Jaffer");
#a = (20,30, 40);
#s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (#n) {
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
I get the error:
Scalar found where operator expected at .\qb.pl line 7, near "$name $age"
(Missing operator before $age?)
syntax error at .\qb.pl line 7, near "$name $age"
Execution of .\qb.pl aborted due to compilation errors.
I'm using Perl 5, version 30, Subversion 2 (v5.30.2) built for MSWin32-x64-multi-thread.
When I run your code on 5.24, I see this warning message:
Use of comma-less variable list is deprecated at...
which points to the $name $age line as well.
When I enable diagnostics, I get this explanation:
(D deprecated) The values you give to a format should be
separated by commas, not just aligned on a line.
When I add the comma as follows:
$name,$age
the warning goes away, and I get this output:
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
This warning became an error in 5.28, according to perl5280delta.
Your first mistake was in thinking that formats were a useful tool that would solve your problem. Formats have been largely ignored for almost as long as I've been using Perl. You'll probably find that using Perl6::Form is a better approach.
Your second mistake was in thinking that Tutorials Point was a good place to get information about anything. The tutorials there are written by people who seem to know next to nothing about their subject and (as you have seen here) the examples are riddled with typos that makes them next to useless.
If you're determined to use Perl formats, then the perlform manual page would be the best place to start.
Perhaps the following code sample is easier to read. The output is also easier to comprehend at a quick glance:
use strict;
use warnings;
my($name, $age, $salary);
while(<DATA>) {
($name, $age, $salary) = split;
write;
}
format STDOUT_TOP =
Employee Age Salary
----------------------------------------
.
format STDOUT =
#<<<<<<<<<<<<<<<<<<<<<< #<< ######.##
$name, $age, $salary
.
__DATA__
Ali 20 2000.00
Raza 30 2500.00
Jaffer 40 4000.00
Output
Employee Age Salary
----------------------------------------
Ali 20 2000.00
Raza 30 2500.00
Jaffer 40 4000.00
There are many ways to provide input data. One of them is a hash to keep related data.
use strict;
use warnings;
my %employees = (
Ali => { age => 20, salary => 2000.00},
Raza => { age => 30, salary => 2500.00},
Jaffer => { age => 40, salary => 4000.00}
);
my($name, $age, $salary);
for $name (sort keys %employees) {
($age, $salary) = #{$employees{$name}}{qw/age salary/};
write;
}
format STDOUT_TOP =
Employee Age Salary
----------------------------------------
.
format STDOUT =
#<<<<<<<<<<<<<<<<<<<<<< #<< ######.##
$name, $age, $salary
.
Output
Employee Age Salary
----------------------------------------
Ali 20 2000.00
Jaffer 40 4000.00
Raza 30 2500.00

Grails stack overflow error when trying to serialize domain class to JSON

More beginner problems for me with Groovy/Grails.
Groovy version 2.4.8 Grails version 2.5.1
I have tried multiple ways to serialize an instance of one of my domain classes or an ArrayList of instances of that domain class.
When trying to serialize a single instance I get a stack overflow error.
The code and stack trace is shown below
def getAdvisors(String keystrokes, String firm) {
def advisors = priceBlotterService.advisorsForKeystrokes(keystrokes, "", 30)
def a1 = advisors[0]
def json = JsonOutput.toJson(a1)
}
Caused by InvocationTargetException: null
->> 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
^ 745 | run . . . in java.lang.Thread
Caused by StackOverflowError: null
->> 100 | invoke in org.codehaus.groovy.reflection.CachedMethod
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 62 | getProperty in groovy.lang.MetaBeanProperty
| 42 | getValue in groovy.lang.PropertyValue
| 388 | getProperties in org.codehaus.groovy.runtime.DefaultGroovyMethods
| 290 | writeObject in groovy.json.JsonOutput
| 329 | writeArray in ''
| 286 | writeObject in ''
| 424 | writeMap in ''
| 294 | writeObject in ''
| 329 | writeArray in ''
| 286 | writeObject in ''
| 424 | writeMap in ''
Advisor, Case, and Firm Classes:
class Advisor {
String firstName
String lastName
String fullName
String city
String state
Firm firm
static belongsTo = [Case, Firm]
static hasMany = [cases:Case]
static constraints = {
}
}
class Case {
String caseCode
String internalComment
String externalComment
Date dateCreated
String createdBy
Date dateUpdated
String updatedBy
static belongsTo = [owner:User, caseStatusType:CaseStatusType]
static hasMany = [advisor:Advisor]
static mapping = {
dateCreated sqlType: "date"
dateUpdated sqlType: "date"
}
static constraints = {
dateCreated(nullabe: false)
dateUpdated(nullable: false)
}
}
class Firm {
String name
static constraints = {
}
}
Edit:
I found a fundamental problem with my domain class/table that could have something to do with this and needs to be resolved.
I try to do a simple get from the user table and I get an error message indicating there is no id field. Having a hard time figuring out what is going on. Some details are below.
line of code
User[] users = User.findAll()
error message
org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not extract ResultSet; bad SQL grammar [n/a]; nested exception is org.postgresql.util.PSQLException: ERROR: column this_.id does not exist Position: 8
User class
class User {
String firstName
String lastName
static constraints = {
}
}
ddl for user table
CREATE TABLE "user"
(
id BIGINT DEFAULT nextval('user_id_seq'::regclass) PRIMARY KEY NOT NULL,
first_name VARCHAR(30),
last_name VARCHAR(30),
version BIGINT
);
CREATE UNIQUE INDEX user_id_uindex ON "user" (id);
Edit:
Fixed issuer with User table/class. User is a keyword in Postresql so I just refactored to EndUser.
I suspect there is some issue with the data structure you have, which is causing the JSON builder to go into an infinite loop.
You may want to review this for info on issues with dates: https://issues.apache.org/jira/browse/GROOVY-7682
This may work instead:
import grails.converters.JSON
def json = new JSON(a1)
I can't find this documented anywhere, but don't use JsonOutput for domain objects.
I just ran into a similar issue. DomainObject instances have this "neat" property called all which will return every instance of the domain object.
When JsonOutput tries to serialize your object, it uses DefaultGroovyMethods.getProperties, which includes the all property. This means that your code will cause hibernate to load EVERY copy of your Advisor class into memory.
In my case I ran out of memory. My system got stuck in garbage collection loops.
In your case, when your a1 class is being rendered, it is including the 'all' property, which is the full list of all Advisors. Each Advisor also has an "all" property so it tries to render every advisor. And so on. Eventually giving you your stack overflow.

ERROR errors.GrailsExceptionResolver - ConcurrentModificationException occurred when processing request:

I have a Grails 2.4.5 GSP page which loads two iFrame:
<iframe scrolling="no"
src="${createLink(controller:'admin', action:'page1', id: serviceCard.id)}"></iframe>
<iframe scrolling="no"
src="${createLink(controller:'admin', action:'page2', id: serviceCard.id)}"></iframe>
After every second reload or so I have the following problem. Note that this does not occur all the time.
On my GSP I see Error 500. The console shows the following error:
2015-08-01 21:41:11,530 [http-nio-8080-exec-3] ERROR errors.GrailsExceptionResolver - ConcurrentModificationException occurred when processing request: [GET] /test/adminServiceCard/previewCard/4b6dc4730fd3acd80a
Stacktrace follows:
Message: Error processing GroovyPageView: Error executing tag <asset:stylesheet>: null
Line | Method
->> 527 | doFilter in /grails-app/views/adminServiceCard/previewCard.gsp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caused by GrailsTagException: Error executing tag <asset:stylesheet>: null
->> 6 | doCall in /grails-app/views/adminServiceCard/previewCard.gsp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caused by ConcurrentModificationException: null
->> 1456 | sort in java.util.ArrayList
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 175 | sort in java.util.Collections
| 145 | fileNameWithoutExtensionFromArtefact in asset.pipeline.AssetHelper
| 99 | loadRequiresForTree in asset.pipeline.DirectiveProcessor
| 76 | getFlattenedRequireList in ''
| 83 | getDependencyList in asset.pipeline.AssetPipeline
| 79 | doCall . . . . . in asset.pipeline.grails.AssetsTagLib$_closure2
| 6 | doCall in Users_mg_Documents_Grails_GGTS3_6_3_test_grails_app_views_adminServiceCard_previewCard_gsp$_run_closure1
| 10 | run . . . . . . in Users_mg_Documents_Grails_GGTS3_6_3_test_grails_app_views_adminServiceCard_previewCard_gsp
| 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter . . . . in grails.plugin.cache.web.filter.AbstractFilter
| 53 | doFilter in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
| 62 | doFilter . . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 46 | doFilterInternal in org.grails.jaxrs.web.JaxrsFilter
| 1142 | runWorker . . . in java.util.concurrent.ThreadPoolExecutor
| 617 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . . in java.lang.Thread
Edit: Here is the content of adminServiceCardpreview_gsp.groovy.gsp:
import org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin
import org.codehaus.groovy.grails.web.pages.GroovyPage
import org.codehaus.groovy.grails.web.taglib.*
import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
import org.springframework.web.util.*
import grails.util.GrailsUtil
class gsp_majestella_adminServiceCardpreview_gsp extends GroovyPage {
public String getGroovyPageFileName() { "/WEB-INF/grails-app/views/adminServiceCard/preview.gsp" }
public Object run() {
Writer out = getOut()
Writer expressionOut = getExpressionOut()
registerSitemeshPreprocessMode()
printHtmlPart(0)
createTagBody(1, {->
printHtmlPart(1)
invokeTag('javascript','g',5,['library':("jquery"),'plugin':("jquery")],-1)
printHtmlPart(1)
invokeTag('stylesheet','asset',7,['src':("perfect-scrollbar/perfect-scrollbar.min.css")],-1)
printHtmlPart(2)
invokeTag('javascript','asset',8,['src':("perfect-scrollbar/perfect-scrollbar.jquery.min.js")],-1)
printHtmlPart(2)
invokeTag('javascript','asset',9,['src':("jquery.cycle.all.js")],-1)
printHtmlPart(1)
invokeTag('stylesheet','asset',11,['src':("preview.css")],-1)
printHtmlPart(3)
})
invokeTag('captureHead','sitemesh',13,[:],1)
printHtmlPart(4)
createTagBody(1, {->
printHtmlPart(5)
if(true && (showCard == true)) {
printHtmlPart(6)
if(true && (serviceCard.imageItems)) {
printHtmlPart(7)
expressionOut.print(createLink(controller:'image', action:'getImage', id:serviceCard.imageItems[0].id, absolute:true))
printHtmlPart(8)
}
printHtmlPart(9)
expressionOut.print(serviceCard?.title)
printHtmlPart(10)
expressionOut.print(serviceCard?.company?.name)
printHtmlPart(11)
}
printHtmlPart(12)
if(true && (showDetail == true)) {
printHtmlPart(13)
loop:{
int i = 0
for( imageItem in (serviceCard.imageItems) ) {
printHtmlPart(14)
expressionOut.print(createLink(controller:'image', action:'getImage', id:imageItem.id, absolute:true))
printHtmlPart(15)
i++
}
}
printHtmlPart(16)
expressionOut.print(raw(serviceCard.description))
printHtmlPart(17)
}
printHtmlPart(18)
})
invokeTag('captureBody','sitemesh',116,[:],1)
printHtmlPart(19)
}
public static final Map JSP_TAGS = new HashMap()
protected void init() {
this.jspTags = JSP_TAGS
}
public static final String CONTENT_TYPE = 'text/html;charset=UTF-8'
public static final long LAST_MODIFIED = 1438521220000L
public static final String EXPRESSION_CODEC = 'html'
public static final String STATIC_CODEC = 'none'
public static final String OUT_CODEC = 'none'
public static final String TAGLIB_CODEC = 'none'
}
How can I solve this problem?
This error looks a lot like this one from asset pipeline.
You should remove all //=require in previewCard.gsp and then work through which is causing the error.

Grails or Hibernate not creating missing table

I'm new to Grails so forgive my ignorance--if other info is helpful I'll do my best to get it posted.
I've created a single domain model class ToolKitComponent that is defined as:
class ToolKitComponent {
String componentName
String componentVersion
int componentDownloads
Date compnentLastUpdate
static constraints = {
}
}
I have a controller that I just want to test the ORM by persisting an example, so here's the contents of the controller:
def index() {
ToolKitComponent i = new ToolKitComponent()
i.setComponentName("TestComponent")
i.setComponentVersion("v1.10")
i.setComponentDownloads(1)
i.setCompnentLastUpdate(new Date())
i.save()
}
I've installed the MySql database plugin and updated my DataSource.groovy to:
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
loggingSql = true
}
// other settings
environments {
development {
dataSource {
String dbCreate = "create"
String url = "jdbc:mysql://localhost/testDataBase"
String username = "myUser"
String password = "myPass"
}
}
}
I've created the database testDataBase and granted all to the username.
When I run the application, I get:
Hibernate: insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?)
| Error 2012-07-11 20:01:52,727 [http-bio-8080-exec-2] ERROR util.JDBCExceptionReporter - Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]
| Error 2012-07-11 20:01:52,752 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - JdbcSQLException occurred when processing request: [GET] /TestProject/
Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]. Stacktrace follows:
Message: Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]
Line | Method
->> 329 | getJdbcSQLException in org.h2.message.DbException
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 169 | get in ''
| 146 | get . . . . . . . . in ''
| 4753 | readTableOrView in org.h2.command.Parser
| 4731 | readTableOrView . . in ''
| 954 | parseInsert in ''
| 375 | parsePrepared . . . in ''
| 279 | parse in ''
| 251 | parse . . . . . . . in ''
| 217 | prepareCommand in ''
| 415 | prepareLocal . . . in org.h2.engine.Session
| 364 | prepareCommand in ''
| 1121 | prepareCommand . . in org.h2.jdbc.JdbcConnection
| 71 | <init> in org.h2.jdbc.JdbcPreparedStatement
| 267 | prepareStatement . in org.h2.jdbc.JdbcConnection
| 1051 | prepareStatement in ''
| 508 | prepareStatement . in org.apache.commons.dbcp.DelegatingConnection
| 400 | prepareStatement in org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
| 11 | index . . . . . . . in TestProject.HomeController
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
I'm using Grails 2.0.4.
Any help is appreciated!
Take away the String in your datasource definition
environments {
development {
dataSource {
dbCreate = "create"
url = "jdbc:mysql://localhost/testDataBase"
username = "myUser"
password = "myPass"
}
}
}

This query in Linq to Sql

i have in my DB table TBus fields like s1,s2.s3.s4,...sn
i get the seatNumber as a parameter and want to get that field just like i have it in my code.
Any idea please.
private string checkSeatValue(int busTripId, int seatNumber)
{
string sNumber = "s" + seatNumber.ToString();
// Some code here
string sqlCommand = "SELECT " + sNumber + " FROM TBus WHERE Id=" + busTripId + "";
// More code here
}
If you want pure Linq2SQL code, you should get the TBus object:
var bus = yourDataContext.GetTable<TBus>().Where(bus => bus.BusTripId == busTripId).SingleOrDefault();
And then switch your seat variable to get the desired field:
var seat;
switch(seatNumber)
{
case "s1":
seat = bus.Seat1;
break;
case "s2":
seat = bus.Seat2;
break;
// And so it goes on...
}
However, you can do pure SQL code via Linq also or play with reflection.
-- EDIT
As I said in the comment, I believe your database model can be improved. My advice would be having two tables:
TBus Table
TBusId - int [PK]
...
TBusSeat Table
TBusSeatId - int [PK]
TBusIs - int [FK referencing TBus.TBusId]
SeatNumber - int
...
That way, you have more natural flexibility to deal with those king of situations. Consider the following set of data:
TBus Table
TBusId
------
1
2
TBusSeat Table
TBusSeatId | TBusId | SeatNumber | PassengerName
------------------------------------------------
1 1 1 Josh Doe
2 1 2 John Doe
3 1 3 Jane Doe
4 2 1 Jack Doe
So, to deal with your desired query with Linq2SQL, it would be simple as this:
var seat = yourDataContext.GetTable<TBusSeat>().Where(seat => seat.TBusId == 1 && seat.SeatNumber == 2).SingleOrDefault();
And calling seat.PassengerName would result in John Doe.