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)
Related
I'm trying to write a workflow validator that makes sure all issues in Epic are in "Done" status.
this is what I got so far:
import com.opensymphony.workflow.InvalidInputException
// Set up jqlQueryParser object
jqlQueryParser = ComponentManager.getComponentInstanceOfType(JqlQueryParser.class) as JqlQueryParser
// Form the JQL query
query = jqlQueryParser.parseQuery('"Epic Link" = {{issue.key}}')
// Set up SearchService object used to query Jira
searchService = componentManager.getSearchService()
// Run the query to get all issues with Article number that match input
results = searchService.search(componentManager.getJiraAuthenticationContext().getUser(), query, PagerFilter.getUnlimitedFilter())
if (results.getIssues().size() >= 1) {
for (r in results.getIssues()) {
//Here I want to check the status of all linked issues and make sure its "Done"
}
return invalidInputException = new InvalidInputException("Validation failure")
}
return "Validation Succes"
I got error in row 4:
and I'm also not sure how can I debug it from the Workflow validator section.
Thanks!
You need to import JqlQueryParser first:
import com.atlassian.jira.jql.parser.JqlQueryParser
Also, in addition to that, you may need some other imports as mentioned in ScriptRunner documentation.
As an example that mentioned in the link above:
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.bc.issue.search.SearchService
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.web.bean.PagerFilter
def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchService = ComponentAccessor.getComponent(SearchService)
def issueManager = ComponentAccessor.getIssueManager()
def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
// edit this query to suit
def query = jqlQueryParser.parseQuery("project = JRA and assignee = currentUser()")
def search = searchService.search(user, query, PagerFilter.getUnlimitedFilter())
log.debug("Total issues: ${search.total}")
search.results.each { documentIssue ->
log.debug(documentIssue.key)
// if you need a mutable issue you can do:
def issue = issueManager.getIssueObject(documentIssue.id)
// do something to the issue...
log.debug(issue.summary)
}
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.link.IssueLink
import com.atlassian.jira.issue.link.IssueLinkManager
import com.opensymphony.workflow.InvalidInputException
// Allow logging for debug and tracking purposes
import org.apache.log4j.Level
import org.apache.log4j.Logger
// Script code for easy log identification
String scriptCode = "Check all issues in Epics are Done -"
// Setup the log and leave a message to show what we're doing
Logger logger = log
logger.setLevel( Level.ERROR )
logger.debug( "$scriptCode Triggered by $issue.key" )
def passesCondition = true
if (issue.issueType.name == 'Epic')
{
IssueLinkManager issueLinkManager = ComponentAccessor.issueLinkManager
def found = issueLinkManager.getOutwardLinks(issue.id).any
{
it?.destinationObject?.getStatus().getName() != 'Done' &&
it?.destinationObject?.getIssueType().getName() != null
}
logger.debug( "$scriptCode Found = $found " )
if (found) {
logger.debug( "$scriptCode return false" )
passesCondition = false
invalidInputException = new InvalidInputException("Please make sure all linked issues are in 'Done' status")
} else {
logger.debug( "$scriptCode return true" )
passesCondition = true
}
}
// Always allow all other issue types to execute this transition
else
{
logger.debug( "$scriptCode Not Epic return true" )
passesCondition = true
}
I am working API which give the list of Ride booking and from the Json response i need to check the DestinationEstimatedTravelTime should not be 0 or Null
Expected via script Assertion: it should scan all the available Array Response and check condition that the "DestinationETA" should be greater then 0.
Below is the image of my Response
Below is the code that i have used I have used For loop.
import groovy.json.JsonSlurper
//grab response
def response = messageExchange.response.responseContent
def jsosl = new JsonSlurper().parseText(response)
for(int i =0 ; i < jsos1.size(); i++)
{
if(Results[i].DestinationETA == 0 | Results[i].DestinationETA != "Null" )
{
log.info("Values are greater than 0")
}
else
{
log.info("test case Fail ")
}
}
Your error is because you call it jsosl in one place, then jsos1 in the next
(last character is a lowercase L then a 1)
You could change your code to:
assert json.Results.every { it.DestinationETA }
As in groovy, 0 or null is false
I was working on this and I my self found the solution
//Import file
import groovy.json.JsonSlurper
import com.eviware.soapui.model.testsuite.TestRunner.*
import com.eviware.soapui.model.testsuite.*
import com.eviware.soapui.model.*
//Grab Response
def response = messageExchange.response.responseContent
def json = new groovy.json.JsonSlurper().parseText(response)
//take count
def count = json.Results.size()
for(int i=0; i<count; i++) //loop to traverse to each object
{
log.info(json.Results[i].DestinationETA) // print result
assert json.Results[i].DestinationETA != null
assert json.Results[i].DestinationETA != 0
}
I have a GitBlit instance on a windows server, and i want to set a hook on post receive callback to start a gitlab ci pipeline on another server.
I already have set a GitlabCi trigger who works well, but my hook doesn't. Here is build-gitlab-ci.groovy file :
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger
logger.info("Gitlab-CI hook triggered by ${user.username} for ${repository.name}")
// POST :
def sendPostRequest(urlString, paramString) {
def url = new URL(urlString)
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write(paramString)
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
}
sendPostRequest("https://xxxxx/api/v4/projects/1/trigger/pipeline", "token=xxxxxxxx&ref=master")
The project configuration :
Moreover, i don't know where logger.info write the log, so i don't know if my script was executed well. Thanks for help
I found my problem, it was a SSL self-certificate problem. I added this code to ignore it :
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger
logger.info("Gitlab-CI hook triggered by ${user.username} for ${repository.name}")
def nullTrustManager = [
checkClientTrusted: { chain, authType -> },
checkServerTrusted: { chain, authType -> },
getAcceptedIssuers: { null }
]
def nullHostnameVerifier = [
verify: { hostname, session -> hostname.startsWith('yuml.me')}
]
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL")
sc.init(null, [nullTrustManager as javax.net.ssl.X509TrustManager] as javax.net.ssl.X509TrustManager[], null)
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as javax.net.ssl.HostnameVerifier)
def url = new URL("https://xxxx/api/v4/projects/{idProject}/trigger/pipeline")
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write("token={token}&ref={branch}")
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
And I identified the error checking the logs in E:\gitblit-1.7.1\logs\gitblit-stdout.{date}.log.
NB : stdout file date can be very old. Gitblit doesn't create a file per day. Mine had a name expired 4 months ago.
I want to get all flowfile from the queu which fileSize is greater than 831 and then put them into the list after that catch last flowfile from the list and transfer to success relationship and finally remove all other flowfiles , here is my code which throws exception that transfer relationship not specified , what should i change in this case?
import org.apache.nifi.processor.FlowFileFilter;
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import java.nio.charset.StandardCharsets
import org.apache.commons.io.IOUtils
def flowFile = session.get()
def n=0;
if(!flowFile)return
def size = flowFile.getAttribute('fileSize');
log.error(size.toString())
int value = size as Integer;
if((value/831)>1){
def ffList = session.get(new FlowFileFilter(){
public FlowFileFilterResult filter(FlowFile ff) {
if( size == ff.getAttribute('fileSize') ) n++; return FlowFileFilterResult.ACCEPT_AND_CONTINUE
return FlowFileFilterResult.REJECT_AND_CONTINUE
}
})
session.transfer(ffList.get(n-1),REL_SUCCESS)
//session.remove(ffList);
}
session.remove(flowFile);
if you get flow file from queue you have to do something with it.
this code returns you a flowFile list:
def ffList = session.get(new FlowFileFilter(){...})
if you wand just remove all of them except the last one just put this code after transferring the last one:
session.remove( ffList[0..-2] )
and i guess there is a mistake in this line:
if( size == ff.getAttribute('fileSize') ) n++; return FlowFileFilterResult.ACCEPT_AND_CONTINUE
the command return FlowFileFilterResult.ACCEPT_AND_CONTINUE executed in any case because it's not under if.
i think should be like this:
if( size == ff.getAttribute('fileSize') ){
n++;
return FlowFileFilterResult.ACCEPT_AND_CONTINUE
}
I am getting the above error in the groovy script in boomi Please help me!! Below is the code.I am trying to format to xml. Data process is throwing this error.
import java.util.Properties;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import com.boomi.execution.ExecutionUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
// Retrieve a handle to the Logger
logger = ExecutionUtil.getBaseLogger();
InputStream io = dataContext.getStream(0);
Properties props = dataContext.getProperties(0);
BufferedReader br = new BufferedReader(new InputStreamReader(io));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
def text = sb.toString();
text = text.replaceAll('<', '')
text = text.replaceAll('>', '')
def xmlStream = new XmlParser().parseText(text);
def data = xmlStream.data;
def result = "<records>"
for (child in data) {
def stringWriter = new StringWriter()
new XmlNodePrinter(new PrintWriter(stringWriter)).print(child)
result = result + stringWriter.toString();
}
result = result + "</records>"
def childIO = new ByteArrayInputStream(result.getBytes());
dataContext.storeStream(childIO, props);
Unless the input data with profile is given in this question, it will be difficult to answer it. However from the code, it seems that an extra parent node is being created to the input XML. This can easily be achieved by a Message component in Boomi. Use a message shape and input the following: <records>{1}</records> and form the parameters option in Message shape, use Current Data. This will give the same output for all your documents which you are trying to achieve from code. In case if it does not fulfill your requirements please provide more details like input profile with fields and expected output.