The "proper" way to implement a REST API service using JBoss AS - rest

I started a new job in a company that loves using the word, "enterprise." As such, everything they've written is in Java. I come from a very web-development heavy background, mainly working with LAMP stacks.
Now, up until three days ago I knew nothing about Java other than people used it and that it is a programming language. Googling up on it, the Java language itself seems simple enough. However, when people say, "Java" it seems they are referring to more than just the language, such as the various frameworks and application servers. It's a little over-the-top, and am having some trouble getting up to speed with "Java."
An upcoming project involves me creating an exposed REST API for one of the products. Seems easy enough. However, I have some questions about how to proceed....
I'm working with JBoss AS for the first time; not sure if there's an equivalent in PHP so I can understand what JBoss does exactly, but I suspect there's a "proper" way of doing things. Here's what I was thinking of doing:
1) Created a package with a single servlet, like so:
package com.awesome.myrestapi;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HiggiltyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HiggiltyServlet() {
super();
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
// #todo ideally, do something more RESTfully useful and less vindictive
out.println( "<html><body>HAHA! all ur api requests are belong to us</body></html>" );
out.close();
}
}
2) As you can see, I was thinking of just overriding the service method to serve my REST API requests.
3) Updated my web.xml file accordingly, so that the url-pattern would match "higgilty", thus making my URL endpoint something like....
http://localhost/awesomeproject/higgilty
Now, I feel like I might be doing something wrong. Am I going about this the right way, or am I totally off the mark?
Any help is greatly appreciated.

You should probably use a REST-oriented framework like Restlet, Jersey or RESTeasy. This will help you deal with various things like splitting URIs, having a system based on resources and representations and perhaps content-type negotiation (if you need it).
Restlets can run within a servlet container or as standalone applications. RESTeasy is a JBoss project, but I wouldn't dismiss the other frameworks just because of that, since JBoss AS should in principle be able to run applications written with the other frameworks (I've run Restlet applications within JBoss AS successfully,, although I don't use it regularly).

Agreed it's probably best to use a framework.
If you want to roll your own, you need to write something to parse the URL and route to the appropriate method. The URL pattern matching you get with web.xml is pretty limited.
Also you'd probably want to override the HttpServlet methods that correspond to HTTP methods - doGet, doPost, etc.

Related

What is the difference between org.apache.http.HttpRequest and javax.servlet.http.HttpServletRequest?

My research so far says that javax.servlet.http.HttpServletRequest is the interface to calling regular Java Servlets while org.apache.http.HttpRequest is typically used to implement RESTful services. I see an example for the same in one of the internally available frameworks in my organization where org.apache.http.HttpRequest is the interface to program RESTful services.
I still feel that org.apache.http.HttpRequest has been made available by Apache to facilitate RESTful implementation since this interface does not have any status code and works with passing entities as responses.
What exactly is the difference between the two interfaces and when one should be used over the other?
HttpServletRequest is a server-side class that is part of the Java EE Servlet APIs. You use it when you are implementing ... a servlet.
In the Java context, HttpRequest could (in theory) be anything ... because it is not a Java SE or EE class. But usually it is a class in the Apache Http Components library. This is typically used for client-side code, though it is also possible to use it server-side too.
(There are HttpRequest classes in non-Java contexts also ...)
What exactly is the difference between the two interfaces and when one should be used over the other?
They are unrelated interfaces. (Or "exactly" unrelated ... if you prefer :-) )
Use HttpServletRequest when you are implementing servlets.
Don't use HttpRequest when you are implementing servlets.
"RESTful" is orthogonal; i.e. you can implement RESTful servers using servlet, and non-RESTful servers without using servlets.
I am still not clear about the basic difference between the two. Why would somebody need a HttpRequest in the first place if HttpServletRequest is already there?
Because that somebody's application may not be using the standard Java EE servlet framework. And if they are not, then it is not "already there".
From this point of view, the basic difference between HttpRequest and HttpServletRequest is that they are part of different frameworks, and you use one or the other depending on which framework you are using.
Why do we have two classes? Because of history. Java EE servlets came first, and were standardized many years ago and are widely used. The Apache HTTP Components library was implemented later to address use-cases that servlets did not address; e.g. where servlets are too heavy-weight.
Oracle can't change Java EE to replace HttpServletRequest with the Apache HttpRequest class because it would break too much customer code.
Apache couldn't have adopted HttpServletRequest in HTTP Components because it has "baggage" that is not appropriate to non-servlet use-cases.
Either way, it is what it is.
Which framework do you choose? How do you choose? Those questions are both off-topic for StackOverflow. (Recommendations, subjective, too broad, etc)
i think the basic difference is Httpservletrequest is part of communication between container and servlet as container creates the object for it and passes it on to servlet,while as Httprequest is part of communication between container and client because container converts Httpservlet respone into Httpresponse and then sends it back to client.

GXT with RestyGWT

I've searched as much as I could but did not find any answers/examples for my question.
I'm completely new to Web UI development but have a decade and a half of experience in Java and other languages. I seem to be completely lost in the sea of available options for the client side, but for the server side I have a Rest server (Play) running already. I can't and don't want to use a complete package for both client and server b/c I want to pass JSON back and forth between the server and the client. This way I can use multiple different clients: web, Excel, Swing, etc. I want to keep it flexible like this.
So far I pretty much decided to use GXT for the client side, and found RestyGWT to be sitting in the middle. This is what causes my problems. So far, I have not been able to find a single example of a GXT + RestyGWT combination. Just a single example (a Grid for example) would be extremely helpful, since I have no experience with J2EE, beans, or any of that.
Any help or examples with GXT + RestyGWT would be greatly appreciated!
What have you tried? RestyGWT is serialization and transport, so ideally you set up a loader that describes what you need based on your widgets (grid? paging toolbar? filters?), and then pass it a DataProxy implementation that knows how to take config objects, and asynchronously send back loaded data objects. Each grid example that loads from the server uses a loader, but a different proxy (and optionally reader) based on whether it us using RPC, RequestFactory or XML/JSON over HTTP. There is also a JSONP example, and while it isn't using the Grid, it is still loading items to a ListStore, so could easily be attached to a grid.
DataProxy is a simple interface - it is given a config object and a callback to invoke when the load is finished or to notify if an error occurred. In your implementation of this interface, call your service with the necessary details of the config, and then invoke the callback when results are ready.
If you want an example of how RestyGWT works you can have a look to
one of my blog article. It is a pure GWT example but should work with GXT as well. GXT is mostly about graphical components for GWT.
In 2 words you need to
1) Define your restServices interfaces
public interface HelloClient extends RestService {
#GET
public void getHellos( MethodCallback<List<Hello>> callback);
}
2) Create your client
HelloClient client = GWT.create(HelloClient.class);
3) Use it
client.getHellos(new MethodCallback<List<Hello>>() {
public void onSuccess(Method method, List<Hello> response) {
//...
}
public void onFailure(Method method, Throwable exception) {
//...
}
});

How do I inject into a Servlet with Dagger?

How do I inject objects into a Servlet using Dagger?
Since the servlet container instantiates the Servlets themselves, they are not created with Dagger. Therefore, the only mechanism I can see to inject into them is via static injections, which the dagger homepage warns against doing. Is there another (best practices) way to do it?
Specifically, I am using Jetty and GWT (my servlets extend RemoteServiceServlet), but I don't think those details matter.
There is not (yet) any stock infrastructure code to support a Java EE servlet stack for Dagger.
That said, there are ways you could home-brew it until we get to it. If you were using it only for singletons, then you could mirror what some people are doing on android, and initialize your graph at app startup using a context listener, then use the Servlet's init() method to self-inject
It gets much trickier when you try to add scoping to requests and such - not impossible, but it requires more scaffolding.
While there is no stock infrastructure for this, I did the following:
I put the ObjectGraph into the ServletContext of the web server. Then, for each Servlet, I can do the following,
#Inject
SomeDependency dependency;
#Inject
SomeOtherDependency otherDependency;
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
((ObjectGraph) filterConfig.getServletContext().getAttribute(DaggerConstants.DAGGER_OBJECT_GRAPH)).inject(this);
}
where I have previously defined the DaggerConstants myself.
There are likely a variety of ways to get the ObjectGraph into the ServletContext, depending on what your application is. We use an embedded jetty server, so we control everything during startup. Not sure how you would do it in a general container, but presuming you instantiate your main ObjecGraph through some init servlet, you would do it there.
servletContext.setAttribute(DaggerConstants.DAGGER_OBJECT_GRAPH, objectGraph);
Note that our application uses a single ObjectGraph for the entire application, which might not be your situation.

Framework Extensibility based on GWT/GIN/GUICE

I hope my question is not to generic.
I created a framework in gwt/gxt which helps developer to create very quick a web application with a set of pre definied widgets.
Now over the days they want to have new functionality which are very related to a specific customer and I found it very difficult to extend my framework. I am using the MVP pattern on client side with GIN and GUICE on server side. The client components which needs to be extended also have related services on the server to load their data.
I already thought about creating new guice modules and over"bind"(dont know if this is the right word) the existing ones but than the developer has to rewrite the complete module or its service.
Does somebody already has some experiences with designing a framework with gwt on client and server side? If yes how can I provide my framework with easy possiblities to extend with customer specific stuff. Maybe there are some nice patterns out there which I could use.
Thanks a lot
If I understand right you question, you can do something similar to this idea I got now.
In your framework, you could provide a module with all your modules, like this:
public class MyAPI {
public static List<Module> MODULES = Arrays.asList(new FooModule(), new BarModule(), new OtherModule());
public static Module getMyAPIModule() {
return new AbstractModule() {
protected void configure() {
for(Module m : MODULES) install(m);
}
}
}
}
Then, in your app, when you create the injector, or in your servlet module, you can do a install(MyAPI.getMyAPIModule()); and it will work

How to bring Spring Roo & GWT together

I am trying to develop a Spring Roo/GWT app with the newest integration of GWT in Roo.
Getting the scaffolding to work is very straightforward, but I don't really understand how the RPC works there.
Can someone of you provide a simple example how to do a simple service to connect client/server within Spring Roo and GWT.
Would be very helpful for a start, as I couldn't find any resource on that.
thx & regards,
Flo
Flo,
Not sure if you are up on google wave at all, but that does seem to be one place to keep apace of the current effort. Specifically this wave is available to the public:
RequestFactory Wave
It covers the details (well emerging details) about the RequestFactory API.
The basic idea is that your domain model objects are needed on the server side and the client side. Using hibernate can cause issues with the class files and people have wound up having two sets of model objects, and using custom GWT-RPC to make server requests and marshall/un-marshall between the client- and server-side model objects. Not an ideal solution. Even if you can use the same model objects, the overhead of the RPC is a drag.
Enter RequestFactory and we see that google engineers are probably getting paid what they are worth. Take a look at the sample code generated from the .roo - specifically ApplicationRequestFactory.java.
package com.springsource.extrack.gwt.request;
import com.google.gwt.requestfactory.shared.RequestFactory;
public interface ApplicationRequestFactory extends RequestFactory {
ReportRequest reportRequest();
ExpenseRequest expenseRequest();
EmployeeRequest employeeRequest();
}
This is an interface that provides request methods for each of the domain objects. There is no implementation of this class defined in the project. It is instantiated in the EntryPoint with a call to GWT.create(...):
final ApplicationRequestFactory requestFactory =
GWT.create(ApplicationRequestFactory.class);
requestFactory.init(eventBus);
Within the com.springsource.extrack.gwt.request package you will see an ApplicationEntityTypesProcessor.java which is cleverly using generics to package the references to the domain classes for use later in the presentation. The rest of that package though are events and handlers for each model object.
Specifically there are four auto-generated classes for each object:
EmployeeRecord.java - This is a DTO for the domain object.
EmployeeRecordChanged.java - This is a RecordChanged event to provide a hook method onEmployeeChanged.
EmployeeChangedHandler.java - This is an interface that will be implemented when specific behaviour for the onEmployeeChanged is needed.
EmployeeRequest.java - This is an interface used by the ApplicationRequestFactory to package up the various access methods for a given object.
Keep in mind there is a lot of code generated behind the scenes to support all this. And from M1 to M2 a lot has been cleaned out of what is visible in a GWT project. I'd expect there to be more changes, but not as drastic as M1 to M2 was.
So finally these events can be used as in the UI package to tie together the domain and the UI. ReportListActivity.java:
public void start(Display display) {
this.registration = eventBus.addHandler(ReportRecordChanged.TYPE, new ReportChangedHandler() {
public void onReportChanged(ReportRecordChanged event) {
update(event.getWriteOperation(), event.getRecord());
}
});
super.start(display);
}
Again I refer you to the wave for more info. Plus the expenses.roo demonstrates how to use Places and has a rather slick Activity framework as well. Happy GWTing.
Regards.
The functionality you are referring to is currently under heavy development (or so the guys at Google want us to believe ;)) so the API and internal workings are not final and will most likely still change before the final release of GWT 2.1 (this was stated a few times during the GWT sessions during Google IO 2010). However, you can browse the Bikeshed sample in the trunk to see a working (hopefully ;)) example. There's also the 2.1 branch that appears to contain the up-to-date (?) sample (and the cookbook that was promised on Google IO).
Personally, I'd wait with switching your code to the new RPC model till the guys working on GWT say it's safe to do so ;) (but it's definitely a good idea to get accustomed with the general idea now - it's not like they will change everything :D).