Error: java.io.NotSerializableException: groovy.util.slurpersupport.Attributes - java

I am using #NonCPS in my Jenkinsfile function Because I need to get attributes on XML use XmlSlurper and i'm still getting java.io.NotSerializableException error even with the #NonCPS annotation.
Follow is my code
#Field prBranchCoverage
#NonCPS
def xmlCovergeParse(CoverageXml) {
println "start coverage"
def prParser = new XmlSlurper()
prParser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
prParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
def prCovergeDoc = prParser.parseText(CoverageXml)
def branchCoverage = prCovergeDoc['#line-rate']
return branchCoverages
}
stage('Pr coverage ') {
sh "mvn -V -B -U cobertura:cobertura -PcodehausCoverage -Dmaven.test.failure.ignore=true -DskipWeaving=true test"
publishTestResults cobertura: [archive: true,pattern: "**/target/site/cobertura/coverage.xml"]
def CoverageXml = readFile file: './target/site/cobertura/coverage.xml'
def prBranchCoverage = xmlCovergeParse(CoverageXml)
echo "start coverage"
println prBranchCoverage
}
I get error is:
Error: java.io.NotSerializableException: groovy.util.slurpersupport.Attributes
an exception which occurred:
in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
in object com.cloudbees.groovy.cps.impl.BlockScopeEnv#72e69aed
in field com.cloudbees.groovy.cps.impl.CallEnv.caller
in object com.cloudbees.groovy.cps.impl.FunctionCallEnv#1a22d024
in field com.cloudbees.groovy.cps.Continuable.e
Could anyone help this?

your method xmlCovergeParse(CoverageXml) returns non serializable object
jenkins requires all variables in the pipeline to be Serializable because the next step could be executed on other node then the previous one. so to transfer variables between the nodes they will be serialized.
just add return branchCoverages.toString() in your method xmlCovergeParse

Related

Unable to use custom variables in Gradle extension

I'm using JIB (not super relevant) and I want to pass in variables from command line in my deployment script.
I append using -PinputTag=${DOCKER_TAG} -PbuildEnv=nonprod in my gradle command, which is cool. But when it's missing, I want that ternary to kick in.
I'm getting the error:
Could not get unknown property 'inputTag' for project ':webserver' of type org.gradle.api.Project.
def inputTag = inputTag ?: 'latest'
def buildEnv = buildEnv ?: 'nonprod'
jib {
container {
mainClass = 'com.example.hi'
}
to {
image = 'image/cool-image'
tags = ['latest', inputTag]
}
container {
creationTime = 'USE_CURRENT_TIMESTAMP'
ports = ['8080']
jvmFlags = ['-Dspring.profiles.active=' + buildEnv]
}
}
Found Solution
def inputTag = project.hasProperty('inputTag') ? project.property('inputTag') : 'latest'
def buildEnv = project.hasProperty('buildEnv') ? project.property('buildEnv') : 'nonprod'
This seems to be working, is this the best way?
How about this?
image = 'image/cool-image:' + (project.findProperty('inputTag') ?: 'latest')
Note jib.to.tags are additional tags. jib.to.image = 'image/cool-image' already implies image/cool-image:latest, so no need to duplicate latest in jib.to.tags.

SoapUI Loop through TestCases and log test case custom property

I have a groovy script that loops through each test step, in each test case, in each test suite in the project. Each test case in the project has two custom properties assigned it is, Test_Case_Response_Time and Test_Case_Response_Size. I am trying to get it so that when it loops through each test case it log.info those two custom property for each test case.
Groovy Script:
//Loop thru the suites, followed by cases in each suite
suites.each
{ suite ->
//For each test SUITE perform the following action
//------------------------------------------------
def tSuite = project.getTestSuiteByName(suite)
tSuite.testCaseList.each
{ kase ->
//For each test CASE perform the following action
//-----------------------------------------------
kase.testStepList.each
{
//For each test step perform the following action
//-----------------------------------------------
if(it.metaClass.hasProperty(it,'assertionStatus')){
def assertions = it.getAssertionList()
assertions.each
{ assertion ->
if(it.assertionStatus == AssertionStatus.VALID)
{
PassedTestCase += 1
}
else if(it.assertionStatus == AssertionStatus.FAILED)
{
FailedTestCase += 1
}
}
}
//-----------------------------------------------
}
log.info testRunner.testCase["Test_Case_00: Setup"].getPropertyValue("Test_Case_Response_Time")
log.info testRunner.testCase.testSuite.getTestCaseByName("Test_Case_00: Setup").getPropertyValue("Test_Case_Response_Time")
//-----------------------------------------------
}
//-----------------------------------------------
}
I have tried the following with no success:
log.info testRunner.testCase[kase.name].getPropertyValue("Test_Case_Response_Time")
log.info testRunner.testCase.testSuite.getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
The first line give me the following
groovy.lang.MissingPropertyException: No such property: Test_Case_00:
Setup for class: com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase
error at line: 37
and the second line gives me the following error:
java.lang.NullPointerException: Cannot invoke method
getPropertyValue() on null object error at line:37
The below statement is not correct as testCase[kase.name] gives you property of testcase and not testcase itself
System is trying to search a property with the name"Test_Case_00: Setup" and hence giving error "No such property: Test_Case_00: Setup"
log.info testRunner.testCase[kase.name].getPropertyValue("Test_Case_Response_Time")
I was able to run the below code
log.info testRunner.testCase.testSuite.getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
In your actual code you have used the below line instead of kase.name
getTestCaseByName("**Test_Case_00: Setup**")
Looks like, testcase name is wrong, please copy the exact name and paste and it will work.
Below code worked for me. Its your code only.
def tSuite = testRunner.testCase.testSuite.project.getTestSuiteByName("TestSuite") // modified to run
tSuite.testCaseList.each
{ kase ->
//For each test CASE perform the following action
//-----------------------------------------------
kase.testStepList.each
{
//For each test step perform the following action
//-----------------------------------------------
}
//-----------------------------------------------
// log.info kase.name
// log.info testRunner.testCase[kase.name].getPropertyValue("Test_Case_Response_Time") <-- wrong syntax
log.info testRunner.testCase.testSuite.getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")
}
I believe I was looking in the wrong Test Suite. Using the following i was able to get it to find the correct properties:
testRunner.testCase.testSuite.project.getTestSuiteByName(suite).getTestCaseByName(kase.name).getPropertyValue("Test_Case_Response_Time")

Run GroovyTestCase in embedded Groovy?

How can you run GroovyTestCase unit tests inside a Groovy script that is running inside a Java program?
The use here is for running GroovyTestCases inside of SoapUI.
Given:
class ExperimentClassTest extends GroovyTestCase {
void testExperimentClass() {
assertEquals( new ExperimentClass(name: "Hi").name, "Hi" )
}
}
class ExperimentClass {String name}
Then (works):
C:\groovytest>\groovy2.6.0\bin\groovy .\ExperimentClassTest.groovy
.
Time: 0.041
OK (1 test)
But given this (contents of a Groovy script run by SoapUI):
evaluate (new File ('C:/groovytest/ExperimentClassTest.groovy'))
Then (doesn't work):
groovy.lang.MissingMethodException: No signature of method: ExperimentClassTest.main()
Also tried:
new ExperimentClassTest().run()
... which does return a junit.framework.TestResult, but the test hasn't actually run...
new ExperimentClassTest().run().failures().collect {it}
returns
"TestCase.fName cannot be null"
this should work:
new GroovyShell().run( new File('./ExperimentClassTest.groovy'), [] )
actually when you run it as groovy .\ExperimentClassTest.groovy
GroovyShell is called and by class it detects how to run it
https://github.com/groovy/groovy-core/blob/master/src/main/groovy/lang/GroovyShell.java#L295
finally the GroovyShell uses approximately this code to run test case class:
def scriptClass = this.getClass().getClassLoader().parseClass( new File('./ExperimentClassTest.groovy') )
def suite = new junit.framework.TestSuite(scriptClass)
def result = junit.textui.TestRunner.run(suite)

Groovy does not executes Java-Method (signature includes generics)

i have the following Java-Code that i want to convert to groovy:
String containerId = "545cdc81a969";
ExecCreateCmdResponse execCreateCmdResponse = dockerClient
.execCreateCmd(containerId)
.withAttachStdout(true)
.withCmd("sh", "-c", "sleep 5 && exit 5")
.exec();
ExecStartResultCallback execStartCmd =
dockerClient.execStartCmd(execCreateCmdResponse.getId())
.exec(new ExecStartResultCallback(System.out, System.err))
.awaitCompletion();
My current version in groovy is this:
String id = "545cdc81a969";
def execCreateCmdResponse = dockerClient
.execCreateCmd(id)
.withAttachStdout(true)
.withCmd('sh','-c','sleep 5 && exit 5')
.exec()
dockerClient.execStartCmd(execCreateCmdResponse.getId())
.withDetach(false)
.exec(new ExecStartResultCallback(System.out, System.err))
.awaitCompletion()
My problem is, that i get the following error, when i try to run the groovy code:
* What went wrong:
Execution failed for task ':werner'.
> No signature of method: com.github.dockerjava.core.command.ExecStartCmdImpl.exec() is applicable for argument types: (com.github.dockerjava.core.command.ExecStartResultCallback) values: [com.github.dockerjava.core.command.ExecStartResultCallback#6ce82155]
Possible solutions: exec(com.github.dockerjava.api.async.ResultCallback), exec(com.github.dockerjava.api.async.ResultCallback), every(), grep(), every(groovy.lang.Closure), grep(java.lang.Object)
The Java-exec-Method has the signature:
public <T extends ResultCallback<Frame>> T exec(T resultCallback);
I tried to cast "new ExecStartResultCallback(System.out, System.err)" to "ResultCallback", but it did not work.
Is there any way to force Groovy to handle the instance as a ResultCallback-Instance so that the correct method is called?
Regards,
marbon
A colleague helped with this problem and we found out, that the instance dockerClient used a custom classloader, which my has some problems. It could be solved by instantiating the new ExecStartResultCallback(System.out, System.err) with the same classloader from dockerInstance:
ClassLoader dockerClientClassLoader = dockerClient.getClass().getClassLoader()
Class callbackClass = dockerClientClassLoader.loadClass("com.github.dockerjava.core.command.ExecStartResultCallback")
def callback = callbackClass.getDeclaredConstructor(OutputStream.class, OutputStream.class).newInstance(System.out, System.err);
dockerClient.execStartCmd(execCreateCmdResponse.getId())
.withDetach(false)
.exec(callback)
.awaitCompletion()

Nullpointer exception while using Weka classifier

I am using Weka to create a classifier via the Java API.
The instances are created using java code.
The classifier is being created from code as well via passing following
String args[]=" -x 10 -s 1 -W weka.classifiers.functions.Logistic".split(" ");
String classname;
String[] tmpOptions = Utils.splitOptions(Utils.getOption("W", args));
classname = tmpOptions[0];
System.out.println(classname);
Classifier cls = (Classifier) Utils.forName(Classifier.class, classname, tmpOptions);
It works fine and does cross validation.
After that I once again load my training instances and label their output as ?
and pass it to classifier using
for (int index = 0; index < postDatas.size(); index++) {
Instance instance = nominal.instance(index);
double label = classifier.classifyInstance(instance);
System.out.println(label);
}
classifier.classifyInstance(instance); gives me following exception:
java.lang.NullPointerException
at weka.classifiers.functions.Logistic.distributionForInstance(Logistic.java:710)
any clues to where am I going wrong?
Since you didn't provide all relevant information, I'll take a shot in the dark:
I'm assuming that you're using Weka version 3.7.5 and I found the following source code for Logistic.java online
public double [] distributionForInstance(Instance instance) throws Exception {
// line 710
m_ReplaceMissingValues.input(instance);
instance = m_ReplaceMissingValues.output();
...
}
Assuming you didn't pass null for instance, this only leaves m_ReplaceMissingValues. That member is initialized when the method Logistic.buildClassifier(Instances train)is called:
public void buildClassifier(Instances train) throws Exception {
...
// missing values
m_ReplaceMissingValues = new ReplaceMissingValues();
m_ReplaceMissingValues.setInputFormat(train);
train = Filter.useFilter(train, m_ReplaceMissingValues);
...
}
It looks like you've never trained your classifier Logistic on any data after you created the object in the line
Classifier cls = (Classifier) Utils.forName(Classifier.class, classname, tmpOptions);

Categories

Resources