java.io.IOException: Stream closed (from groovy) - groovy

In groovy I am trying to run two calls to git using Process with:
def fireCommand(String command) {
def proc = command.execute()
proc.waitFor()
println "Process exit code: ${proc.exitValue()}"
def result = proc.in.text
println "Std Err: ${proc.err.text}"
println "Std Out: ${proc.in.text}"
}
def executeOnShell(String command) {
fireCommand("git --version")
fireCommand("git status")
}
But only the first call works. The second call throws:
java.io.IOException: Stream closed
From what I understand I am NOT reusing the same process so why the error?

When you use inputStream.text or inputStream.getText() method, input stream is closed before method returns result - content of the stream (as String). So when you called
println "Std Out: ${proc.in.text}"
it tried to read from the same stream that already been closed.
println "Std Out: $result"
will be OK.

Related

Groovy to fetch only specify file from various folders

I am running below groovy script to fetch dynamic values from aws s3 bucket.
And below script is working fine and it will fetch all objects like shown in below output.
current output is
test-bucket-name/test/folde1/1.war
test-bucket-name/test/folder2/2.war
test-bucket-name/test/folder3/3.txt
Where as I want to display only *.war files in the output from "test-bucket-name" folder like below.
1.war
2.war
My Script:
def command = 'aws s3api list-objects-v2 --bucket=test-bucket-name --output=text'
def proc = command.execute()
proc.waitFor()
def output = proc.in.text
def exitcode= proc.exitValue()
def error = proc.err.text
if (error) {
println "Std Err: ${error}"
println "Process exit code: ${exitcode}"
return exitcode
}
return output.split()
Please let me know how to extract/display only war files from test-bucket-name folder.
Firstly you need to filter the entries that end with .war. Then split every entry once again (with /) and pick the last element:
def input = '''test-bucket-name/test/folde1/1.war
test-bucket-name/test/folder2/2.war
test-bucket-name/test/folder3/3.txt'''
input
.split()
.findAll { it.endsWith('.war') }
.collect { it.split('/') }
.collect { it[-1] }

How to run shell command in JIRA script runner groovy

I'm trying to configure Jenkins build trigger from Jira post-function Groovy script
Here is my Groovy code:
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.fields.CustomField;
import com.onresolve.scriptrunner.runner.util.UserMessageUtil
def WANITOPUSHField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10802);//customfield id
def WANITOPUSHValue = issue.getCustomFieldValue(WANITOPUSHField);
def SelectVersionField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10805);//customfield id
def SelectVersionValue = issue.getCustomFieldValue(SelectVersionField);
if(WANITOPUSHField != null) {
if(WANITOPUSHValue.toString() == 'Yes') {
'curl --user USERNAME:PASSWORD "http://JENKINS_URL/job/deploy-dev-test/buildWithParameters?token=MYTOCKEN&ENV=1"'.execute()
UserMessageUtil.success("Jenkins Build started ");
} else {
UserMessageUtil.success("Condition Not sucsess "+WANITOPUSHValue.toString());
}
}
Here I have used curl command to trigger Jenkins build if the Jira ticket status changed, but the curl command is not working here
It is throwing output on the alert box
java.lang.UNIXProcess#4d0c79da
I don't know what its mean whether the command is executing successfully or not, Please anyone can help me on this and suggest me if I can use some different method with Groovy to achieve this
"something".execute() returns instance of UNIXProcess java class. When toString() method is not overriden you will see something like java.lang.UNIXProcess#4d0c79da
Here some code which will help you to get shell command output:
def command = 'curl --user USERNAME:PASSWORD "http://JENKINS_URL/job/deploy-dev-test/buildWithParameters?token=MYTOCKEN&ENV=1"'
def proc = command.execute()
proc.waitFor()
println "Process exit code: ${proc.exitValue()}"
println "Std Err: ${proc.err.text}"
println "Std Out: ${proc.in.text}"

groovy.lang.MissingPropertyException: No such property: file for class: Script7 error at line 5

I am writing groovy script to save raw soap request & response and i get this error:
groovy.lang.MissingPropertyException: No such property: file for class: Script7 error at line 5
Here is the Script:
def myOutFile = context.expand( '${#TestSuite#fileName}' )+"_PostPaid-Success_Payment_BillInqReq.xml"
def response = context.expand( '${BillInq#Request}' )
def f = new File(myOutFile)
f.write(response, "UTF-8")
file.write(context.rawRequest,'utf-8')
Please follow the steps below:
Go to Test Suite PostPaid
Add a custom property say DATA_STORE_PATH and its value to a directory name where you like to save the requests and responses
Go to test case PostPaid_Success_Payment
Disable the Step 2 & Step 3 i.e., SaveInquiryReq and SaveInquiryResponse steps. or you may remove altoger as well if no other work is done apart from save the request & response respectively.
Click on step1 BillInq, click on assertions, Choose Script Assertion, see here for more details how to add script assertion
Have below script and click ok
Now you run the step1, you should be able to see the request and responses saved in the above mentioned directory
/**
* This script logs both request and response
*/
assert context.response, "Response is empty or null"
assert context.request, "Request is empty or null"
//Save the contents to a file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
file.write(content)
assert file.exists(), "${file.name} not created"
}
def dirToStore = context.expand('${#TestSuite#DATA_STORE_PATH}')
def currentStepName = context.currentStep.name
def requestFileName = "${dirToStore}/${currentStepName}_request.xml"
def responseFileName = "${dirToStore}/${currentStepName}_response.xml"
//Save request & response to directory
saveToFile(new File(requestFileName), context.rawRequest)
saveToFile(new File(responseFileName), context.response)

Groovy execute bash script that has ssh

I am trying execute a bash script from my grails app. The script has a ssh call in it. I am using keys to connect between servers.
If I run the script via CLI it works as expected but when I run it via the grails app the script runs but only the part that deals with the local machine. I do not see any output from the remote script.
Any help in pointing me in the right direction will be appreciated.
Bash Script:
echo "Starting Data pushed..."
ssh -t -i /path/to/.ssh/id_rsa_remote_user remote_user#remote_server 'sudo /opt/remote_user/script.sh'
echo "Starting Data pushed... Done!"
Grails/Groovy code:
class CommonService {
def executeScript(String script, Integer waitTimeInMinutes = 1){
def sout = new StringBuilder()
def serr = new StringBuilder()
Integer exitCode = -1
def proc
try {
proc = script.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(waitTimeInMinutes * 60 * 1000)
exitCode = proc.exitValue()
}
catch(e){
log.error e.printStackTrace()
serr << e.toString()
}
log.info "Executed Script: ${sout}"
log.info "Executed Script Extended Output: \n${serr}"
return [output: sout, error: serr, exitCode: exitCode]
}
}
Map outcome = commonService.executeScript('/path/to/local/scripts/pushToProduction.sh', waitTime)

verify interaction in spock not working

I have a spock test similar to this:
def "test" () {
given:
def mockOutput = new Output()
Service mockService = Mock()
classUnderTest.service = mockService
mockService.method(_, "some string") >> mockOutput
when:
def returnedObject = classUnderTest.run()
then:
1* mockService.method(_, "some string")
}
I am trying to verify an method call of a service inside a class but it does not work.
Based on my debugging, the stubbed call that is suppose to return mockOutput is not working anymore.
However, I am successful when Im asserting the returnedObject which is the mockOutput (with exactly the same given and when blocks):
Note that the returned object of the service is the returnObject of the class calling it.
then:
returnedObject instanceof Output
returnedObject != null
What am I missing?
I found what is wrong.
When trying to verify the interaction with a stubbed method, you should include the interaction return values in the 'then' block
then:
1* mockService.method(_, "some string") >> mockOutput

Resources