I am creating a web service. I want to know how do I declare parameter type and use it
as Java type is different for eg. date. I have written client to consume web services in Java which is working fine, but I want to know whether I can consume same web services using client written in some other language. I am giving you a code example of my web service:
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.Endpoint;
#WebService
public class WiseQuoteServer {
#SOAPBinding(style = Style.RPC)
public String getQuote(String category) {
if (category.equals("fun")) {
return "5 is a sufficient approximation of infinity.";
}
if (category.equals("work")) {
return "Remember to enjoy life, even during difficult situatons.";
} else {
return "Becoming a master is relatively easily. Do something well and then continue to do it for the next 20 years";
}
}
public static void main(String[] args) {
WiseQuoteServer server = new WiseQuoteServer();
Endpoint endpoint = Endpoint.publish(
"http://localhost:9191/wisequotes", server);
}
}
Jigar is correct. JAX-WS uses JAXB to convert parameters into XML. JAXB has an extensive set of annotations that you can use to customize how the data is turned into XML. Since the data is sent as XML almost any language can read/write to the service. Furthermore, most languages have some kind of SOAP library available.
Related
I am totally new to the whole Google Cloud Endpoint/Google App Engine world. If you have gone through the Hello World example that Google provides(and you probably have), you might remember that there are 2 classes that are auto-generated for you: MyBean and MyEndpoint.
These are something like this:
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}
And,
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.DJ.example.com",
ownerName = "backend.myapplication.DJ.example.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
response.setData("Hi, " + name);
return response;
}
}
Now, I examined the code in index.html(which gets opened on deploying the backend). I found the following call in the javascript:
gapi.client.myApi.sayHi({'name': name}).execute(
Now, I can see that myApi is the name through annotation and sayHi() is the corresponding method, What I don't understand is the concept of exposing an API and annotation is aiding in that. There isn't any information about exposing APIs.
Could anyone help me understand this?
I think your question can be divided in 3 parts:
1/ What is exposing an API?
Basically, you are offering an access to your business logic through an Interface (the API), with full control on what you want to show or not. This Stack Exchange answer is a great explanation: https://softwareengineering.stackexchange.com/questions/203844/what-does-it-mean-to-expose-something
2/ What are these annotations in the auto-generated endpoints class?
If I can summarize it like that, Google endpoint is a "framework" which generates "default" APIs based on your java beans. By default you get CRUD operations in the API, but you can modify and/or enrich the endpoint to offer more complex business logic. The Endpoints classes that are generated include specific annotations that are used by the framework (in particular while generating a corresponding servlet) and define the URI you will call to interact with the methods of the APIs. See https://cloud.google.com/appengine/docs/java/endpoints/
3/ What is this gapi.client call?
gapi stands for Google API Client Library. It is the library that is offered by Google to interact with Endpoints from a web browser. See https://developers.google.com/api-client-library/javascript/
You could use other methods to call the Endpoint APIs, like jquery Ajax methods (http://api.jquery.com/jquery.ajax/), since Endpoints follow the REST architectural style. Note that you can call your endpoints from other "clients" than a web browser, e.g. an Android or iOS App. In these cases, you would not use the Google API Client Library but some other libraries.
I hope this clarifies a bit. Do not hesitate to ask for more details.
I am trying to access web services that are defined in WSDL by giving the url of the WSDL. The specific case I am working on is the ebay "FindingService".
After parsing the WSDL, I search for the service I am looking for (for example "FindingService"). Next, I want to be able to use that service (send keywords and get results) through some sort of client. I looked around and found the following code that I tried to modify to use it for my example. Since I am still new to WSDL, I am not sure of how to adapt it and I keep getting the error: Undefined port type: {http://WSDL/}face
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class client{
public static void main(String[] args) throws Exception {
URL url = new URL("http://developer.ebay.com/webservices/finding/latest/findingservice.wsdl");
//1st argument service URI, refer to wsdl document above
//2nd argument is service name, refer to wsdl document above
QName qname = new QName("http://www.ebay.com/marketplace/search/v1/services", "FindingService");
Service service = Service.create(url, qname);
face hello = service.getPort(face.class);
System.out.println(hello.getHelloWorldAsString("test"));
}
}
the second class is:
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
#WebService
#SOAPBinding(style = Style.RPC)
public interface face{
#WebMethod String getHelloWorldAsString(String name);
}
the third class is:
import javax.jws.WebService;
//Service Implementation
#WebService(endpointInterface = "face")
public class endp implements face{
#Override
public String getHelloWorldAsString(String name) {
return "Hello World JAX-WS " + name;
}
}
I'd be thankful if I can get some guidance. Is it possible to access services like that or do I have to use the ebay API (with keys etc..) ?
WSDL is just a contract between the client and the server.
The best solution is not parse the WSDL in runtime and try to call the actions. You probably want to call these actions to do something useful. Ex: find all user Ebay orders.
Each of these actions can have complex inputs and outputs. The best solution to work with SOAP webservices in Java is usually generate code based in the WSDL, so you will have a full working client without too much work.
I can recommend these APIs:
JAX-WS:
http://www.mkyong.com/webservices/jax-ws/jax-ws-wsimport-tool-example/
Spring-WS:
https://spring.io/guides/gs/consuming-web-service/
Axis 2:
https://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html
I have the task of creating a web service that takes requests from multiple clients. I am new to web services so i used this tutorial:
http://www.java-forums.org/blogs/web-service/1145-how-create-java-web-service.html
This is exactly what i am looking for. A web service with no java ee.
It is preferable that is stick with java se, it's a policy that is prefered to be kept.
Now i would like to go one step further and implement the service so that it processes requests from multiple clients that operate on a shared resource.
Ideally i would like something like this:
Client client = new Client();
client.processRequest(string);
And the web service will process the requests in the order they arrive. The requests will come in as an request is processed so it will be kept in a stack.
The problem is i just on't know how to send the response back to the specific client. The response will be a string. The only thing i came up with, at least in principle, is to send a object that remembers where it came from but that just seems the web services job.
I have searched the internet but did not find a solution.
If possible using only SE please help.
If you think it is not possible without EE you can say so, but i would very much like an answer using only SE
I think what you are trying to implement is an Asynchronous Webservice. The following link tells you how to implement it in Java SE.
http://java.dzone.com/articles/asynchronous-java-se-web
You can do this using the Endpoint.publish methods in Java SE. First, you create a simple "endpoint interface":
package com.example;
import javax.jws.WebService;
#WebService
public interface ExampleService {
String getDateTime();
}
Then you specify that interface in an implementation class. As you can see, both classes must be annotated with #WebService.
package com.example;
import java.io.IOException;
import java.net.URL;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import javax.xml.ws.Service;
import javax.xml.namespace.QName;
#WebService(endpointInterface = "com.example.ExampleService",
serviceName = "ExampleService",
portName = "timeService",
targetNamespace = "http://example.com/time")
public class ExampleServiceImpl
implements ExampleService {
public String getDateTime() {
return String.format("%tc", System.currentTimeMillis());
}
public static void main(String[] args)
throws IOException {
// Create server
Endpoint endpoint =
Endpoint.publish("http://localhost:8080/example",
new ExampleServiceImpl());
URL wsdl = new URL("http://localhost:8080/example?wsdl");
// Create client
Service service = Service.create(wsdl,
new QName("http://example.com/time", "ExampleService"));
ExampleService e = service.getPort(ExampleService.class);
// Test it out
System.out.println(e.getDateTime());
endpoint.stop();
}
}
By default, JAX-WS will treat all public methods of an endpoint interface as web methods (since that is commonly what developers will want). You can have more control by placing the #WebMethod annotation on only the methods you want exposed as web services.
See the JAX-WS specification for all the details.
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 gradually piecing together how I can receive a serialized object within Spring and have gotten a web service working, by following a tutorial, that uses Jax-WS. I have verified that I can access this basic service through a browser by pulling up the XML page using a url like http://localhost:8080/WebServicesExample/hello?wsdl
The code I currently have is like below, however I want to make a service so that a serialized object can be passed in, for example a HashMap and then have spring de-serialize it, etc. I have been doing a lot of reading on this but am still a bit lost, I would appreciate if anyone can offer advice how to get from where I am at currently to what I am trying to do. Thanks
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.mkyong.bo.HelloWorldBo;
#WebService
public class HelloWorldWS{
//DI via Spring
HelloWorldBo helloWorldBo;
#WebMethod(exclude=true)
public void setHelloWorldBo(HelloWorldBo helloWorldBo) {
this.helloWorldBo = helloWorldBo;
}
#WebMethod(operationName="getHelloWorld")
public String getHelloWorld() {
return helloWorldBo.getHelloWorld();
}
}
I am not completely sure which WS stack you have used for exposing this service, assuming that you just want to create a JAX-WS based sample, let me point you to a working sample that I had created earlier available at : git://github.com/bijukunjummen/memberservice-codefirst.git .
This sample uses Apache CXF as the JAX-WS implementation, and uses JAXB2 for binding (converting the incoming xml to Java objects and back)
In your example, Apache CXF would allow you to expose a WS interface using an entry into spring configuration files of the type:
<jaxws:endpoint address="/helloworldservice" id="helloworld" implementor="#helloworldBean" >
</jaxws:endpoint>