Need run Step by Step with Karate Testng [duplicate] - karate

This question already has an answer here:
Karate Extent Report integrtion
(1 answer)
Closed 1 year ago.
CucumberFeature feature = wrapper.getCucumberFeature();
// extentReportHelper.CreateTest(wrapper.toString(),"just for test");
File file = FileUtils.resolveIfClassPath(feature.getPath(), runtimeOptions.getClassLoader());
KarateRuntime runtime = runtimeOptions.getRuntime(file, null);
resultListener.startFeature();
RuntimeOptions ro = runtimeOptions.getRuntimeOptions();
int scenario=feature.getFeatureElements().size();
feature.run(ro.formatter(runtimeOptions.getClassLoader()), resultListener, runtime);
The above steps are per design in the class.feature.run() runs the scenario and give the result pass or fail. I need capture log for every step output and attached to the report.
I want to change the code to run step by step capture the logs in my customized report. Please can someone suggest to me how can I capture the logs with below code.
for(int scecnt=0;scecnt<scenario;scecnt++) {
int getstepcnt=feature.getFeatureElements().get(0).getSteps().size();
for (int stepcnt=0;stepcnt<getstepcnt;stepcnt++) {
// runtime.runStep(feature.getPath(),feature.getFeatureElements().get(scecnt).getSteps().get(stepcnt), resultListener ,feature.getI18n());
}
}
This approach is throwing below error. Please let me know, how can execute step by step.
java.lang.NullPointerException
at com.intuit.karate.cucumber.KarateRuntime.addStepToCounterAndResult(KarateRuntime.java:69)
at com.intuit.karate.cucumber.KarateRuntime.runStep(KarateRuntime.java:96)
at com.intuit.karate.testng.KarateRunner.feature(KarateRunner.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:643)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)

It is not clear what you are trying to do, and you seem to be using Karate internal API-s which are not intended for use by others. These will change in future.
Please follow the instructions here and explain what exactly you need if you need help: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
Also see Karate hooks: https://github.com/intuit/karate#hooks
* configure afterScenario =
"""
function(){
var info = karate.info;
karate.log('after', info.scenarioType + ':', info.scenarioName);
karate.call('after-scenario.feature', { caller: info.featureFileName });
}
"""

Related

handleChallenge() being trigger even handleSuccess() in mfp authentication

Good day,
I have a mobile app that will call through mfp8 to my channel service.
In my front end angular code, I have create the mfp securityCheckChallengHadler, and call the mfp login, the following is my code of front end:
this.userLoginChallengeHandler = null;
this.userLoginChallengeHandler = WL.Client.createSecurityCheckChallengeHandler(this.securityCheckName);
this.userLoginChallengeHandler.securityCheckName = this.securityCheckName;
this.userLoginChallengeHandler.handleSuccess = (loginSuccess) => {
console.log("handleSuccess");
this.isChallenged = false;
if (this.currentEventHandler != this.eventHandler.success) {
this.currentLoginGrantType = this.processLoginGrantType;
//alert("initEventHandler|loginSuccess=\n" + JSON.stringify(loginSuccess));
this.mfpAuthResponse = {
id: loginSuccess.id,
accessToken: loginSuccess.user.attributes.access_token,
tokenType: loginSuccess.user.attributes.token_type,
expiresIn: loginSuccess.user.attributes.expires_in,
scope: loginSuccess.user.attributes.scope,
clientId: loginSuccess.user.attributes.client_id
};
}
this.currentEventHandler = this.eventHandler.success;
};
this.userLoginChallengeHandler.handleFailure = (loginError) => {
console.log("handleFailure");
this.isChallenged = false;
if (this.currentEventHandler != this.eventHandler.failure) {
this.authFailureEvent.emit(loginError);
}
this.currentEventHandler = this.eventHandler.failure;
};
this.userLoginChallengeHandler.handleChallenge = (challenge) => {
console.log("handleChallenge");
this.isChallenged = true;
this.challengeResponseModel = challenge;
this.authChallengeEvent.emit(challenge);
this.currentEventHandler = this.eventHandler.challenge;
};
And this is the part call the WLAuthorizationManager.login(this.securityCheckName, authObj):
if (this.isChallenged) {
console.log("mfp-performLogin|submitChallengeAnswer=");
this.userLoginChallengeHandler.submitChallengeAnswer(authObj);
} else {
console.log("mfp-performLogin|WLAuthorizationManager.login=");
WLAuthorizationManager.login(this.securityCheckName, authObj).then(
() => {
console.log("mfp-performLogin|WLAuthorizationManager.login.performed=" + performed + "\nmfpAuthResponse=\n" + JSON.stringify(this.mfpAuthResponse) + "\n\n");
if (!performed) {
this.ngZone.run(() => {
this.authSuccessEvent.emit(this.mfpAuthResponse);
});
}
performed = true;
},
(err) => {
console.log("mfp-performLogin|WLAuthorizationManager.login.err=\n\n" + JSON.stringify(err) + "\n");
console.log('wllogin err => ', err);
this.authFailureEvent.emit(err);
}
);
}
During WLAuthorizationManager.login(this.securityCheckName, authObj), I saw the handleSuccess() being trigger, as my understanding, this is means my authentication with mfp is successful, and I can proceed to call any protected resource. However, not only handleSuccess(), I saw handleChallenge() being trigger as well.
And because of this, I cant get the accessToken value by calling the following mfp function, even the bad response also not show:
WLAuthorizationManager.obtainAccessToken(userLoginChallengeHandler.securityCheckName).then(
function (accessToken) {
WL.Logger.debug("obtainAccessToken onSuccess");
showProtectedDiv();
},
function (response) {
WL.Logger.debug("obtainAccessToken onFailure: " + JSON.stringify(response));
showLoginDiv();
});
However, everything will be smooth if I remove my scope-elements mapping and mandatory application scope in mfp console.
For your information, I keep seeing this in my mfp log:
[2/10/21 22:52:17:035 MYT] 00000289 p.server.security.internal.context.ClientSecurityContextImpl E FWLSE4054E: Failed to externalize the security checks. The security checks are deleted for client: bdfe187e-f881-4678-a65a-335de2f0a427
java.io.NotSerializableException: java.util.logging.Logger
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.LinkedList.writeObject(LinkedList.java:1131)
at sun.reflect.GeneratedMethodAccessor501.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1128)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1577)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:351)
at com.ibm.mfp.server.security.internal.context.SecurityChecksState.toExternalString(SecurityChecksState.java:114)
at com.ibm.mfp.server.security.internal.context.SecurityChecksState.toExternalString(SecurityChecksState.java:29)
at com.ibm.mfp.server.security.internal.context.ExternalState.buildDataItemFromCurrentState(ExternalState.java:90)
at com.ibm.mfp.server.security.internal.context.ExternalState.store(ExternalState.java:68)
at com.ibm.mfp.server.security.internal.context.ClientSecurityContextImpl.store(ClientSecurityContextImpl.java:270)
at sun.reflect.GeneratedMethodAccessor276.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy165.store(Unknown Source)
at com.ibm.mfp.server.persistency.internal.transaction.StorageManagerImpl.storeLayer(StorageManagerImpl.java:79)
at com.ibm.mfp.server.persistency.internal.transaction.StorageManagerImpl.doWithStorage(StorageManagerImpl.java:61)
at com.ibm.mfp.server.security.internal.rest.PreAuthorizationEndpoint.authorize(PreAuthorizationEndpoint.java:78)
at sun.reflect.GeneratedMethodAccessor434.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1287)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:475)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1158)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:81)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:928)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:262)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:955)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:341)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:470)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:404)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:284)
at com.ibm.ws.http.channel.internal.inbound.HttpICLReadCallback.complete(HttpICLReadCallback.java:66)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:504)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:574)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:929)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1018)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
I tried to google for these, but cant get any answer, is it my configuration having some problem?
I tried to troubleshoot for this for weeks, but until now cant get any clue. Hope someone can help me please.
For your information, this is my scope element mapping from my mfp console:
WLAuthorizationManager.obtainAccessToken(userLoginChallengeHandler.securityCheckName).then(
function (accessToken) {
WL.Logger.debug("obtainAccessToken onSuccess");
showProtectedDiv();
},
function (response) {
WL.Logger.debug("obtainAccessToken onFailure: " + JSON.stringify(response));
showLoginDiv();
});
In the above API you are passing a scope which is name of your security check. If the client is already logged-in or is in the remembered state, the API triggers a success. If the client is not logged in, the security check sends back a challenge.
The reason why you see handleChallenge() function is being called because your user login success state has expired. Handle the challenge accordingly and call submitChallengeAnswer() API to submit the answer when handleChallenge() function is called.
If you don't pass scope in WLAuthorizationManager.obtainAccessToken() API you won't be challenged even if login success state has expired
For more details read here : https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/authentication-and-security/user-authentication/javascript/

Problem with passing config as part of karate.callSingle() [duplicate]

This question already has an answer here:
How to pass multiple parameters to callSingle karate on karate-config.js
(1 answer)
Closed 1 year ago.
As the title says I'm experiencing issues when trying to pass a config item to the feature file I call from callSingle() in karate-config.js. Everything works as expected if I only pass 1 parameter which is the path to the feature file. I tried copying the entire config from the example karate-config.js and yet was still getting the same error. Would appreciate any explanation.
karate-config.js:
function fn() {
var env = karate.env; // get system property 'karate.env'
karate.log('karate.env system property was:', env);
if (!env) {
env = 'kermit';
}
karate.log('karate.env system property was:', env);
var config = {
env: env,
base_url: 'https://api.'+env+'.chdev.org',
account_url: 'https://account.'+env+'.chdev.org'
}
var result = karate.callSingle('classpath:authorization/authorization.feature', config);
karate.log(result);
return config;
}
Error I'm getting:
16:48:10.548 [main] ERROR com.intuit.karate - evaluation of 'karate-config.js' failed: javascript function call failed: unexpected feature call arg type: class jdk.nashorn.internal.scripts.JO4
Exception in thread "main" java.lang.NullPointerException
at com.intuit.karate.core.ScenarioExecutionUnit.init(ScenarioExecutionUnit.java:147)
at com.intuit.karate.core.ScenarioExecutionUnit.run(ScenarioExecutionUnit.java:236)
at com.intuit.karate.core.FeatureExecutionUnit.run(FeatureExecutionUnit.java:164)
at com.intuit.karate.core.FeatureExecutionUnit.run(FeatureExecutionUnit.java:73)
at com.intuit.karate.core.Engine.executeFeatureSync(Engine.java:109)
at com.intuit.karate.IdeUtils.exec(IdeUtils.java:64)
at cucumber.api.cli.Main.main(Main.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
In fact no matter what I pass as 2nd arg I always get a variation of class jdk.nashorn error.
config} definitely looks like a typo to me.
Sorry but I think the best option for you is to follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
MR Peter Thomas has confirmed the project I've sent to him as a github issue works as expected which proved it is an environmental issue.
It was resolved by updating the maven and jdk8 to the latest releases.

Path has type Object rather than String

I am implementing SSL connection for my web application. I have keystore which i am passing while running SBT. But i am getting error "PATH HAS TYPE OBJECT RATHER THAN STRING".
This way i am passing keystore :-
run -Dhttp.port=disabled -Dhttps.port=9448 -Dhttps.keyStore.path="certs\example.com.jks" -Dhttps.keyStore.type=JKS -Dhttps.keyStore.password=changeit
I am getting below error :-
error] p.c.s.AkkaHttpServer - Cannot load SSL context
ava.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at play.core.server.ssl.ServerSSLEngine$.createScalaSSLEngineProvider(ServerSSLEngine.scala:103)
at play.core.server.ssl.ServerSSLEngine$.createSSLEngineProvider(ServerSSLEngine.scala:35)
at play.core.server.AkkaHttpServer.$anonfun$httpsServerBinding$1(AkkaHttpServer.scala:126)
at play.core.server.AkkaHttpServer.$anonfun$httpsServerBinding$1$adapted(AkkaHttpServer.scala:124)
at scala.Option.map(Option.scala:146)
at play.core.server.AkkaHttpServer.<init>(AkkaHttpServer.scala:124)
aused by: com.typesafe.config.ConfigException$WrongType: system properties: path has type OBJECT rather than STRI
at com.typesafe.config.impl.SimpleConfig.findKeyOrNull(SimpleConfig.java:159)
at com.typesafe.config.impl.SimpleConfig.findOrNull(SimpleConfig.java:170)
at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:184)
at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:189)
at com.typesafe.config.impl.SimpleConfig.getString(SimpleConfig.java:246)
at play.core.server.ssl.DefaultSSLEngineProvider.createSSLContext(DefaultSSLEngineProvider.scala:34)
at play.core.server.ssl.DefaultSSLEngineProvider.<init>(DefaultSSLEngineProvider.scala:24)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
Please tell me if anything wrong in the above.
The Exception suggest, that one of your path is wrong.
Here is the code, the exception happened:
def createSSLContext(applicationProvider: ApplicationProvider): SSLContext = {
val httpsConfig = serverConfig.configuration.underlying.getConfig("play.server.https")
val keyStoreConfig = httpsConfig.getConfig("keyStore")
val keyManagerFactory: KeyManagerFactory = if (keyStoreConfig.hasPath("path")) {
val path = keyStoreConfig.getString("path") // HERE EXACTLY
As you can see it expects a path, called: play.server.https.keyStore.path.
It seems that you have configured that path wrong: Check your application.conf.
Or adjust your run command.

Node Identifier of copied node in Jackrabbit not found while deleting

I copied a node in Jackrabbit using session.getWorkspace().copy(sourceNode.getPath(), destinationNode.getPath())
This operation changes are persisted instantly as far as I know. But when I tried to get the copied node for deleting it using session.getNodeByIdentifier("nodeId of copied node"), it gives ItemNotFoundException. The reason for that error is that the copied node loses is mix:referenceable property during copy which causes getNodeByIdentifier to fail.
The question is how do I set the mix:referenceable property to copied node as I m not able to get the node from session after copy operation. Could someone help me out on this?
UPDATE:
CODE:
Node srcNode = session.getNodeByIdentifier("SOURCE_NODE_ID");
if(srcNode == null) {
System.out.println("File not found");
}
Node rootNode = session.getRootNode();
Node appNode = rootNode.getNode("JACKRABBIT");
Node destNode = appNode.addNode("Copy_Test_"+System.currentTimeMillis(),"nt:file");
session.getWorkspace().copy(srcNode.getPath(),destNode.getPath());
destNode.addMixin(MIX_VERSIONABLE);
destNode.addMixin(MIX_LOCKABLE);
destNode.addMixin(MIX_REFERENCEABLE);
destNode.addNode(DMSConstants.RESOURCE_NODE,"nt:unstructured");
session.refresh(true);
session.save();
EXCEPTION:
Exception in thread "main" javax.jcr.InvalidItemStateException: Unable to update a stale item: item.save()
at org.apache.jackrabbit.rmi.server.ServerObject.getRepositoryException(ServerObject.java:111)
at org.apache.jackrabbit.rmi.server.ServerSession.save(ServerSession.java:265)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:276)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:253)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:162)
at org.apache.jackrabbit.rmi.server.ServerXASession_Stub.save(Unknown Source)
at org.apache.jackrabbit.rmi.client.ClientSession.save(ClientSession.java:272)
Please note that I am using JCR 2.0 Also if I change the code to session.refresh(false), the code works fine but I m not able to find the node identifier from session for deleting the same which is my original issue.
Why are you creating a node at the destination then copying to the same place? I believe the stale exception is because the call to copy has updated the underlying node making your destNode reference stale/out-of-date.
Simply remove the addNode then do something like ...
String destPath = "Copy_Test_" + System.currentTimeMillis()";
session.getWorkspace().copy(srcNode.getPath(), destPath);
Node destNode = session.getPath(destPath);
As #TedTrippin pointed out the issue was with creating a destination node before copy which was not required. As part of copy, the node is created. So my final working code is as follows:
Node srcNode = session.getNodeByIdentifier("SOURCE_NODE_ID");
if(srcNode == null) {
System.out.println("File not found");
}
Node rootNode = session.getRootNode();
Node appNode = rootNode.getNode("JACKRABBIT");
String destNodeName = "Copy_Test";
session.getWorkspace().copy(srcNode.getPath(),appNode.getPath() + "/" + destNodeName);
Node destNode = appNode.getNode(destNodeName);
destNode.addMixin(MIX_VERSIONABLE);
destNode.addMixin(MIX_LOCKABLE);
destNode.addMixin(MIX_REFERENCEABLE);
session.refresh(true);
session.save();

How to print a Groovy variable in Jenkins?

I have the following code within a Jenkins pipeline:
stage ('Question') {
try {
timeout(time: 1, unit: 'MINUTES') {
userInput = input message: 'Choose server to publish to:', ok: '', parameters: [
[$class: 'hudson.model.ChoiceParameterDefinition', choices: 'pc-ensureint\nother-server', description: 'Choose server to publish to:', name: 'server']
]
}
} catch (err) {
userInput = [server: 'pc-ensureint'] // if an error is caught set this value
}
}
node () {
println ${server}
}
I'm trying to troubleshoot a problem with the server variable which is set in the ChoiceParameterDefinition.
When I run the build, I get the following error:
java.lang.NoSuchMethodError: No such DSL method '$' found among steps [AddInteractivePromotion, ArtifactoryGradleBuild, ArtifactoryMavenBuild, ConanAddRemote, ConanAddUser, InitConanClient, MavenDescriptorStep, RunConanCommand, ansiblePlaybook, archive, artifactoryDownload, artifactoryPromoteBuild, artifactoryUpload, bat, build, catchError, checkout, collectEnv, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerPullStep, dockerPushStep, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, getArtifactoryServer, getContext, getDatabaseConnection, git, input, isUnix, library, libraryResource, load, mail, milestone, newArtifactoryServer, newBuildInfo, newGradleBuild, newMavenBuild, node, parallel, properties, publishBuildInfo, pwd, readFile, readTrusted, resolveScm, retry, script, sh, sleep, sql, stage, stash, step, svn, timeout, timestamps, tool, unarchive, unstash, validateDeclarativePipeline, waitForQualityGate, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, wrap, writeFile, ws, xrayScanBuild] or symbols [all, allOf, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, batchFile, booleanParam, branch, buildButton, buildDiscarder, caseInsensitive, caseSensitive, choice, choiceParam, cleanWs, clock, cloud, command, configFile, configFileProvider, cron, crumb, defaultView, demand, disableConcurrentBuilds, docker, dockerfile, downloadSettings, downstream, dumb, envVars, environment, expression, file, fileParam, filePath, fingerprint, frameOptions, freeStyle, freeStyleJob, git, github, githubPush, gradle, hyperlink, hyperlinkToModels, installSource, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, junit, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, modernSCM, msbuild, msbuildError, msbuildWarning, myView, node, nodeProperties, nonStoredPasswordParam, none, not, overrideIndexTriggers, paneStatus, parameters, password, pattern, pipeline-model, pipelineTriggers, plainText, plugin, pollSCM, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, remotingCLI, run, runParam, schedule, scmRetryCount, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slave, stackTrace, standard, status, string, stringParam, swapSpace, text, textParam, tmpSpace, toolLocation, unsecured, upstream, usernameColonPassword, usernamePassword, viewsTabBar, weather, withSonarQubeEnv, zfs, zip] or globals [Artifactory, currentBuild, docker, env, params, pipeline, scm]
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:149)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:108)
at groovy.lang.GroovyObject$invokeMethod.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:151)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:21)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:115)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:123)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:123)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:16)
at WorkflowScript.run(WorkflowScript:16)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:109)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:82)
at sun.reflect.GeneratedMethodAccessor637.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:46)
at com.cloudbees.groovy.cps.Next.step(Next.java:74)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:165)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:330)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:82)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:242)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:230)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
at java.util.concurrent.FutureTask.run(Unknown Source)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Finished: FAILURE
As far as I know, server is a groovy variable and thus I'm supposed to be able to access it using ${ }.
So I've tried:
echo ${server}
print ${server}
println ${server}
println "${server}"
But no matter what I try I keep getting this error.
Any idea what I'm doing wrong?
The following code worked for me:
echo userInput
You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.