SOAPUI - Groovy scripting - jsonBuilder strips quotes - groovy

I have a problem where jsonBuilder strips quotes from the result string. How do I format the output to return a JSON response with quotes ?
import com.eviware.soapui.support.XmlHolder
import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import groovy.json.*
import groovy.json.JsonOutput
import net.sf.json.JSONObject
def ResponseMessage = testRunner.testCase.testSteps["MerchantEMS_POST"].testRequest.response.contentAsString
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
log.info ResponseMessage
def merchantResult = ResponseMessage
def newMerchantID = "60300004055"
def entityID = jsonSlurper.entityId
jsonSlurper.merchantId = newMerchantID
def jsonBuilder = new groovy.json.JsonBuilder()
def updatedjson = jsonBuilder(jsonSlurper)
log.info "updated JSON = $updatedjson"
return updatedjson
ResponseMessage : { "entityId" : "93LSHLXW7BJ5K00MJALWZJMLL0", "creatorId" : "HPCDKMSV763K2VGHCKQQ09QSGM", "createdTimestamp" : "2015-09-02T00:26:34.015Z", "updaterId" : "HPCDKMSV763K2VGHCKQQ09QSGM", "updatedTimestamp" : "2015-09-02T00:26:34.015Z", "merchantId" : "L7QWKA0001F5W1RRZY4Z006153",
"createdBy" : "ralgg00", "isDeleted" : false }
updatedjson (no quotes) = [updatedTimestamp:2015-09-02T00:26:34.015Z, createdBy:ralgg00, createdTimestamp:2015-09-02T00:26:34.015Z, creatorId:HPCDKMSV763K2VGHCKQQ09QSGM, entityId:93LSHLXW7BJ5K00MJALWZJMLL0, merchantId:60300004055, isDeleted:false, updaterId:HPCDKMSV763K2VGHCKQQ09QSGM]

EDIT:
When you log the 'updatedjson' it recognises it as Map object and prints its fields. You need to use something that can convert a Map object to JSON and print it out. There are many ways to do this, for example:
def json = JsonOutput.toJson(updatedjson)
println json
Source: http://www.groovy-lang.org/json.html

Related

groovy jsonbuilder remove json node

I try to remove a json node when it contains specific value.
but I get an error.
Goal is to remove an element from my json by checking its path if it contains a prefix and a suffix
could you help me to make my code working ?
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
String pathPrefix = "/server_information/environment"
String pathSuffix = "/server_information/environment"
String diffOfApi = """[{op:replace, path:/server_information/environment, value:QCSGERFX023}, {op:replace, path:/json_detail/pick_batch/0/support_list/0/already_send, value:false}]""" JsonSlurper slurper = new JsonSlurper()
def slurped = slurper.parseText(diffOfApi)
def parsedJsonDiff = new JsonBuilder(slurped)
println "removeDiffByPath() - avant removeAll parsedJsonDiff : $parsedJsonDiff"
//parsedJsonDiff.removeAll { it.path == "/json_detail/preparation_list/0/consignee/update_date" }
parsedJsonDiff.removeAll { it.path.contains(pathPrefix) && it.path.contains(pathSuffix) }
println "removeDiffByPath() - apres removeAll parsedJsonDiff : $parsedJsonDiff"
println parsedJsonDiff.toString()
for the moment, I get this error :
Test Cases/_DEBUG SEB/TEST groovy FAILED. Reason:
groovy.json.JsonException: expecting '}' or ',' but got current char
'o' with an int value of 111
The current character read is 'o' with an int value of 111 expecting
'}' or ',' but got current char 'o' with an int value of 111 line
number 1 index number 2 [{op:replace,
path:/server_information/environment, value:QCSGERFX023}, {op:replace,
path:/json_detail/pick_batch/0/support_list/0/already_send,
value:false}] ..^ at TEST groovy.run(TEST groovy:27) at
com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194) at
com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
at
com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:430)
at
com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:421)
at
com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:400)
at
com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:392)
at
com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:273)
at
com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
at
com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown
Source) at
TempTestCase1637062445227.run(TempTestCase1637062445227.groovy:25)
thanks to cfrick, I corrected diffOfApi json which were malformed (missing "").
Then I used jsonSlurper instead of jsonBuilder in order to use removeAll()
Here is working code :
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import groovy.json.JsonParserType
String pathPrefix = "/server_information/environment"
String pathSuffix = "/server_information/environment"
int i=0
//String diffOfApi = """[{op:replace, path:/server_information/environment, value:QCSGERFX023}, {op:replace, path:/json_detail/pick_batch/0/support_list/0/already_send, value:false}]"""
String diffOfApi = """[{"op":"replace", "path":"/server_information/environment", "value":"QCSGERFX023"}, {"op":"replace", "path":"/json_detail/pick_batch/0/support_list/0/already_send", "value":"false"}]"""
JsonSlurper slurper = new JsonSlurper()
//slurper.setType(JsonParserType.LAX)
def slurped = slurper.parseText(diffOfApi)
//def parsedJsonDiff = new JsonBuilder(slurped)
println "removeDiffByPath() - avant removeAll parsedJsonDiff : $slurped"
// on ne tient pas compte des modifs de date de consignee
slurped.each {println "slurped " + ++i + " "+it}
slurped.removeAll { it.path.contains(pathPrefix) && it.path.contains(pathSuffix) }
println "removeDiffByPath() - apres removeAll parsedJsonDiff : $slurped"
def parsedJsonDiff = new JsonBuilder(slurped)
println parsedJsonDiff.toPrettyString()
now I get this result :
2021-11-16 15:00:59.997 DEBUG testcase.TEST groovy - 12: println(parsedJsonDiff.toPrettyString())
[
{
"op": "replace",
"path": "/json_detail/pick_batch/0/support_list/0/already_send",
"value": "false"
}
]

groovy - replace values in json when loading from jmx

I have a piece a code as below. This is loading data from JMX to monitoring tool. Unfortunately, there are some 'NaN' values, which are not read properly by monitoring tool, and this interrupts transfer. My intention is to replace 'on fly' values 'NaN' to 'null'.
Has anybody any idea how to do it?
BR
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import java.security.PrivilegedAction;
def hostName = hostProps.get("system.hostname")
def jmxPort = "10002"
def query = "Hadoop:service=hiveserver2,name=hiveserver2"
def metricsURL = "http://${hostName}:${jmxPort}/jmx?qry=${query}"
def ad = true
public class FetchMetrics implements PrivilegedAction {
def url;
public FetchMetrics(String url) {
this.url = url;
}
public Object run() {
URL urlObject = new URL(url);
def con = (HttpURLConnection) urlObject.openConnection();
return con.getInputStream();
}
}
lc = new LoginContext("Client");
lc.login();
Subject subject = lc.getSubject();
PrivilegedAction action = new FetchMetrics(metricsURL);
def metrics = Subject.doAsPrivileged(subject, action, null);
def jsonSlurper = new JsonSlurper()
def deviceMetrics = jsonSlurper.parse(metrics)
// Hit out endpoint and get our metrics
//deviceMetrics = jsonSlurper.parse(new URL(metricsURL))
deviceMetrics.'beans'[0].each {
println it
}
return 0
simplest way to use LAX json slurper, however it will parse NaN as a string "NaN"...
import groovy.json.JsonSlurper
import groovy.json.JsonParserType
import groovy.json.JsonBuilder
def jsonSlurper = new JsonSlurper().setType( JsonParserType.LAX )
def json = jsonSlurper.parseText('{ "a":111, "b": NaN}')
println new JsonBuilder(json).toPrettyString()
prints
{
"a": 111,
"b": "NaN"
}

error seeing when parsing the json response using groovy

import groovy.json.JsonSlurper
def testStepName = 'Adding_Users'
def jsonSlurper = new JsonSlurper()
def response = context.expand('$(testStepName#Response)')
def usersInfomration = jsonSlurper.parseText(response)
String userName = userInformation.name
log.info UserName

Soapui unexpected end of file

I'm working on a project with Soapui when I send the request I have this error unexpected end of file here is my code:
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.Date
import java.io.*
import org.apache.poi.hssf.usermodel.HSSFCell
import org.apache.poi.hssf.usermodel.HSSFCellStyle
import org.apache.poi.hssf.usermodel.HSSFDataFormat
import org.apache.poi.hssf.usermodel.HSSFRow
import org.apache.poi.hssf.usermodel.HSSFSheet
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.hssf.util.HSSFColor
import org.apache.poi.xssf.usermodel.*
import com.opencsv.CSVReader
import com.opencsv.CSVWriter
CSVReader reader = new CSVReader(new FileReader("C:\\Users\\******\\Desktop\\Groovy Script test\\data.csv"))
CSVWriter writer = new CSVWriter(new FileWriter("C:\\Users\\******\\Desktop\\Groovy Script test\\Output.csv"))
//get property
propTestStep = context.testCase.getTestStepByName("PRO-Number-property") // get the Property step (ours is named "property-loop")
//loop
String [] nextLine
while ((nextLine = reader.readNext()) != null ) {
writer.writeNext(nextLine)
log.info ("The value on the excel sheet is data " + nextLine[5])
//assign value of pro
propTestStep.setPropertyValue("PRO Number", (nextLine[2])) //set the value of Pro" property equal to Excel's column B ( getCell(1) )
//Get node of the response
testRunner.runTestStepByName("GetByProNumber") //we're going to run the Soap Request after each iteration of the Excel's rows.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
if( "GetByProNumber#Response" == null){
log.info("Null try again")
} else {
def holder = groovyUtils.getXmlHolder("GetByProNumber#Response")
log.info (holder)
holder.namespaces["ns"] = "http://www.SaiaSecure.com/WebService/Shipment"
if (holder != null){
writer.writeNext("${holder.getNodeValue('//ns:Activity')}", nextLine[0])
log.info("Node Response:${holder.getNodeValue('//ns:Activity')}")
} else {
log.info("Null try again")
}
}
}// end of while loop
//writer.close()
writer.close()
log.info ("Done" )
Please I want to know what I'm doing wrong Thanks for any help I'm working on a project with Soapui when I send the request I have this error unexpected end of file here is my code:
Oh ok, your comment is very useful to identify the issue.
That appears to be a trivial error.
Change your code snippet from:
def holder = groovyUtils.getXmlHolder("GetByProNumber#Response")
To:
//Get the specified test step response and assign to variable
def stepResponse = context.expand('${GetByProNumber#Response}')
//Now pass the above variable to xmlholder to create the object
def holder = groovyUtils.getXmlHolder(stepResponse)

Updating JSON Data with Groovy's HTTP Builder using PUT

I have requirement of updating Zendesk Tickets using Groovy HTTP Builder. I use the following code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import java.util.Properties;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import groovyx.net.http.*;
import static groovyx.net.http.Method.*;
import groovy.json.*;
import groovyx.net.http.ContentType;
def jsonBuilder = new groovy.json.JsonBuilder();
class MyTicket
{
def subject
}
def myTicket = new MyTicket(
subject: 'xyz'.toString()
)
def ticketList=[myTicket]
jsonBuilder(ticket:ticketList)
println(jsonBuilder)
def authSite = new HTTPBuilder('https://{subdomain}.zendesk.com/api/v2/tickets/{ticketid}.json');
authSite.auth.basic 'username', 'password';
authSite.request( Method.PUT, ContentType.JSON )
{ req ->
uri.path = ''https://{subdomain}.zendesk.com/api/v2/tickets/{ticketid}.json'';
requestContentType = ContentType.JSON;
headers.Accept = 'application/json';
body =[jsonBuilder]
response.success = { resp, reader->
reader.ticket.subject;
}
}
But the ticket is not being updated. Is there any kind of execute method. Kindly Suggest me where I went wrong.
Try this, you'll need to set up your subdomain, ticketid, user and pass (I've removed all the unnecessary imports as well):
#Grab( 'org.codehaus.groovy.modules.http-builder:http-builder:0.6' )
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.PUT
import static groovyx.net.http.ContentType.JSON
def subdomain = 'woo'
def ticketid = '123'
def authSite = new HTTPBuilder("https://${subdomain}.zendesk.com/api/v2/tickets/${ticketid}.json");
authSite.auth.basic( 'user', 'pass' )
authSite.request( PUT, JSON ) { req ->
body = [ ticket:[ subject: 'xyz' ] ]
response.success = { resp, json ->
println "Success! ${resp.status}"
}
response.failure = { resp ->
println "Request failed with status ${resp.status}"
}
}

Resources