Calling a SOAP Web service using spring integration dsl - spring

I need to call a SOAP Webservice from my REST service. I'm using Spring integration in my project. Currently I'm using xml based configuration to achieve the target. But I want to write code in java dsl. Kindly help me how to call a SOAP service from a REST Service using Spring integration DSL.
One example would be really helpful.

See the documentation: https://docs.spring.io/spring-integration/docs/current/reference/html/ws.html#webservices-dsl
#Bean
IntegrationFlow outboundMarshalled() {
return f -> f.handle(Ws.marshallingOutboundGateway()
.id("marshallingGateway")
.marshaller(someMarshaller())
.unmarshaller(someUnmarshalller()))
...
}
or
.handle(Ws.simpleOutboundGateway(template)
.uri(uri)
.sourceExtractor(sourceExtractor)
.encodingMode(DefaultUriBuilderFactory.EncodingMode.NONE)
.headerMapper(headerMapper)
.ignoreEmptyResponses(true)
.requestCallback(requestCallback)
.uriVariableExpressions(uriVariableExpressions)
.extractPayload(false))
)

Related

How to inject Feign Client with out using Spring Boot and call a REST Endpoint

I have two Java processes - which get spawned from the same Jar using different run configurations
Process A - Client UI component , Developed Using Spring bean xml based approach. No Spring Boot is there.
Process B - A new Springboot Based component , hosts REST End points.
Now from Process A , on various button click how can I call the REST end points on Process B using Feign Client.
Note - Since Process A is Spring XML based , right at the moment we can not convert that to Spring boot. Hence #EnableFeignClients can not be used to initialise the Feign Clients
So Two questions
1) If the above is possible how to do it ?
2) Till Process A is moved to Spring boot - is Feign still an easier option than spring REST template ?
Feign is a Java to HTTP client binder inspired by Retrofit, JAXRS-2.0, and WebSockets and you can easily use feign without spring boot. And Yes, feign still better option to use because Feign Simplify the HTTP API Clients using declarative way as Spring REST does.
1) Define http methods and endpoints in interface.
#Headers({"Content-Type: application/json"})
public interface NotificationClient {
#RequestLine("POST")
String notify(URI uri, #HeaderMap Map<String, Object> headers, NotificationBody body);
}
2) Create Feign client using Feign.builder() method.
Feign.builder()
.encoder(new JacksonEncoder())
.decoder(customDecoder())
.target(Target.EmptyTarget.create(NotificationClient.class));
There are various decoders available in feign to simplify your tasks.
You are able to just initialise Feign in any code (without spring) just like in the readme example:
public static void main(String... args) {
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com");
...
}
Please take a look at the getting started guide: feign on github

How to use ActiveMQ queue with Spring Integration

I have a local ActiveMQ server and i want to poll messages from a queue named "test" using Spring Integration.
After i have polled the message i want to send it to another channel which would write it on a text file in the file system.
I have seen some examples using
<int-jms:message-driven-channel-adapter id="jmsIn" destination="inQueue" channel="exampleChannel"/>
I want to create this JMS "poller" using Java Annotations. I could not find any reference on how to replace the above XML stuff to annotations.
Could anyone provide a working snippet that would have connection factory configuration and jms:message-driven-channel-adapter done with annotations?
P.S. Here is a reference that has XML configuration
https://examples.javacodegeeks.com/enterprise-java/spring/integration/spring-boot-integration-activemq-example/
Thanks a lot in advance !
Well, for proper Java & Annotations configuration you need to consider to use Spring Integration Java DSL.
Here is some example for the <int-jms:message-driven-channel-adapter> equivalent:
#Bean
public IntegrationFlow jmsMessageDrivenRedeliveryFlow() {
return IntegrationFlows
.from(Jms.messageDrivenChannelAdapter(jmsConnectionFactory())
.errorChannel(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)
.destination("jmsMessageDrivenRedelivery")
.configureListenerContainer(c -> c
.transactionManager(mock(PlatformTransactionManager.class))
.id("jmsMessageDrivenRedeliveryFlowContainer")))
.<String, String>transform(p -> {
throw new RuntimeException("intentional");
})
.get();
}
To write to file you need to use a Files.outboundAdapter(): https://docs.spring.io/spring-integration/docs/5.0.6.RELEASE/reference/html/files.html#_configuring_with_the_java_dsl_9
I agree that we are missing similar Docs for JMS part, so feel free to raise a JIRA on the matter.

Spring Integration RedisLockRegistry example

I want to use Spring Integration RedisLockRegistry . I have some questions about Spring Integration RedisLockRegistry.
Can I use the redisLockRegistry as a Spring bean ? it means my application just a single redisLockRegistry.
I see the RedisLockRegistry implement ExpirableLockRegistry in the version 5.0,
Should I need run the expireUnusedOlderThan method?
I met the same questions and start analyze spring code. So from sources I can state that:
Yes you can create and configure it as a bean of any instance of LockRegistry like RedisLockRegistry, JdbcLockRegistry. For test purposes I'd like even use PassThruLockRegistry
I tried to find any invocation of expireUnusedOlderThan inside Spring without success.
So I have created simple scheduler as following:
#Autowired
private ExpirableLockRegistry lockRegistry;
#Scheduled(fixedDelay=50000)
public void cleanObsolete(){
lockRegistry.expireUnusedOlderThan(50000);
}

How to configure StepExecutionListener with Spring Integration DSL

I am trying to configure a Spring Batch listener to send a message to a Spring Integration Gateway for StepExecution events.
The following link explains how to configure this with XML
http://docs.spring.io/spring-batch/trunk/reference/html/springBatchIntegration.html#providing-feedback-with-informational-messages
How can this be setup using Spring Integration DSL? I've found no way to configure a gateway with a service interface using DSL.
At the moment I worked around this by implementing an actual StepExecutionListener, and have this then calling an interface which is annotated with #MessagingGateway (calling the corresponding #Gateway method) in order to get a message to a channel. And I then setup an Integration DSL flow for this channel.
Is there a simpler way using DSL, avoiding that workaround? Is there some way to connect a Batch listener direct to a gateway, like one can using XML config?
Cheers,
Menno
First of all SI DSL is just an extension of existing SI Java and Annotation configuration, so it can be used together with any other Java config. Of course an XML #Import is also posible.
There is no gateway configuration in the DSL, because its methods can't be wired with linear IntegrationFlow. There is need to provide downstream flows for each method.
So, #MessagingGateway is a right way to go ahead:
#MessagingGateway(name = "notificationExecutionsListener", defaultRequestChannel = "stepExecutionsChannel")
public interface MyStepExecutionListener extends StepExecutionListener {}
From other side #MessagingGateway parsing as well as <gateway> tag parsing ends up with GatewayProxyFactoryBean definition. So, you just can declare that bean, if you don't want to introduce a new class:
#Bean
public GatewayProxyFactoryBean notificationExecutionsListener(MessageChannel stepExecutionsChannel) {
GatewayProxyFactoryBean gateway = new GatewayProxyFactoryBean(StepExecutionListener.class);
gateway.setDefaultRequestChannel(stepExecutionsChannel);
return gateway;
}
After the latest Milestone 3 I have an idea to introduce nested flows, when we may be able to introduce Gateway support for flows. Something like this:
#Bean
public IntegrationFlow gatewayFlow() {
return IntegrationFlows
.from(MyGateway.class, g ->
g.method("save", f -> f.transform(...)
.filter(...))
.method("delete", f -> f.handle(...)))
.handle(...)
.get();
}
However I'm not sure that it will simplify the life, as far as any nested Lambda just adds more noise and might break loosely coupling principle.

How to consume REST URLs using Spring MVC?

I have developed few RESTful methods and exposed them via Apache Cxf
I'm developing the client side application using Spring MVC and I'm looking for a simple example to demonstrate how to call/consume these REST methods using Spring MVC
I know how to do it using Apache http client but prefer to use Spring MVC in case such this has already been implemented there.
Spring provides simple wrapper to consume RESTful services called RestTemplate. It performs path variable resolution, marshalling and unmarshalling:
Map<String, Integer> vars = new HashMap<String, Integer>();
vars.put("hotelId", 42);
vars.put("roomId", 13);
Room room = restTemplate.getForObject(
"http://example.com/hotels/{hotelId}/rooms/{roomId}",
Room.class, vars);
Assuming Room is a JAXB object which can be understood by The RestTemplate.
Note that this class has nothing to do with Spring MVC. You can use it in MVC application, but also in a standalone app. It is a client library.
See also
REST in Spring 3: RestTemplate
Use path variables to consume REST data. For example:
https://localhost/products/{12345}
This pattern should give you the detail of the product having product id 12345.
#RequestMapping(value="/products/{productId}")
#ResponseBody
public SomeModel doProductProcessing(#PathVariable("productId") String productId){
//do prpcessing with productid
return someModel;
}
If you want to consume Rest Service from another service then have a look at:
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html
and
http://www.informit.com/guides/content.aspx?g=java&seqNum=546

Resources