Friday, October 26, 2012

Java EE 6

Web Tie

JSF: JavaServer Faces technology is a server-side component framework for building Java technology-based web applications.

  • JavaServer Faces technology provides a well-defined programming model and various tag libraries. These features significantly ease the burden of building and maintaining web applications with server-side user interfaces (UIs). With minimal effort, you can complete the following tasks.
  • Create a web page.
  • Drop components onto a web page by adding component tags.
  • Bind components on a page to server-side data.
  • Wire component-generated events to server-side application code.
  • Save and restore application state beyond the life of server requests.
  • Reuse and extend components through customization.

Diagram of web application technologies. JavaServer Pages, the JSP Standard Tag Library, and JavaServer Faces rest on Java Servlet technology. .

  • One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation for web applications. A JavaServer Faces application can map HTTP requests to component-specific event handling and manage components as stateful objects on the server.
  • Facelets technology, available as part of JavaServer Faces 2.0, is now the preferred presentation technology for building JavaServer Faces technology-based web applications
  • Createing a simple JSF app
  • In the Java EE 6 platform, JavaServer Faces provides built-in support for Ajax. 
    • By using the f:ajax tag along with another standard component in a Facelets application. This method adds Ajax functionality to any UI component without additional coding and configuration.
    • By using the JavaScript API method jsf.ajax.request(), directly within the Facelets application. This method provides direct access to Ajax methods, and allows customized control of component behavior.

EL :  Expression Language. Used by both JSP and JSF.

Web Services

Enteprise Beans

Persistence(JPA)

Security

Contexts and Dependency Injection

The most fundamental services provided by CDI are as follows:
  • Contexts: The ability to bind the lifecycle and interactions of stateful components to well-defined but extensible lifecycle contexts
  • Dependency injection: The ability to inject components into an application in a typesafe way, including the ability to choose at deployment time which implementation of a particular interface to inject

Wednesday, October 24, 2012

Design for Scalability


Common Techniques

Server Farm (real time access)
  • If there is a large number of independent (potentially concurrent) request, then you can use a server farm which is basically a set of identically configured machine, frontend by a load balancer.
  • The application itself need to be stateless so the request can be dispatched purely based on load conditions and not other factors.
  • This strategy is even more effective when combining with Cloud computing as adding more VM instances into the farm is just an API call.
Data Partitioning
  • Spread your data into multiple DB so that data access workload can be distributed across multiple servers
  • By nature, data is stateful. So there must be a deterministic mechanism to dispatch data request to the server that host the data
  • Data partitioning mechanism also need to take into considerations the data access pattern. Data that need to be accessed together should be staying in the same server. A more sophisticated approach can migrate data continuously according to data access pattern shift.
Map / Reduce (Batch Parallel Processing)
  • The algorithm itself need to be parallelizable. This usually mean the steps of execution should be relatively independent of each other.
  • Google's Map/Reduce is a good framework for this model. There is also an open source Java framework Hadoop as well.
Content Delivery Network (Static Cache)
  • This is common for static media content. The idea is to create many copies of contents that are distributed geographically across servers.
  • User request will be routed to the server replica with close proxmity
Cache Engine (Dynamic Cache)
  • This is typically implemented as a lookup cache.
  • Memcached and EHCache are some of the popular caching packages
Resources Pool
  • DBSession and TCP connection are expensive to create, so reuse them across multiple requests
Asynchronous Processing
  • The service call in this example is better handled using an asynchronous processing model. This is typically done in 2 ways: Callback and Polling
  • In callback mode, the caller need to provide a response handler when making the call. Some kind of co-ordination may be required between the calling thread and the callback thread.
  • In polling mode, the call itself will return a "future" handle immediately. The caller can go off doing other things and later poll the "future" handle to see if the response if ready. In this model, there is no extra thread being created so no extra thread co-ordination is needed.
Implementation design considerations
  • Use efficient algorithms and data structure. Analyze the time (CPU) and space (memory) complexity for logic that are execute frequently (ie: hot spots). For example, carefully decide if hash table or binary tree should be use for lookup.
  • Analyze your concurrent access scenarios when multiple threads accessing shared data. Carefully analyze the synchronization scenario and make sure the locking is fine-grain enough. Also watch for any possibility of deadlock situation and how you detect or prevent them. Also consider using Lock-Free data structure (e.g. Java's Concurrent Package have a couple of them)
  • Analyze the memory usage patterns in your logic. Determine where new objects are created and where they are eligible for garbage collection. Be aware of the creation of a lot of short-lived temporary objects as they will put a high load on the Garbage Collector.

Tuesday, October 23, 2012

Spring Security

Five minute guide to Spring Security

Web.xml


 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/spring-app-servlet.xml
   /WEB-INF/applicationContext-security.xml
  </param-value>
 </context-param>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
 
    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>


Security.xml

    <http auto-config="true" access-denied-page="/accessDenied.jsp">
        <intercept-url pattern="/login.jsp*" filters="none"/>  
        <intercept-url pattern="/admin/editUser.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/admin/searchUsers.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/**.do" access="ROLE_USER,ROLE_ADMIN"  />
     <form-login authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home.do"/>
     <logout logout-success-url="/home.do"/>
    </http>
 
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="select username,authority from users where username=?"/>
    </authentication-provider>


Example:

 <security:global-method-security secured-annotations="enabled" />

 <security:http access-decision-manager-ref="accessDecisionManager">
  <security:access-denied-handler error-page="/signin.mvc?from=ACCESS_DENIED&amp;status=403"/>
  <security:form-login login-page="/signin.mvc?from=ACCESS_DENIED&amp;status=403" default-target-url="/home.mvc" />
  <security:custom-filter position="PRE_AUTH_FILTER" ref="customPreAuthFilter" />
  <security:logout logout-url="/signoutSpring.mvc" logout-success-url="/signin.mvc"/>

  <security:intercept-url pattern="/home.mvc*" access="APPLICATION-ADMIN,APPLICATION-CUSTOMERSERVICE" />
  <security:intercept-url pattern="/dashboard.mvc*" access="APPLICATION-ADMIN,APPLICATION-CUSTOMERSERVICE" />
  <security:intercept-url pattern="/orders.mvc*" access="APPLICATION-CUSTOMERSERVICE" />
 </security:http>

 <bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
  <property name="decisionVoters">
   <list>
    <ref bean="roleVoter" />
    <ref bean="authenticatedVoter" />
   </list>
  </property>
 </bean>

 <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
  <property name="rolePrefix" value="" />
 </bean>

 <bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter" />

Load Testing Tools



  • YouKit :  seems like YouKit handsdown beat JProfiler. It's low overhead, stable, easy to install on the JVM to be profiled (just one dll) and powerful.
  • JProfiler
  • for JDK >=1.6, jvisualvm comes bundled. 
             For "general purpose" profiling, jvisualvm is great. no extra building or setup or anything, just attach        and go. once you find something, you might need to go to one of these other apps to get real in depth coverage, though.

  • JProbe
  • JMeter

UML


Types of UML Diagrams



  • Class Diagram
Class Diagrams

  • Object Diagram:  describe the static structure of a system at a particular time
Object Diagrams
  • Use Case Diagaram

Use Case Diagrams


  • Sequence Diagram: describe interactions among classes in terms of an exchange of messages over time.

Sequence Diagrams

  • Component Diagram:  describe the organization of physical software components, including source code, run-time (binary) code, and executables.
Component Diagrams


  • Deployment Diagram: depict the physical resources in a system.
Deployment Diagrams


Monday, October 22, 2012

Spring MVC






web.xml

    <context-param>
        <description>Spring config files</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/beans/*.xml
        </param-value>
    </context-param>
    <!--
     The ContextLoaderListener listener loads the Spring ApplicationContext container beans from XML files. It uses the contextConfigLocation web application context parameter from above to know what
     XML bean files to load into the container.
     -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springMvcDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <!- If the location is not defined, it default to <servlet-Name>-servlet.xml -->
          <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/beans/dispatcherServlet.xml</param-value>
        </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvcDispatcher</servlet-name>
        <url-pattern>*.mvc</url-pattern>
    </servlet-mapping>

<servlet-name>-servlet.xml


Bean type Explanation
controllers Form the C part of the MVC.
handler mappings Handle the execution of a list of pre-processors and post-processors and controllers that will be executed if they match certain criteria (for example, a matching URL specified with the controller).
view resolvers Resolves view names to views.
locale resolver A locale resolver is a component capable of resolving the locale a client is using, in order to be able to offer internationalized views
Theme resolver A theme resolver is capable of resolving themes your web application can use, for example, to offer personalized layouts
multipart file resolver Contains functionality to process file uploads from HTML forms.
handler exception resolvers Contains functionality to map exceptions to views or implement other more complex exception handling code.


after locae resolver, theme resolver, multipart resolver

  1. An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering.
  2. If a model is returned, the view is rendered. If no model is returned, (may be due to a preprocessor or postprocessor intercepting the request, perhaps for security reasons), no view is rendered, because the request could already have been fulfilled


HandlerMapping 

First method:  DispatcherServlet enables the DefaultAnnotationHandlerMapping, which looks for @RequestMapping annotations on @Controllers. Typically, you do not need to override this default mapping, unless you need to override the default property values

   <!--
     URL to Controller mappings.
     Defines the mapping of a HTTP request URL to a Spring MVC controller class that is designated to handle the HTTP request.
     Add a property to this bean for each new URL/Controller combination that is defined. Like the property in blue.
     -->
    <bean id="urlToControllerMappings" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

        <property name="mappings">
            <props>
                <prop key="/users.html">userController</prop> 
                <prop key="/editUser.html">userFormController</prop>
                <prop key="/fileUpload.html">fileUploadController</prop>
                <prop key="/userReport.*">reportController</prop>
            </props>
        </property>

    </bean>

Second method:  <mvc:annotation-driven/>
This tag registers the DefaultAnnotationHandlerMapping and 
AnnotationMethodHandlerAdapter beans that are required for Spring MVC to 
dispatch requests to @Controllers




ViewResolver

Spring supports multiple view resolvers. Thus you can chain resolvers. You chain view resolvers by adding more than one resolver to your application context and, if necessary, by setting the order property to specify ordering. Remember, the higher the order property, the later the view resolver is positioned in the chain.


<bean id="viewResolver"
      class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="order" value="1"/>
<property name="basename" value="views"/> <property name="defaultParentView" value="parentView"/> </bean>

<bean id="excelViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
  <property name="order" value="2"/>
  <property name="location" value="/WEB-INF/views.xml"/>
</bean>

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="order" value="3"/>
<property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
Then order is ResourceBundleViewResolver, XmlViewResolver, InternalResourceViewResolver, UrlBasedViewResolver

Note: When chaining ViewResolvers, a UrlBasedViewResolver always needs to be last, as it will attempt to resolve any view name, no matter whether the underlying resource actually exists.

Note: use the InternalResourceViewResolver instead of the UrlBasedViewResolver, which remove the need to specify viewClass.

Spring Q&A


1.  What is IOC (or Dependency Injection)?

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

2. What are the different types of IOC (dependency injection) ?

There are three types of dependency injection:
  • Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
  • Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection (e.g. Avalon): Injection is done through an interface.
    Note: Spring supports only Constructor and Setter Injection

3. What are features of Spring ?

  • Spring contains and manages the life cycle and configuration of application objects.
  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI.
  • Allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.

4. What is Bean Factory ?

A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
  • BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
  • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

5. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.
6. What are the common implementations of the Application Context ?
   The three commonly used implementation of 'Application Context' are
  • ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .
    ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
  • FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
    ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
  • XmlWebApplicationContext : It loads context definition from an XML file contained within a web application. 

ApplicationContext.

BeanFactory
Here we can have more than one config files possible
In this only one config file or .xml file
Application contexts can publish events to beans that are registered as listeners
Doesn’t support.
Support internationalization (I18N) messages
It’s not
Support application life-cycle events, and validation.
Doesn’t support.
Support  many enterprise services such JNDI access, EJB integration, remoting
Doesn’t support.


7.  What is the typical Bean life cycle in Spring Bean Factory Container ?
   Bean life cycle in Spring Bean Factory Container is as follows:
  • The spring container finds the bean’s definition from the XML file and instantiates the bean.
  • Using the dependency injection, spring populates all of the properties as specified in the bean definition
  • If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
  • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
  • If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
  • If an init-method is specified for the bean, it will be called.
  • Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called. 

8. How to integrate Spring and Hibernate using HibernateDaoSupport?
   Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
  • Configure the Hibernate SessionFactory
  • Extend your DAO Implementation from HibernateDaoSupport
  • Wire in Transaction Support with AOP 

9. What do you mean by Aspect ?
   Aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).
1) schema-based approach   XML style.
 <aop:config>
<aop:pointcut id="cccdoperation"
         expression="(execution(* com.elleinfo.admin.service.*Service.save*(..))) or (execution(* com.elleinfo.admin.service.*Service.process*(..)))" />
<aop:advisor advice-ref="joeTxAdvice" pointcut-ref="cccdoperation" />
<aop:advisor advice-ref="cccdTxAdvice" pointcut-ref="cccdoperation" />
<aop:advisor advice-ref="appsTxAdvice" pointcut-ref="cccdoperation" />
</aop:config>


<aop:config>
  <aop:aspect id="myAspect" ref="aBean">
    <aop:pointcut id="businessService" 
          expression="execution(* com.xyz.myapp.service.*.*(..)) &amp;&amp; this(service)"/>
    <aop:before pointcut-ref="businessService" method="monitor"/>
    ...
    
  </aop:aspect>

</aop:config>
2)    @Aspect {
               @Pointcut
               @Before/ @Around /@AfterReturning / @AfterThrowing/ @After
        }


The XML style has two disadvantages.

  1. It does not fully encapsulate the implementation of the requirement it addresses in a single place.
  2. The XML style is slightly more limited in what it can express than the @AspectJ style: only the "singleton" aspect instantiation model is supported, and it is not possible to combine named pointcuts declared in XML.
@Aspect reuqires Java 5.
It is ok to mix both.

10. Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction management ?
   The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual method level. It is possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are:
  • Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only.
  • The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs.
  • The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided.
  • The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly().
  • The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers. 


11: What is difference between singleton and prototype bean?
Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.
 all the beans in spring framework are by default singleton beans

.

12. How many modules are there in Spring? What are they?
       Spring comprises of seven modules. They are. spring.core, spring.beans, spring.aop, sping.context, spring.jdbc, spring.orm, spring.web, spring.transaction, spring.aspect.
  • The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.
  • The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
  • The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
  • The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
  • The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.
  • The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
  • The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
13. What are the different types of events related to Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.springframework.context.Application-Event. They are
  • ContextClosedEvent – This is fired when the context is closed.
  • ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
  • RequestHandledEvent – This is fired when the web context handles any request.
14.  What is the Exception class related to all the exceptions that are thrown in spring applications?
DataAccessException - org.springframework.dao.DataAccessException


15.  list of new features for Spring 3.0

  • Spring Expression Language.can be used when defining XML and Annotation based bean definitions。 @Value("#{systemProperties.databaseName}")
  • IoC enhancements/Java based bean metadata: @Configuration, @Bean, @Value
  • General-purpose type conversion system and field formatting system
  • Object to XML mapping functionality (OXM) moved from Spring Web Services project
  • Comprehensive REST support
  • @MVC additions
  • Declarative model validation
  • Early support for Java EE 6
  • Embedded database support

To be Continued.

Wednesday, October 17, 2012

GWT(1)

GWT's compiler generating JavaScript from your client-side Java code.


A compiled GWT application consists of fragments of HTML, XML, and JavaScript. However, these are pretty much indecipherable, and the compiled application is best regarded as a black box -- GWT's equivalent of Java bytecode.

more like AWT, SWING

can add css style

In GWT terminology, client code communicates with services running on the Web server. RPC calls in GWT are between JavaScript code (client) and Java code (server)

JavaScript Native Interface (JSNI):  JSNI lets you make JavaScript calls directly from GWT client Java code. JSNI uses a cunning combination of the Java language's native keyword and JavaScript embedded in a special java comment block.


Because GWT services are just HTTP servlets, they can be integrated easily into Struts or SpringMVC, for example, and placed behind authentication filters.


advantage:

  • Share the same validation class between both tiers
  • Unite testing for client side code.

JAXB vs XMLBeans



Both are JAVA to XML mapping tools.

Both XMLBeans and JAXB produce Java models that make it easy for developers to interact with XML.  XMLBeans produces a set of Java interfaces that are backed by implementation classes. The JAXB model however is annotated POJOs which has the following advantages:
  • JPA annotations could easily be applied to the JAXB model enabling the model to be persisted in a relational database.
  • Once generated the JAXB model could be modified to handle changes in the XML schema, the XMLBeans model would need to be regenerated.
  • Starting with Java SE 6 no additional compile/runtime dependencies are required for the JAXB model. 
  • There are multiple JAXB implementations available:  EclipseLink MOXy, Metro, Apache JaxMe, etc.
  • JAXB is the standard binding layer for JAX-WS (SOAP) and JAX-RS (RESTful) Web Services

JSTL

  • JSP without JSTL
<UL>
<% for(int i=0; i<messages.length; i++) {
String message = messages[i];
%>
    <LI><%= message %>
<% } %>
</UL>
  • JSP with JSTL
<UL>
<c:forEach var="message" items="${messages}">
    <LI>${message}
</c:forEach>
</UL>

<c:out value="${foo}" default="${calculatedValue}"/>

<c:if test="${someTest}">
    Content
</c:if>

<c:choose>
    <c:when test="test1">Content1</c:when>
    <c:when test="test2">Content2</c:when>
    ...
    <c:when test="testN">ContentN</c:when>
    <c:otherwise>Default Content</c:otherwise>
</c:choose>

<c:import>
  • Read content from arbitrary URLs
  1. Insert into page
  2. Store in variable
  3. Or make accessible via a reader
  • Unlike <jsp:include>, not restricted to own system
<c:redirect> Redirects response to specified URL
<c:param>
– Encodes a request parameter and adds it to a URL
– May be used within body of <c:import> or <c:redirect>

<fmt:formatNumber>  Formats a numeric value as a number, currency value, or
percent, in a locale-specific manner
<fmt:parseNumber> Reads string representations of number, currency value, or percent
<fmt:formatDate>
<fmt:parseDate>
<fmt:timeZone>
<fmt:setTimeZone>

Can build your own custom tags based on JSTL tags.

Hibernate Q&A

Spring Support

UserDAOHibernate extends org.springframework.orm.hibernate.support.HibernateDaoSupport


    <bean id="userDAO" class="org.appfuse.dao.hibernate.UserDAOHibernate">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
    </bean>    


    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
        <property name="dataSource"><ref local="dataSource"/></property>
        <property name="mappingResources">
            <list>
                <value>org/appfuse/model/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">net.sf.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
        </property>
    </bean>


    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
    </bean>
    <bean id="userManagerTarget" class="org.appfuse.service.impl.UserManagerImpl">
        <property name="userDAO"><ref local="userDAO"/></property>
    </bean>

    <bean id="userManager" 
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager"><ref local="transactionManager"/></property>
        <property name="target"><ref local="userManagerTarget"/></property>
        <property name="transactionAttributes">
            <props>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
                <prop key="remove*">PROPAGATION_REQUIRED</prop>
                <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
            </props>
        </property>
    </bean>

What are the key benifits of Hibernate?

There are several benefits of using Hibernate 
  • Powerful object-oriented hibernate query language
  • Transparent persistence based on POJOs without byte code processing
  • Descriptive O/R Mapping through mapping file.
  • Automatic primary key generation 
  • Hibernate cache : Session Level, Query and Second level cache.
  • Performance: Lazy initialization, Outer join fetching, Batch fetching

What type of transaction management is supported in hibernate? 

Non-Managed transaction:

     <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

Managed transaction using JTA:
    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
         <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

What is lazy loading and how do you achieve that in hibernate?

Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.


Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.


What are the different fetching strategy in Hibernate?

Hibernate3 defines the following fetching strategies:
  • Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
  • Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
  • Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
  • Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
       For more details read short primer on fetching strategy at http://www.hibernate.org/315.html

What are different types of cache hibernate supports ?

Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects:
  1. First-level cache: First-level cache is associated with the Session object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.
  2. Second-level cache: second-level cache is associated with the Session Factory object. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. 
  3. Query-level cache: In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache.
Hibernate supports the following open-source cache implementations out-of-the-box:
    • EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
    • OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
    • SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
    • JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
    • Commercial Tangosol Coherence cache.

What are the different caching strategies?


  • Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
  • Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
  • Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
  • Transactional: This is a fully transactional cache that may be used only in a JTA environment.

How do you configure 2nd level cach in hibernate?

To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
        </session-factory>
    </hibernate-configuration>
By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.

What is the difference between sorted and ordered collection in hibernate?


A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
What are the types of inheritence models and describe how they work like vertical inheritence and horizontal?
There are three types of inheritance mapping in hibernate :
Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
  1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
  2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
  3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker.


What is the difference between the session.get() method and the session.load() method?


Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.


What is the difference between the session.update() method and the session.lock() method?


Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.
How would you reatach detached objects to a session when the same object has already been loaded into the session?
You can use the session.merge() method call.


What are the general considerations or best practices for defining your Hibernate persistent classes?


  1. You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables. 
  2. You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object. 
  3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 
  4. The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 
  5. Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files. 

Tuesday, October 16, 2012

Behavioral Design Patterns

Behavioral Patterns

Mediator:-Defines simplified communication between classes.
Memento:-Capture and restore an object's internal state.
Interpreter:- A way to include language elements in a program.
Iterator:-Sequentially access the elements of a collection.
Chain of Resp: - A way of passing a request between a chain of objects.
Command:-Encapsulate a command request as an object.
State:-Alter an object's behavior when its state changes.
Strategy:-Encapsulates an algorithm inside a class.
Observer: - A way of notifying change to a number of classes.
Template Method:-Defer the exact steps of an algorithm to a subclass.
Visitor:-Defines a new operation to a class without change.


  • Mediator


Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.
  • Memento

Memento pattern helps us to store a snapshot which can be reverted at any moment of time by the object.



  • Command

Command pattern moves the action into objects. These objects when executed actually execute the command. Every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in ‘clsExecuteExit’ , open action is wrapped in ‘clsExecuteOpen’, print action is wrapped in ‘clsExecutePrint’ and so on. All these classes are inherited from a common interface ‘IExecute’.

Object and Command

Invoker and the clean client


  • State



  • Observer


Observer client code
 

  • Template



/**
 * An abstract class that is common to several games in
 * which players play against the others, but only one is
 * playing at a given time.
 */
 
abstract class Game {
 
    protected int playersCount;
    abstract void initializeGame();
    abstract void makePlay(int player);
    abstract boolean endOfGame();
    abstract void printWinner();
 
    /* A template method : */
    public final void playOneGame(int playersCount) {
        this.playersCount = playersCount;
        initializeGame();
        int j = 0;
        while (!endOfGame()) {
            makePlay(j);
            j = (j + 1) % playersCount;
        }
        printWinner();
    }}
 
//Now we can extend this class in order //to implement actual games:
 
class Monopoly extends Game {
 
    /* Implementation of necessary concrete methods */
    void initializeGame() {
        // Initialize players
        // Initialize money
    }
    void makePlay(int player) {
        // Process one turn of player
    }
    boolean endOfGame() {
        // Return true if game is over 
        // according to Monopoly rules
    }
    void printWinner() {
        // Display who won
    }
    /* Specific declarations for the Monopoly game. */
 
    // ...}
 
class Chess extends Game {
 
    /* Implementation of necessary concrete methods */
    void initializeGame() {
        // Initialize players
        // Put the pieces on the board
    }
    void makePlay(int player) {
        // Process a turn for the player
    }
    boolean endOfGame() {
        // Return true if in Checkmate or 
        // Stalemate has been reached
    }
    void printWinner() {
        // Display the winning player
    }
    /* Specific declarations for the chess game. */
 
    // ...}
 
 
  • Visitor


Visitor Class


Object Codes
 
Client Codes