Save attachments automatically in SoapUI with Groovy - groovy

I try to save all the attachments from a SOAP response. I use following Groovy script.
def testStep = testRunner.testCase.getTestStepByName("SubmitFile")
def response = testStep.testRequest.response
assert null != response, "response is null"
def outFile = new FileOutputStream(new File(System.getProperty('java.io.tmpdir')+'/test.zip'))
for(i=0; i<3; i++){
def ins = response.responseAttachments[0].inputStream
if (ins) {
com.eviware.soapui.support.Tools.writeAll(outFile, ins)
}
}
ins.close()
outFile.close()
I get following error message:
No such property : responseAttachments for class

Use following script in assertion (Script assertion) in Soap UI.
def response = messageExchange.response
assert null != response, "response is empty"
def outFile
def inputStream
if(messageExchange.responseAttachments.size() >0){
inputStream = messageExchange.responseAttachments[0].inputStream
if (inputStream) {
outFile = new FileOutputStream(new File('/Users/sys/Documents/test/bank_response.txt'))
com.eviware.soapui.support.Tools.writeAll(outFile, inputStream)
}
}else{
log.error 'No attachments found!!!'
}
if(inputStream) inputStream.close()
if(outFile) outFile.close()

responseAttachments is a property on MessageExchange. You're using Response, so you'd need attachments instead. See the API docs for more details.

def testCaseName = 'Messages-IP-Mail'
def testStepName = '001_1ConventMailToPDF'
//context.testCase.testSuite.testCases[testCaseName].testSteps[testStepName].testRequest.responseContent
def projectDir = context.expand('${projectDir}');
log.info "Current dir:" + projectDir
def response = context.testCase.testSuite.testCases[testCaseName].testSteps[testStepName].testRequest.response.getAttachments()
def fileName = projectDir + '/pdf.pdf'
def outFile = new FileOutputStream(new File(fileName))
testRunner.testCase.testSteps["fileName"].setPropertyValue("fileName", fileName)
def ins = response[0].inputStream
if (ins) {
com.eviware.soapui.support.Tools.writeAll(outFile, ins)
}
ins.close()
outFile.close()

Related

Nifi - Groovy Json Script define null attributes

I have a Nifi Groovy Script. Assigns fields to nifi attributes but it define null if json values ​​are empty. if json value is null I want to define attribute empty.
null attributes look like this ;
I want to like this ;
this is the script i use ;
import org.apache.commons.io.IOUtils
import java.nio.charset.*
def flowFile = session.get();
if (flowFile == null) {
return;
}
def slurper = new groovy.json.JsonSlurper()
def attrs = [:] as Map<String,String>
session.read(flowFile,
{ inputStream ->
def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
def obj = slurper.parseText(text)
obj.each {k,v ->
attrs[k] = v.toString()
}
} as InputStreamCallback)
flowFile = session.putAllAttributes(flowFile, attrs)
session.transfer(flowFile, REL_SUCCESS)
flowFile = session.putAllAttributes(flowFile, attrs.collectEntries{k,v->[k,v?:'']})
This is i solved it ;
import org.apache.commons.io.IOUtils
import java.nio.charset.*
def flowFile = session.get();
if (flowFile == null) {
return;
}
def slurper = new groovy.json.JsonSlurper()
def attrs = [:] as Map<String,String>
session.read(flowFile,
{ inputStream ->
def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
def obj = slurper.parseText(text)
obj.each {k,v ->
if (v.toString()=="null")
{
attrs[k] = ''
} else {
attrs[k] = v.toString()
}
}
} as InputStreamCallback)
flowFile = session.putAllAttributes(flowFile, attrs)
session.transfer(flowFile, REL_SUCCESS)

Groovy include new Groovy script

I'm pretty new to Groovy an I want to import a class from another groovy script in the main groovy script. I saw already this post. However due to environment restrictions I can't us functions like GroovyClassLoader or or import any libs/frameworks. The only possibility I have is to use the evaluate method.
I tried this:
main script (The evaluate does not throw any error)
File csvFile = new File("./Csvreader.groovy");
evaluate(csvFile);
Csvreader script
class CSVReader{
def csvFile = new File('./test.csv');
def separatorChar = ";"
def values = [];
def headers = [];
void setSeperator(String s){
if(s != ""){
separatorChar = s;
}
}
void readCsv(){
csvFile.eachLine{ line, number ->
if(number == 1){
def head = line.split(separatorChar);
for (entry in head) {
headers.add(entry);
}
} else{
def value = line.split(separatorChar);
def map =[:];
def i = 0;
for (entry in value) {
map.put(headers[i], entry);
i++;
}
values.add(map);
}
}
}
def getValues(){
return values;
}
def getHeaders(){
return headers;
}
def getSize(){
return values.size();
}
def getLine(def keyParam, def value){
for(int i = 0; i < values.size(); i++){
def line = values[i];
if(values[i][keyParam] == value){
return values[i];
}
}
}
}
However I would need to pass parameters with the evaluate call (and I would move the methods outside the class) or I need to create an instance of the class.
Unfortunately I don't really know how I can do that, does anyone have a solution for that?
you could try to put at the end of your Csvreader.groovy file the expression return CSVReader.class that will return you a compiled class.
Then in your caller script you could create an instance of this class and use it as any other class instance.
Csvreader.groovy
class CSVReader{
def separatorChar = ";"
void setSeparator(String s){
if(s != ""){
separatorChar = s;
}
}
}
return CSVReader.class
caller script
File csvFile = new File("./Csvreader.groovy")
def CSVReaderClass = evaluate(csvFile)
def cvsReader = CSVReaderClass.newInstance()
cvsReader.setSeparator("Z")
println cvsReader.separatorChar

Nexus3 only downloads 50 in list

So I have a code that downloads the version nr of each nuget package but it all stops after 50 in list.
I use jenkins with groovy code and get out a list of versions.
import groovy.json.JsonSlurperClassic
import groovy.json.JsonBuilder
import wslite.rest.*
def data = new URL("http://nexus.xx.xx.se:8081/service/rest/v1/search?repository=xx-sx-nuget&name=XXXFrontend").getText()
println data
/**
* 'jsonString' is the input json you have shown
* parse it and store it in collection
*/
Map convertedJSONMap = new JsonSlurperClassic().parseText(data)
//If you have the nodes then fetch the first one only
if(convertedJSONMap."items"){
println "Version : " + convertedJSONMap."items"[0]."version"
}
def list = convertedJSONMap.items.version
Collections.sort(list)
list
So the problem is that it only get 50 of the versions. How can I get more than 50? I have read about a continuetoken but I dont understand how to use that?
UPDATE
I have added this but still dont work
while(convertedJSONMap."continuesToken" != null){
def token = convertedJSONMap."continuationToken"
def data2 = new URL("http://nexus.xxx.xxx.se:8081/service/rest/v1/search?repository=xxx-xx-nuget&name=xxxxxx&continuationToken=" +token).getText()
convertedJSONMap = JsonSlurperClassic().parseText(data2)
}
This is how I solved it for me. It is just a snippet of the code that I use
def json = sendRequest(url)
addResultToMap(map2, json, release) //I do something here with the received result
def continuationToken = json.continuationToken
if (continuationToken != null) {
while (continuationToken != null) {
json = sendRequest(url + "&continuationToken=" + continuationToken)
addResultToMap(map2, json, release) //I do something here with the received result as above
continuationToken = json.continuationToken
}
}
And my sendRequest method looks like this
def sendRequest(def url, String method = "GET") {
String userPass = "${nexus.username}:${nexus.password}"
String basicAuth = "Basic " + "${printBase64Binary(userPass.getBytes())}"
def connection = new URL( url ).openConnection() as HttpURLConnection
connection.setRequestProperty('Accept', 'application/json' )
connection.setRequestProperty('Authorization', basicAuth)
connection.setRequestMethod(method)
try {
if ( connection.responseCode <= 299 ) {
if (connection.responseCode == 200) {
return connection.inputStream.withCloseable { inStream -> new JsonSlurper().parse( inStream as InputStream ) }
}
} else {
displayAndLogError(connection.responseCode + ": " + connection.inputStream.text, loglevel.DEBUG)
}
} catch(Exception exc) {
displayAndLogError(exc.getMessage())
}
}
Here is an alternative :
import groovy.json.JsonSlurper
try {
N_PAGES_MAX = 10
List<String> versions = new ArrayList<String>()
continuationToken = "123"
artifactsUrl = "http://nexus.zzz.local/service/rest/v1/components?repository=releases-super-project"
currentPage = 1
while (true) {
artifactsObjectRaw = ["curl", "-s", "-H", "accept: application/json", "-k", "--url", "${artifactsUrl}"].execute().text
artifactsJsonObject = (new JsonSlurper()).parseText(artifactsObjectRaw)
continuationToken = artifactsJsonObject.continuationToken
if (continuationToken!=null && continuationToken!='123') {
artifactsUrl = artifactsUrl + "&continuationToken=$continuationToken"
}
def items = artifactsJsonObject.items
for(item in items){
versions.add(item.name)
}
currentPage += 1
if (continuationToken==null || currentPage>N_PAGES_MAX) break
}
return versions.sort().reverse()
}
catch (Exception e) {
print "There was a problem fetching the versions"
}

Excel formula is not updating when SOAP UI writes the data

When I run my SOAP UI project, it works fine and it updates the result i.e pass or fail in the specific column however whatever formula I have written which will take input from pass / fail result is not getting updated.
Can you please let me know any reason?
I am using SOAP UI 5.4
The code is given below
import jxl.*;
import java.io.*;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.*;
import static org.apache.poi.ss.usermodel.CellStyle.*;
import static org.apache.poi.ss.usermodel.IndexedColors.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import groovy.json.*;
import groovy.utils.*;
def soapTestCase = context.testCase
def requestPropertyVariable = soapTestCase.getTestStepByName("requestProperty")
def globalProperties = com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils.globalProperties
def responseText = context.expand('${responseText}')
def inputFilePath = globalProperties.getPropertyValue("inputFilePath")
def testDataID = globalProperties.getPropertyValue("testDataID")
def testCaseID = globalProperties.getPropertyValue("testCaseID")
int outputRowCount = Integer.parseInt((requestPropertyVariable.getPropertyValue("outputRowCount")))
def responseStatus = testRunner.testCase.getTestStepByName(testCaseID).getTestRequest().response.responseHeaders.find{ it.key == "#status#" }?.value.getAt(0)
int k = Integer.parseInt((requestPropertyVariable.getPropertyValue("outIteration")))
FileInputStream xlwb = new FileInputStream(new File(inputFilePath));
def inptDataWb = new HSSFWorkbook(xlwb);
def inputxlsh = inptDataWb.getSheetAt(2);
def outputxlsh = inptDataWb.getSheetAt(3);
String otestDataID = outputxlsh.getRow(k+1).getCell(0);
String eleName = outputxlsh.getRow(k+1).getCell(1);
DataFormatter formatter = new DataFormatter();
String expectedResult = formatter.formatCellValue(outputxlsh.getRow(k+1).getCell(2));
String mulEleFLg = outputxlsh.getRow(k+1).getCell(4);
//Validate results
if (responseStatus == "HTTP/1.1 200 OK") {
log.info "Response status code check pass"
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def responseHolder = groovyUtils.getXmlHolder(testRunner.testCase.testSteps[testCaseID].testRequest.response.getContentAsXml())
def tagElement = responseHolder.getNodeValue(eleName) as String //tagElement is a value of a tag
if(mulEleFLg=="Y"){
responseResultArray = tagElement
multiElementValidation(expectedResult, responseResultArray, inptDataWb, outputxlsh, inputFilePath, k)
}else{
if(expectedResult==tagElement.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
xlOwb.close();
}else{
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("F");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("Expected Result is " + expectedResult + " but actual result is " + tagElement.toString().replaceAll('\\[','').replaceAll('\\]',''));
log.info "Expected Result is " + expectedResult + " but actual result is " + tagElement.toString().replaceAll('\\[','').replaceAll('\\]','')
inptDataWb.write(xlOwb);
xlOwb.close();
}
}
FormulaEvaluator evaluator = inptDataWb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : inptDataWb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
evaluator.evaluateAll();
inptDataWb.setForceFormulaRecalculation(true);
log.info "Refreshed"
}
}
}
}
}
def multiElementValidation(expectedResult, responseResultArray, inptDataWb, outputxlsh, inputFilePath, k){
int resResArrCnt = responseResultArray.size()
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
boolean match = false;
if(resResArrCnt==1){
for (item in responseResultArray)
{
for (itemOfItem in item){
log.info itemOfItem
if(expectedResult==itemOfItem.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
match = true;
break;
}
}
}
}else{
for (item in responseResultArray)
{
if(expectedResult==item.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
match = true;
break;
}
}
}
if(!match){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("F");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("Expected Result is " + expectedResult + " but not exist in the array");
log.info "Expected Result is " + expectedResult + " but not exist in the array"
inptDataWb.write(xlOwb);
}
xlOwb.close()
}
def evaluateWorkbook(){
def inputFilePath = globalProperties.getPropertyValue("inputFilePath")
FileInputStream xlwb = new FileInputStream(new File(inputFilePath));
def inptDataWb = new HSSFWorkbook(xlwb);
FormulaEvaluator evaluator = inptDataWb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : inptDataWb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
evaluator.evaluateFormulaCell(c);
log.info "Refreshed the cell"
}
}
}
}
}
I have handle it in excel macro vba under openworkbook. So the workbook formula get updated when the user opens the workbook

Groovy class to extract json returns null

I'm in the process of adding to the Library of reusable functions. I've added a class to extract JSON from the SOAP response but I get a NULL in return. The script below works fine, the issue is when I add this to a class.
import com.eviware.soapui.support.types.StringToStringMap
import groovy.json.JsonSlurper
import groovy.json.*
responseContent = testRunner.testCase.getTestStepByName("TestStepName").getPropertyValue("response");
slurperresponse = new JsonSlurper().parseText(responseContent);
log.info (slurperresponse.items[0].id);
//Write response to property
def addResponseID = slurperresponse.items[0].id
testRunner.testCase.testSuite.setPropertyValue("ScheduleId", addResponseID)
The Class:
import com.eviware.soapui.support.types.StringToStringMap;
import groovy.json.JsonSlurper;
import groovy.json.*;
class GetXmlNode
{
def log
def context
def testRunner
def responseSOAXmlStep
def resultValue
def responseNodePath
def responseContent = "mycontent"
def slurperresponse = "myresponse"
def storeProperty = "id"
// Class constructor with same case as Class name
def GetXmlNode(logIn,contextIn,testRunnerIn)
{
this.log = logIn
this.context = contextIn
this.responseSOAXmlStep = responseSOAXmlStep
this.responseNodePath = responseNodePath
this.testRunner = testRunnerIn
this.storeProperty = storeProperty
}
def execute(responseSOAXmlStep,responseNodePath,storeProperty)
{
responseContent = testRunner.testCase.getTestStepByName(responseSOAXmlStep).getPropertyValue("response");
slurperresponse = new JsonSlurper().parseText(responseContent);
resultValue = (slurperresponse.responseNodePath);
log.info("Node value: " + resultValue );
testRunner.testCase.testSuite.project.setPropertyValue(storeProperty, resultValue );
return responseSOAXmlStep
}
}
context.setProperty( "GetXmlNode", new GetXmlNode( log, context, testRunner) )
The Calling script:
// get a reference to the library TestSuite
library = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName("Library")
library = library.getTestSuiteByName("Library");
// find the module within the library
module = library.testCases["Library"].testSteps["GetXMLNodeValueByJSON"]
// initialise the library; which places an instance of Example in the context
module.run(testRunner, context)
// get the instance of example from the context.
def GetXmlNode = context.GetXmlNode
// run the method, with parameter
log.info "GetXmlNode.execute(responseSOAXmlStep,responseNodePath,storeProperty) = " + GetXmlNode.execute("TestStepName","items[0].id","JsonId")
The Response:
Wed Nov 19 14:00:58 CAT 2014:INFO:Node value: null
Updated Code:
import com.eviware.soapui.support.types.StringToStringMap;
import groovy.json.JsonSlurper;
import groovy.json.*;
class GetXmlNode
{
def log
def context
def testRunner
def responseSOAXmlStep
def resultValue
def responseNodePath = "items[0].id"
def responseContent = ""
def slurperresponse = ""
def storeProperty = ""
// Class constructor with same case as Class name
def GetXmlNode(logIn,contextIn,testRunnerIn)
{
this.log = logIn
this.context = contextIn
this.responseSOAXmlStep = responseSOAXmlStep
this.responseNodePath = responseNodePath
this.testRunner = testRunnerIn
this.storeProperty = storeProperty
}
def execute(responseSOAXmlStep,responseNodePath,storeProperty)
{
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
responseContent = testRunner.testCase.getTestStepByName(responseSOAXmlStep).getProperty("Response").getValue();
def jsonSlurper = new JsonSlurper().parseText(responseContent);
// log.info (slurperresponse.responseNodePath);
// def holder = groovyUtils.getXmlHolder( responseSOAXmlStep+"#ResponseAsXml" );
resultValue = "resultValue " + jsonSlurper[responseNodePath];
log.info("Node value: " + resultValue );
log.info("Response Node Path: " +responseNodePath)
testRunner.testCase.testSuite.project.setPropertyValue(storeProperty, resultValue );
return responseSOAXmlStep
}
}
context.setProperty( "GetXmlNode", new GetXmlNode( log, context, testRunner) )
Response:
Tue Dec 02 10:16:33 CAT 2014:INFO:Node value: resultValue null

Resources