How to integrate results from RESTful api with JSF? - java

How to pass results from RESTful service to JSF components? I read many postings, but couldn't find a straightforward method. Using RESTful APIs wherever possible is the main requirement for my application. Performance is also a key as thousands of data elements will be processed in a day. If I can't find a solution in JSF, I might have to switch to another technology..
Therefore, I'm asking in case I'm missing something completely from other postings since I'm new. Here are a couple of simple scenarios.
On a JSF page, there is a datatable (Primefaces Checkbox based selection). The datatable displays records available (up to thousands). The datatable needs to be loaded through a RESTful api on the fly. Below is the code for my datatable.
<p:dataTable id="addSampleTable" var="sample" value="#{testBean.sampleDataModel}"
selection="#{testBean.selectedSamples}" >
<p:column selectionMode="multiple" style="width:2%" />
<p:column headerText="Sample">
<h:outputText value="#{sample.name}" />
</p:column>
</p:dataTable>
What's the best way to load the data? Is there a performance concern if every time I have to call the API from the server side (as opposed to client side using jquery and plain html)?
Second scenario, on the same page, there is also a button that allows user to add new record through another RESTful api. In turn, the newly added record should be displayed in the datatable.
After I call the RESTful API to insert a record, the api also returns the record that was created. How can I insert this new record into my datamodel #{testBean.sampleDataModel} so that I don't have to load the entire table again? I suppose I can replace this datatable with plain html and append the new record to the table using jQuery, but then I can't leverage the selection table from JSF.
What are my options?

Your question seems to be too broad, however I try to give some answers.
How to pass results from RESTful service to JSF components?
You can use the pattern implemented by NetBeans' guys. If you use this IDE, there is an option to automatically Build RESTful web services from database. Essentially, this pattern create all DAO basic functionalities in an abstract generic class called AbstractFacade. Then, for each concrete Entity class present in your JPA representation, it creates a Stateless class extending AbstractFacade, and adds jax-rs annotations to it in order to let it expose the Entity class through RESTful web service.
You can then access the service directly by EJB injection. Just use #EJB annotation to inject your service in any container-managed class (in the same application, but also in other applications provided that you use portable JNDI naming rules). In particular, you'll be interested in injecting the facade classes in the managed beans backing your facelets components.
What's the best way to load the data? Is there a performance concern if every time I have to call the API from the server side (as opposed to client side using jquery and plain html)?
Since you need to display thousands of records, your best bet is using Primefaces' lazy loading in your datatable. Your application will then call the db only for retrieving the few tens of records displayed in the current page. Absolutely avoid displaying more than those records, otherwise the client browser will likely be negatively impacted.
How can I insert this new record into my datamodel #{testBean.sampleDataModel} so that I don't have to load the entire table again?
Please distinguish between loading from db and loading in jsf. You can program your backing bean in order to call the db (which is usually the most expensive operation) only when you think it's necessary. As far as I know, both JSF's and PrimeFaces' dataTable implementations don't give you the possibility to manage the table contents at a row level: at every ajax update, the entire table will be reloaded. However, as already said, this won't impact your application's performances as long as you have correctly programmed your backing bean (i.e. choosing the right bean scope and avoid calling the db service in getters).
Useful Links:
NetBeans' tutorial about RESTful web services
Rubinoff's article about the pattern used by Netbeans' RESTful web services
PrimeFaces showCase about lazy loading
How to choose the right bean scope
Why JSF calls getters multiple times

Although this question is a little bit old, it's still a current issue. I'm not happy with the anwsers above because the both technologies mentioned above are together a missmatch.
The most important question here is: Does the given RESTful API actually act as a ...
service/buisness layer or ...
... does it provide CRUD operations only? If it only provides typical CRUD operations, it acts as a persistance layer and there is a need for a service layer.
In the second case, you can implement your service layer in a technology of your choice, JSF backed beans or even EJBs are a good choice. In the Java EE context the JAX-RS specification is a good choice, Jersey is an implementation of this specification. You can use this client API to access the RESTful API from Java: [1]
But...
When you design a complete new application, ensure your RESTful api provides not just CRUD operations but also provide higher leven service layer operations (accessed by https POST method) and deal with security concerns.
In this case heterogeneous systems like webapplications, mobile webapps, native mobile apps and so on can access the service layer directly and the particular view (the REST service consumer) is loosly coupled with the service layer (wich is a good thing in software engineering in general).
My opinion: forget old fashioned server side web frameworks like JSF, Struts and so on, provide a RESTful API with service layer operations and use JavaScript frameworks like AngularJS in order to access the RESTful operations directly... mobile apps are the next step. The complete Java EE technology stack is a little bit rusty ;-)
[1] https://jersey.java.net/documentation/latest/user-guide.html#client

What's the best way to load the data? Is there a performance concern if every time I have to call the API from the server side (as opposed to client side using jquery and plain html)?
Yes, there is a performance concern. The best way is to load your collection once into page context and operate on the list in this context. Then once you have done all your changes you synchronize with the stateless REST service.
How can I insert this new record into my datamodel #{testBean.sampleDataModel} so that I don't have to load the entire table again?I suppose I can replace this datatable with plain html and append the new record to the table using jQuery, but then I can't leverage the selection table from JSF.
No, you don't have to do that! There are several JSF datatable implementations which use AJAX partial submit, the datatable code already includes the logic you describe above. Your collection in page scope is extended with the new element without rerendering the whole list again.

Related

Build OData API without Entity Framework

I have an existing web forms project which consists of 3 different projects: UI layer (Web project), Business Logic Layer and Database Project. I have already written the data access methods which connect to the database and return data to the business logic layer.
Now we need to provide a REST API, and I was thinking of using oData API along with REST. But all the examples I have seen use Entity Framework and I just cannot use Entity Framework because our data access layer returns data to the business layer, which then processes that data and adds some logic, and then present it to the UI layer.
Can I still use oData API? If yes, then will I need to create fresh methods manually for each of the complex query of oData API? How will OData API access my BL Layer?
You can do this (I have just done similar myself) but it is very hard work.
To me, OData always felt like a way of exposing the entity framework through web services so if you were to try and implement it without the entity framework you will end up spending a lot of time parsing queries to your data access layer.
If you do decide to go down this route, maybe consider only implementing part of the OData spec - work out which parts you actually want to be able to use - as it is huge and the task is daunting.
These are only from my experiences though and you may have a better data access layer API setup than I had when I started which could make things significantly easier.
EDIT to answer last question:
Will you need to create fresh methods manually for each of the complex query of oData API? This will really depend on how your data will be exposed and how your data access layer is setup.

Java server side form validation using DTO and hash map

I am developing an app using MVC pattern.
Controllers: servlets
Model: I am following DAO/DTO pattern for accessing database
View: simple JSP EL and JSTL
For accessing database I am using DAO pattern. I want to put validation method and a HashMap for error messages inside the DTO classes for validating FORM data, something similar to Putting validation method and hashmap into DTO.
My question is - this a right approach? If not what is an ideal way for doing this?
As a summary: I want to know real world solutions for server side form validation when we are using DAO/DTO pattern. Please help me.
I believe you need to treat separately the architecture you're implementing and the frameworks you're using to implement the architecture.
Java has a rich set of tools for working on the three standard tiers of your application and choices depend on some factors like expected load and server resources, if you have a two or three users application then it is just a matter of taste.
In terms of DAO/DTO then you have also some options, for example you can build your Data access layer with hibernate and then for your service layer API use DTO's. In this situation you probably want to use a tool for mapping between your domain model and your DTO's (for example jDTO Binder).
Another common approach is to use Spring JDBC Template, there you can go a little bit more crazy and use the same Domain objects as part of the Service layer API.
Finally, the truth is, you can do this by the book or you can do it completely different choice is based on your scenario, taste and experience.

What is the preferred way to use EJBs and Servlets for web applications?

I am trying to familiarize myself with JavaEE. I am a bit confused as to what the purpose of each "component" (for lack of a better word) is: Session Beans and Servlets, and how they properly interact with a web application (client-side JavaScript).
In an attempt to understand this I am building a simple web application. What is the preferred way to use each component to build something similar to the following:
User visits a "Log in" page
User inputs data and clicks submit. I then send an request with AJAX to log in the user.
The server side then validates the user input and "logs" the user in (returns user profile, etc.)
When sending the request, do I send it to a Servlet (which uses an EJB), or to a Session Bean through WSDL? How do I go about maintaining a "state" for that user using either method? I assume with Session Beans it's as simple as annotating it with #Stateful.
Also, I assume the requests sent from the client side must be in SOAP format. How easy is it to use something more lightweight (such as JSON)? While I would prefer to use something lightweight, it's not necessary if SOAP makes development faster/easier.
The Java Enterprise Edition tutorial address pretty much all of the topics you bring up; what's the purpose with the different kind of bean types, how do I implement web services, how do I implement authentication, etc.
I highly recommend you take the time to build the sample application, especially if you're completely new to the Java Enterprise Edition (Java EE). It is important you build up a good understanding of the core concepts because it can be hard to know what to focus on in the beginning due to the breadth and depth of technologies and standards that comprise Java EE.
One thing to keep in mind is that while Java EE certainly tries to support best practice and enable design and development of secure enterprise applications that perform and scale well, it does not prescribe or limit enterprise applications to follow one particular protocol, data format, and enterprise application design pattern. Some protocols and formats are better supported out of the box by the core framework implementations, and some choices are vendor-dependent, but very few specific technology choices are locked into the specification.
To answer some of your specific questions, Java EE has great support for SOAP, but it does not preference nor limit web services to the SOAP protocol. With JAXB and JAX-RS it is just as easy to develop RESTful web services that accept and return XML or JSON, or both. It's up to you to decide whether you need to use SOAP, REST, or another protocol.
It's also your choice whether you want to use frameworks like JAX-RS or explicitly develop Servlets to handle HTTP requests and responses. In many cases, JAX-RS will have everything you need, meaning you'll be able to implement your web services as plain old Java methods with a few annotations without ever having to bother with marshalling and unmarshalling contents and parameters.
Similarly, with JAXB it's up to you whether you want to use WSDL or not. It's great if you have WSDL definitions, but no problem if you don't.
In many cases you will typically maintain state using the Java Persistence Architecture framework (JPA), and access and manipulate such data through stateless session beans. Developers new to Java EE are often tempted to use stateful session beans to maintain state that is better managed in the persistent storage. The tutorial takes you through the different kinds of bean types and their purpose.
Web services (WSDL, SOAP, etc.) are usually used for communications between applications.
Inside a single web app, you usually make simple GET/POST requests, using AJAX or not, and receive either a full HTML page, or a fragment of HTML (AJAX), or XML or JSON data (AJAX). The browser usually talks to a servlet, but it's rare to use servlets directly.
The usual way is to use a framework on top of servlets. The frameworks can be divided in two big categories : action-based frameworks (Stripes, Spring MVC, Struts, etc.) or component-based frameworks (JSF, Wicket, Tapestry, etc.).
In a n-tier application, all of the above technologies are supposed to only contain the presentation layer. This presentation layer talks to a business layer, where the real business logic happens, where transactions are used to access databases, messaging systems, etc. This business layer is where EJBs are used.
You can create basic architecture as follows :
Create EAR instread two different Project like EJB Jar and Web Application WAR
You can create servlets which will call some delegate class which has logic to reffer the EJB
Either by calling it as remote call/ Either by Using #EJB annotation in the Delegation Class.
ServletClass {
do/post(){
DelegateClass d = new DelegateClass();
d.callMethod(withParam);
}
}
DelegateClass {
#EJB
EJBlocalinterface ejbintance;
void callMethod(DefinPrarm){
ejbinstance.callEJBMethod();
}
}
#Statelss
EJBbeanClass implements EJBlocalinterface{
void callEJBmethod(someParam){
}
}

spring mvc dao and service bean mapping

I am new to Spring and hibernate.
I am trying to learn the best practices and design methodoligies in j2ee apps.
I have a managed to create a basic spring mvc web app. now lookin for that
- how should i map my service beans to dao beans or should just use dao beans only.
- Is there any need to make DAO classes singleton
- If i use same dao bean for the jsp, then e.g. onSubmit if I have to enter data on multiple tables (dao beans) then how would I do that.
1 service bean to more than 1 dao beans??
and any refrence material on designing good web app using spring hibernate would appreciated ;)
thanks
You must use service bean. service logic should be there only.
DAO should only for DB related operation.
Now you can inject multiple DAO in your service bean.
FWIW - I just went through a similar learning process on Spring. The good news is, there are a lot of examples out on google; the bad news is, there are not a lot of "complete" examples that are good for rookies (also if you are going to target v3 Spring, there is a lot of pre-v3 stuff out there that can be confusing based on the new baseline). What worked for me was the following: started with the sample applications on the SpringSource site (http://www.springsource.org/documentation). Between their handful of examples, there are just about all the pieces you will need, at least in minimal form. When I found something in those examples that I needed, I googled based on similar terms (some of the # annotations etc) to find more complete information/better examples on that given topic. Many of those searches led me back to this site, which is why I started frequenting here - lots of good questions already answered. I guess this isn't an overly insightful answer, but this process got me up and working through the basics in a fairly quick amount of time.
DAO layer and service layer are different entities:
DAO is responsible for getting and putting single objects from\to DB. For example, get User(id, name, lastname) from DB.
Service layer is responsible for your business logic. It can use several DAO objects for making one action. For example, send message from one user to another and save it in sent folder of first user and in inbox of recipient.
A service is about presenting a facade to the user that exposes business functions that the user can take. Basically, if you have a set of low-level use cases, the methods on the service would line up with individual user actions. Services are transactional, generally if the user does something we want all the consequences of that action to be committed together. The separation between controller and service means we have one place to put webapp-specific functionality, like getting request parameters, doing validation, and choosing where to forward or redirect to, and a separate place to put the business logic, stuff that doesn't depend on webapp apis and is about what objects get updated with what values and get persisted using which data access objects.
I see a lot of cases where people seem to think they need one service for each dao. I think their assumption is that because Data Access Objects and Controllers and Models are fairly mechanical about how they're defined, services must be the same way, and they construct them with no regard for the use cases that are being implemented. What happens is, in addition to having a lot of useless service boilerplate code, all the business logic ends up in the controller jumbled up with the web-specific code, and the controllers become big and unmanageable. If your application is very simple you can get by with this for a while, but it is disorganized, it's hard to test, and it's generally a bad idea. Separation of concerns, keeping infrastructure code in one place and business code in another, is what we should be aiming for, and using services properly is very helpful in getting there.

Custom web MVC for a legacy Java EE project

I am in the middle of creating my own custom MVC web framework for a project. This project has very old code base where one JSP page directly submits a form to another JSP whereas the paths are also hardcoded. Now it is a big project and putting Struts or JSF will take considerable amount of time.
So my suggestion is to build a small custom MVC framework and convert many existing page flows into it and also encourage them to develop newer applications using this new MVC frameworks.
I would like to review this with all of you whether it makes sense or we should directly go to the standard MVC frameworks.
My idea
1. Create one front controller servlet which will have URL pattern like /*.sm
2. This servlet reads one config file and creates a map whose key is requestedURI and value is the class name of the command bean.
3. upon intercepting any action request it reads the parameter map (request.getParameterMap()). This servlet refers the already built map, understand whose command bean is to be invoked? Creates an instance of this command bean.
4. pass the parameter map to this command bean and calls execute method.
5. if any exception is found, front controller servlet forwards the request to one global error page
6. if everything is fine, it then forwards the request to the expected URI (by removong .sm and replace it with .jsp)
Do you think I am missing anything here? I know I can make it more fancy by providing error page per request page in the config file or so but those can be done later as well.
I think that you will end up reinventing the wheel rolling your own MVC framework. I know that it is tempting to make your own, since you won't have to get used to a new API but instead create your own and you can more easily adapt it to your specific usecases. But since it seems to be a very long lived application you will have to consider the fact, that your own framework (which may now be state of the art) will be legacy in a couple of years, too.
And that's where adapting one of the popular frameworks comes in handy. The creators of a new framework usually want others to move, too, so they will (or should) offer easy integration or migration options away from the frameworks they think they are doing better (Spring is a good example since it e.g. seamlessly integrates with existing Struts applications and you can gradually move your application without putting the old one into trash). Additionally most current frameworks are very versatile (which can sometimes be a problem since they need more time to get into it) and can be adapted to almost all usecases.
So I would recommend to review the existing solutions carefully (you can learn a lot from their design decisions and errors, too) and only start making your own if none of them matches your requirements.

Categories

Resources