I wrote a simple SOAP endpoint essentially following the Spring tutorial found here: https://spring.io/guides/gs/producing-web-service/
Below is the class which is used to intercept the requests (assume repository object injected):
#Endpoint
public class SampleEndpoint {
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "SampleRequest")
public
#ResponsePayload
JAXBElement<SampleResponseType> sampleQuery(
#RequestPayload JAXBElement<SampleRequestType> request) {
ObjectFactory factory = new ObjectFactory();
SampleResponseType response = repository.query(request.getValue());
JAXBElement<SampleResponseType> jaxbResponse = factory.createSampleResponse(response);
return jaxbResponse;
}
}
The service performs correctly. One issue I'm running into is performance, particularly with unmarshalling the response. On average it's taking seconds to unmarshall the object into an XML response. Is there a way to cache/inject the JaxbContext Spring is using for this process to improve on this time?
Here's the web service configuration file I'm using for this endpoint. I've tried alternating between Saaj and Axiom message factories but didn't see much performance change:
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public SaajSoapMessageFactory soap12MessageFactory() {
SaajSoapMessageFactory factory = new SaajSoapMessageFactory();
factory.setSoapVersion(SoapVersion.SOAP_12);
return factory;
}
#Bean
public AxiomSoapMessageFactory axiomSoapMessageFactory() {
AxiomSoapMessageFactory factory = new AxiomSoapMessageFactory();
factory.setSoapVersion(SoapVersion.SOAP_12);
factory.setPayloadCaching(false);
return factory;
}
#Bean
public ServletRegistrationBean dispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
servlet.setMessageFactoryBeanName("soap12MessageFactory");
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "wsdlname")
public DefaultWsdl11Definition xcpdDefaultXcpdWsdl11Definition(XsdSchema
schema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setCreateSoap11Binding(false);
wsdl11Definition.setCreateSoap12Binding(true);
wsdl11Definition.setPortTypeName("xcpdPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition
.setTargetNamespace("http://somenamespace.org/");
wsdl11Definition.setSchema(schema);
return wsdl11Definition;
}
#Bean
public XsdSchema schema() {
return new SimpleXsdSchema(
new ClassPathResource(
"schema.xsd"));
}
}
We obtained a solution to the issue two days ago. The first issue we saw was that the client version of the JVM was installed on the server. I installed the server build of the JVM and changed Tomcat to use that instance. The performance of some of the web services improved dramatically. Previously simple requests were taking three seconds, now they are taking 250 ms. However when testing the Spring service I wrote, I didn't see much of an improvement.
To resolve this last issue, I added the following to the Java options for Tomcat:
-Dcom.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.fastBoot=true
After restarting the Tomcat instance, the response times of the services are now under one second each. Previously requests were taking up to 30 seconds to complete. The server JRE we used is the following:
http://www.oracle.com/technetwork/java/javase/downloads/server-jre8-downloads-2133154.html
Related
In my use case I need to do request-reply call to a remote system via managed queues. Using Spring Boot and IBM's MQ starter I have the problem that the application wants to create dynamic/temporary reply queues instead of using the already existing managed queue.
Configuration is set up here
#EnableJms
#Configuration
public class QueueConfiguration {
#Bean
public MQQueueConnectionFactory connectionFactory() throws JMSException {
MQQueueConnectionFactory factory = new MQQueueConnectionFactory();
factory.setTransportType(CT_WMQ); // is 1
factory.setHostName(queueProperties.getHost());
factory.setPort(queueProperties.getPort());
factory.setChannel(queueProperties.getChannel()); // combo of ${queueManager}%${channel}
return factory;
}
#Bean
public JmsMessagingTemplate messagingTemplate(ConnectionFactory connectionFactory) {
JmsMessagingTemplate jmt = new JmsMessagingTemplate(connectionFactory);
jmt.setDefaultDestinationName(queueProperties.getQueueName());
return jmt;
}
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.foo.model");
return marshaller;
}
#Bean
public MessageConverter messageConverter(Jaxb2Marshaller marshaller) {
MarshallingMessageConverter converter = new MarshallingMessageConverter();
converter.setMarshaller(marshaller);
converter.setUnmarshaller(marshaller);
return converter;
}
}
Usage is pretty straight forward: Take the object convert and send it. Wait for response receive
and convert it.
#Component
public class ExampleSenderReceiver {
#Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
#Override
#SneakyThrows
public ResponseExample sendAndReceive(RequestExample request, String correlationId) {
MessagePostProcessor mpp = message -> {
message = MessageBuilder.fromMessage(message)
.setHeader(JmsHeaders.CORRELATION_ID, correlationId)
// .setHeader(JmsHeaders.REPLY_TO, "DEV.QUEUE.3") this triggers queue creation
.build();
return message;
};
String destination = Objects.requireNonNull(jmsMessagingTemplate.getDefaultDestinationName());
return jmsMessagingTemplate.convertSendAndReceive(destination, request, ResponseExample.class, mpp);
}
I read already a lot of IBM documentation and think, I need to set the message type to "MQMT_REQUEST" but I do not find the right spot to do so.
Update
Added Spring Integration as Gary proposed and added a configuration for JmsOutboundGateway
#Bean
public MessageChannel requestChannel() {
return new DirectChannel();
}
#Bean
public QueueChannel responseChannel() {
return new QueueChannel();
}
#Bean
#ServiceActivator(inputChannel = "requestChannel" )
public JmsOutboundGateway jmsOutboundGateway( ConnectionFactory connectionFactory) {
JmsOutboundGateway gateway = new JmsOutboundGateway();
gateway.setConnectionFactory(connectionFactory);
gateway.setRequestDestinationName("REQUEST");
gateway.setReplyDestinationName("RESPONSE");
gateway.setReplyChannel(responseChannel());
gateway.setCorrelationKey("JMSCorrelationID*");
gateway.setIdleReplyContainerTimeout(2, TimeUnit.SECONDS);
return gateway;
}
And adapted my ExampleSenderReceiver class
#Autowired
#Qualifier("requestChannel")
private MessageChannel requestChannel;
#Autowired
#Qualifier("responseChannel")
private QueueChannel responseChannel;
#Override
#SneakyThrows
public ResponseExample sendAndReceive(RequestExample request, String correlationId) {
String xmlContent = "the marshalled request object";
Map<String, Object> header = new HashMap<>();
header.put(JmsHeaders.CORRELATION_ID, correlationId);
GenericMessage<String> message1 = new GenericMessage<>(xmlContent, header);
requestChannel.send(message1);
log.info("send done" );
Message<?> receive = responseChannel.receive(1500);
if(null != receive){
log.info("incoming: {}", receive.toString());
}
}
The important part is gateway.setCorrelationKey("JMSCorrelationID*");
Without that line the correlationId was not propagated correct.
Next step is re-adding MessageConverters and make it nice again.
Thank you.
The default JmsTemplate (used by the JmsMessagingTemplate) always uses a temporary reply queue. You can subclass it and override doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator) to use your managed queue instead.
However, it will only work if you have one request outstanding at a time (e.g. all run on a single thread). You will also have to add code for discarding "late" arrivals by checking the correlation id.
You can use async sends instead and handle replies on a listener container and correlate the replies to the requests.
Consider using spring-integration-jms and its outbound gateway instead - it has much more flexibility in reply queue handling (and does all the correlation for you).
https://docs.spring.io/spring-integration/reference/html/jms.html#jms-outbound-gateway
You are missing the queue manager.
ibm:
mq:
queueManager: QM1
channel: chanel
connName: localhost(1414)
user: admin
password: admin
Good day. I am new to spring integration. I wrote a simple SOAP server, and I need to connect a client that communicates through JSON and a server that communicates via SOAP, but I’ve got confused in the technology that this framework provides. As I understand it there are JsonToObjectTransformer and ObjectToMapTransformer transformers. As I understand it is necessary to transform the data before transmitting it to the controller. Is it possible to do this with the help of transformers, or I can use other technologies in the spring integration. And can this be done only with the help of DSL?
Controller:
#Endpoint
public class CityEndpoint {
private static final String NAMESPACE_URI = "http://weather.com/senchenko";
private CityRepository cityRepository;
#Autowired
public CityEndpoint(CityRepository cityRepository) {
this.cityRepository = cityRepository;
}
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCityRequest")
#ResponsePayload
public GetCityResponse getCityResponse(#RequestPayload GetCityRequest request){
GetCityResponse response = new GetCityResponse();
response.setCity(cityRepository.findCity(request.getName()));
return response;
}
}
Config:
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "city")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema citySchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CityPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://weather.com/senchenko");
wsdl11Definition.setSchema(citySchema);
return wsdl11Definition;
}
#Bean
public XsdSchema citySchema() {
return new SimpleXsdSchema(new ClassPathResource("xsd/weather.xsd"));
}
#Bean
#Transformer()
JsonToObjectTransformer jsonToObjectTransformer() {
return new JsonToObjectTransformer();
}
#Bean
#Transformer()
ObjectToMapTransformer objectToMapTransformer(){
return new ObjectToMapTransformer();
}
}
Addition
I solved the problem with redirection to SOAP, but still do not know the best way to convert JSON into an SOAP Envelope and back.
#Bean
public IntegrationFlow httpProxyFlow() {
return IntegrationFlows
.from(Http.inboundGateway("/service"))
.transform(t -> TEST_ENVOLOPE)
.enrichHeaders(h -> h.header("Content-Type", "text/xml; charset=utf-8"))
.handle(Http.outboundGateway("http://localhost:8080/ws")
.expectedResponseType(String.class))
.transform(t -> TEST_RESPONSE)
.get();
}
Your question isn't clear or you are not fully familiar with technologies you need to work.
The SOAP is fully about XML messages exchange. On the server side you have a specific MessageDispatcherServlet which converts an incoming HTTP request to the SOAP envelop fully in XML. There is just nothing about JSON at all.
Your CityEndpoint.getCityResponse() is triggered by the Spring WS Framework when an incoming SOAP request is unmarshalled from the XML into the domain model via JaxB according your XSD definition and generated model. There is just nothing about Spring Integration at all.
Your JsonToObjectTransformer and ObjectToMapTransformer just don't make any sense in this scenario. They are not involved in the SOAP request process.
Sorry to disappoint you in my answer, but it even not clear by your question how that JSON client is going to call SOAP service when JSON and XML are fully different and not compatible protocols.
I am using spring webservices for consuming a service. I am following this article https://spring.io/guides/gs/consuming-web-service/, I have created a client by extending WebServiceGatewaySupport and using that to invoke the service.
The first doubt I have is that I haven't generated any java classes from wsdl (other than jaxb objects for the types mentioned in wsdl). Don't I have to generate the stub (endpoint) classes on the client side? If not, then how does spring know which operation to be invoked as my wsdl has multiple operations?
Here is my code
public class SOAPConnector extends WebServiceGatewaySupport {
public Object callWebService(String url, Object request){
return getWebServiceTemplate().marshalSendAndReceive(url, request);
}
}
#Configuration
public class Config {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this is the package name specified in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("com.example.howtodoinjava.schemas.school");
return marshaller;
}
#Bean
public SOAPConnector soapConnector(Jaxb2Marshaller marshaller) {
SOAPConnector client = new SOAPConnector();
client.setDefaultUri("https://www.example.com/ExampleServiceBean");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
The second issue is that on executing above code I am getting following error message, can someone please help me how to fix it:
org.springframework.ws.soap.client.SoapFaultClientException: Message part Request was not recognized. (Does it exist in service WSDL?)
at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:38)
at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:830)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:624)
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:506)
at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:446)
at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:436)
at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:424)
I might be a missing a very basic thing as I am using spring webservices for the first time. Thanks in advance.
How can I configure a spring boot config client microservice to fetch its configuration from an OAuth2 configServer which is #EnableResourceServer ?
I have one OAuth2 Authorization server (#EnableAuthorizationServer). There is a configServer (#EnableConfigServer) which I have configured to respond only to valid requests authorized by authorization server containing JWT tokens.
There is also a microservice client APP1 of the config server which needs to fetch its configuration upon startup from the aforementioned config server. Since the server only responds to requests containing valid access tokens (jwt tokens) I tried to inject OAuth2RestTemplate into ConfigServicePropertySourceLocator so that my config client (APP1) could fetch its config.
In order to do that I tried the partial solution which was discussed here.
This is my OAuth2 ready RestTemplate that I want to inject
#Configuration
public class OAuthConfig {
#Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
OAuth2ProtectedResourceDetails details) {
return new OAuth2RestTemplate(details, oauth2ClientContext);
}}
and this is my custom property locator
public class CustomConfigServicePropertySourceLocator {
#Autowired
private ConfigurableEnvironment environment;
#Autowired
private RestTemplate restTemplate;
#Bean
public ConfigClientProperties configClientProperties() {
ConfigClientProperties client = new ConfigClientProperties(this.environment);
client.setEnabled(false);
return client;
}
#Bean
#Primary
public ConfigServicePropertySourceLocator configServicePropertySourceLocator() {
ConfigClientProperties clientProperties = configClientProperties();
ConfigServicePropertySourceLocator configServicePropertySourceLocator = new ConfigServicePropertySourceLocator(
clientProperties);
configServicePropertySourceLocator.setRestTemplate(restTemplate);
return configServicePropertySourceLocator;
}}
I Followed the instructions in Customizing the Bootstrap Configuration
I created a META_INF > spring.factories file containing
org.springframework.cloud.bootstrap.BootstrapConfiguration=com.company.mcapp.CustomConfigServicePropertySourceLocator
By debugging I can see that this custom locator will get called but my APP1 is failing to contact config server to fetch the configurations.
In initialize method of PropertySourceBootstrapConfiguration (below) I can see that the propertySourceLocators does not contain my CustomConfigServicePropertySourceLocator.
#Override
public void initialize(ConfigurableApplicationContext applicationContext) {
CompositePropertySource composite = new CompositePropertySource(
BOOTSTRAP_PROPERTY_SOURCE_NAME);
AnnotationAwareOrderComparator.sort(this.propertySourceLocators);
boolean empty = true;
ConfigurableEnvironment environment = applicationContext.getEnvironment();
for (PropertySourceLocator locator : this.propertySourceLocators) {
PropertySource<?> source = null;
source = locator.locate(environment);
if (source == null) {
continue;
}
logger.info("Located property source: " + source);
composite.addPropertySource(source);
empty = false;
}
.
.
.
UPDATE: The issue was a silly mistake That I made. Instead of creating META-INF I created META_INF.
I'm trying to configure Solr (with Multicore Support) in my application and I get a ConverterNotFoundException whenever I try and register converters.
I've stepped through and can see the query being executed and documents being returned. Just the converters not being found.
I followed the example from the official docs here.
Hopefully someone can shed some light on what's going on as examples are hard to find and the docs aren't overly clear about adding converters when using multicoreSupport=true.
#Configuration
#EnableSolrRepositories(
multicoreSupport = true,
basePackages = {"uk.co.foo.bar.repository"})
public class SolrConfig {
#Resource
private Environment environment;
#Bean
public SolrClient solrClient(HttpClient httpClient) {
String solrHost = environment.getRequiredProperty("solr.host");
return new HttpSolrClient(solrHost, httpClient);
}
#Bean
public HttpClient httpClient() {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, "user");
params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, "pass");
return HttpClientUtil.createClient(params);
}
#Bean
public SolrConverter solrConverter(CustomConversions customConversions){
MappingSolrConverter mappingSolrConverter= new MappingSolrConverter(new SimpleSolrMappingContext());
mappingSolrConverter.setCustomConversions(customConversions);
return mappingSolrConverter;
}
#Bean
public CustomConversions customConversions(){
return new CustomConversions(Arrays.asList(new fooConverter(), new barConverter()));
}
#Bean
public SolrTemplate solrTemplate(SolrClient solrClient, SolrConverter solrConverter){
SolrTemplate solrTemplate = new SolrTemplate(solrClient);
solrTemplate.setSolrConverter(solrConverter);
return solrTemplate;
}
}
Having multicore support enabled currently does not allow to register global CustomConverters. Unfortunately there's no workaround available. I'll take care of DATASOLR-173 to get this fixed.