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
  •  

    Monday, 30 November 2015

    Structs

    Framework is a tool that provides common required features like Internalization, validation, form backup, Exceptions and supports in building applications quickly.
    Structs is a MVC framework to build web application. It is an MVC framework and provides support to build web application UI and Controller layers. It is not useful for building Model


    • View Layer/presentation support
      • Form tags         //to provide validation and form backup support
        • It provides Form beans and Validator classes
      • I18N tags         //Multiple language support
      • Logical tags     //
      • Tile tags
      • Ajax tags in Structs 2.0
      • OGNL (Object Graph Notation language) in Structs 2.0
    • Controller support
      • Multi action contollers
      • Multi button controllers
      • Multi form controllers
      • Exception handler support
      • plugin support -- to integrate with Model layer
      • Pre handling support
      • Post handling (interceptors) support(In structs 2.0)
      • I18N controller classes   //to change browser language
    Model can be designed using following combination for Business Logic and DAO

    EJB Session beans & EJB entity beans
    EJB Session beans & Hibernate
    Spring & Hibernate
    Spring & Spring ORM

    JSP Model1:
      Multiple form request need to map to one controller and controller will be jsp.
    JSP Model2:
      Multiple form request need to map to one controller and controller will be servlet.
    JSP Model3:
      Multiple form request need to map to one controller and controller will be filter.
    JSP Model4:
      Multiple form request need to map to one controller and controller will be tags.

    Model 1 & 4 are not recommended and no frameworks are built using them.

    Structs 1.x, JSF and Spring designed using JSP model2. The controller names is ActionServlet(Structs), FacesServlet(JSF), DispatcherServlet(Sprint MVC)

    Structs 2.x designed using JSP model3. The filters  are FilterDispatcher & StructsPrepareAndExecuteFilter


    Default controllers(ActionServlet) will support common required features like form backup support, exceptions and etc. For user specific operations one should provide user specific controllers.

    ActionServlet has some helper classes as well. Using ActionServlet and helper classes, we can achieve all the features. 

    Architecture:
    Directory structure for Structs:

    • Application Folder -> Its name will be application name.
      • view resources -> html, css, java script, jsp, image, audio & video
      • WEB-INF -> folder
        • web.xml -> Configure action servlet (Front controller) & and init parameter Config with structs-config.xml as value
        • structs-config.xml
        • classes -> folder. This will have servlet classes & Model(jdbc, spring, simple java) classes
        • lib  -> folder  -> additional api's. like file upload api, spring related jar files.

    JSP Model architecture rules:
    • Multiple input form requests need to be mapped to single controller. The controller should be Servlet. (ActionServlet is the controller in Structs 1.x). ActionServlet reads structs-config.xml to find bean and user defined Controller classes for the form request.
    • ActionServlet will read the request object data and hold the values in Bean Object. (User need not read from request object as required in Servlets/jsps)
    • After storing the values in bean object, it will execute the validations on bean data. If it finds validation errors, it will return to ActionServlet. ActionServlet inturn return and reflect the same on input pages.
    • ActionServlet then invokes user defined Controller by passing Bean, Request and Response objects. User defined Controller will in turn invoke model for execution and it can pass the Bean reference as required. (For Controller to pass bean to Model, we need DTO object(a simple serializable object). DTO will be sent to Model. Model reads DTO and performs business operations. After completion of Business operations to hold data into database table the data should be sent to DAO. For sending to DAO the data need to be placed/moved to Model object. Model object can be persisted by using Hibernate.)
    • User defined Controller just returns Success/Fail to the ActionServlet. ActionServlet will use the value and then invoke respective jsp defined in structs-config.xml for the return value. The output of jsp will be returned as output for the form request.
    Create Hello World Structs application from eclipse

    • Create dynamic web project, add structs jar to lib folder
    • Create index.jsp with action="hello"
    • Create HelloBean extends ActionForm class (Action form classes are ActionForm/DynaActionForm/ValidatorForm/DynaValidatorForm/ValidationActionForm/DynaValidationActionForm)
    • Create HelloController extends Action Class (Action, DispatchAction, LookupDispatchAction, MappingDispatchAction, EventDispatchAction)
    • web.xml - > Configure FrontController class i.e ActionServlet org.apache.structs.action.ActionServlet
    • Add following mappings in structs-config.xml
      • Input form to bean
      • Bean to input form
      • Bean to controller
      • Controller to success/failure page 
    • properties file for error messages
    Sample structs-config.xml with out controller file
    <structs-config>
    <form-beans>
         <form-bean name="<bean ref name>" type="<class-name>" </form-bean>
         <form-bean name="EMP" type="pkg1.hello" </form-bean>
    </form-beans>

    <action-mappings>
         <action path="<form action>" name="<bean ref name>" input="/index.jsp" </action>
         <action path="/hello" name="EMP" validate="true" input="/index.jsp"  </action>
    </action-mappings>

     <message-resources>  parameter="Messages"  </message-resources> //file name without extn
    </structs-config>

    Structs Flow of Control
    1. On first user form request, ActionServlet will be instantiated by calling init(ServletConfig).
    2. init() reads the location of servlet configuration file(structs-config.xml) from config object, and structs-config.xml file data will be loaded into ModuleConfig object
    3. After init(), either doGet() or doPost() method on ActionServlet will be called. They inturn delegate redirect it to Process(request,response)
      1. The Process(), creates form reference Bean object as declared in structs-config file. The bean object will be stored in session scope.
      2. Process() will then create/get RequestProcessor object by calling RequestProcessorUtil(ModuleConfig) factory method
      3. Process() inturn delegates the control to RequestProcessor.process(req,res)
        1. RequestProcessor.process() calls following methods
          1. processPreProcess(req,res) where security checks can be performed
          2. processLocale(req, res). This prepare Locate object with Browser language value. The locale object will be stored in session object.
          3. processFormBean(req,res) - This will store request scope data in Bean Object.
          4. processValidation(req,res) - This validates the data by calling validate() on bean. This method returns ActionErrors object. If ActionErrors object has data then it redirects control to same page using requestDispatcher.Forward. In the page, if the bean has valid data it will populate other wise it will just clear the value for the invalid data field. Along with the bean data it will show ActionErrors data.
          5. (ProcessController) If Validation is successful, it creates Controller object configured in structs-config file. The execute() in controller class will be executed by passing Bean object as parameter. This method returns ActionForward object to RequestProcessor. Based on ActionForward defined in structs-config file, the request processor returns the output to user.
    Validations
    Programmatic - ActionForm, DynaActionForm: These can support application level(server side) validations & form backup support
    Declarative -  ValidatorForm, DynaValidatorForm, ValidatorActionForm, DynaValidatorActionForm : These can support client side validation, application level(server side) validations , form backup & Localization support

    ValidatorForm, DynaValidatorForm  are for single form operations
    ValidatorActionForm, DynaValidatorActionForm are for multi form operations

    How does Validations execute in case of Declartive approach:
    • Create validation.xml for every input file
    • predefined validations are given under validation-rules.xml file
    • Validator plugin to read the validation files
    • Validator plugin will be started by Action Servlet init(). It will create object of Validator calls init() on Validator plugin class. The validations will be stored in ServletContext scope object.
    •  RequestProcessor stores data in bean and then executes validations stored in Context scope. 
    • Advantage with validation.xml files is that, they generate java script validation. This will help reduce network traffic between server and browser.

    Application using ValidatorForm
    Components required:
    • index.jsp -
    • success.jsp
    • bean extending from ValidatorForm
    • Messages.properties
    • validation.xml
    • validator-rules.xml
    • web.xml
    • structs-config.xml
    • controller by extending from Action class
     Validation.xml
    <form-validation>
       <formset>
        <form name="RF">
           <field name="id" depends="intRange">
             <arg key="id">
             <arg key="${var.min}>
             <arg key="${var.max}>
            <var>
                <var-name>min</var-name>
                <var-value>111</var-value>
             </var>
            <var>
                <var-name>max</var-name>
                <var-value>200</var-value>
             </var>


    <structs-config>
    <form-beans>
         <form-bean name="<bean ref name>" type="<class-name>" </form-bean>
         <form-bean name="EMP" type="pkg1.hello" </form-bean>
    </form-beans>

    <action-mappings>
         <action path="<form action>" name="<bean ref name>" input="/index.jsp" </action>
         <action path="/hello" name="EMP" validate="true" input="/index.jsp"  </action>
    </action-mappings>

     <plug-in classname="validatorplugin">
     <set-property property="pathnames"
                             value="validation-rules.xml, empvalidation.xml"/> 
     </set-property

      </plug-in>

     <message-resources>  parameter="Messages"  </message-resources> //file name without extn
    </structs-config>



    Monday, 16 November 2015

    Servlets

    Servlets are server side java classes. Servlet container is needed to execute these serverside java classes. They are capable to read data coming from browser. Data from browser is sent using http protocol. The data can be sent either thru header(query string) or body(payload) of HTTP protocol.
    The servlet container can understand the http data. It will accept the http protocol data and read it. It will make the http protocol data into java bean object(HttpServletRequest). It will then forward HttpServletRequest to servlet classes.

    Servlet classes will generate HttpServletResponse object and container will convert into http protocol data.  The http protocol data will be forwarded to the browser. 

    Servlet container responsibilities:
    • Read http request data and convert to HttpServletRequest object.
    • Based on the browser request url/address, create servlet object(if first call) and pass HttpServletRequest object data to servlet
    • Convert HttpServletResponse into Http protocol data. And send the response to browser.
    Note: Container will prepare servlet object for the initial/first request(all the servlets are singleton classes).

    Directory structure for Servlet:
    • Servlet container will accept well directory structured application. 
    • Application Folder -> Its name will be application name.
      • view resources -> html, css, java script, jsp, image, audio & video
      • WEB-INF -> folder
        • web.xml -> mapping information
        • classes -> folder. This will have servlet classes & Model(jdbc, spring, simple java) classes
        • lib  -> folder  -> additional api's. like file upload api, spring related jar files.

    How to write a servlet 
    There are 3 servlet implementations. A servlet class can be created either by implementing the interface or extending the following classes.
    • servlet interface
    • Generic servlet (Child of servlet interface) . Its an abstract class
    • HTTP servlet - Abstract class.
    Servlet Interface
    • void init(javax.servlet.ServletConfig)
    • void service(ServletRequest, ServletResponse)
    • void destroy()
    • String getServletInfo()
    • String ServletConfig getServletConfig()
    Generic Servlet -  It is child of Servlet interface
    • Only one single abstract method. Other methods are implemented. 
    • void service(ServletRequest, ServletResponse) -> needs implementation
    • Session management is not possible in this case.
    HTTP Servlet -  All methods are concrete, even though the class is abstract
    • recommendation is to override following methods
    • doGet(HttpServletRequest, HttpServletResponse)
    • doPost(HttpServletRequest, HttpServletResponse)
    • Session management is possible in this case.

    Eg using Servlet Interface
      import   javax.servlet.*;

      public class HelloServlet implements Servlet{
          public void init() { }
          public void service(ServletRequest req, ServletResponse resp) throws ServletException {
                String name=req.getParameter("ParamName");
                resp.setContentType("text/html");
                PrintWriter out=  resp.getWritter;
                out.println("hello "+name);
                }
          public void destroy(){  }
          public String getServletInfo() {  return null; }
          public String ServletConfig getServletConfig() { return null; }
         
    }

    Sevlet Lifecycle -
    • Containers role(when it is started)
      1. Extracts all WAR files and stores(deploys) the application in webapps folder
      2. Reads web.xml file and creates 2 objects, ServletContext & ServletConfig.
        ServletContext is accessible by every servlet in the application. ServletConfig is specific/private to a servlet.
      3. Creates Servlet Object and executes init() passing ServletConfig object as parameter
    Create Servlet from eclipse
    • Create dynamic web project
    • add view pages under webcontent
    • add servlet classes in java resources/src folder
    • sample web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>ServletLifeCycle</display-name>
      <welcome-file-list>
        <welcome-file>registration.html</welcome-file>
      </welcome-file-list>
      <servlet>
          <servlet-name>reg</servlet-name>
          <servlet-class>RegistrationServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
          <servlet-name>reg</servlet-name>
          <url-pattern>/RegServlet</url-pattern>
      </servlet-mapping>
    </web-app>
    We can configure configurations data and context data in web.xml

    Context & Config
      init parameters are local for a servlet and Context parameters for global

    Http Servlet
    • For each browser(until open to close), it maintains session object with unique session id.
    • It maintains sessions 
    • It maintains browser caches
    • HttpSession hs = request.getSession(); // to get session object
    Inter Servlet Communication
    • getServlet("<servletname">)
      • getServletContext().getServlet("PrintServlet").doGet(req, res); //not recommended
    • requestDispatcher
      •  request.getRequestDispatcher("PrintServlet").forward(req,res);
      •  request.getRequestDispatcher("PrintServlet").include(req,res);
    • sendRedirect
    Filters:
    • It is to validate the input data, security and so
    • Filter Object is created during deployment time itself.
    • Filter will execute 2 times. Before data is submitted to servlet, and when servlet output is returned back via Filter
      • filterChain.doFilter(req,response) - call servlet and then continues after Servlet execution is complete.
    • It comes with 3 methods
      • init(FilterConfig)
      • doFilter(ServletRequest, ServletResponse, FilterChain)
      • destroy()
    • How to create?
      • Create a Filter implementing javax.servlet.Filter(web.xml entries same as Servlet)
      • url pattern should be same as that of respective servlet for which it acts as Filter
      •  
    Servlet Listners:
      Servlet Container has some event handlers. - On start of container, on stop of container. The event handler is ServletContextListner

    Listners will be instantiated and executed prior to Filters & Servlets during initialization and executes after Servlet & Filter during destroy.
    • ServletContextListner
      • contextInitialized(ServletContextEvent sce)  //on container start
        • When container is started, it creates ServletContext object, and instantiates Listnerclass that implements ServletContextListner and executes contextInit()
      • contextDestroyed(ServletContextEvent sce) //on container stop
      •  Uses: Initialization required for entire application like - jndi object, connection pool object
      Servlet Session has some event handlers(Session Listener handlers). - On start of session, on invalidate of session. The event handler is ServletSessionListner
    • ServletSessionListner  interface
      • sessiontInit()  //at the time of creating session object httpreq.getSession()
      • sessionDestroy() //on session invalidate

      Servlet Request has some event handlers(Servlet Request Listener). - On start of request, on destroy of request. Request and Response objects will be destroyed after sending response to client.

    The event handler is ServletSessionListner
    • ServletRequestListner  interface
      • requestInit()  //at the time of creating request object
      • requestDestroy() //on destroy of request object
    How to create Listner-
    •   Eclipse - new Listner class -> It configures listner class in web.xml using Listner and Listner-class tags

    MVC Architecture- Controller responsibility is to read data and send into model.

    JSP
    • To generate dynamic webpages(Java script executes on browser/client machine, where as JSP executes on server
    • JSP container is required to run JSPs,
    • JSP container convers jsp into Servlet java class
    • JSP pages can containe both HTML and java code
    • <%!        %> is a declaration tag. This is used for declaration, jsp init and jsp destroy
    • <%! _jspInit(){}       %>  to place the code into init() method
    • <%! _jspDestroy(){}       %>  to place the code into destroy() method
    • <%        %>  is a scriplet tag. This code will be placed in service() method
    •  <%=        %>  is an expression. This is equivalent to out.println()
    • HTML content will be placed under out.Println()
    • To print with in scriptlet, we should use out.println()
    Print a dynamic table:
    <table>
    <tr> <th>Number</th> <th>Value</th> </tr>
     <%for(int i=0;i<10;i++){ %>
    <tr> <td>Number =</td> <td><%= i+1%></td> </tr>

     <% }  %>
    </table>

    9 JSP predefined/builtin objects - Service method will create following implict variables .
    • context
    • session
    • request
    • response 
    • config
    • out
    • exception
    • page  //this
    • pageContext
    JSP Include
    • To include different pages(html for header, footer and menu) into main page(jsp)
    • Following directives can be used to include pages into jsp
        • <jsp:include page="<page path>"  //soft link to page.
      • <@include file="<page path>"  // copies the file content
    •  

    Response Send Redirect
    • response.sendRedirect("url"); - This will send page url to browser. The browser in turn sends request to the page(with new request and response objects)


    Tuesday, 10 November 2015

    Multi Threading

    Introduction:
    Executing multiple tasks simultaneously is called Multi Tasking. Java provides in built support for multi-threading with rich API [Thread, Runnable, ThreadGroup..]
    • Process based multi tasking- Executing several tasks simultaneously, where each task is separate independent process.
    • Thread based multi tasking- Executing several tasks simultaneously, where each task is independent part of same program. Main important application areas are - to develop multimedia graphics, to develop animation movies, video games, to develop webservers and application servers
    Thread is a flow of execution.

    Ways to define a thread:
    • Extend Thread class and override run() 
    • Implement Runnable interface
    Thread Definition eg1: 
      class MyThread extends Thread{
        public void run(){
        for (int i=0;i<10;i++){
             System.out.println("child thread");
    }
    }
    }


      class ThreadDemo {
        public static void main(String[] args){
         MyThread t=new MyThread();  //thread instantiation 
         t.start();  //starting of a thread
        for (int i=0;i<10;i++){
             System.out.println("main thread");
    }}
    }

    • Implement Runnable interface
    Thread Definition eg1: 
      class MyRunnable implements Runnable{
        public void run(){
        for (int i=0;i<10;i++){
             System.out.println("child thread");
    }
    }
    }


      class ThreadDemo {
        public static void main(String[] args){
         MyRunnable r=new MyRunnable();  //thread instantiation
          Thread t=new Thread(r); // r is target runnable
         t.start();  //starting of a thread
        for (int i=0;i<10;i++){
             System.out.println("main thread");
    }}
    }
    • Code within the run() is called "job" of thread.
    • job of thread and main thread will be executed in parallel
    • Among two ways of defining a thread, implements runnable approach is recommended. As we inheritance benefit will not be lost. 
    Constructors
    • Thread t=new Thread()
    • Thread t=new Thread(Runnable r)
    • Thread t=new Thread(String name) 
    • Thread t=new Thread(Runnable r, String name)
    • Thread t=new Thread(ThreadGroup g, String name) 
    • Thread t=new Thread(ThreadGroup g, Runnable r)
    • Thread t=new Thread(ThreadGroup g, Runnable r, String name)
    • Thread t=new Thread(ThreadGroup g, Runnable r, String name, long stacksize)
    Setting name of a thread-

      class MyThread extends Thread{

    }


      class ThreadDemo {
        public static void main(String[] args){
              System.out.println(Thread.currentThread().getName());
              Thread t =new MyThread();
               System.out.println(t.getName());
              Thread.currentThread().setName("My Main Thread")
    }
    Thread Priorities
    • Every thread has some priority(either default or programmer specified custom priority)
    • Valid priority range is 1-10. Thread class defines following constants
      • Thread.MIN_PRIORITY //1
      • Thread.NORM_PRIORITY //5
      • Thread.MAX_PRIORITY //10
    • Default priority for main thread is 5. For other threads, default priority is inherited from parent.
    • Thread Scheduler will use the priorities while allocating the processor.  The thread which is having highest priority will get first chance. 
    • If two threads have same priority, then the execution order cannot be predictable. It depends on Thread Scheduler. 
    • Methods to get and set priority of a thread
      • public final int getPriority()
      • public final void setPriority(int p)
    Methods to prevent thread execution-  We can prevent a thread execution by using following metholds:
    • yield() - To pause the execution and give chance to other waiting threads with same priority. 
      • public static native void yield()
    • join() - To make a thread wait until completion of some other thread.
      • public final void join() throws InterruptedException
      • public final void join(long ms) throws InterruptedException
      • public final void join(long ms,int ns) throws InterruptedException
    • sleep() - To stop thread from performing any operation for a specified duration.
      • public static native void sleep(long ms)
      • public static void yield(long ms, int ns)
    How to make child wait for Main thread:
      class MyThread extends Thread{
       static Thread mt;
        public void run(){
       mt.join();
        for (int i=0;i<10;i++){
             System.out.println("child thread");
    }
    }
    }


      class ThreadDemo {
        public static void main(String[] args){
         MyThread.mt=Thread.currentThread();
         MyThread t=new MyThread();  //thread instantiation  
         t.start();  //starting of a thread
        for (int i=0;i<10;i++){
             System.out.println("main thread");
    }}
    }

    How a thread can interrupt another thread:
     A thread can interrupt a sleeping thread or waiting thread by using interrupt() of Thread class.
    •  public void interrupt()
    • If target thread not in sleeping/waiting state, then there is not impact of interrupt() call immediately. interrupt call will wait until target thread enters into sleeping/waiting state. 
    • If target thread never enters into sleeping/waiting stage, then interrupt call will not impact any.

      class MyThread extends Thread{
       static Thread mt;
        public void run(){

        try{
        for (int i=0;i<10;i++){
             Thread.sleep(2000);
             System.out.println("child thread");
    }
    }catch(InterruptedException){
      System.out.println("Interrupted");
    }
    }
    }

      class ThreadDemo {
        public static void main(String[] args){
         MyThread.mt=Thread.currentThread();
         MyThread t=new MyThread();  //thread instantiation  
         t.start();  //starting of a thread
         t.interrupt();
    }}
    }
    Synchronization
    • synchroinzed is a modifier, applicable for methods and blocks(not applicable for class and variables)
    • If multiple threads operate simultaneously on same java object, then there may be chance of data inconsistency problem. To overcome this problem we should go for synchronized modifier
    • If a method or block declared as synchronized then at a time ONLY one thread is allowed to execute the method or block, on the given object. 
    • Synchronization concept is implemented by using lock. Every object in java has a unique lock.  
    • A thread to execute Synchronized method on a given object, it has to get lock of that object. Once it gets lock, then it is allowed to execute any synchronized method on that object. 
    • Thread releases lock automatically once the method execution is complete.
    • Acquiring and releasing lock is internally taken care by jvm
    • When a thread is executing synchronized method on a given object, remaining threads are not allowed to execute any synchronized method on that object. 
    Class Level Lock
    • A thread to execute static synchronized method, a class level lock(Lock on Class class object) is required.
    Synchronized Block
     If very few lines of code require synchronization, then it is not recommended to declare entire method as synchronized. We have to enclose those few lines of code by using Synchronized block
    • synchronized(this) //get lock on current object
    • synchronized(a)  //get lock on particular object
    • synchronized(MyThread.Class) // to get class level lock 
    Multi Threading is implemented using following two models:
    • Green thread model - Thread which is managed completely by JVM with out taking underlying OS support. Few Operating systems like Sun Solaries support this model. However, this model is deprecated and not recommended to use. 
    • Native OS model - Thread life cycle is managed by JVM with the help of underlying OS. All Windows OS, provide support for native OS model.
     How to stop a Thread-  We can stop a thread execution by using stop() of thread class. If we call stop(), then the thread will enter into dead state. Any way, stop() is deprecated and not recommended to use. 
    public void stop()

     How to suspend and resume a Thread- We can suspend a thread by using suspend() of thread class. The thread will enter into suspended state. We can resume a suspended thread by using resume() of thread class. The suspended thread can continue its execution.
    public void suspend()
    public void resume()

    These methods are deprecated and not recommended to use.


    Thursday, 5 November 2015

    JVM Architecture

    JVM -  Cornerstone of Java Platform. It helps achieve Java goals like
    • Platform independence
    • Security
    • Fast execution
    It is called virtual as it is abstract computing machine.  It is like a real computing machine with instruction set that it executes. Java Byte Code is its instruction set.  Like real computing system, jvm manipulates memory at runtime.

    Core Responsibilities of JVM 
    • Loading and interpreting bytecode
    • Security
    • Automatic memory management
    Components
    • Specification 
      • Document that describes JVM features and how it should work. Anyone can use specification to implement their own jvm
      • Specifies BYTE code instruction set
    • JLS- Java Language Specification
    • Concrete Implementation of JVM
      • Oracle's Hotspot JVM
      • IBM's JVM
    • Runtime Instance
      • It is instance of concrete jvm implementation
      • eg: java Hello
        • an instance of JVM is created and loaded into memory
        • JVM inturn loads Hello program into memory and then executes it
        • Each java application runs inside a runtime instance of some concrete jvm
        • Runtime instance runs only one java application
    • Performance
      • Java bytecode is compact, compiled and optimized
      • JIT compilation
        • Identify frequently executed bytecode  ~ hotspots 
        • hot spots are executed by separate jvm component - jit compiler
          • JIT compiler converts hotspots into machine code
          • Machine code is then cached
          • It is also referred as dynamic compilation


    JVM Basic Architecture



    Step1: Class Loading








    Linking:






    Virtual Machine: It is a Software simulation of a machine(calculator) which can perform operations like Physical machine. It doesn't have physical existence

    Types of Virtual Machines:
    • Hardware/ System based VM: Provides logical systems on the same computer with isolation of each other. eg: VMware, Cloud computing, Kernel based VM for linux
      • Advantage: Effective utilization of hardware resources.
    • Application based/Software based/Process based VM: Runtime engines to run a particular programming language applications. eg: JVM, CLR(Common Language Runtime for .net), pvm for perl,
    JVM Basic Architecture
    • JVM is runtime engine to to run java based applications
    • It is an interpreter and is JRE. (JRE is part of JDK.)
    • It loads .class file and executes line by line. 
    • Jvm has 3 components - ClassLoader sub system, memory area, execution engine
      • ClassLoader Sub System is responsible for 3 activities
        • Loading 
          • Reads the class file and store corresponding binary data(byte code) to method area
          • It will store ClassName, ParentClassName, Modifiers, variables, methods, constructors and constants.
          • After loading, it creates a Class object to represent class level binary info on the heap memory.
        • Linking-
          • Verification- a) It(Byte code verifier) is process of ensuring that binary representation of a class is structurally correct.  b) whether .class file is generated by valid compiler and properly formatted or not
          • Preparation -Allocate memory for class level static variable and assign default values(in method area)
          • Resolution- It is the process of replacing all symbolic references used in class with original references from method area.
        • Initialization- Assign original values for class level static variables. Static blocks will be executed from top to bottom.

    Class loader subsystem: Types of class loaders
    • BootStrap/Primordial class loader
      • This class loader is responsible for loading core java API classes i.e the classes present in rt.jar(jdk\jre\lib\rt.jar). This location is called bootstrap classpath i.e Bootstrap class loader is responsible to load classes from Bootstrap classpath. Bootstrap class loader is by default available in jvm. It is implemented in native languages like c & c++.
    • Extension class loader
      • It is child of bootstrap class loader. The class loader is responsible to load classes from Extension class path. (jdk\jre\lib\ext). This loader is implemented in java.
    • Application/System class loader
      • It is child of Extension class loader. It is responsible to load classes from application class path. It internally uses Environment variable class path. This loader is implemented in java.
    How java class loader works
    • Class loader follows Delegation Hierarchy Principle.
    • When jvm come across a class, first it will check whether the corresponding class is already loaded or not.
    • If it is already loaded in method area, then jvm will use that loaded class.
    • It is it not already loaded then jvm requests class loader subsystem to load that particular class, then class loader sub system hand overs the request to Application Class Loader
    • Application Class Loader delegates the request to Extension class loader, and Extension class loader delegates the request to Bootstrap class loader.
    • Bootstrap class loader searches in bootstrap class path(jdk\jre\lib). If the specified class is available then it will be loaded. Otherwise bootstrap class loader delegates the request to Extension class loader.
    • Extension class loader searches in Extension class path(jdk\jre\lib\Ext). If the specified class is available then it will be loaded. Otherwise Extension class loader delegates the request to Application class loader.
    • Application class loader searches in Application class path. If the specified class is available then it will be loaded. Otherwise Runtime exception - Class Not Found Exception will be raised.
    need of Customized class loader
     Memory areas of JVM
    • method area -- Class level data and static variables.
    • heap area -- Objects and instance variable, also arrays(array is an object in java)
    • stack area--For every thread, a runtime stack area will be created(for method calls). Each entry in stack is called stack frame. Stack frame consists of 3 parts
      • Local variable array
      • Operand stack -
      • frame data -
    • pc registers - one pc register for each thread. It is to hold address of current executing instruction.
    • native method stacks - Separate thread a separate runtime stack will be created to hold native method information.
    Execution engine - It is central component of jvm like cpu
    •  Interpreter - responsible for read, interpret and execute java program line by line.
    • JIT compiler (to handle/avoid repeat method call interpretation).
      • Intermediate code generator - Produces intermediate code. 
      • Code optimizer
      • Target code generator - generate machine code
     Profiler: It identify hot spots(repeatedly required method).
    JNI(Java Native interface) - provides java native method informatiod.

    Customized Class Loader:(When default class loader doesn't meet our requirements.)
    • Default class loader loads the class only once. It doesn't load the class on fly. 
    • We may want the loader to load the latest version of .class file. In such cases, we may have to go for Customized class loader.
    • Custom class loader can be created by extending java.lang.ClassLoader class
    eg:
      public class CustomClassLoader extends ClassLoader{
         public Class loadClass(String cname) throws ClassNotFoundException{
    Check whether updated version available
        if updated version available, then load updated version and return corresponding Class Object
        Else return Class Object of already loaded .class
    }
    }

    Note:
      Heap and Method area is shared memory. Hence, data saved in this is not thread safe. 

    Monday, 2 November 2015

    Reflection API

    Reflection refers to ability of a program to create objects and invoke methods of objects at runtime.




    Why to use Reflection:  It lets you write programs that you do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime !!

    Lots of modern frameworks uses reflection extensively eg: Hibernate, Spring, Junit.


    The api is useful in Product development like compilers, jvms, frameworks, servers development. These products reads the declarative part of the java class using Reflection API.

    eg: where jvm needs to read declaration details(zero arg constructor) for a CLASS and uses Reflection API
      Class A{
         A(int i){
    }
    }
      Class Test{
         public static void main(String args[]){
         Class c=Class.forName("A"); // to load A class byte code to jvm memory
         A a= (A)c.newInstance(); //Creates instance with NO argument & non private constructor.
    }
    }


    3 ways to prepare Class Object for a Class definition.

    • Class c=Class.forName("Employee");
      • It will search for Employee.class file in current location, java pre defined library & locations referred by classpath environment variable.  It will load byte class code into memory. JVM will collect meta data of the class and creates Class Object.
      • Argument is Fully Qualified Class name
      • Doesn't work with Primitives
    • Employee e=new Employee(); //loads class to memory and jvm creates Class Object implicitly
      Class c=e.getClass(); // assigns Class Object reference to c
    • Class liternals
      • Works with classes, interfaces, arrays, and primitives
      • Class c=Employee.class //When a class is compiled, internally a class public static final variable will be appended to class which refers to Class object 
      • eg: String.class, boolean.class, int[][][].class, void.class
      •  
     Methods to retrieve Class metadata:
    • public String getName(); //returns name of the respective class
    • public Class getSuperClass(); // returns Super Class Object
    • public Class[] getInterfaces();
    • public int getModifiers() -> public static String toString(int modifier)

    Employee.java
    public abstract class Employee implements java.io.Serailizable,Cloneable {
         public int eno;
         public static String ename;
         public final String eaddress;
         public Employee(){
         }
         public Employee(int i, String name, String address){
            eno=i;  ename=name;eaddress=address;
         }
    }

    Test.java
      import java.lang.reflect.*;
    public class Test throws Exception {

         public static void main(String args[]){        Class c=Class.forName("Employee");
            System.out.println("Name :"+c.getName());
            System.out.println("Super Class :"+c.getSuperclass.getName());
            Class[] ci=getInterfaces();
            System.out.println("Interfaces :");
            for (Class cls:ci)  System.out.println(cls.getName()+ "  ");

           int i=c.getModifiers();
           System.out.println("access modifiers"+Modifier.toString(i));
         }
    }

    //Meta data for variables.
      import java.lang.reflect.*;
    public class Test throws Exception {

         public static void main(String args[]) throws Exception{   
            Employee e=new Employee();
            Class c=e.getClass();
    //        Field[] flds1=c.getFields(); //public variables only of the class and super class
            Field[] flds2=c.getDeclaredFields(); //All the variables meta data of the class alone
            for (Field f:flds2){
                   System.out.println("Field Name: "+f.getName());
                   System.out.println("Data Type: "+f.getType().getName());
                   int i=f.getModifiers();
                   System.out.println("access modifiers"+Modifier.toString(i));
           }
         }
    }

    //Meta data for methods.
      import java.lang.reflect.*;
    public class Test throws Exception {

         public static void main(String args[]) throws Exception{   

            Class c= Employee.class();
    //        Field[] mthd1=c.getMethods(); //public methods only of the class and super class
            Method[] mthd2=c.getDeclaredMethods(); //All the methods of the class alone
            for (Method m:mthd2){
                   System.out.println("Method Name: "+m.getName());
                   System.out.println("Return Type: "+m.getReturnType().getName());
                   int i=m.getModifiers();
                   System.out.println("access modifiers"+Modifier.toString(i));
                   Class[] cls1=m.getParameterTypes();
                   System.out.println("Parameter Types");
                   for(Class c1:cls1){
                    System.out.println(c1.getName());
                   }
                  Class[] cls2=m.getExceptionTypes();
                   System.out.println("Exception Types");
                   for(Class c2:cls2){
                    System.out.println(c2.getName() + "  ");
                   }
           }
         }
    }