Create REST Services using Java in Eclipse - java

I have been looking for a few days at tutorials on this subject but either they aren't exactly what i'm looking for or I cant get them to work. I cant imagine that more people aren't confused on the subject so I will ask here.
What I would like to create is a REST service in Eclipse that I can run on my web server and "connect to" using ajax from a separate dynamic web project. All i'm looking for here at the moment is a simple hello world example of a service returning ajax working alongside a separate web project that consumes the JSON it returns.
Im hoping to get a usable user guide (or at least links to one) that will help me out and future people looking for this same thing.
I have gotten as far as this simple class (i have included Jersey Jars but I dont understand what to do from here):
public class UserRestService {
private static final Logger log = Logger.getLogger(UserRestService.class.getName());
private CreateUserService createUser;
#POST
#Path("/CreateUser/{name}/{age}")
#Consumes("text/html")
public User createUser(#PathParam("name") String name, #PathParam("age") Integer age) {
return createUser.createUser(name, age);
}
}
How do i get this class to be an accessible api service on my tomcat server? How do I setup another web project to consume it (I understand how to make an ajax call this is more a question of how do i setup the projects)? Where do servlets come in ?

Rather than copying jars, it would be better to use maven or gradle for package management. A simple pom.xml (maven) with the dependencies can help you abstract determining the compile and runtime dependencies.

Okay so the Java standard is jaxrs (https://jax-rs-spec.java.net/). You can use Jersey which is the rest implementation of jaxrs (https://jersey.java.net/).
A sample of implementing a service using eclipse, jersey and tomcat can be found here: http://www.vogella.com/articles/REST/article.html
If you are feeling like an adventure you can look at vertx.io (http://vertx.io) and my beta release of jaxrs 2.0 framework for vertx called 'vest' (https://github.com/kevinbayes/vest)
Addition:
Jersey provides examples on github of how to implement services at https://github.com/jersey/jersey/tree/master/examples

Related

Java service using Jersey won't deploy to Jboss

I'm trying to build a Java service that other services could call.
This service is not a WS, but is calling a RestfulWS.
I'm really just building a wrapper around this call. This would find the correct data it needs, set up the JSON for the call. Get a response and send it back up.
Was told to use Jersey for this. Trying to set up all the pom.xml to use Jersey.
Building code works fine, it is when the deploy to the server happens that things fail.
I get the error -- "JBAS011232: Only one JAX-RS Application Class allowed. "
I don't have a web.xml, which I guess is used to skip some ResetEasy files.
I do have exclusions in pom.xml and jboss-deployment-structure.xml.
I still get the error when deploy happens. Not really sure what else to check.
It looks like you have a problem with JAX-RS dependencies. JBoss already has its own implementation of JAX-RS and probably that’s causing the issue. Some solutions are already suggested here Jboss error: Only one JAX-RS Application Class allowed

Java Decorate Functions

I am new to Java so apologies if this is a simple thing. I have built decorators in Python for authorizing RESTFul endpoints in Flask and have just built my first Java Webserver but am unable to figure out how to create a similar decorator in Java.
I want to do some pre-checks before running the method (i.e. is the user allowed to access this route). Ideally this would be a decorator like #authorize that, if authorized, will execute the method, but if unauthorized then it would through a 403 error instead.
#Path("/")
public final class HelloWorld {
#GET
#Path("/hello")
#authorize // How would I implement this?
public String sayHelloWorld() {
return "Hello World!";
}
}
EDIT: I am using Grizzly as the web Framework and I will be using an external Policy Management System (Apache Ranger) for managing authorization.
First of all: defining such custom annotations is exactly how you can approach such things in Java. The JAX-RS specification provides all the things you need for such kind of method binding.
The thing that is slightly more complicated: how to nicely do that for the framework that you are using.
With JAX-RS and Jersey for example, creating your own annotations is well documented. And Jersey might be a good starting point, as that is simply a straight forward way to get JAX-RS working.
So, first you start by learning how to use Jersey in general, for example from vogella. Next: you can start to add your custom annotations, see here for an example.
There is even an existing question about using custom annotations for access validation.

Calling a REST service using business central and JBPM

We're trying to do a POC showing we can call an external REST service using JBPM in business-central.
We've created a new BPM, then added a REST service task. We notice at this point that a WID file is created that has REST definition. Inside the WID file, it defines things like URL, Method, and authentication.
We've sifted through all the 7.2 docs, but for the life of us, we cannot figure out how to actually set those parameters and do something useful. Does anyone have a simple "Hello World" using business central 7.2 calling out to an external process?
We see there's a predefinied REST handler: https://github.com/kiegroup/jbpm/blob/master/jbpm-workitems/jbpm-workitems-rest/src/main/java/org/jbpm/process/workitem/rest/RESTWorkItemHandler.java
We're lacking how to assemble all of this; we can't find documentation or examples on something that seems so simple.
Thank you!
If you're using Busines Central, you can edit the process model and check the data assignments for the specific REST node. In there you can set the values of the variables or use some process variable to map dynamic values. Hope it helps.

Generate Wsdl/Client Stubs For Web Service

I have been doing some reading up on web services programming with Java, Eclipse, etc. and I found one particular example where the person created the web service and client by doing the following:
define the web service java class (interface + impl)
deploy the web service using Endpoint.publish
grab the wsdl from the url of the web service (eg, localhost://greeting?wsdl)
use wsimport to generate stubs
create a client class using generated stubs
Is there another way to generate the wsdl without having to publish the web service and download it? Perhaps a maven plugin to auto-generate wsdl and client stubs?
Update: Rather than creating a new question I am just going to piggyback on this one.
I have created my web service by defining an interface:
#WebService
public interface HelloWorldWs {
#WebMethod
public String sayHello(String name);
}
and an impl class:
#WebService(endpointInterface = "com.me.helloworldws.HelloWorldWs")
public class HelloWorldWsImpl implements HelloWorldWs {
#Override
#WebMethod
public String sayHello(String name) {
return "Hello World Ws, " + name;
}
}
When I run wsgen I get the following error:
The #javax.jws.WebMethod annotation cannot be used in with #javax.jws.WebService.endpointInterface element.
Eclipse seems to be okay with it.
Any idea why?
Note, I originally did not have the annotation but when I tried to call my webservice I got the following error:
com.me.helloworldws.HelloWorldWsImpl is not an interface
The JSR 224 says in 3.1 section:
An SEI is a Java interface that meets all of the following criteria:
Any of its methods MAY carry a javax.jws.WebMethod annotation (see 7.11.2).
javax.jws.WebMethod if used, MUST NOT have the exclude element set to true.
If the implementation class include the javax.jws.WebMethod, then you cant put #WebMethod(exclude=true) and that in not possible, according to specification.
Depends of custom version of Eclipse, shows a warning for this. e.g. Rational Application Developer for Websphere shows:
JSR-181, 3.1: WebMethod cannot be used with the endpointInterface
property of WebService
While programming/building a project (with some advanced IDE) normally you should be able to find it between auto-generated stuff - the IDE should generate it. Just check carefully.

Grails and consume SOAP webservice

Being fairly new to Grails i was wondering what people use to consume a webservice in Grails projects. So the client side of the system? Any recommendations? I see people using GroovyWS, Spring-WS etc.. What is a good and easy on to use?
GroovyWS is very easy to use and has great documentation I would definitely recommend it.
Using Grails CXF plugin here. Needed:
classloader workaround - DynamicClientFactoryit changed a current classloader;
and to code WS invocations by hand.
Besides that, the consumer code is pretty slim.
Edit: sorry, no more then this, and I'm not sure I'm not breaking and NDA yet:
#1:
def arrayOfLong = objectFactory.createArrayOfLong(XXX, ids)
result = client.invoke(methodName, arrayOfLong as Object[])
#2:
def dcf = DynamicClientFactory.newInstance()
def classLoader = Thread.currentThread().getContextClassLoader()
// create a WS client
// and assign end point address to it
def client = dcf.createClient(WSDL_URL, classLoader)
client.conduit.target.address.setValue(endpointUrl)
// reacquire classloader because 'createClient' changes it
def changedClassLoader = Thread.currentThread().getContextClassLoader()
def objectFactory = changedClassLoader.
loadClass(FACTORY_CLASS_NAME).newInstance()
Using Grails 1.3.7 I am consuming my own web service with WS-Client Grails plugin. It is actually based on GroovyWS, which in turn uses CXF. It is very easy to use at least in my simple scenario, where I only get Strings from the backend web service. I have no idea how it works with complex data types yet though.
I had never consumed or created a webservice before but using that plugin in the frontend and the Grails CXF plugin in the backend I got a SOAP discussion between my grails apps in two days. You don't really need to use CXF or GroovyWS directly with the very nice ws-client plugin. Speed (of development) and simplicity.

Categories