I'm struggling a little creating a timestamp in a format that I want using a scripted pipeline in Jenkins. Here's my code from the pipeline:
def cal = Calendar.instance
def dateFormat = 'YYYYMMDD-hhmmss'
def timeZone = TimeZone.getTimeZone('CST')
def timeStamp = cal.time.format(dateFormat,timeZone)
println "Timestamp is: ${timeStamp}"
env.BUILD_TIMESTAMP = timeStamp
When I run via Jenkins, I get the following:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field java.util.GregorianCalendar time
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:387)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:371)
I've seen mention of similar issues with different fields online, but the workaround of adding it to scriptapproval.xml (and restarting Jenkins) doesn't seem to be working.
Anyone have a method of generating a timestamp in a format similar to what I'm trying to do?
I figured out a way around it. I was accessing the field time directly. If I change the call from cal.time to cal.getTime() Jenkins behaves a lot better. I consolidated it into a one-liner, but the functionality's the same:
def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd-hhmmss',TimeZone.getTimeZone('CST'))
Thanks to those that had a look.
Or use Date() formatted with SimpleDateFormat():
import java.text.SimpleDateFormat
def dateFormat = new SimpleDateFormat("yyyyMMddHHmmss")
def date = new Date()
def timestamp = dateFormat.format(date)
Related
I am new to Jenkins. I am trying some basic functions using radio buttons.
In the below code it seems to have a problem displaying prevJob value. When i select either radio buttons, no value is returned (value should be display to the right of HANDLE_VERSION (Image provided)). However the code works in Jenkin's Script Console. I tried some other functions such as def
jobName = this.binding.jenkinsProject.name
And that worked and return the current job name when selecting the radio button.
Why is that? Eventually i would like to get the prev build version and handle some logic which will adjust the build version for the user before kicking off the job. Any clarity/help would be greatly appreciative. Thank you!
switch(MAJOR_OR_MINOR){
case~/.*Major.*/:
//vOption="Major"
def jobName = "Test"
def job = Jenkins.instance.getItem(jobName)
def prevJob = (job.getBuilds()[0]).toString()
return "<b>${prevJob}</b>"
break
case~/.*Minor.*/:
//vOption="Minor"
def jobName = "Test"
def job = Jenkins.instance.getItem(jobName)
def prevJob = (job.getBuilds()[0]).toString()
return "<b>${prevJob}</b>"
break
}
Here are some screenshots:
Solved: Sorry, i realized that i did not import my packages.
import hudson.model.*;
import jenkins.model.Jenkins
In my domain I have
Time startTime
Time endTime
In my controller I need to covert the time from the view which is in a format of HH:MM to the acceptable format to submit to the domain. I have installed the plugin Joda-Time but I've come a bit stuck.
def startTime = params.startTime
def fmt_in = DateTimeFormat.forPattern("HH:mm:ss")
def fmt_out = ISODateTimeFormat.dateTime()
println fmt_out.print(fmt_in.parseDateTime(startTime))
sorry, newbie to groovy grails
After parsing for DateTime, you need to transform it to the desired type. For date and time without considering timezone I suggest you to use LocalDateTime and LocalTime.
def formatter = DateTimeFormat.forPattern("HH:mm:ss")
LocalTime time = formatter.parseLocalDateTime(params.startTime).toLocalTime()
This sounds a painfully simple question but I'm having the hardest time finding how I can grab all the entries that were updated today.
def today = new Date()
def q = "from UserMapping as u where u.updateTime like :today"
def updated = UserMapping.findAll(q, [today: today])
java.lang.String cannot be cast to java.util.Date. Stacktrace follows:
I've tried about 10 other ways but I can't figure it out.
I solved it using:
def today = new Date().clearTime()
def updated = UserMapping.findAllByUpdateTimeGreaterThanEquals(today)
If anyone has a more elegant method, please post it.
I have a inetgration test case like this :
void testSomething() {
def cardTable = new CardStorage();
cardTable.cardSecurityCode = "something"
def date = new Date()
System.metaClass.static.currentTimeMillis = {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,11);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
return date.getTime()
}
assert cardTable.save(flush:true) //this works.
}
The line : cardTable.save(flush:true) is working. It asserts true. But the problem is that the dateCreated field is still the same as (new Date()). I wonder,how this can happen. Because I have coded the currentTimeMillis method as per my req. But still grails doesn't pick it up. But I'm sure that my new currentTimeMillis is working (because making error in it, results in a compilation error).
Where I'm missing? How can I disable the timeStamp feature for testing alone?
Thanks in advance.
Java code in core library in new Date() does not and will never pick up your changes in Groovy metaclass code.
I can recommend using joda-time (make dateCreated a DateTime) and setting current time by its means.
Even better way is not to tie your code to the current time, but to pass the time into your class from outside.
Dont use 'dateCreated', grails will automatically fill it in for you.
I have a database table TableA, which has a column 'theDate' for which the datatype in the database is DATE.
When I save a java.util.Date to 'theDate' through GORM it appears to save just the date value when I look at the data in the table by just executing select * from TableA.
However, when I run a query such as:
select * from TableA where theDate = :myDate
No results are found, but if I run something like;
select * from TableA where theDate <= :myDate
I do get results.
So it's like the Time is relevant.
My question is how do I save a Date and query for a Date ignoring the Time completely and just matching on an exact Date only?
Thanks.
note: I have also tried using sql.Date and util.Calendar but to no success.
clearTime()
You can use clearTime() before saving and before comparing to zero out the time fields:
// zero the time when saving
new MyDomain(theDate: new Date().clearTime()).save()
// zero the target time before comparing
def now = new Date().clearTime()
MyDomain.findAll('SELECT * FROM MyDomain WHERE theDate = :myDate', [myDate: now])
joda-time plugin
An alternative would be to install the joda-time plugin and use the LocalDate type (which only holds date information, no times) instead of Date. For what it's worth, I don't think I've worked on a project with dates without using the Joda plugin. It's completely worth it.
If you have date saved without clearing you could retrieve it using range, as Jordan H. wrote but in more simple way.
def getResults(Date date) {
def from = date.clearTime()
def to = from + 1
def results = MyDomain.findAll("from MyDomain where dateCreated between :start and :stop" ,[start:from,stop:to])
}
Your question may be a duplicate. See Convert datetime in to date. But if anyone has more recent information, that would be great.
If that doesn't help, you can hack it the way I might, with a BETWEEN restriction, e.g.
def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
def dateYmd = ymdFmt.format(today)
def dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
def startDate = dateTimeFormat.parse("${dateYmd} 00:00:00");
def endDate = dateTimeFormat.parse("${dateYmd} 23:59:59");
MyDomain.findAll("from MyDomain where dateCreated between ? and ?", [startDate, endDate])
It's definitely not pretty, but it may get you where you're going.
I figured it out.
I used DateGroovyMethods.clearTime to clear the time value before saving.
You can use the DB type date not datetime , in the filed type