Calculate difference between 2 date-time in soapui - groovy

I'm using SoapUI free version. I have a REST response that returns date-time like this
<startTime>2018-02-22T17:10:00-05:00</startTime>
<endTime>2018-02-22T18:05:00-05:00</endTime>
How do I calculate the difference between them (in minutes) using groovy test step?

//Assuming string teased out of response, if not you need to extract the value to a string....
def startString = '<startTime>2018-02-22T17:10:00-05:00</startTime>';
def endString = '<endTime>2018-02-22T18:05:00-05:00</endTime>';
// If you have the tags, ditch them.
startString = startString.replace("<startTime>", "");
startString = startString.replace("</startTime>", "");
endString = endString.replace('<endTime>', '');
endString = endString.replace('</endTime>', '');
log.info("Now just strings... ${startString} - ${endString}");
// Convert strings to dates...
def convertedStartDate = Date.parse("yyyy-MM-dd'T'HH:mm:ssX",startString);
def convertedEndDate = Date.parse("yyyy-MM-dd'T'HH:mm:ssX",endString);
log.info("Now dates... ${convertedStartDate} - ${convertedEndDate}");
//Use time category to tease out the values of interest...
use(groovy.time.TimeCategory) {
def duration = convertedEndDate - convertedStartDate
log.info( "Days: ${duration.days}, Hours: ${duration.hours}, Minutes: ${duration.minutes}, Seconds: ${duration.seconds}, etc.")
}

Related

NIFI: Generating dates between two dates using ExecuteScript processor

I am currently trying to get list of all dates in a flowfile between the two dates specified using ExecuteScript. But I am somehow getting empty attribute.
Following is my Groovy code of ExecuteScript for the specified startdate and enddate variable specified:
flowFile = session.get();
if(!flowFile)
return;
DATE_FORMAT = 'dd-MM-yyyy';
startDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("startdate"));
endDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("enddate"));
allDates = "";
Calendar calendar = Calendar.getInstance();
Set allDates = new LinkedHashSet();
numbers = TimeUnit.MILLISECONDS.toDays(Math.abs(endDate - startDate))
for (int i = 1; i <= numbers; i++) {
calendar.setTime( startDate );
calendar.add( Calendar.DATE, i );
}
days.each {
day -> allDates = allDates + day + "\n";
}
flowFile = session.putAttribute(flowFile,"allDates", allDates );
session.transfer(flowFile,REL_SUCCESS)
On my outgoing queue I find the attribute allDates is empty String
What is going wrong with my code?
you have some problems in your code
for example the variable allDates declared twice i two different scopes:
global (without type or def)
allDates = "";
and local (with type)
Set allDates = new LinkedHashSet();
after that it's hard to predict which one is used
and actually code could be easier in groovy:
def DATE_FORMAT = 'dd-MM-yyyy';
def startDate = Date.parse(DATE_FORMAT, '01-11-1970');
def endDate = Date.parse(DATE_FORMAT, '09-11-1970');
def allDates = ""
for (def d = startDate; d<=endDate; d++){
allDates+=d.format(DATE_FORMAT)+"\n"
}
println allDates
note that this is runable code so you can use groovyconsole or any IDE to debug it before integrating into nifi
of cause you have to wrap it with flow file handling before using in nifi

inbuilt parser in Python for handling dates like : 05/May/2010:12:01:15 +0000

In a logfile, I have my date and time recorded in the format :
[05/May/2010:12:01:15 +0000]
I am trying to extract only the time from the above in Python3.x. I was mainly looking for a inbuilt parser in Python3.x. I ran into different formats except for this. I came up with a solution in JAVA using the below code and I am looking for something similar in Python3.x. Is there one ? Or do I have to write my own parser for extracting the date,time out of this ? Here is the JAVA code of what I wanted :
//field[3] contains "[25/May/2015:23:11:15 +0000]"
String timeStamp = fields[3].substring(1,fields[3].length()).split(" ")[0];
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.US);
Date d = null;
try {
d = df.parse(timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Time :"+ d.getTime());// Prints 23:11:15
You can use time.strptime() to parse it into a time.struct_time object:
import time
your_field = "[25/May/2015:23:11:15 +0000]"
parsed = time.strptime(your_field, "[%d/%b/%Y:%H:%M:%S %z]")
# NOTE: %z depends on implementation, you might need to remove the timezone info
# before parsing your date/time with `time.strptime()`.
# print time:
print(time.strftime("%H:%M:%S", parsed))
# prints: 23:11:15
But if you just want to get the time you don't need to parse it just to build it again, instead you can just substring it out:
your_field = "[25/May/2015:23:11:15 +0000]"
your_time = your_field.split(":", 1)[1].split(" ", 1)[0]
# print time:
print(your_time)
# prints: 23:11:15
Here is a solution using datetime.strptime:
from datetime import datetime
field3 = '[25/May/2015:23:11:15 +0000]'
result = datetime.strptime(field3, '[%d/%b/%Y:%H:%M:%S %z]')
print(result.strftime("%H:%M:%S"))
Output
23:11:15

Why can't I directly assign to object properties using multiple return values from a method?

Based on this question I've coded the following which throws a compilation time error:
Here is the code:
43. Currency currency = new Currency()
44. (currency.rate_one, currency.time_one) = getDateAndRate()
My method with two return values:
def getDateAndRate(){
Date date = new Date()
double rate = getRate();
return [rate, date]
}
Error thrown
expecting '}', found ',' # line 44, column 26.
(currency.rate_one, currency.time_one) = getDateAndRate()
^
Try this instead
def (rate, time) = getDateAndRate()
currency.rate_one = rate
currency.time_one = time
There is a trick I learned only recently myself and that is to combine multiple assignment and with:
with (currency) {
(rate_one, time_one) = getDateAndTime()
}

groovy read a file, resolve variables in file content

I am new to Groovy and I could not get around this issue. I appreciate any help.
I want to read a file from Groovy. While I am reading the content, for each line I want to substitute the string '${random_id}' and '${entryAuthor}' with different string values.
protected def doPost(String url, URL bodyFile, Map headers = new HashMap() ) {
StringBuffer sb = new StringBuffer()
def randomId = getRandomId()
bodyFile.eachLine { line ->
sb.append( line.replace("\u0024\u007Brandom_id\u007D", randomId)
.replace("\u0024\u007BentryAuthor\u007D", entryAuthor) )
sb.append("\n")
}
return doPost(url, sb.toString())
}
But I got the following error:
groovy.lang.MissingPropertyException:
No such property: random_id for class: tests.SimplePostTest
Possible solutions: randomId
at foo.test.framework.FooTest.doPost_closure1(FooTest.groovy:85)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:427)
at foo.test.framework.FooTest.doPost(FooTest.groovy:83)
at foo.test.framework.FooTest.doPost(FooTest.groovy:80)
at tests.SimplePostTest.Post & check Entry ID(SimplePostTest.groovy:42)
Why would it complain about a property, when I am not doing anything? I also tried "\$\{random_id\}", which works in Java String.replace(), but not in Groovy.
You are doing it the hard way. Just evaluate your file's contents with Groovy's SimpleTemplateEngine.
import groovy.text.SimpleTemplateEngine
def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'
def binding = ["firstname":"Sam", "lastname":"Pullara", "city":"San Francisco", "month":"December", "signed":"Groovy-Dev"]
def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(binding)
def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev'
assert result == template.toString()
you better use groovy.text.SimpleTemplateEngine class; check this for more details http://groovy.codehaus.org/Groovy+Templates
The issue here is that Groovy Strings will evaluate "${x}" by substituting the value of 'x', and we don't want that behaviour in this case. The trick is to use single-quotes which denote plain old Java Strings.
Using a data file like this:
${random_id} 1 ${entryAuthor}
${random_id} 2 ${entryAuthor}
${random_id} 3 ${entryAuthor}
Consider this code, which is analogous to the original:
// spoof HTTP POST body
def bodyFile = new File("body.txt").getText()
StringBuffer sb = new StringBuffer()
def randomId = "257" // TODO: use getRandomId()
def entryAuthor = "Bruce Eckel"
// use ' here because we don't want Groovy Strings, which would try to
// evaluate e.g. ${random_id}
String randomIdToken = '${random_id}'
String entryAuthorToken = '${entryAuthor}'
bodyFile.eachLine { def line ->
sb.append( line.replace(randomIdToken, randomId)
.replace(entryAuthorToken, entryAuthor) )
sb.append("\n")
}
println sb.toString()
The output is:
257 1 Bruce Eckel
257 2 Bruce Eckel
257 3 Bruce Eckel

Groovy : Dates not being calculated correctly? Using TimeCategory

can anyone tell me why these aren't being calculated correctly. I'm trying to add 1 second to the time and it seems to be adding 60 milliseconds when I apply formatting?
import java.text.*
import java.util.*
import groovy.time.TimeCategory
def xmlSlurper = new groovy.util.XmlSlurper()
// Get the previous total for number of journals
def journalCountProp = testRunner.testCase.getTestStepByName("Properties")
def journalCountTotal = journalCountProp.getPropertyValue( "journalCount" )
log.info " 1. Previous JournalCount from last run: "+journalCountTotal
def lastDateProp = testRunner.testCase.getTestStepByName("Properties")
def lastDateHolder = lastDateProp.getPropertyValue( "journalQueryDate" )
log.info " 2. Previous lastDate from last run: "+lastDateHolder
// Get the response for a given timeline
def response = xmlSlurper.parseText(context.expand('${GET Journal using JournalDate#Response}'));
def currentJournalCount = response.Journals.Journal.size()
log.info " 3. Number of Journals in this Run: "+currentJournalCount
//Getting the date from the last Journal (including an offset as the array count starts at 0)
def lastDate = response.Journals.Journal[currentJournalCount-1].CreatedDateUTC
log.info " 4. CreatedDate from last journal in this response: "+lastDate
//log.info response.Journals.Journal[currentJournalCount-1].CreatedDateUTC
def newdate = Date.parse("yyyy-MM-dd'T'HH:mm:ss.mmm",lastDate.toString())
log.info "dateBeforeChange: "+newdate.format("yyyy-MM-dd'T'HH:mm:ss.mmm")
use(TimeCategory){
newdate = newdate+1.seconds
}
log.info "date After Change: "+newdate.format("yyyy-MM-dd'T'hh:mm:ss.mmm")
log.info " 5. "+newdate.format("yyyy-MM-dd'T'HH:ss:mmm")
OUTPUT:
CreatedDate from last journal in this response: 2007-03-29T23:19:52.073
dateBeforeChange: 2007-03-30T00:13:52.013
date After Change: 2007-03-30T12:13:53.013
I can't figure it out?!!
Cheers,
- Richard
HH means "hour in a day (0-23)", whereas hh means "hour in am/pm (1-12)".
See the SimpleDateFormat ApiDoc for a reference (SimpleDateFormat is used under the hood).

Resources