Java log request with corresponding response - java

I have web application which interacts with SOAP and REST external web services for some use cases as a client, and as a server for other use cases.
By the business requirements I need to log all outcoming requests to the external systems with the corresponding response, and I also need to log all incoming requests with the corresponding response.
So i need to write the list of objects like this:
{communicationId, timestamp, OUT[IN], request, response}.
What is the best way to achieve it from several perspectives:
1. To have the code in the single place if it is possible.
2. To map request with corresponding response effectively.

The best solution is dependent on the tooling you are using.
I assume you have an ESB (such as Mule) in front of your web application. If so, you have the ESB log the necessary information on the way in/out of the app.
If you have Apache CXF available, you could use interceptors to do the logging for you.
As for logging the 'response' - does this mean the actual object? If so, you could use JAXB to convert to XML and then log.

Related

How do I create a Java Jersey client from an existing XML based RESTful service

I'm used to integrating with SOAP Webservices where the wsdl is accessible and can be used to generate a java client using wsimport. I've recently been given a RESTful end point which uses XML as the payload type. So far as I can see there is no WADL\ Swagger YML file I can access to get a definition of the service.
All I know so far is:
1. The endpoint
2. It operates behind HTTP basic auth
3. It accepts a POST
4. The 3 test XML payloads I have all seem to "work" returning an XML response relating to what I am trying to do
5. The URI does not change depending on the the action I am perform, the service reacts differently based on varying XML input (the request contains a payload-id attribute which seems to indicate the type of operation being performed)
From the above the service doesn't seem very "REST-like" it could just be a process listening on port for a specific request and doing crude string manipulations to parse values and then use string concatenations to crudely build a response. I get that for the most part REST is just that at a low level but I am hoping to somehow manage the apparent crudeness of the service a bit better.
How I can generate a "clean" Java client for this service (something akin to what can be done with wsimport) given that I have the XML sample requests for the 3 different operations that appear to be exposed?
For the above I was thinking that I'd somehow need to create the WADL\ Swagger YML myself, or perhaps there is a tool which could use the requests I have to build these definitions dynamically?
We eventually went for using the Feign which is a Java to HTTP client binder. It's Netflix OSS but seems to be an older library (osslifecycle=archived).
Wrapping the HTTP service was extremely easy as it only has one URI which we POST an XML payload to. We received XSD's from the service owner which we have converted into JAXB object which are then marshaled and un-marshaled within the Feign call. Feign has a concept of encoders and decoders which you can use to write your own mappers or use a provided mapper (JAXBEncoder\ JAXBDecoder).

Using webservices with javax.ws or javax.jws

I'm starting to choose a way to create my webservice, so i found 2 ways to do it:
1) Using the package javax.jws, with annotation #WebService:
#WebService(...)
public class MyServiceImpl {
2) The other way is using javax.ws, with annotation #Path:
#Path("/MyService")
public class MyServiceImpl
In my understand using the second solution is more simple, because when i need to create the Client i just need make a HTTP call (GET/POST). Using the first solution i need create a WSDL client, more complex solution.
So, I would like to know which is the advantage in use FIRST SOLUTION.
The SOAP/WSDL style is useful when a formal contract must be established to describe the interface that the web service offers.The Web Services Description Language (WSDL) describes the details such as messages, operations, bindings, and location of the web service.
Also the SOAP/WSDL style is useful when the application architecture needs to handle asynchronous processing and invocation (e.g. using JAX-WS the assynchronous clients can be created).
The disadvantages of SOAP/WSDL style are
its complexity: tools are required to create a client
heavier on Bandwidth : SOAP requires a heavy XML wrapper arround each request or response
complicated security rules
The advantages of REST style are
simplicity: REST client can be accessed from any browser (however, this is only true for GET method. Data creation request requires also the XML wrapper).
lighter on Bandwidth : data on the wire are usually bare xml elements (not wrapped within the <Envelope><Body> tags).
REST application security rules can be setup using the http standards: the administrator (or firewall) can discern the intent of each message by analyzing the HTTP command used in the request.
For example, a GET request can always be considered safe because it can't, by definition, modify any data.
The disadvantage of REST style is that it still doesn't cover all business requirements
There is no common standard accepted yet for the formal REST service description
REST requests (especially GET method) are not suitable for large amount of data
REST doesn't cover all web services standards, like Transactions, Security, Addressing, Trust, Coordination,

How to stub wsdl service endpoints?

I want to run some integration tests on a WSDL client application. Therefore I'd like to have the WSDL server (which is not in control of me) to response with the same xml response always.
How could I achieve this? Is there any tool out that offers a wsdl endpoint an can always return the same xml (which I then could take from my live logs)?
SOAPUI offers this functionality. I've used it before with ease.
Alternatively if you do not want to go through the hassle of converting the WSDL request to a meaningful response, take a look at services like mocky which simply echo back a payload.
Take a look at Soap-UI - it has the ability to mock web services exactly as you mentioned using just a wsdl. You can then decide which XML the mocked web service will return, and it will run as a server locally. Instead of pointing to the 'real' server you can then point to your own local endpoint in order to retreive the same response. More information available on my blog here

How REST is "lightweight"?

I have been seeing SOAP is "Heavy Weight" and REST is "Light Weight". On what parameters, we are telling REST is lightweight than SOAP?
We were using IFW model web services in our company earlier. But our management told us to develop all the new APIs going forward in REST. We are backend service providers in my company.
How REST is best useful for us?
What does "lightweight" means in context?
This question seems like repetition but don't understand the terms used.
REST gives you a session less window into a system. It does not track you, it does not care about you. All you have done is send a request which contains..hopefully some id to verify that you can make it. It may return a HTTP status code, it may return some body but ultimately, once the request is complete you are forgotten.
SOAP is heavy in a sense that it describes a "contract" between the remote system and your client. In order for your client to communicate effectively it MUST implement its schema...this is the SOAP skeleton. It describes the calls you can make and the objects you can expect back.
The reason why SOAP is heavy is because of serialization. Upon each SOAP request you typically serialize a java object, send it over HTTP and get a serialized response which is deserialized into an object via reflection...this is heavy. It also means that if the endpoint changes how they work, you must change your contract. You don't have to do this with REST.
With SOAP you run into multi threaded issues.
To answer quickly..
they might mean that a REST service is "lightweight" because you do not need to release changes to clients. You simply make changes to your logic, retaining URLS and the response should remain the same.
With SOAP...if you added a new field to an object, you would have to get the client to implement the new schema. SOAP is pretty old had.
REST is lightweight in that it and relies upon the HTTP standard to do its work. It is great to get a useful web service up and running quickly. If you don't need a strict API definition, this is the way to go. Most web services fall into this category. You can version your API so that updates to the API do not break it for people using old versions(as long as they specify a version). REST essentially requires HTTP and is format-agnostic, so you can use XML, JSON, HTML etc).
But the SOAP will wrap the structure into a SOAP envelope (follows an XML standard). The complexity of the SOAP envelope is based on the used message version and additional Web Service protocols. SOAP is generally transport-agnostic, meaning you don't necessarily need to use HTTP.
It can be pointed out that SOAP was designed for a distributed computing environment whereas REST was designed for a point-to-point environment.
I wonder if it is OK to say that while SOAP gives more security, REST-based API s will be easier on the resources and more scalable? As an example, Twitter, Facebook, Google Drive, Blogger, etc all have REST-based APIs that clients can consume.
Generally REST reduces the size and scope of request payloads by mapping request semantics to the underlying HTTP protocol. For example, SOAP will usually add an envelope (of varying complexity) which utilizes a WSDL (a contract) for both request and response types and service mappings. REST will just use POST, GET, etc to a URL with some HTTP encoded parameters and thus lacks an enforced contract.
There are several aspects of lightweight. SOAP is XML only, while REST allows you to send any payload, such as JSON which is less verbose and simpler than XML. Generally speaking, it takes less memory and less bandwidth to deal with JSON than XML.
On another level, using SOAP you typically describe everything as services. So, you need to define a message schema/structure for each verb and noun i.e. "CreateOrder". In REST, you use the predefined HTTP methods such as POST and put the noun/"resource" in the URI which uses already existing constructs on the HTTP level - not reinventing them in XML.
Then there is the effort it takes to adapt to change. A small change in SOAP requires you to redefine the schema, redefine the wsdl and handle versions. In rest, in the best of worlds, there is a degree of dynamic coded into the API (links to referenced resources, among other things), so that some changes can be implemented and takes effect directly.
All the heavy weight strictness of SOAP of course has a valid reason for existence. It's less likely two implementations have different interpretations of the API, than in a loosely defined REST API. SOAP also allows you to implement skeleton code in various languages based on a WSDL. In some complex scenarios, this is actually almost the only productive way to work with SOAP. Marshalling and unmarshalling between objects and serialized XML is rather heavy and adds to the heavyness of SOAP.

Consuming Spring (SOAP) web service in a java servlet

Is there any way to consume a SOAP based Spring web service without generating stubs on the client (as suggested by umpteen threads pointing to JAX-WS)?
Here is my complete scenario:
I have 2 web applications, say APP1 & APP2, both of which have Spring support. APP2 exposes it's APIs as Spring-WS that accept POJOs (Reqeust and Response objects) via. SOAP. Now, I want to call these web services from APP1, but would like to avoid having to create stubs using the WSDL frmo APP2. Is this possible?
For more detail, here is one of my web service's operation:
#PayloadRoot(localPart = "CreateNewRequest", namespace = "myNameSpace")
public CreateNewReqResponse createNewRequest( CreateNewReqRequest requestObj ) throws Exception
{
NewCase newCase = this.localSpringService.createNewCase( requestObj.getParam1(), requestObj.getParam2() );
CreateNewReqResponse response = this.objectFactory.createCreateNewReqResponse();
CreateNewReqResponseObject responseObject = this.objectFactory
.createCreateNewReqResponseObject();
if( null != newCase )
{
responseObject.setParam1( newCase.getParam1() );
responseObject.setParam2( newCase.setParam2() );
}
responseObject.setCaseRequestedDate( caseRequestedDate );
}
response.setResponseObject( responseObject );
return response;
}
Now, as you can see, the web service method accepts CreateNewReqRequest and returns CreateNewReqResponse. What I am trying to figure out is how can I call this web service from APP1, which does not have any clue about these classes - CreateNewReqRequest and CreateNewReqResponse? Is there no other way other than creating stubs in APP1 (from the WSDL) using JAX-WS?
Both the applications in question are our own (that is we have developed them) but run on different servers, because of which APP1 can not call the web service directly - cross-domain policy. Hence, I will writing a servlet in APP1 which will consume the web service exposed by APP2.
At the end of they day SOAP is simple a protocol on top of HTTP. So if you wish to forgo the usage of JAX-WS, you could start using raw http connections and hand code the SOAP requests and manually parse the SOAP Response on your own. This would simply mean you are re - inventing the wheel which is JAX-WS Client stubs.
So If you absolutely want to avoid Stub creation, have a go it at with HTTP post and get Messages at the WSDL end point URL.
What the client Stub does is simply abstract out that implementation for you. i.e. you will not have to deal with nitty gritty of SOAP/WSDL and http connection, you would be dealing with SOAP at a higher level, i.e through Java Objects.
You could also look into other libraries such as Apache CXF or Axis, but even there you will have to generate client stubs.
Thus the question you want to ask is, Do you want to really go in and manually muck around with http connections and SOAP XMLs or let the a framework take do that grunt work for you.
Reply to Nitin's comment follows below
To answer your questions, 1. Yes you will have to re-create the stubs if the WSDL changes, if you are not using the stubs but parsing everything manually you will have to change that code. So effectively there is no difference between the two. Your program will have to change if the WSDL (i.e. the contract between client and service) changes. This would be same even for REST, i.e. if the contract published by the service changes(Maybe the parameters, or the action etc), you will have to Change your client code. There is no escaping that. Hopefully, the public Webservices would have been designed in such a way to allow future modification, and such modifications wouldn't happen overnight thus giving you enough time to modify your code. This issue has nothing to do with how the web service has been implemented i.e. Spring Web Service has nothing to do with.
You seem to be missing the point of the Client stubs that a SOAP framework like JAX-WS, Axis, CXF generate for you. The Client Stub is one way to talk to the Web service. It is not the only way. The Client stub is the preferred method, because it abstracts outout the nitty gritties of handling SOAP calls manually. So, rather then you re inventing the wheel and implementing a SOAP(XML) parsing library, you can concentrate your efforts on the actual application that you are writing. In your actual program you would only have to deal with POJOs and never have to worry about how the SOAP magic happens i.e. how to convert your data and package it up in a SOAP message, send that SOAP Message to the Service using a HTTP connection, handle the response, Parse the response SOAP Message and retrieve the data you care about. All of this you avoid by using the POJOs. You set the properties for request, make a method call to the client stub service method, and recieve an object, everything else is you don't have to worry about (ideally).
I hope this clear things up a bit.
Take a look at WebServiceTemplate class.

Categories

Resources