i have this
class MainController {
def test = {
def day1 =1
def month1 = 10
def year1 = 2011
def date1 = new Date(year1 ,month1, day1);
}
}
But the OutPut is
Wed Nov 01 00:00:00 PKT 3911
Why its 3911 , shouldnt it be 2011 ??
Any solution
Thanks
Read the Date API of this deprecated constructor. You must pass in the year-1900. Also, the month is zero-based (also in the API docs).
That information was also shown in my answer to one of your previous questions.
Related
I am using Ready API/SOAP UI. I added a SOAP request and I get a SOAP response XML. My response object has up to 40 Key/Value pairs.
I have functional tests to specifically test each.
Loop through the whole ArrayOfObjects and Assert if the Key exists and if it exists assert the value.
Can I get a working solution for this scenario. I am unable to do assert on the output object.
SOAP structure looks like this:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ArrayOfallObjects>
<ArrayOfObjects>
<Key>Key1</Key>
<Value>Value1</Value>
</ArrayOfObjects>
<ArrayOfObjects>
<Key>Key2</Key>
<Value>Value2</Value>
</ArrayOfObjects>
---------------
<ArrayOfObjects>
<Key>Key40</Key>
<Value>Value40</Value>
</ArrayOfObjects>
</ArrayOfallObjects>
</soap:Body>
</soap:Envelope>
And I am using groovy script snippet as below
//Code Snippet Starts//
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def request = context.testCase.getTestStepByName("RequestName")
def responseCurrentHolder = groovyUtils.getXmlHolder( request.name +"#Response")
responseCurrentHolder.namespaces["ns1"] = "https://test.com"
def nodes = responseCurrentHolder.getDomNodes( "//ns1:Response/ns1:Result/ns1:ArrayOfallObjects/ns1:ArrayOfObject/*" )
def nodeCount = responseCurrentHolder.getNodeValues("//ns1:Response/ns1:Result/ns1:ArrayOfallObjects/ns1:ArrayOfObject/ns1:Key").length
def object = [:]
for (def nodeIndex = 1; nodeIndex <= nodeCount; nodeIndex++) {
def nodeKey = responseCurrentHolder.getNodeValues("//ns1:Response/ns1:Result/ns1:ArrayOfallObjects/ns1:ArrayOfObject[$nodeIndex]/ns1:Key/text()")
def nodeValue = responseCurrentHolder.getNodeValue("//ns1:Response/ns1:Result/ns1:ArrayOfallObjects/ns1:ArrayOfObject[$nodeIndex]/ns1:Value/text()")
object.put( nodeKey,nodeValue)
}
log.info "Object =" +object
// Code snippet ends//
And the object looks like:
Object =[[Key1]:Value1, [Key2]:Value2, and so on upto --,[Key40]:Value40]
You can use Script Assertion for the same soap request test step to verify the same without adding additional Groovy Script test step.
Not sure if above sample has the same xml structure (if not exact). Otherwise, adopt the changes to suit your need.
Here is the approach:
Since there is complex data to be verified, and there is key, value pattern; so define a map as expected data like you pointed in the last.
Read the xml response, and create similar map out of it. At times, it may require to sort the retrieved data by key (or other criteria based on the data).
Then check if both expected and actual data.
Script Assertion:
//Define expected data; using few elements as sample
def expectedMap = [Key1: 'Value1', Key2: 'Value2', Key40: 'Value40']
//Check if there is response
assert context.response, 'Response is empty or null'
//Parse the response
def xml = new XmlSlurper().parseText(context.response)
//Extract the data, create actual map and sort by key
def actualMap = xml.'**'.findAll {it.name() == 'ArrayOfObjects' }.collectEntries {[(it.Key.text()): it.Value.text()]}?.sort {it.key}
log.info actualMap
assert expectedMap == actualMap
You can quickly try it online demo
The below code first get all keys in an array(x) and all values in another array
y(x). You may add them in a map if not you can directly assert values
The below is one of the easiest and simpler way of validating key value pair
Just replace the 'First Step' with the name of the step where response is generated
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def response = groovyUtils.getXmlHolder("First Step#Response")
def x = response.getNodeValues("//*[local-name()='ArrayOfObjects']//*[local-name()='Key']")
for ( def keys in x)
{
log.info keys
}
def y = response.getNodeValues("//*[local-name()='ArrayOfObjects']//*[local-name()='Value']")
for ( def values in y)
{
log.info values
}
log.info "total keys are " + x.size()
for(int i = 0 ; i < x.size() ; i++)
{
log.info " key = " + x[i] + " Value = " + y[i]
}
Here is the result when i ran the above script
Sat Oct 28 14:41:57 IST 2017:INFO:Key1
Sat Oct 28 14:41:57 IST 2017:INFO:Key2
Sat Oct 28 14:41:57 IST 2017:INFO:Key40
Sat Oct 28 14:41:57 IST 2017:INFO:Value1
Sat Oct 28 14:41:57 IST 2017:INFO:Value2
Sat Oct 28 14:41:57 IST 2017:INFO:Value40
Sat Oct 28 14:41:57 IST 2017:INFO:total keys are 3
Sat Oct 28 14:41:57 IST 2017:INFO: key = Key1 Value = Value1
Sat Oct 28 14:41:57 IST 2017:INFO: key = Key2 Value = Value2
Sat Oct 28 14:41:57 IST 2017:INFO: key = Key40 Value = Value40
I am trying to get the current date and change the format and add 30 days to it, i tried the following in groovy :
def date = new Date().format("yyyy-MM-dd")
def laterdate = date + 30
log.info laterdate
I get the output as (formatting looks good)
Mon Jul 24 12:24:04 MST 2017:INFO:2017-07-2430
can someone please advise where i am doing wrong
To add days:
Date date = new Date().plus(30)
To Substract days:
Date date = new Date().plus(-30)
def today = new Date()
def yesterday = today + 30
log.info today.format("yyyy-MM-dd")
log.info yesterday.format("yyyy-MM-dd")
Is there a function to convert time in milliseconds to date format (YYYY-MM-DD) in Groovy?
I have a Groovy script which needs to compare to date values as follows:
for(i in order_lineitems)
{
if(i.startDate==order_submit_date)
{
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Here i.startDate has time in milliseconds of the date format yyyy-mm-dd whereas order_submit_date has the time in milliseconds in the date format yyyy-MM-dd HH:mm:ss. I need to convert order_submit_date into this format yyyy-mm-dd within the if block itself.
I am new to the Groovy script and I need help here.
There was a small mistake in my code. I corrected it.
The if block should be as follows if (i.startDate == order_submit_date) and both are long values represented in millis.
Now I need to make sure the condition is right i.e. start date is equal to order submit date.
Here what is happening is :
i.startDate has the value 1452105000000 (Thu Jan 07 2016 00:00:00) which is been stored in the DB when a Sales Order is created
and order_submit_date has the value 1452158393097 (Thu Jan 07 2016 14:49:53) which is being genertaed on the flow when a user submits the Sales order for approvals in the UI.
Now since order_sbmit_date has both date and time the long value is different and am unable to satisfy the condition.
Hence now i have a question as to wether there a function in groovy which would convert my order_submit_date long value to Date(yyyy-mm-dd) format and then compare both the values so as to satisfy the if block.
You can compare your dates in millis like this:
Notice that solutions depend on timezone.
Groovy option:
def compare(def m1, def m2) {
def dateInMillis1 = new Date(m1)
def dateInMillis2 = new Date(m2)
dateInMillis1.clearTime() == dateInMillis2.clearTime()
}
Java option 1:
boolean compare1(long millis1, long millis2) {
Date dateFromMillis = new Date(millis1);
Date dateFromMillis2 = new Date(millis2);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
sdf.format(dateFromMillis).equals(sdf.format(dateFromMillis2));
}
or you can use Calendar:
Java option 2:
boolean compare2(long m1, long m2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(m1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(m2);
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) &&
calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) &&
calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}
Your question is not clear that whether your dates are in string format or in milliseconds (long).
If dates are in string format like "2015-10-31"
You can use SimpleDateFormat for this.
import java.text.SimpleDateFormat
...
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd")
SimpleDateFormat dateTimeParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for (i in order_lineitems) {
if (dateParser.parse(i.startDate) >= dateTimeParser.parse(order_submit_date)) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
If dates are in milliseconds:
for (i in order_lineitems) {
if (new Date(i.startDate.toString().toLong()) >= new Date(order_submit_date.toString().toLong())) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Note: Capital Y and small y (similarly for m & h) matterns in terms of formatting so please be clear about the usage.
Actual Answer to the Question:
You don't need any of the above solution instead you can simply use the clearTime() method on the date like below:
for (i in order_lineitems) {
if (new Date(i.startDate) >= new Date(order_submit_date).clearTime()) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
The clearTime() method will simply remove the time part from your date i.e. will convert Thu Jan 07 2016 14:49:53 to Thu Jan 07 2016 00:00:00`
What are type for i.startDate and order_submit_date java.util.Date? or String?
And do you want use i.startDate and order_submit_date only to do compare?
-- updated --
ok, then maybe like folowing?
import java.text.SimpleDateFormat
String startDate = "2016-01-20"
String order_submit_date = "2016-01-20 12:34:56"
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
if (formatDate.parse(startDate) >= formatDateWithTime.parse(order_submit_date)) {
println "hehe"
} else {
println "hoho"
}
SimpleDateFormat#parse() returns java.util.Date.
Also you can compare with these.
You can also write like follows!
import java.text.SimpleDateFormat
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
def matchedIds1 = order_lineitems.findAll {
formatDate.parse(it.startDate) >= formatDateWithTime.parse(order_submit_date)
}.join(",")
Long(type) version
def matchedIds1 = order_lineitems.findAll {
new Date(it.startDate).clearTime() == new Date(order_submit_date).clearTime()
}.join(",")
Long(type) without clearTime version
String format = "yyyy-MM-dd 00:00:00"
SimpleDateFormat fillByZero = new SimpleDateFormat(format)
def matchedIds1 = order_lineitems.findAll {
Date a = new Date(it.startDate)
Date b = new Date(order_submit_date)
fillByZero.parse(a.format(format)) == fillByZero.parse(b.format(format))
}.join(",")
see below simple groovy script for Date parsing:
def setProperty=testRunner.testCase.getTestStepByName("Properties");
Date currentDate = new Date();
String tmpDate = currentDate
//setting current DateTime to corresponding property
def DateTime = new Date().parse("E MMM dd H:m:s z yyyy", tmpDate).format("yyyy-MM-dd'T'hh:mm:ss")
setProperty.setPropertyValue('DateTime', DateTime);
This scripts correctly works on some machines with Win 8.1, java 7 or 8 installed. But for one of machines (Win 8.1) it returns an error
java.text.ParseException: Unparseable date: "Tue Jan 20 11:59:58 EET 2015"
What's the problem? Script absolutely the same...
Sincerely,
Dmitry
What you are doing is extremely awkward! You should consider using String.format() to format your date straight up:
def propertiesStep = testRunner.testCase.getTestStepByName("Properties")
propertiesStep.setPropertyValue('DateTime',
String.format("%tFT%tT", new Date(), new Date()))
Your code seems confusing... you're generating a java.util.Date with new Date(), then you're generating a String when you do String tmpDate=currentDate, then you're trying to get a Date() again parsing the tmpDate string and finally you're parsing the last date to get a string date with specific format...
I think that you must clean up your code a bit... I think that you're looking for something as follow:
def setProperty=testRunner.testCase.getTestStepByName("Properties")
def currentDate = new Date()
def dateTime = currentDate.format("yyyy-MM-dd'T'hh:mm:ss")
log.info dateTime
setProperty.setPropertyValue('DateTime', dateTime)
Hope this helps,
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).