Groovy: WSClient throwing JAXBException - groovy

I am trying to call a simple public Web Service with WSClient in a Groovy script, but it explodes when initializing ...
TestService.groovy:
#Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient
def proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize();
def result = proxy.CelsiusToFahrenheit(0)
println "You are probably freezing at ${result} degrees Farhenheit"
The error message:
SEVERE: Could not compile java files for http://www.w3schools.com/webservices/tempconvert.asmx?WSDL.
Caught: java.lang.IllegalStateException: Unable to create JAXBContext for generated packages: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
java.lang.IllegalStateException: Unable to create JAXBContext for generated pack
ages: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: jav
ax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or j
axb.index
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:343)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:196)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:175)
at groovyx.net.ws.AbstractCXFWSClient.createClient(AbstractCXFWSClient.java:229)
at groovyx.net.ws.WSClient.initialize(WSClient.java:108)
at groovyx.net.ws.IWSClient$initialize.call(Unknown Source)
at TestService.run(TestService.groovy:5)
Caused by: javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index - with linked exception:
[javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.classor jaxb.index]
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:340)
... 6 more
Caused by: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:197)
... 7 more
Any hint? Why should I have a jaxb.index?
Just discovered that the problem occurs with Java 1.7 (jdk1.7.0_21)... it's OK when running with Java 6 (jdk1.6.0_31)
Any hint to work with Java 7?

As noted on the GroovyWS page, GroovyWS is currently dormant. You could do the same thing (albeit with a wordier syntax) using the groovy-wslite library:
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import wslite.soap.*
def client = new SOAPClient('http://www.w3schools.com/webservices/tempconvert.asmx')
def response = client.send(SOAPAction:'http://tempuri.org/CelsiusToFahrenheit') {
body {
CelsiusToFahrenheit('xmlns':'http://tempuri.org/') {
Celsius('0')
}
}
}
def result = response.CelsiusToFahrenheitResponse.CelsiusToFahrenheitResult.text()
println "You are probably freezing at ${result} degrees Farhenheit"
Note that this requires you to look at the WSDL to get the SOAP message namespace, unlike the GroovyWS version of the code. But it works!

Related

Quarkus unable to load the cassandra custom retry policy class

I am working on a task to migrate Quarkus from 1.x to 2.x and Quarkus integration with embedded Cassandra failed in unit testing with error -
Caused by: java.lang.IllegalArgumentException: Can't find class com.mind.common.connectors.cassandra.CassandraCustomRetryPolicy
(specified by advanced.retry-policy.class)
**Custom retry policy**
public class CassandraCustomRetryPolicy implements RetryPolicy {
public CassandraCustomRetryPolicy(DriverContext context, String profileName) {
}
//override methods
}
****quarkus test be like** -**
#QuarkusTest
#QuarkusTestResource(CassandraTestResource.class)
class Test {}
**CassandraTestResource class start the embedded cassandra**
public class CassandraTestResource implements QuarkusTestResourceLifecycleManager {
private Cassandra cassandra;
#Override
public Map<String, String> start() {
cassandra = new CassandraBuilder().version("3.11.9")
.addEnvironmentVariable("JAVA_HOME", getJavaHome())
.addJvmOptions("-Xms512M -Xmx512m").build();
cassandra.start();
}
I have override the default Cassandra driver policy in application.conf inside resource folder.
datastax-java-driver {
basic.request {
timeout = ****
consistency = ***
serial-consistency = ***
}
advanced.retry-policy {
class = com.mind.common.connectors.cassandra.CassandraCustomRetryPolicy
}
I have observed that my custom retry policy class comes under banned resource in QuarkusClassLoader.java-
String resourceName = sanitizeName(name).replace('.', '/') + ".class";
boolean parentFirst = parentFirst(resourceName, state);
if (state.bannedResources.contains(resourceName)) {
throw new ClassNotFoundException(name);
}
I have captured the following logs -
java.lang.ClassNotFoundException: com.mind.common.connectors.cassandra.CassandraCustomRetryPolicy
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:438)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at com.datastax.oss.driver.internal.core.util.Reflection.loadClass(Reflection.java:57)
at com.datastax.oss.driver.internal.core.util.Reflection.resolveClass(Reflection.java:288)
at com.datastax.oss.driver.internal.core.util.Reflection.buildFromConfig(Reflection.java:235)
at com.datastax.oss.driver.internal.core.util.Reflection.buildFromConfigProfiles(Reflection.java:194)
at com.datastax.oss.driver.internal.core.context.DefaultDriverContext.buildRetryPolicies(DefaultDriverContext.java:359)
at com.datastax.oss.driver.internal.core.util.concurrent.LazyReference.get(LazyReference.java:55)
at com.datastax.oss.driver.internal.core.context.DefaultDriverContext.getRetryPolicies(DefaultDriverContext.java:761)
at com.datastax.oss.driver.internal.core.session.DefaultSession$SingleThreaded.init(DefaultSession.java:339)
at com.datastax.oss.driver.internal.core.session.DefaultSession$SingleThreaded.access$1100(DefaultSession.java:300)
at com.datastax.oss.driver.internal.core.session.DefaultSession.lambda$init$0(DefaultSession.java:146)
at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98)
at io.netty.util.concurrent.PromiseTask.run(PromiseTask.java:106)
at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
I am using quarkus version 2.7.2.Final with cassandra driver version 4.14.0
It's not a complete answer but I wanted to leave some notes here in case anybody else can get this over the finish line before I get back to it.
The underlying problem here is that in the Quarkus test case described above the Java driver code is loaded by the QuarkusClassLoader which (a) is more restrictive about where it loads code from and (b) doesn't appear to immediately support calling it's parent if necessary. So in this case executing the following in the test will fail with a ClassNotFoundException:
CqlSession.class.getClassLoader().forName(customretrypolicyclassname)
while the following works without issue:
CqlSession.class.getClassLoader().getParent().forName(customretrypolicyclassname)
The class loader used to load CqlSession is the QuarkusClassLoader instance while it's parent is a stock JVM class loader.
The Java driver uses Class.forName() to load the classes specified for this policy. But since the Quarkus class loader is used to load the driver code itself that's the loader that's used for these reflection ops... and as mentioned above that driver has some specific characteristics that make loading external code harder.
It worked after I initialized CQL session like -
CqlSession.builder()
.addContactPoint(new InetSocketAddress(settings.getAddress(), settings.getPort()))
.withLocalDatacenter("***")
. withClassLoader(Thread.currentThread().getContextClassLoader()).build())

Is there a replacement of com.sun.jndi.dns.DnsContextFactory in Java 9?

The follow simple code:
Hashtable<String, String> env = new Hashtable();
env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
DirContext dns = new InitialDirContext( env );
produce the follow exception in Java 9. Currently I use 9-ea+164-jigsaw-nightly.
javax.naming.NoInitialContextException: Cannot instantiate class:
com.sun.jndi.dns.DnsContextFactory [Root exception is java.lang.IllegalAccessException:
class javax.naming.spi.NamingManager (in module java.naming) cannot access
class com.sun.jndi.dns.DnsContextFactory (in module jdk.naming.dns) because module jdk.naming.dns
does not export com.sun.jndi.dns to module java.naming]
at java.naming/javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:719)
at java.naming/javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:305)
at java.naming/javax.naming.InitialContext.init(InitialContext.java:236)
at java.naming/javax.naming.InitialContext.<init>(InitialContext.java:208)
at java.naming/javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:101)
I checked jdk-9+168 and I don't see this issue. Are you seeing it with a recent build?

Is there mongodb mapping converter for generic message

Is there mongodb mapping converter for generic message.
No argument constructor not available for generic message.
.11:47:30.937 [http-nio-9080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.messaging.MessageHandlingException: error occurred in message handler [messageHandler]; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate org.springframework.messaging.support.GenericMessage using constructor NO_CONSTRUCTOR with arguments ] with root cause
java.lang.NoSuchMethodException: org.springframework.messaging.support.GenericMessage.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:61)
at org.springframework.data.convert.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:83)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:251)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:231)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1186)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.access$200(MappingMongoConverter.java:78)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1134)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1097)
Also I am trying following config of mongotemplate
Please advise if correct
public MongoTemplate messagingMongoTemplate() throws Exception {
MongoTemplate mongoTemplate=null;
try {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingContext mappingContext = new MongoMappingContext();
MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(dbRefResolver,mappingContext);
CustomConversions customConversions = new CustomConversions(Arrays.asList(new MongoDbMessageBytesConverter()));
mappingMongoConverter.setCustomConversions(customConversions);
mongoTemplate=new MongoTemplate(mongoDbFactory,mappingMongoConverter);
Starting with version 3.0 it is recommended to use ConfigurableMongoDbMessageStore as that provides more options for customization, including a Converter for Message.
Out-of-the-box Spring Integration provides MongoDbMessageBytesConverter, which has become public since 4.2.10 and is used by default if there is no any external customization for the ConfigurableMongoDbMessageStore.

Why is this Groovy code trying to cast?

Im getting a cast exception thrown at the line "handDetailList.each". I don't understand why my code is trying to cast a list to a "Hand" class? It seems to me that sometimes Groovy does strange things with casting....?
private Hand buildHands(List handDetailList) {
def parsedHand = new Hand()
parsedHand.setTableName(handDetailList.get(1))
handDetailList.each {
}
}
I get the following exception (I have edited the exception, line 70 is "handDetailList.each {"):
Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object <details of the list, omitted> with class 'java.util.ArrayList' to class 'gameMechanics.Hand' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: gameMechanics.Hand(java.lang.String,........
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:358)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:599)
at advisor.HistoryParser.buildHands(HistoryParser.groovy:70)
at advisor.HistoryParser.this$2$buildHands(HistoryParser.groovy)
at advisor.HistoryParser$this$2$buildHands.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at advisor.HistoryParser.parse(HistoryParser.groovy:57)
at advisor.HistoryParser$parse.call(Unknown Source)
each returns the list that each was called on.
You have said the function returns an object of type Hand, and as Groovy automatically returns the last statement in a method, it is trying to convert the list to an instance of Hand and failing...
What is it you want to return? The parsedHand variable?
Maybe try:
private Hand buildHands(List handDetailList) {
def parsedHand = new Hand()
parsedHand.setTableName(handDetailList.get(1))
handDetailList.each {
}
parsedHand
}
if so.

Gradle remembers old source code

I want to create gradle custom task. The problem is that sometimes when I change something in source code, gradle shows error that in my code is error with that non existing code. For example I've created local variable timestamp and compiled project. Everything worked fine. But later I changed that variable to final ... TIMESTAMP. After that change gradle shows me error Could not find property 'timestamp'.... How to solve this problem? I assume that gradle has got cache?
Code
class MyCustomTask extends DefaultTask {
private final String TIMESTAMP = System.currentTimeMillis().toString()
public MyCustomTask() {
}
#TaskAction
def build() {
// do something
}
}
Exception
* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating project ':customer'.
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.ja
va:54)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
at org.gradle.configuration.BuildScriptProcessor.execute(BuildScriptProcessor.java:36)
at org.gradle.configuration.BuildScriptProcessor.execute(BuildScriptProcessor.java:23)
at org.gradle.configuration.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
at org.gradle.configuration.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:55)
at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:465)
at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:76)
at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:31)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:142)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:113)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:81)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.ja
va:64)
at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:50)
at org.gradle.api.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:201)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:174)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:170)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:139)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
at org.gradle.launcher.Main.doAction(Main.java:48)
at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
at org.gradle.launcher.Main.main(Main.java:39)
at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:50)
at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:32)
at org.gradle.launcher.GradleMain.main(GradleMain.java:26)
Caused by: org.gradle.api.tasks.TaskInstantiationException: Could not create task of type 'MyCustomTask'.
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:115)
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:110)
at org.gradle.api.internal.AbstractTask.injectIntoNewInstance(AbstractTask.java:141)
at org.gradle.api.internal.project.taskfactory.TaskFactory.createTaskObject(TaskFactory.java:110)
at org.gradle.api.internal.project.taskfactory.TaskFactory.createTask(TaskFactory.java:70)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.createTask(AnnotationProcessingTaskF
actory.java:98)
at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.createTask(DependencyAutoWireTaskFacto
ry.java:39)
at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:53)
at org.gradle.api.internal.project.AbstractProject.task(AbstractProject.java:908)
at org.gradle.api.internal.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:216)
at org.gradle.api.internal.BeanDynamicObject.invokeMethod(BeanDynamicObject.java:122)
at org.gradle.api.internal.CompositeDynamicObject.invokeMethod(CompositeDynamicObject.java:147)
at org.gradle.groovy.scripts.BasicScript.methodMissing(BasicScript.java:83)
at build_1i1akohldagki7rlpcas5oct58.run(C:\workspace-eclipse-juno\Is2k8\customer\build.gradle:19)
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.ja
va:52)
... 30 more
Caused by: groovy.lang.MissingPropertyException: Could not find property 'timestamp' on task ':customer:is2k8Test'.
at org.gradle.api.internal.AbstractDynamicObject.propertyMissingException(AbstractDynamicObject.java:43)
at org.gradle.api.internal.AbstractDynamicObject.getProperty(AbstractDynamicObject.java:35)
at org.gradle.api.internal.CompositeDynamicObject.getProperty(CompositeDynamicObject.java:94)
at pl.ydp.gradle.MyCustomTask_Decorated.getProperty(Unknown Source)
at pl.ydp.gradle.MyCustomTask.<init>(MyCustomTask.groovy:15)
at pl.ydp.gradle.MyCustomTask_Decorated.<init>(Unknown Source)
at org.gradle.api.internal.DependencyInjectingInstantiator.newInstance(DependencyInjectingInstantiator.java:62)
at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36)
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:113)
... 44 more
At the end you will find Caused by: groovy.lang.MissingPropertyException: Could not find property 'timestamp' on task ':customer:is2k8Test'.

Resources