SOAP over Websocket with Appache CXF and Embedded Jetty - java

I have been trying to set a a SOAP endpoint with Websocket as transport protocol via CXF and implement invoke it via CXF. With Embeded jetty. I have tried a couple of approaches non of the aproaches worked unfortunatly. Here is what I did:
Aproach 1. According to CXF documentation websocket is supported as transport protocol and its support is given via
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-websocket</artifactId>
<version>3.3.2</version>
</dependency>
I have setup the following dependencies:
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.0.39</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.3.2</version>
</dependency>
The code I executo is the following:
Endpoint endpoint = Endpoint.create(new MyHelloWorldServicePortType() {
#Override
public String sayHello(HelloMessage message) throws FaultMessage {
return message.sayHello();
}
};
((org.apache.cxf.jaxws.EndpointImpl)endpoint).getFeatures().add(new
WSAddressingFeature());
endpoint.publish("ws://localhost:8088/MyHelloWorldService" );
URL wsdlDocumentLocation = new URL("file:/path to wsdl file");
String servicePart = "MyHelloWorldService";
String namespaceURI = "mynamespaceuri";
QName serviceQN = new QName(namespaceURI, servicePart);
Service service = Service.create(wsdlDocumentLocation, serviceQN);
MyHelloWorldServicePortType port = service.getPort( MyHelloWorldServicePortType.class);
portType.sayHello(new HelloMessage("Say Hello"));
The result of this code is:
SEVERE: [ws] onError java.util.concurrent.TimeoutException: Request
timeout to not-connected after 60000 ms at
org.asynchttpclient.netty.timeout.TimeoutTimerTask.expire(TimeoutTimerTask.java:43)
at
org.asynchttpclient.netty.timeout.RequestTimeoutTimerTask.run(RequestTimeoutTimerTask.java:48)
at
io.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:682)
at
io.netty.util.HashedWheelTimer$HashedWheelBucket.expireTimeouts(HashedWheelTimer.java:757)
at
io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:485)
at java.base/java.lang.Thread.run(Thread.java:834)
jun. 12, 2019 1:13:33 P.M.
org.apache.cxf.transport.websocket.ahc.AhcWebSocketConduit$AhcWebSocketWrappedOutputStream
connect SEVERE: unable to connect
java.util.concurrent.ExecutionException:
java.util.concurrent.TimeoutException: Request timeout to
not-connected after 60000 ms at
java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
at
java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at
org.asynchttpclient.netty.NettyResponseFuture.get(NettyResponseFuture.java:172)
at
org.apache.cxf.transport.websocket.ahc.AhcWebSocketConduit$AhcWebSocketWrappedOutputStream.connect(AhcWebSocketConduit.java:309)
at
org.apache.cxf.transport.websocket.ahc.AhcWebSocketConduit$AhcWebSocketWrappedOutputStream.setupWrappedStream(AhcWebSocketConduit.java:167)
at
org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleHeadersTrustCaching(HTTPConduit.java:1343)
at
org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.onFirstWrite(HTTPConduit.java:1304)
at
org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:47)
at
org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:69)
at
org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1356)
at
org.apache.cxf.transport.websocket.ahc.AhcWebSocketConduit$AhcWebSocketWrappedOutputStream.close(AhcWebSocketConduit.java:139)
at
org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
I have absolutly no idea why. When I try to connect via websocket chrome client on the URL. It says success. At the same time when connecting via the client it says Timeout.
Aproach 2.
I decided to cheat CXF and provide a handmade Websocket endpoint that will be used as a front to the CXF webservice. The idea is that the Client will send a message via websocket the message will be unwrapped and then sent over CXF. This aproach is very similar to the aproach here but here it uses JMS as transport
https://github.com/pbielicki/soap-websocket-cxf
In oprder to do this I created the following Websocket enpoint:
#ServerEndpoint("/jaxWSFront")
public class JaxWSFrontEnd {
#OnOpen
public void onOpen(final Session session) {
System.out.println("Hellooo");
}
#OnMessage
public void onMessage(String mySoapMessage,final Session session) throws Exception{
// The goal here is to get the soap message and redirect it via SOAP web //service. The JaxWSFacade acts as a point that understands websocket and then //gets the soap content and sends it to enpoint that understands SOAP.
session.getBasicRemote().sendText("Helllo . Now you see me.");
System.out.println("Hellooo again");
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Hellooo");
}
#OnError
public void onError(Throwable t, Session session) {
System.out.println("Hellooo");
}
}
Now I pointed my Client proxy to the jaxWsFrontEnd instead of the webservice endpoint. My expectation is that I will recieve the SOAP message in the onMessage method and then I will be able to forwards to SOAP to the CXF web service.
Now my code looks like this:
server = new Server(8088);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath( "/" );
server.setHandler(context);
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
container.addEndpoint(JaxWSFrontEnd.class);
server.setHandler( context );
server.start();
Endpoint endpoint = Endpoint.create(new MyHelloWorldServicePortType() {
#Override
public String sayHello(HelloMessage message) throws FaultMessage {
return message.sayHello();
}
};
((org.apache.cxf.jaxws.EndpointImpl)endpoint).getFeatures().add(new
WSAddressingFeature());
URL wsdlDocumentLocation = new URL("file:/path to wsdl file");
String servicePart = "MyHelloWorldService";
String namespaceURI = "mynamespaceuri";
QName serviceQN = new QName(namespaceURI, servicePart);
Service service = Service.create(wsdlDocumentLocation, serviceQN);
MyHelloWorldServicePortType port = service.getPort( MyHelloWorldServicePortType.class);
portType.sayHello(new HelloMessage("Say Hello"));
For the second aproach I had in addition to the aproach 1 the following dependencies:
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-common</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>javax-websocket-server-impl</artifactId>
</dependency>
Result from aproach 2 is absolutly the same as Aproach 1 the exceptions I recieve are the same, with one minor difference. When I use the the Chrome websocket client and point it directly the the jaxWsFrontend I am able to successfuly send a message. Why I am not able to connect to websocket wia the CXF websocket transport mechanisms ???? What am I doing wrong ?
UPDATE: enabling the loging from NETTY. It apears that netty has thrown java.lang.NoSuchMethodError: io.netty.channel.DefaultChannelId.newInstance()Lio/netty/channel/DefaultChannelId;
Maybe I have a version compatability issue with netty. The version I can see is imported in the project is 4.1.33. It is a transitive dependency I don|t have it declared.

Ok I actualy managed to crack it alone. I will post the answer for completion. Apparantly CXF guys should update their documentation IMO. On their website it is stated that in order to enable Websocket as transport protocol we need
cxf-rt-transports-websocket dependency.
What they do not say is that you in addition need async-http-client not any version but 2.0.39 a prettey old one. The problem is that it automaticaly includes transitive dependencies to netty 4.1 and the error specified above begins to manifest. What you actualy need is nett 4.0.56
Here is the fragment that made the things work for me:
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.0.39</version>
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-codec</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.56.Final</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-websocket</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.3.2</version>
</dependency>
Aproach 1 is working
Aproach 2 I managed to trigger the onConnect event, the onMessage timedout, but in my opinion it should work I am missing something small. Anyway I don|t have more time to spent and I am happy with Aproach 1.

Related

I got this message: Cannot construct instance of `reactor.core.publisher.Mono`

I used Jersey and Webflux with R2DBC. after send the POST via the postman I got this message " Cannot construct instance of reactor.core.publisher.Mono "
This is my JerseyConfiguration:
#Component
public class JerseyConfiguration
extends ResourceConfig {
public JerseyConfiguration() {
register(ProductController.class, 1);
}
}
and this is my Controller:
#Path("/v1")
#Controller
public class ProductController {
#Autowired
private ProductService productService;
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/product")
public Mono<Product> createProduct(#RequestBody Mono<Product> productMono){
return productMono.flatMap(this.productService::createProduct);
}
}
and this sis my service:
#Service
public class ProductService {
#Autowired
private ProductRepository repository;
public Mono<Product> createProduct(final Product product){
return this.repository.save(product);
}
}
and also this my pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Now, this is my problem; I got this message from the postman:
Cannot construct instance of `reactor.core.publisher.Mono` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 1]
Please let me know how to solve that problem.
Thank you
You cannot mix WebFlux and Jersey. You should choose one or the other, not both. They both provide an HTTP server engine, but:
Jersey is a Servlet JAX-RS implementation, it does not know anything about reactive streams, Mono, Flux, etc.
Webflux is the Spring HTTP server engine based on reactive streams and async Netty HTTP server.
If you look at Spring Boot reference documentation, section 3.5: Web, you will see that Jersey is one of the available engines, competing with other possible engines, i.e Web MVC and web reactive (webflux).
So, the answer is : Jersey is incompatible with Webflux, and you must choose between Webflux reactive Web and Spring rest annotation, or Jersey and Jax_RS without using Mono/Flux as return-type.
Note 1 : You should annotate your class with #RestController whe using webflux, so it understand that method return is the HTTP response body (see the last paragraph of reference documentation section 1.4.1: #Controller for details.
Note 2 : If you really want to use jersey, but you still require to consume Mono objects from other parts of your system, you might use one of the conversion functions provided by Reactor to return an object that jersey can work with. For example, on Mono object, you will find a toFuture() method. You could also block(), but it could be dangerous.

Disable introspection query in graphql java tools spring boot

I am facing issues while disabling the introspection query in a spring boot graphql project on a get endpoint query parameter.
I was replicating this by using one of the GET endpoint and using the below parameter
baseurl/servicename/insight_graph?query=fragment+FullType+on+__Type+{++kind++name++description++fields(includeDeprecated%3a+true)+{++++name++++description++++args+{++++++...InputValue++++}++++type+{++++++...TypeRef++++}++++isDeprecated++++deprecationReason++}++inputFields+{++++...InputValue++}++interfaces+{++++...TypeRef++}++enumValues(includeDeprecated%3a+true)+{++++name++++description++++isDeprecated++++deprecationReason++}++possibleTypes+{++++...TypeRef++}}fragment+InputValue+on+__InputValue+{++name++description++type+{++++...TypeRef++}++defaultValue}fragment+TypeRef+on+__Type+{++kind++name++ofType+{++++kind++++name++++ofType+{++++++kind++++++name++++++ofType+{++++++++kind++++++++name++++++++ofType+{++++++++++kind++++++++++name++++++++++ofType+{++++++++++++kind++++++++++++name++++++++++++ofType+{++++++++++++++kind++++++++++++++name++++++++++++++ofType+{++++++++++++++++kind++++++++++++++++name++++++++++++++}++++++++++++}++++++++++}++++++++}++++++}++++}++}}query+IntrospectionQuery+{++__schema+{++++queryType+{++++++name++++}++++mutationType+{++++++name++++}++++types+{++++++...FullType++++}++++directives+{++++++name++++++description++++++locations++++++args+{++++++++...InputValue++++++}++++}++}}
and with the below dependencies
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>5.4.1</version>
<exclusions>
<exclusion>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.4.1</version>
</dependency>
This works pretty well when we request the same using post and with the below request body and using graphql.tools.introspection-enabled=false and
POST baseurl/servicename/insight_graph
[
{
"operationName": "IntrospectionQuery",
"variables": {},
"query": "query IntrospectionQuery {__schema {queryType { name },mutationType { name },subscriptionType { name },types {...FullType},directives {name,description,args {...InputValue},onOperation,onFragment,onField}}}\nfragment FullType on __Type {kind,name,description,fields(includeDeprecated: true) {name,description,args {...InputValue},type {...TypeRef},isDeprecated,deprecationReason},inputFields {...InputValue},interfaces {...TypeRef},enumValues(includeDeprecated: true) {name,description,isDeprecated,deprecationReason},possibleTypes {...TypeRef}}\nfragment InputValue on __InputValue {name,description,type { ...TypeRef },defaultValue}\nfragment TypeRef on __Type {kind,name,ofType {kind,name,ofType {kind,name,ofType {kind,name}}}}"
}
]
I also tried this via spring filters and it works fine
Is there any way to disable introspection via spring boot property for this?

What is the difference between UndertowJaxrsServer.deploy and UndertowJaxrsServer.deployOldStyle?

I'm trying to produce a bootable jar with Undertow + Resteasy + Jackson2 with those dependencies in my pom.xml:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-undertow</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-cdi</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
when I use 3.* versions of resteasy, I can start the WebServer this way:
public static UndertowJaxrsServer startServer() {
server = new UndertowJaxrsServer()
.deploy(MyOwnApplication.class) // replace this with .deployOldStyle(MyOwnApplication.class) for versions grater than 4.0 of resteasy
.start(
Undertow.builder()
.addHttpListener(Integer.parseInt(SERVER_PORT), SERVER_HOST)
);
return server;
}
but, after upgrading resteasy from v3.0.9.Final to v4.6.0.Final, this service does not work (always produces errors 405 - method not allowed, on every POST request).
The solution I found was to replace the deploy method with deployOldStyle (present only in versions grater than 4 of reasteasy), but it seems to be undocumented.
Can anybody explain me how the deploy method has changed and why?
Should I adapt some other part of my code and continue using the deploy method?
Thanks

Error casting context.lookup(...) returned object to ejb3 remote object interface

I have an EJB stateless running under a JBoss server and a client under another JBoss server.
In the client side, I am using the following code:
final Properties initialContextProperties = new Properties();
initialContextProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
initialContextProperties.put(Context.PROVIDER_URL, "remote://127.0.0.1:8083");
initialContextProperties.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
initialContextProperties.put("jboss.naming.client.ejb.context", true);
final InitialContext contexte = new InitialContext(initialContextProperties);
Object remoteObj = contexte.lookup("ejb:my-web-app/MyEjbRemoteImpl!my.ejb.remote.MyEjbRemoteInterface");
MyEjbRemoteInterface myEjb = (my.ejb.remote.MyEjbRemoteInterface) remoteObj;
While running this code, I have this exception:
org.jboss.ejb.client.naming.ejb.EjbNamingContext cannot be cast to my.ejb.remote.MyEjbRemoteInterface
These dependencies are in the classpath of the client side:
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jboss-remote-naming</artifactId>
<version>2.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.xnio</groupId>
<artifactId>xnio-nio</artifactId>
<version>3.3.6.Final</version>
</dependency>
Have you any idea?
Thanks for your help
The problem was in the lookup method string parameter. It must be like: ejb:/my-web-app//MyEjbRemoteImpl!my.ejb.remote.MyEjbRemoteInterface. Generally like ejb:AppName/EjbModuleName/DistinctName/EjbRemoteBeanImpName!ejb.remote.interface.Name
And all required dependencies:
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-ejb-client-bom</artifactId>
<version>7.2.0.Final</version>
<type>pom</type>
</dependency>

Jersey with Jetty hard time

I can't run up my RESTful service with embedded Jetty 7 and Jersey. When I call my simple hello test I get:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message
body writer for Java class java.lang.String, and Java type class java.lang.String,
and MIME media type text/plain was not found
I saw errors similar posted here on SO, but it was for custom classes, and mine is for just String. Any hints? My init server code:
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
ServletContainer container = new ServletContainer();
ServletHolder h = new ServletHolder(container);
h.setInitParameter("com.sun.jersey.config.property.packages", "api");
context.addServlet(h, "/res/*");
And dependances:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.11.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>7.1.6.v20100715</version>
</dependency>
Do you have any hints?
Exchange jersey-server to :
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.11.1</version>
</dependency>

Categories

Resources