I had a java project and after lots of research I managed to convert it to a Dynamic Web Project in Eclipse. Now I want to add a new Web Service to it. I have already developed a class. I want to convert it to a standard Web service so I can call it from my silverlight application. Here's my current class:
public class MyWebService
{
#Resource
WebServiceContext context;
#WebMethod
public String ProcessQuery(#WebParam(name="query") String q)
{
MessageContext messageContext = context.getMessageContext();
HttpServletRequest request = (HttpServletRequest) messageContext.get(SOAPMessageContext.SERVLET_REQUEST);
// now you can get anything you want from the request
}
public static void main(String[] args) throws Exception
{
String address = "http://127.0.0.1:8023/_WebServiceDemo";
Endpoint.publish(address, new MyWebService());
new DocumentServer();
System.out.println("Listening: " + address);
}
}
How can I do it in Eclipse? Please post a link to a tutorial or a quick step by step guide. I'm a .Net developer and I'm very new to Java.
Thank you.
PS: So basically I want to publish this service in a standard way rather than calling this main function and using Endpoint.publish() method.
The Eclipse wiki has a tutorial using the Web Tools Platform to do just what you are looking for. It requires WTP and Tomcat, if you don't have those already available to Eclipse. It starts with an unannotated class and finishes with a WSDL and test client. It allows you to view generated SOAP messages.
To create, it instructs you to select the file you want to convert into a web service and run File -> New -> Other... -> Web Services -> Web Service. Then you click Next, move the slider to the Start Service position, and client to Test Client. You select Monitor the Web Service and then click Finish. Then you can play with your Test Client and see your generated WSDL.
Note that the above paragraph is a summary of the tutorial, which you can find in full at the provided link.
Related
I have the following problem: I am completely new to java EE (know only about servlets and JSPs) and especially web services.
I need to develop a client for a web service (it needs to query the service for useful information once in a minute).
In my mind this client would be a simple java-SWing-based program, which would query the web service through simple Socket when the application client runs. How can that be done?
Is it possible to do in that way? If not, which is the easiest way to create such a client?
I would suggest using Apache CXF. Simple and powerful framework.
And yes, that is possible to implement what you said using this framework. Just read tutorials and play around for a bit with it.
Inorder to connect to a web service using a java client follow the below mentioned steps:
1. Get the URL in which the webservice is hosted. This is usually of the fomat http://<IP_OF_SERVER>:<PORT_OF_SERVER>/<WEB_APP_NAME>?wsdl
2. Get the qualified name of the service:
// 1st arg is the service URI
// 2nd is the service name published in the WSDL
QName qname = new QName(<Service_URI>, <SERVICE_NAME_PUBLISHED_WSDL>);<br/>
3. Create a factory for the service:
Service service = Service.create(url, qname);
4. Extract the endpoint interface, the service "port":
<Port_Class_Name> eif = service.getPort(<Port_Class_Name>);
5. Now use the methods on the Port, which are the actual methods in your webservice.
You might want to try REST Webservice, try Jersey REST (or others). With rest you can connect it with http connection (GET and POST).
Inorder to connect to a web service using a java client follow the below mentioned steps:
1.URL wsdlUrl = new URL("your wsdl url);
2.QName qname = new QName("targetNamespace in ur wsdl file","service name in your wsdl file");
Service service = Services.create(wsdlUrl,qname);
4.suppose getData() is your SEI
GetData data = (GetData)service.getPort(GetData.class);
5.call the your methods using data object
ex:data.getId(String name); this will return your response
Am pretty new to web services and have been trying to implement Soap Faults. I used Apache Axis2 to generate webservice in the following manner.
public interface XYZ{
public String myMethod(User[] user)
}
Here I have created a User class with some variables so that I can generate User object at .Net environment to pass User[] of objects.
Public class Webservice implements XYZ
{
Public String myMethod(User[] user){
//My implementation
}
}
Now, I created a dynamic project using Eclipse and with the help of Axis2 plugin I created webservice for my "Webservice" class which generates wsdl file. I deployed the webcontent in the Tomcat folder and able to access the WSDL file in the .Net environment. I am able to pass array of objects (User[]) from .Net to Java and able to do my task. Now, I need to implement Soap Faults in Java which I am not sure how to implement.
Can anyone help me with an example or tutorial ?
Your best bet is to Google for something like "jax-ws faults". For example:
http://www.ibm.com/developerworks/webservices/library/ws-jaxws-faults/index.html
You can also implement an error handler, as discussed under "Using handlers in JAX-WS Web services" here:
http://axis.apache.org/axis2/java/core/docs/jaxws-guide.html#BottomUpService
Most frameworks will trigger a SOAP fault when you throw an Exception in the method implementing your operation. That will not give you much control on the SOAP fault content though.
See here for some details on Axis
Generally, You don't need any specific coding for implementing SOAP fault.. Whenever there is any exception thrown by the method (here myMethod in your example.), axis will automatically generate SOAPFault element in the resulting response. The exception is actually wrapped into AxisFault exception and sent to the client.
See here a i.
I need to create a rest server and client.
I stumbled upon this tutorial which uses sockets. I want to be able to use REST calls, possibly HTTP, because the clients will be actually in different languages.
Instead of using Socket api from java.net.* what should i use ? if i use Socket API can I use c++ and php to communicate with this server? or should i go with REST?
any directions appreciated.
There's a lot of things you can use to create rest services, and then they can be consumed by almost anything. Of particular awesomeness is the ability to hit them in your web browser, just because we're all so familiar with them.
When I need a 'quick and dirty' rest solution, I use Restlet - I won't claim it's the only solution, but it's the easiest I've ever worked with. I've literally said in a meeting "I could have XYZ up in 10 minutes." Someone else in the meeting called me on it, and sure enough, using Restlet I was able to get a functioning REST server running with the (very simple) features I said I would get in the meeting. It was pretty slick.
Here's a barebones server that has one method, returning the current time. Running the server and hitting 127.0.0.1:12345/sample/time will return the current time.
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;
/**
* This Application creates an HTTP server with a singple service
* that tells you the current time.
* #author corsiKa
*/
public class ServerMain extends Application {
/**
* The main method. If you don't know what a main method does, you
* probably are not advanced enough for the rest of this tutorial.
* #param args Command line args, completely ignored.
* #throws Exception when something goes wrong. Yes I'm being lazy here.
*/
public static void main(String...args) throws Exception {
// create the interface to the outside world
final Component component = new Component();
// tell the interface to listen to http:12345
component.getServers().add(Protocol.HTTP, 12345);
// create the application, giving it the component's context
// technically, its child context, which is a protected version of its context
ServerMain server = new ServerMain(component.getContext().createChildContext());
// attach the application to the interface
component.getDefaultHost().attach(server);
// go to town
component.start();
}
// just your everyday chaining constructor
public ServerMain(Context context) {
super(context);
}
/** add hooks to your services - this will get called by the component when
* it attaches the application to the component (I think... or somewhere in there
* it magically gets called... or something...)
*/
public Restlet createRoot() {
// create a router to route the incoming queries
Router router = new Router(getContext().createChildContext());
// attach your resource here
router.attach("/sample/time", CurrentTimeResource.class);
// return the router.
return router;
}
}
And here's the 'current time resource' that it uses:
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* A resource that responds to a get request and returns a StringRepresentaiton
* of the current time in milliseconds from Epoch
* #author corsiKa
*/
public class CurrentTimeResource extends ServerResource {
#Get // add the get annotation so it knows this is for gets
// method is pretty self explanatory
public Representation getTime() {
long now = System.currentTimeMillis();
String nowstr = String.valueOf(now);
Representation result = new StringRepresentation(nowstr);
return result;
}
}
JAX-RS is the API for REST in Java. There are a lot of implementations, but the main ones are Jersey (the reference implementation), Apache's CXF and Restlet.
Usually, you don't create a server. You create a web application and deploy it on the server or servlet container. Some servlet containers are embedable into your web application, e.g. Jetty. Poppular free servlet containers are Tomcat, Glassfish, Jetty, etc.
For Restlet, it is not a servlet container. It is a framework that allow you to create a wep application with RESTful styles. So this should not be confused.
If you decide to use servlet container, then the problem is how you can create a web application with the RESTful styles. REST is not a technology - it is a design principle. It is a concept of how you should create the interface.
The design of REST is stateless so you do not need to store the state of the transaction. All information from a request should be sufficient to produce a respose to client.
There are several servlet framework that allows you to implment the REST styles easily. Some of them are very sophisticated, e.g. Spring framework.
Download JBoss 7. Problem solved.
Heres a restful service:
#Path("/myservice")
public class MyService {
#GET
#Produces(MediaTypes.TEXT_PLAIN)
public String echoMessage(#QueryParam("msg") String msg) {
return "Hello " + msg;
}
}
Create a WAR. Deploy. Open up browser and go http://myserver/myapp/myservice?msg=World. Done!
I would say go with an HTTP based RESTful service. It's rapidly becoming a defacto standard. Check my answer to this similar question for pros and cons.
This is the best one out there. Spring MVC which has lot of REST capabilities in itself. This takes just a single jar file to be included. And you are all set to use all it's capabilities. Even as simple as the below guy explained in JBOSS and much more flexibility as well.
http://java.dzone.com/articles/spring-30-rest-example
I use JBoss 6 with RestEasy. I have created a tutorial located here. I hope this helps you.
You're also welcome to see my very simple example for REST server implementation here.
I've been searching for SOAP client libraries for Java and have found a plethora of libraries based on the idea of building stub and proxy classes based on a WSDL. I'm interested in allowing the user to enter a WSDL at runtime, parsing the WSDL, then allowing the user to perform operations on the Web Service.
Does anyone know of a good SOAP client library which will allow this runtime use? Or is there a way I can use the axis2 wsdl2java functionality to build stubs into the classloader and use them at runtime?
Later than never. :)
You should achieve that in two steps:
1) parse the WSDL informed by the user to retrieve the available operations. Refer to this question to know how to do this in a simple way.
2) Create a dynamic client to send a request using the selected operations. It can be done by using the Dispatch API from Apache CXF.
Build the Dispatch object for the dynamic client (It can be created on the fly by informing web service endpoint, port name, etc):
package com.mycompany.demo;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class Client {
public static void main(String args[]) {
QName serviceName = new QName("http://org.apache.cxf", "stockQuoteReporter");
Service s = Service.create(serviceName);
QName portName = new QName("http://org.apache.cxf", "stockQuoteReporterPort");
Dispatch<DOMSource> dispatch = s.createDispatch(portName,
DOMSource.class,
Service.Mode.PAYLOAD);
...
}
}
Construct the request message (In the example below we are using DOMSource):
// Creating a DOMSource Object for the request
DocumentBuilder db = DocumentBuilderFactory.newDocumentBuilder();
Document requestDoc = db.newDocument();
Element root = requestDoc.createElementNS("http://org.apache.cxf/stockExample", "getStockPrice");
root.setNodeValue("DOW");
DOMSource request = new DOMSource(requestDoc);
Invoke the web service
// Dispatch disp created previously
DOMSource response = dispatch.invoke(request);
Recommendations:
Use ((BindingProvider)dispatch).getRequestContext().put("thread.local.request.context", "true"); if you want to make the Dispatch object thread safe.
Cache the Dispatch object for using later, if it is the case. The process o building the object is not for free.
Other Methods
There are other methods for creating dynamic clients, like using CXF dynamic-clients API. You can read in project's index page:
CXF supports several alternatives to allow an application to
communicate with a service without the SEI and data classes
I haven't tried that myself but should worth giving it a try.
I'm trying to write a simple web service client to interact with my simple web service which only returns a user id that's passed in. So I created a web service client in eclipse and generated a few files for me; wsCall, wsCallBindingStub, wsCallProxy, wsCallService, wsCallServiceLocator. The stub is the conly class I found that has my web service methods in it, because my ws is simple at this stage?
So I want to invoke the call, what do I need to make the call?
I've seen all the examples online have the try-catch for a remote exception or Axis fault, then the classes are instantiated (including a response class, to deserialize?) and make the ws call via the stub class. Is that all I need to call for my case?
wsCallBindingStub stub = new wsCallBindingStub();
String retString = stub.sayHi(1); // 1: my user id
return retString;
Thank you!
Ahh I figured it out, I was getting an error because my wsdl uses the hostname and I needed to specify the ip.. as for the code needed it was pretty much identicle;
wsCall ws = new wsCallServiceLocator().getWsCallPort();
result = ws.sayHi(x);