Grails 2.3.8 function being called by itself? - grails

I have this grails function in my controller:
def remediationSearch() {
def resultList
if (params.rerender) {
println "<><><> remediationsearch called with rerender."
resultList = recordSearchService.individualSearch(session.oldIndRemedParams)
}
else {
params.selectedBatch = selectedBatch
session.oldIndRemedParams = params
resultList = recordSearchService.individualSearch(params)
println "<><><> remediationsearch called fresh."
}
render(template: 'indivSearchResults', model: [resultList: resultList, resultCount: resultList?.size()])
println "<><><> remediationsearch done at " + new Date()
}
which seems to get called when I call this method(in the same controller) which has nothing to do with it:
def chooseupload = {
println "<><><> Begin choose/upload at: " + System.nanoTime()
if (session.user == null) {
render(contentType: 'text/json') {
[success: true, url: createLink(controller: 'customer', action: 'logout')]
}
}
else {
selectedBatch = null
def batchList = (Batch.findAllWhere(userId: session.user.id.toLong(), [sort: "lastUpdate", order: "desc"]))
render(template: 'chooseupload', model: [batchList: batchList, batchCount: batchList.size()])
}
println "<><><> End choose/upload at: " + System.nanoTime()
}
The second method finishes executing and then the first one gets called for a reason I don't understand.
Is it(the first function) being called by some browser mechanism that is being invoked because it stores things in the session? I'd appreciate any pointers in the right direction. I get this printed as a result of calling the 'chooseupload' method:
<><><> Begin choose/upload at: 446158993759810
<><><> End choose/upload at: 446159022252873
<><><> Begin remediationSearch at: 446159080286132
<><><> Rerender call to entityRemediationSearch.
<><><> End remediationSearch at: 446159135646835
So what is happening is that the chooseupload function's template renders but it is immediately rendered over by the template rendered by the remediationSearch() function. And that is the undesired result that led me to investigate this whole thing.

Not sure if this makes more sense as a comment or answer, but I don't have the 50 reputation needed to make a comment, so here it is as an answer :-)
I noticed that in your text output you have the line:
<><><> Rerender call to entityRemediationSearch.
But that is not included in the code you provided. Would it be possible that you're using an IDE that has not properly cleaned out old versions of the class files? Did chooseupload() call remediationSearch() at one point in time? If so, it seems like it would be good to try running this from the command line, after running grails clean.

Related

function lines after httpRequest are not executed in groovy jenkins pipeline

None of the lines after making httpRequest are getting executed. Everything else works fine in this function. What could be going wrong here?
However, network request is going fine and I am able to see the response in the console. httpRequest is being made via plugin
I've even tried CURL - but lines after curl are not executed.
#NonCPS
def doPRCommentBasedTesting() {
def causes = currentBuild.rawBuild.getCauses()
def commentURL
for(cause in causes) {
if (cause.class.toString().contains("GitHubPullRequestCommentCause")) {
commentURL = cause.getCommentUrl()
commentURL = commentURL.substring(commentURL.lastIndexOf("-") + 1)
println "This job was caused by job " + commentURL
def url1 = "https://<git_url>/api/v3/repos/<owner>/<repo>/issues/comments/" + commentURL
def commentText = httpRequest authentication: '<auth_cred>', url: url1, consoleLogResponseBody: true
println commentText
println commentText.getClass()
println "hello world, how are you doing today?"
}
else {
println "Root cause : " + cause.toString()
}
}
println "==============================="
return 0
}
A non cps function does not have the ability to pause in between because it runs in a go. You need to put network call into a different function that is not marked as nonCPS and then it will work. In general the nonCPS block should be very small and limited to code that cannot be serialised

Want to Delete and Insert in same Action

I have one action in my controller that upload csv file with list of numbers.
Now the process is first I need to delete existing data from the table on certain condition then insert fresh data.
My snippet code is as follows..
Controller:
#Transactional
def uploadFile() {
if(!params?.updateExisting){
println "Going to call service to delete records"
myService.deleteNumbers()
def newList = Number.findAllByDeleted(false)
println "NEW LS:"+newList
//HERE I'm GETTING BLANK
}
def file = request.getFile("fileCsv")
file.inputStream
.splitEachLine(',') { fields ->
Number.withNewTransaction {
def number = fields[0]?.toString().replaceAll(" ","").replaceAll("-","")
Number numberInstance = new Number()
def numberExist = Number.findAllByNumberAndDeleted(number, false)
//HERE NUMBER IS STILL EXIST
if(!numberExist){
numberInstance.number = number
numberInstance.save(flush:true)
count++
}else{
println "Number exist: "+number
}
}
}
redirect(uri:'/number/list')
}
myService:
#Transactional
def deleteNumbers(){
Number.findAll().each {
it.deleted = true
it.save(flush: true)
}
}
After calling service method deleteNumbers I'm getting blank list NEW LS:[], But then def numberExist = Number.findAllByNumberAndDeleted(number, false) returns me a number means already exist.
Thanks..
Try removing Number.withNewTransaction closure. Your code should work..

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 ....

Grails Asynchronous Request with HttpSession behaves strangely

I have a simple controller with an action for a long running task and an action for checking a status of the long task:
class AsyncController {
def index() { }
def longTerm() {
session.longTerm = 0
session.longTermDone = false
task {
for (int i; i < 10; i++ ) {
try {
sleep(3000) //NOT WORKING
println " TASK: sessionID ${session.id} value ${session.longTerm++}"
//sleep(3000) //WORKING
} catch (e) {
println(e.class.name)
}
}
session.longTermDone = true
}
render(text: [] as JSON, status: 200)
}
def longTermStatus() {
println "STATUS: sessionID ${session.id} value ${session.longTerm}"
render(text: [successCount: session.longTerm, done: session.longTermDone] as JSON, status: 200)
}
}
In the longTerm action there is a problem with HttpSession.
If the first line of code in the task closure is doing something with HttpSession the rest of the code is working fine. But if the first line is doing something else I get NullPointerException when I try to access session.id
Working code example is at https://github.com/machacekjan/StackOverflowAsyncRequest
Does anyone know why Grails behaves this way?
The issue here appears to be that you're performing the render() outside of the tasks block. If you move render() inside the tasks block, the NullPointerException disappears.
I think this is because the render() finishes the request and you bypass the Servlet 3 Async support. You need to return a promise from the action, which task() does .
Unfortunately, render() doesn't seem to work with the async stuff in Grails 2.3.7 or 2.3.10. But that's a separate issue.

Resources