Tuesday, 29 December 2015

DAO

DAO(Data Access Object)- main aim is to interact with data machines
  • Do persistence operations
  • Interact with rdbms, ldap, nosql or xml
  • Interface between Business & data machine for simple data access operations
  • We can implement DAO using
    • jdbc from sun
    • jax-b, jax-p parsers for xml files
    • ORM tools to access data from rdbms database
      • EJB
      • JPA
      • Hybernate
      • ibates
    • OGM to interact with nosql
    • Spring-jdbc for rdbms machines
    • Spring-orm for rdbms machines
    •  
    •  
For implementing DAOs we should follow interface implementation pattern
  • Standard way of creating DAO
    • Create a modal with fields/structure same as DB table. Add getters/setters
    • Create DAO interface with all the required methods(signatures and return values). eg: update, delete, findByName, findAll
    • Create DAOImpl1 implementing all the methods of DAO interface in previous step using JDBC 
      • in side the method, get the connection from pool, do operation, and release the connection to pool


DataSource is interface given by Sun, for implementing connection pool. Similarly DriverManagerDataSource is given by Spring
WeblogicDataSource by Weblogic
BasicDataSource by Apache

Sample code to create connection pool:
BasicDataSource bds=new BasicDataSource();  //pool reference.
bds.setDriverClassName(driver);
bds.url(dburl);
bds.setUsername(user);
bds.setPassword(pass);
bds.setMaxActiveConnections(20);
bds.setMinIdle(5);
bds.setWaitTime(1000*5);

bds.getConnection() -> To get a connection object


Pool is maintained using map objects(freeMap and consumed map). When user closes a connection, it is moved from consumed map to freemap


http://theblasfrompas.blogspot.in/2007/10/using-dao-j2ee-design-pattern-with-adf.html

Sunday, 6 December 2015

JSF

HellowWorld with Maven:http://javaonlineguide.net/2015/06/jsf-2-2-hello-world-tutorial-with-example-basic-concepts.html

  • Create Maven webapp project and open in Eclipse
    • mvn archetype:generate -DgroupId=payables  -DartifactId=automation -DarchetypeGroupId=org.apache.maven.archetypes  -DarchetypeArtifactId=maven-archetype-webapp
  •  Create java folder under src/main 
  • update pom.xml 
    •     <dependency>
          <groupId>com.sun.faces</groupId>
          <artifactId>jsf-api</artifactId>
          <version>2.2.11</version>
          </dependency>
       
          <dependency>
          <groupId>com.sun.faces</groupId>
          <artifactId>jsf-impl</artifactId>
          <version>2.2.11</version>
          </dependency>
       
          <dependency>
          <groupId>javax.el</groupId>
          <artifactId>javax.el-api</artifactId>
          <version>3.0.1-b04</version>
          </dependency>
       
          <dependency>
          <groupId>javax.servlet.jsp.jstl</groupId>
          <artifactId>jstl-api</artifactId>
          <version>1.2</version>
          </dependency>
       
       update web.xml

       
      <servlet>
          <servlet-name>Faces Servlet</servlet-name>
          <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
        </servlet>
       
          <servlet-name>Faces Servlet</servlet-name>
          <url-pattern>*.xhtml</url-pattern>
        </servlet-mapping>
       
        <context-param>
          <param-name>javax.faces.CONFIG_FILES</param-name>
          <param-value>
              WEB-INF/faces-config.xml
          </param-value>
        </context-param>

      hello.xhtml
       
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       
      <h:head>
      <title>My First JSF Application</title>
      </h:head>
      <h:body>
      <h3>JSF 2.2 Hello World Example with faces-config.xml</h3>
      <h:form>
      <h3>Now The time is <h:outputLabel> #{helloWorldBean.currentTime}</h:outputLabel></h3>
      Your Name Please?
      <h:inputText value="#{helloWorldBean.name}"></h:inputText>
      <h:commandButton value="Say Hello" action="#{resultBean.result}"></h:commandButton>
      </h:form>
      </h:body>
      </html>
       


JSF is Server sider component oriented Java web framework. It helps to build Robust, Scalable, Flexible, Secure applications.
  •  Rapid development
  • wires component events to Java server-side code
  • Binds UI components to pojos
  • Built in validators & converters, also customizable
  • Exception handling
  • Navigation handling
  • Page and application templates
  • Define page flow that reflects app requirement

Facelets:
  • It is new technology created from jsf2.0. It is created as jsp doesn't support all the technology that jsf provides. Hence, jsf created their own rendering technology.

Life Cycle


JSF is a MVC framework of Java EE platform. Contrary to the widely used Spring MVC and Structs Frameworks, it is a component oriented MVC framework.

Action Oriented MVC architecture:


Component Oriented MVC architecture:


 


 1.  What is JSF (or JavaServer Faces)?
A server side user interface component framework for Java™ technology-based web applications.JavaServer Faces (JSF) is an industry standard and a framework for building component-based user interfaces for web applications. 

JSF contains an API for representing UI components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features. 

New to JSF ? Check JavaServer Faces (JSF) tutorial

2. What are the advantages of JSF? 
The major benefits of JavaServer Faces technology are:
JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
Offers a clean separation between behavior and presentation.
Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
Robust event handling mechanism.
Events easily tied to server-side code.
Render kit support for different clients
Component-level control over statefulness
Highly 'pluggable' - components, view handler, etc
JSF also supports internationalization and accessibility
Offers multiple, standardized vendor implementations


 

 Build Hello World Program
  • Installation/configuration
    • latest Eclipse EE(Neon), Tomcat 8. Connect Eclipse to Tomcat
  • Dynamic Web Project
    • Target Runtime 8.0
    • Configuration -> Modify to select JavaServer Faces 2.2
    • Generate 'Deployment Descriptor'
    • Add jars jsf-api-2.2.9.jar & jsf-impl-2.2.9.jar as library
    • Create and run following files
hello-world.xhtml
<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:a="http://xmlns.jcp.org/jsf/facelets">
   
    <h:head>
        <title>Hello World -Input Form</title>
        <style>   .error {color:red}  </style>
    </h:head>
    <h:body>
        <h:form>
            <h:messages styleClass="error" />
            <h:inputText id="name" value="#{theUserName}" a:placeholder="ur name" />
            <h:commandButton value="Submit"  action="myresponse" />
        </h:form>
    </h:body>
</html>
myresponse.xhtml
<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html">
   
    <h:head>
        <title>Hello World -Response</title>
    </h:head>
   
    <h:body>
            Hello, #{theUserName}
    </h:body>
</html>
  • Validation features
    • Required 
      • <h:inputText value="#{...}"  label=".."   required="true" id="name" requiredMessage="Your NAME is mandatory" />
        <h:message for="name" styleClass="error" />
    • validateLength
    • validateLong/Double
    • validateRegex
    • Custom Validation

      • <h:inputText value="#{...}"  label=".."   required="true" id="name"
         validator="#{bean.method}"  />
      • public void validateTheCourseCode(FacesContext context, UIComponent component, Object value) throws ValidatorException{
             FacesMessage msg = new FacesMessage("xyz");
             throw new ValidatorException(message);
        }
Managed Bean Scopes

  • Request - per web request - This is the DEFAULT scope if none is specified
  • Session - per user or once per user's browser session
  • Application - shared by all users
    • Commonly used to share an instance of a utility class. eg: DB utility class
  • View - Same bean is used while user is on same page. Best for Ajax requests.
  • Flow - Same bean is used while user is on same SET of pages. For Wizard type pages
  • Flash - Same bean will survive a page redirect
  • Custom - Bean stored in a map and developer controls the lifecycle
  • None - Bean not placed in any scope. Useful when used by other scoped beans.
Conditional Naviagation
JSF UI
  • JSF includes components that will generate HTML
Managed Bean
  • Rules
    • Public no arg constructor
    • public setter/getters
    • annotation @ManagedBean(in Jsf2)


Components of a JSF application:
  • A set of web pages to layout UI components. We use special JSF technology called facelets.
  • A set of managed beans. It is java code for holding form data and also to perform backend operations like talking to data base
  • A web deployment descriptor(web.xml)
  • Optionally
    • application configuration files (faces-config.xml)
    • custom objects, components, custom tags and validators


Enterprice is a group of business organizations running under a single name/label

Structs, Jsf, Spring, Hibernate are frameworks/products developed by thrid party organizations.

Framework is a semi-implemented application. It can be used to design applications as per our convenience. It is a collection of tools which provide a good environment  to simplify enterprise application development.
It is a free fabricated environment that we can reuse, customize, share, extend as per our enterprise application simplification.

Advantages of using Frameworks:
  • It is a semi implimented application
  • controller service
  • internalization service
  • validation service
  • security service
  • exception handling service
  • Provides standard flow of execution between the components available on server side.

Web Frameworks - These framworks provide very good environment to design and execute web applications. eg: Structs, JSF
Application Frameworks - These framworks provide very good environment to design any type of Java, J2EE applications. eg: Spring

Enterprise applications have 3 main components
  • user interface layer(Presentation logic) -- AWT, Swing, Html, jsp and so
  • Business process layer(Business logic) -- Servlets, JSP, EJB and so
  • Data storage and access layer(to provide data persistency) -- JDBC, ejb, Hibernate, jpa and so..

Level of enterprise application and height of enterprise application

Web Application
  • Application logic is on serverside only 
  • web technologies - servlets, jsp, cgi..
  • web servers and application servers
  • collection of web components and executed by web containers
  • services only web clients
Distributed Application
  • Application logic is distributed over client and server
  • Distributed technologies - Socket programming, rmi, corba, ejb, web service
  • Application servers
  • executed by ejb container
  • any client

Model1 Architecture(out dated)
  • Single JSP acts as front controller and view
  • This architecture is also called as JSP front. Also called as page centric architecture.
  • Drawbacks
    • jsp features are not enough to handle complete application. Java code is required.
    • Controller and presentation are performed by single jsp(tightly couple design)
 ModelII Architecture
  • Designed completely on the basis of MVC architecture
  • Servlets acts as front controller, jsp for  view, Java Beans, EJB, Hbn, JPA are used as model
  • Controller servlet takes all the requests, identifies the model and instantiates, executes business logic and interacts with DB as needed, identifies target view jsp and forwards the control. 
  • It is a loosely couple design
  • Servlet centric architecture
  • Servlet front architecture
  • Structs & JSF are designed on the basis of MVC architecture( 
JSF lifecycle: As part of Faces Servlet initialization, a jsf life cycle object is created. Following phases are available in life cycle object
  • Restore view
  • Apply request values
  • process validators phase
  • update model
  • invoke application
  • Render response 
When a request comes, Faces Servlet service() will execute the life cycle methods in sequence. Following is the sequence
  • When container forwards request to Faces servlet, the servlet will create FacesContext object specific to the request
    • Facescontext is the anchor point for connecting to framework-and container- specific services
    • FacesContext contains all of the per-request state information related to the processing of a single JavaServer Faces request, and the rendering of the corresponding response. It is passed to, and potentially modified by, each phase of the request processing lifecycle.
    • FacesContext gives you access to multiple useful contexts and objects, like:
      •     the Application object, containing application-related 'settings'
      •     the external context, which is in most cases the ServletContext
      •     Various JSF UI objects, like the render kit, the UIViewRoot
  • FacesServlet will then execute jsf request processing life cycle.
  • RestoreView
    • New Request(Request arrives from browser): It creates component tree of the page, in memory.  The component tree will depict the view along with validators, converters and listeners. It will bypass request to RenderResponse phase.
    • PostBack Request(when a submit action on a form calls method on managed bean): Restore View recovers the component tree of the previous request.
  • Apply Request Values
    • This phase will get the values from Request object and set the values of the respective Components in the component tree.
  • Process Validators
    • This phase will execute the validators & converters configured in the component tree. If any errors, the error message is stored in FacesContext Object and bypasses request to render response phase.
  • Update Model
    • Instantiates Managed Bean. Dump the values of the components into the properties of the Managed Bean.
  • Invoke Application
    • Executes the method associated with the action event. If the return is VOID, the request is transferred to next stage(Render Response).
    • It it returns a String, request is transferred to a new request and process continues to new page(i.e Restore View -> Render Response) 
  • RenderResponse
    • from Restore View phase -New Request
      •  Render response instantiates ManagedBean, get methods initialize the components and html page is generated and sent to client. The component tree is placed in FacesContext object & HTTP session object.
    • Process Validations
      •  Error messages are added and the html response is constructed and sent to client.
    • from Invoke Application-return void
      • Dumps the values of Managed Bean attributes to component tree, and html/xml code is generated. 
Hello World:
  • Create new Dynamic Web Project-> Under configuration section add JSF2.2 ->Generate deployment descriptor-> Download JSF library
  • Create new .xhtml file and delete the default content
Managed Bean
  • It is a regular java calss
  • Commonly used to hold form data. 
  • It can also contain business logic
  • It is created and managed by JSF, hence "managed bean"
  • Rules/requirements for Managed Bean
    • Public no-org constructor
    • Expose properties via public getter/setter methods
    • JSF2 added support for annotation: @ManagedBean
JSF Validation Support:
  • Required
  • validateLength
  • validateDouble
  • validateRegex
  • custom Validation
  •