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! :)
Related
We have a Jenkins pipeline script that requests approval from the user after all the preparatory steps are complete, before it actually applies the changes.
We want to add a timeout to this step, so that if there is no input from the user then the build is aborted, and are currently working on using this kind of method:
try {
timeout(time: 30, unit: 'SECONDS') {
userInput = input("Apply changes?")
}
} catch(err) {
def user = err.getCauses()[0].getUser()
if (user.toString == 'SYSTEM') { // if it's system it's a timeout
didTimeout = true
echo "Build timed out at approval step"
} else if (userInput == false) { // if not and input is false it's the user
echo "Build aborted by: [${user}]"
}
}
This code is based on examples found here: https://support.cloudbees.com/hc/en-us/articles/226554067-Pipeline-How-to-add-an-input-step-with-timeout-that-continues-if-timeout-is-reached-using-a-default-value and other places online, but I really dislike catching all errors then working out what's caused the exception using err.getCauses()[0].getUser(). I'd rather explicitly catch(TimeoutException) or something like that.
So my question is, what are the actual exceptions that would be thrown by either the approval step timing out or the userInput being false? I haven't been able to find anything in the docs or Jenkins codebase so far about this.
The exception class they are referring to is org.jenkinsci.plugins.workflow.steps.FlowInterruptedException.
Cannot believe that this is an example provided by CloudBeeds.
Most (or probably all?) other exceptions won't even have the getCauses() method which of course would throw another exception then from within the catch block.
Furthermore as you already mentioned it is not a good idea to just catch all exceptions.
Edit:
By the way: Scrolling further down that post - in the comments - there you'll find an example catching a FlowInterruptedException.
Rather old topic, but it helped me, and I've done some more research on it.
As I figured out, FlowInterruptedException's getCauses()[0] has .getUser() only when class of getCauses()[0] is org.jenkinsci.plugins.workflow.support.steps.input.Rejection. It is so only when timeout occured while input was active. But, if timeout occured not in input, getCause()[0] will contain object of another class: org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution$ExceededTimeout (directly mentioning timeout).
So, I end up with this:
def is_interrupted_by_timeout(org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e, Boolean throw_again=true) {
// if cause is not determined, re-throw exception
try {
def cause = e.getCauses()[0]
def cause_class = cause.getClass()
//echo("cause ${cause} class: ${cause_class}")
if( cause_class == org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution$ExceededTimeout ) {
// strong detection
return true
} else if( cause_class == org.jenkinsci.plugins.workflow.support.steps.input.Rejection ) {
// indirect detection
def user = cause.getUser()
if( user.toString().equals('SYSTEM') ) {
return true
} else {
return false
}
}
} catch(org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException e_access) {
// here, we may deal with situation when restricted methods are not approved:
// show message and Jengins' admin will copy/paste and execute them only once per Jenkins installation.
error('''
To run this job, Jenkins admin needs to approve some Java methods.
There are two possible ways to do this:
1. (better) run this code in Jenkins Console (URL: /script):
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval;
def scriptApproval = ScriptApproval.get()
scriptApproval.approveSignature('method org.jenkinsci.plugins.workflow.steps.FlowInterruptedException getCauses')
scriptApproval.approveSignature('method org.jenkinsci.plugins.workflow.support.steps.input.Rejection getUser')
scriptApproval.save()
'''.stripIndent())
return null
}
if( throw_again ) {
throw e
} else {
return null
}
}
And now, you may catch it with something like this:
try {
...
} catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException err) {
if( is_interrupted_by_timeout(err) ) {
echo('It is timeout!')
}
}
P.S. I agree, this is bad Jenkins design.
I am working on Jenkins version 2.32.1 pipeline. I want to extract the parameters that were chosen in the previous build of my job.
In our previous Jenkins instance ( 1.627 ) we were using jenkins.model.Jenkins.instance.getItem(job).lastBuild.getBuildVariables().get(param);
For some reason this is not working in this version (I also tried disabling the sandbox).
Any pointers on how to accomplish it?
Simplified version of the previous script:
def build = Jenkins.get().getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).find {it.displayName == 'YOUR_JOB_NAME_HERE'}?.getLastBuild()
build.actions.find{ it instanceof ParametersAction }?.parameters.each {echo "${it.name}=${it.value}"}
Actually a little bit shorter version for those who want to get the params for the current build from the previous run and is working on new 2+ Jenkins versions.
To get 1 particular parameter:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters.find{it.name == 'cls'}?.value
Get all params respectfully:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters
Something like this might work, based on https://stackoverflow.com/a/19564602/3920342:
def h = hudson.model.Hudson.instance
def r = null
h.getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).each {project ->
if (project.displayName.equals('YOUR_JOB_NAME')) {
r = project
}
}
r.getBuilds().findAll { b -> // here we loop over all past builds, apply some filter if necessary
def p = b?.actions.find{ it instanceof ParametersAction }?.parameters
p.each {
echo "parameter ${it.name}: ${it.value}"
}
}
For those who are not able to access getActions() due to admin permissions i.e. facing the following error:
Scripts not permitted to use method hudson.model.Actionable getActions
They can copy the parameter variables to the env and get them using build.previousBuild.buildVariables
stage('Prepare environment') {
steps {
script {
env.MY_PARAM_COPY = "${MY_PARAM}"
}
}
}
println("MY_PARAM in previous build: ${currentBuild.previousBuild.buildVariables["MY_PARAM_COPY"]}")
That's how I made it works, answer from #dan.goriaynov and #jherb caused some CPS closure issues for me.
(the gist of the code is to allow only greater TAG number than the previous one to be deployed)
stage('Validate build number') {
def previous_build = currentBuild.getPreviousBuild().getRawBuild();
def PREVIOUS_TAG = '';
for (int i = 0; i < previous_build.allActions.size(); i++) {
if (previous_build.allActions[i] in hudson.model.ParametersAction) {
PREVIOUS_TAG = previous_build.allActions[i].getParameter("TAG").value
}
}
if (PREVIOUS_TAG.toInteger() > TAG.toInteger()) {
echo PREVIOUS_TAG
error('TAG number needs to be greater than the previous one')
}
}
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.
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 ....
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
}