Writing Webservice clients using HttpURLConnection - web-services

I have a question related to Axis2 Webservices .
I have My Webservice deployed in Tomcat Server .
Right now i am writing a Client for my Webservice using
public static void main(String[] args) {
try {
samples.quickstart.StockQuoteServiceStub stub = new samples.quickstart.StockQuoteServiceStub();
samples.quickstart.StockQuoteServiceStub.GetPrice request = new samples.quickstart.StockQuoteServiceStub.GetPrice();
request.setSymbol("ABCDE");
samples.quickstart.StockQuoteServiceStub.GetPriceResponse response = stub
.getPrice(request);
}
catch (org.apache.axis2.AxisFault e) {
e.printStackTrace();
} catch (java.rmi.RemoteException e) {
e.printStackTrace();
}
}
This works fine.
I have seen from net some clients are written using HttpURLConnection.
Please tell me what is the difference between writing clients by using the former way and the later way.

The way you have done give you a more abstract way. It has generated the code for you and you need only to provide the parameters to pass. Here Axis2 users the commons httpclient as to send message using http transport. As you can see Axis2 handles all the transport specific things for you.
On the other hand you can create the soap message to send from your own and send using an httpClient. But there you need to do a lot of work.

Related

Webservice client generation - stubs vs. Soap messages

I need help with choosing an approach and take certain actions based on that help or advise if I can get it.
I am given a URL to a wsdl
If I generate stubs, I am using the functionality of that webservice
I generate stubbs 3 different ways - (some redundant)
- Eclipse
- Ant commands (creates the same structure as with an eclipse)
- using maven
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
maven creates a slightly different API, but - all workable.
Now, I am given a URL, that I am also generating an API, and able to make a call, however, get an error back - error is system specific. It means, I do have communication with the webservice functionality.
So, the owners of webservice send me the sample code - they are using SOAP Messages to talk to the webservice. And it works fine.
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = null;
SOAPConnection soapConnection = null;
soapConnectionFactory = SOAPConnectionFactory.newInstance();
soapConnection = soapConnectionFactory.createConnection();
System.setProperty("https.protocols",
"TLSv1,TLSv1.1,TLSv1.2");
System.setProperty("java.net.useSystemProxies", "true");
String url = "https://someUrl?wsdl";
SOAPMessage soapResponse =
soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
try {
String op = printSOAPResponse(soapResponse);
System.out.println("Res" +op);
} catch (Exception e) {
e.printStackTrace();
}
I know that this is not very reliable and easy way of working with webservices.
So, should I force, the webservice owners to do something, to fix the issue, or is there something I am not adding in my stubs, .. or whatever else can go wrong here ?
What is the general advise you could give ?
Thanks
Disclaimer: This is opinion based answer because of the nature of the question.
should I force, the webservice owners to do something, to fix the issue, or is there something I am not adding in my stubs, .. or whatever else can go wrong here
In SOAP, two parties are involved, the server and the client. And then between them there is contract called as WSDL. SO if they have provided you WSDL, you should be able to generated the specific SOAP message that server should be able to understand. Hence, you try solving the client side problem without forcing them. I'm less sure about your actual use case and SOAP services you are trying to consume, but usually service providers(i.e. SOAP Service) stick to protocols and then clients need to adjust in order to consume that specific service unless and otherwise you are too big of client to them and could force them to change their system that may be serving other customers(SOAP clients.).
As an example, if you are using Azure or SAP SOAP service to use specific service, you are bound to make the messages that Azure or SAP could understand(though such big players provide their SDK to deal with such unnecessary headaches).

How to write Spring Interceptor to handle any Web Service exception

I am working on a Web Project which is having few SOAP Web Services that we are developing using CXF 2.7.8(& Spring 3.0.7). I have a requirement to add interceptor which can handle the exception occurred during a method call, extract the root cause and send it to the caller.
We don't have any Controllers in our web project as we don't have UI. The project is hosting few web services only.
I implemented a Spring based interceptor by referring to the sample code/example available on internet. By my interceptor is not being called when I call a webservice method. The same code/interceptor works fine in different web application which has a Controller (and uses Spring MVC flow).
I am not sure why it is not working? Is it because that we don't have Spring MVC based flow and I am trying to use a Spring Interceptor? If yes, then could somebody please suggest as how can I write an interceptor which will be called when some exception occurs. I am using CXF based SOAP web services.
Below is the Interceptor & Spring configuration that I tried:
public class ExceptionHandlerInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOG = Logger
.getLogger(ExceptionHandlerInterceptor.class);
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
LOG.info("Before handling the request");
return super.preHandle(request, response, handler);
}
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
LOG.info("After handling the request");
super.postHandle(request, response, handler, modelAndView);
}
// #SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
LOG.info("After rendering the view");
System.out.println("Exception is-->" + ex);
super.afterCompletion(request, response, handler, ex);
}
}
And this is the Spring configuration:

Accessing WSO2 ESB proxy in java program

I have configured one wsdl proxy for external wsdl in WSO2 esb. Its successfully created proxy. While creating proxy, I have not selected Publish Same Service Contract check box. If we are consuming external web services, is it mandatory to check? When I click on try it, it is not showing operations which are available in wsdl.
If at all the above issues gets solved, we need to access the proxy from our java project. How can we access WSO2 ESB proxy in our java program?
Thanks in advance.
Thanks,
Raghu
Yes you need to check Publish Same Service Contract if you want to publish the same WSDL.
in java code you can write a simple axis2 client like shown below. To the enxpoint of your proxy.
public OMElement sendReceive(OMElement payload, String endPointReference, String operation)
throws AxisFault {
ServiceClient sender;
Options options;
OMElement response = null;
try {
sender = new ServiceClient();
options = new Options();
options.setTo(new EndpointReference(endPointReference));
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
options.setTimeOutInMilliSeconds(45000);
options.setAction("urn:" + operation);
sender.setOptions(options);
response = sender.sendReceive(payload);
} catch (AxisFault axisFault) {
throw new AxisFault("AxisFault while getting response :" + axisFault.getMessage(), axisFault);
}
Assert.assertNotNull(response);
return response;
}
You can get the sample payload by tying a tool like soap UI.
Thank You,
Dharshana.
Try like this:
CentralUuidService service = new CentralUuidService(new URL("http://wls02.tigeritbd.com:8280/services/CentralUuidService?wsdl"),new QName("http://bean.service.uuid.gov.bd/", "CentralUuidService"));
GetBirthPlaceServiceResponse response = service.getCentralUuidServiceHttpSoap11Endpoint().getBirthPlace(request);
if(response != null) {
System.out.println("Operation status is:"+response.isOperationStatus());
}
}

Generated proxy does not throw EndpointNotFound or similar when the web service is not available

I have a WCF web service which is working seamlessly. Now the aim is to generate a Java proxy to access this web service. I have installed the newest Eclipse with the WTP extension and generated the WebClient (proxy, stub, etc.). I made a web service call which succeeded. On the other side, when I shut down the web service, the call succeeded as well. What am I doing wrong, does the proxy not throw an EndpointNotFoundException or RemoteException when the service is not available?
Here is my sample code:
try
{
IRemoteControlProxy rc = new IRemoteControlProxy("http://localhost:666/MyService");
rc.InsertOrUpdate(0, new DtoObj());
}
catch (RemoteException e)
{
System.out.println(e);
}
catch (ServiceException e)
{
System.out.println(e);
}
System.out.println("No exception");
I get only the "No Exception" even though the call must have failed. I checked the default URL in the proxy and there is no web service running at this URL, I double checked the URL with the Internet Explorer. I still don't get any EndpointNotFoundException, why? Do I even instantiate the right object (the one ending with "proxy")?
Notice that if the service is running properly, the communication works seamlessly.
Well, the problem here was that I added the "IsOneWay" attribute to the service method definition. In this case, the generated proxy calls invokeOneWay(), which is basically fire&forget. This method does not throw any exception when the target is not available.
If I remove the "IsOneWay" attribute from the service method definition, the proxy calls invoke() which throw a proper exception when the target is not available.

Passing a MailMessage object to a web service

Can anyone please tell me if it's possible to pass a
System.Web.Mail.MailMessage object to a ASP.NET Web Service? Maybe using XML
Serialization / Deserialization? I've been asked to investigate the
possibility of building a front-end web page which captures MailMessage
properties such To, From Subject, Attachments etc, builds a MailMessage
object, passes the MailMessage object to a web service, the web service then
sends the message via the Smtp.Send method.
Any assistance gratefully received. Thanks!
Certainly this can be done using web services. WCF would make this extremely simple. Just create a new WCF web service and the method would look something like this:
[WebMethod]
public bool ReceiveMailMessage(MailMessage mm)
{
//Send the MM
return true;
}