Bootstrap doesn't save entities - grails

I'm completely new to Grails and I'm doing the tutorial "Getting started with Grails Second Edition" by Scott Davis and Jason Rudolph.
When I'm setting up the BootStrap it seems like grails doesn't save the entities and I can't see them in my application.
I've already tried save(failOnError:true), but it compiles and saves without any errors.
Here is the code of BootStrap.groovy
package racetrack
import grails.util.GrailsUtil
class BootStrap {
def init = { servletContext ->
switch(GrailsUtil.environment){
case "development":
def jane = new Runner(
firstName:"Jane",
lastName:"Doe",
dateOfBirth:(new Date() - 365*30),
gender:"F",
address:"123 Main St",
city:"Goose",
state:"NC",
zipcode:"12345",
email:"jane#whereever.com"
)
jane.save()
if(jane.hasErrors()){
println jane.errors
}
def trot = new Race(
name:"Turkey Trot",
startDate:(new Date() + 90),
city:"Duck",
state:"NC",
distance:5.0,
cost:20.0,
maxRunners:350
)
trot.save()
if(trot.hasErrors()){
println trot.errors
}
def reg = new Registration(
paid:false,
runner:jane,
race:trot
)
reg.save()
if(reg.hasErrors()){
println reg.errors
}
break
case "production" : break
}
}
def destroy = { }
}
Thank you very much

are you in development mode?
Mybe you should add a log.debug or println statement to see if your code gets executed.
and have your tried a .save(flush:true, failOnError:true)? the flush might help

Use enums instead of Strings. Enums fit best in switch-case scenario and you can avoid mistakes. Maybe GrailsUtil.environment returns DEVELOPMENT not development? Instead of:
case "development"
use
case Environment.DEVELOPMENT

Using the grails.util.Environment enum doesn't work as is. Because the grails.util.GrailsUtil.environment returns a string, not an Environment.
You are more or less forced using strings.

Though old I thought it might help if I posted something I just found :)
if (GrailsUtil.developmentEnv){
// do dev stuff
}
else {
// do other stuff
}

Related

How to set default language to English

I've tried to set it in Bootstrap but it don't work
Also tried in ../conf/spring/resources.groovy .. it don't work either.
In Bootstrap i tried with:
Locale defLocale = new Locale("en", "GB");
Locale.setDefault(defLocale);
And in resources.groovy I tried this:
import org.springframework.web.servlet.i18n.SessionLocaleResolver
beans = {
localeResolver(SessionLocaleResolver) {
defaultLocale= new java.util.Locale("en","GB")
}
}
and a lot of variants I found when googling.
I'm sure it must be a way but it seems very hard to find.
When you create a session(for example when logging in), you can do the following:
if(setDefaultLanguage) {
session['org.springframework.web.servlet.i18n.' +
'SessionLocaleResolver.LOCALE'] = 'en-GB'
}
Try this,
String springLocaleAtt = 'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'
session[springLocaleAtt] = new Locale('en_GB')

Curious call of merge inside un-true if case

If sample is not null the line with merge(..) is called while the other 5 lines in the if are not. Why the ****? I'm jumping out the window soon...
class SampleService {
def markError(def job, def prop) {
def sample = job.getSamples().find { sample ->
sample.getProp() == prop }
if (sample == null) {
log.debug("i can see this only when sample == null")
println "i can see this only when sample == null"
def newSample = new Sample(prop: prob)
newSample.setJob(job)
newSample.merge(flush: true, failOnError: true)
}
}
}
I did already:
grails clean & grails compile.
deleted target folder and bin folder.
restarted app several times.
checked with intellij and eclipse.
I was missguided by the debuggers: The line has not been executed but highlighted. I don't know why it has been highlighted.
Hope this prevents anyone else from going crazy! :)

Grails sImple chat - Chat messages not displaying on screen

Following is a code fragment obtained from Grails website.
<script>
function messageKeyPress(field,event) {
var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
var message = $('#messageBox').val();
if (theCode == 13){
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="temp"/>
$('#messageBox').val('');
return false;
} else {
return true;
}
}
function retrieveLatestMessages() {
<g:remoteFunction action="retrieveLatestMessages" update="chatMessages"/>
}
function pollMessages() {
retrieveLatestMessages();
setTimeout('pollMessages()', 5000);
}
pollMessages();
</script>
The above code worked but when i added the Controller it stopped working. I meant that the records gets saved in the DB, but i am not able to retrieve the data and display on screen.
This is what i did
<g:remoteFunction controller="message" action="retrieveLatestMessages" update="chatMessages"/>
The MessageController function is as follows:
#Secured([ 'ROLE_USER'])
def retrieveLatestMessages() {
println "test"
def messages = Message.listOrderByDate(order: 'desc', max:1000)
[messages:messages.reverse()]
println messages
}
The above controller function gets executed (I see the println statements on console), but the data isn't getting populating on the screen.
Can someone help me out here
UPDATE
[{"class":"myPro.Message","id":3,"date":"2014-07-23T17:31:58Z","message":"dfdf","name":"hi"},{"class":"myPro.Message","id":2,"date":"2014-07-23T17:31:56Z","message":"dfdfdf","name":"dd"},{"class":"myPro.Message","id":1,"date":"2014-07-23T17:31:18Z","message":"xxxx","name":"fie"}]
Your method - retrieveLatestMessages() action in your case - must return a model, but it returns the output of println instead.
To make your code work, you must place the model in the last line, or explicitly return it by using return statement:
def retrieveLatestMessages() {
println "test"
def messages = Message.listOrderByDate(order: 'desc', max:1000)
println messages
[messages:messages.reverse()]
}
Try this
import grails.converters.JSON
#Secured([ 'ROLE_USER'])
def retrieveLatestMessages() {
println "test"
def messages = Message.listOrderByDate(order: 'asc', max:1000)
render messages as JSON
}
Enjoy.
I had this sample app working on mine with no issues but here is the thing, this process requires you to poll the page consistently and it is resource intensive:
I ended up writing a domainClass that was bound to a Datasource that was using the HQL db and was outside of my own app, the process requires a DB table to stream chat....
Alternative is to move away from polling and use websockets:
check out this video
https://www.youtube.com/watch?v=8QBdUcFqRkU
Then check out this video
https://www.youtube.com/watch?v=BikL52HYaZg
Finally look at this :
https://github.com/vahidhedayati/grails-websocket-example
This has been updated and includes the 2nd method of using winsocket to make simple chat ....

neo4j 2.0 findNodesByLabelAndProperty not working

I'm currently trying the Neo4j 2.0.0 M3 and see some strange behaviour. In my unit tests, everything works as expected (using an newImpermanentDatabase) but in the real thing, I do not get results from the graphDatabaseService.findNodesByLabelAndProperty.
Here is the code in question:
ResourceIterator<Node> iterator = graphDB
.findNodesByLabelAndProperty(Labels.User, "EMAIL_ADDRESS", emailAddress)
.iterator();
try {
if (iterator.hasNext()) { // => returns false**
return iterator.next();
}
} finally {
iterator.close();
}
return null;
This returns no results. However, when running the following code, I see my node is there (The MATCH!!!!!!!!! is printed) and I also have an index setup via the schema (although that if I read the API, this seems not necessary but is important for performance):
ResourceIterator<Node> iterator1 = GlobalGraphOperations.at(graphDB).getAllNodesWithLabel(Labels.User).iterator();
while (iterator1.hasNext()) {
Node result = iterator1.next();
UserDao.printoutNode(emailAddress, result);
}
And UserDao.printoutNode
public static void printoutNode(String emailAddress, Node next) {
System.out.print(next);
ResourceIterator<Label> iterator1 = next.getLabels().iterator();
System.out.print("(");
while (iterator1.hasNext()) {
System.out.print(iterator1.next().name());
}
System.out.print("): ");
for(String key : next.getPropertyKeys()) {
System.out.print(key + ": " + next.getProperty(key).toString() + "; ");
if(emailAddress.equals( next.getProperty(key).toString())) {
System.out.print("MATCH!!!!!!!!!");
}
}
System.out.println();
}
I already debugged through the code and what I already found out is that I pass via the InternalAbstractGraphDatabase.map2Nodes to a DelegatingIndexProxy.getDelegate and end up in IndexReader.Empty class which returns the IteratorUtil.EMPTY_ITERATOR thus getting false for iterator.hasNext()
Any idea's what I am doing wrong?
Found it:
I only included neo4j-kernel:2.0.0-M03 in the classpath. The moment I added neo4j-cypher:2.0.0-M03 all was working well.
Hope this answer helps save some time for other users.
#Neo4j: would be nice if an exception would be thrown instead of just returning nothing.
#Ricardo: I wanted to but I was not allowed yet as my reputation wasn't good enough as a new SO user.

spock test for a service in grails

I have a service in my application which return a list of tracks, here is the code for that
List<Track> getTrackListTracks(String listName, int max) {
def tracks = getTrackListTracks(listName)
if(tracks?.size() > max) {
tracks = tracks[0 ..< max]
}
return tracks
}
List<Track> getTrackListTracks(String listName) {
def tl = TrackList.findByName(listName)
if(tl?.tracks) {
return tl?.tracks?.collect { Track.read(it.trackId) }
}
}
i have to write the unit test for this but I am not able to write. Can anyone help me in this.
Thanks Already
Hopefully you've progressed beyond this, but for those coming after, the grails-spock-examples project # google code (https://github.com/pschneider-manzell/grails-spock-examples) has a wide range of examples.
More specifically, for a service (as you've asked), check out Testing Services.
Caution, though - there are a few differences between that and what is required for Grails 2. For example, if testing controllers, 'redirectArgs' is no longer valid. Make sure to also consult the Grails Documentation for differences.

Resources