Thursday, December 27, 2012

Git Merge and Stash


When you are in the middle of something, you learn that there are upstream changes that are possibly relevant to what you are doing. Two ways to solve it

Method 1:


PRE-MERGE CHECKS
Before applying outside changes, you should get your own work in good shape and committed locally, so it will not be clobbered if there are conflicts. git pull and git merge will stop without doing anything when local uncommitted changes overlap with files that git pull/git merge may need to update.
To avoid recording unrelated changes in the merge commit, git pull and git merge will also abort if there are any changes registered in the index relative to the HEAD commit. (One exception is when the changed index entries are in the state that would result from the merge already.)
Warning: Running git merge with uncommitted changes is discouraged: while possible, it leaves you in a state that is hard to back out of in the case of a conflict.


After commit, you can do a git pull or merge.
If seeing a conflict, you can do two things:
  • Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git merge --abort can be used for this.
  • Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.

$ git commit
$ git pull
$ git add
$ git commit


Method 2:


Pulling into a dirty tree
When you are in the middle of something, you learn that there are upstream changes that are possibly relevant to what you are doing. When your local changes do not conflict with the changes in the upstream, a simplegit pull will let you move forward.
However, there are cases in which your local changes do conflict with the upstream changes, and git pull refuses to overwrite your changes. In such a case, you can stash your changes away, perform a pull, and then unstash, like this:
$ git pull
 ...
file foobar not up to date, cannot merge.
$ git stash
$ git pull
$ git stash pop
 that basic stash support is now available in the "Git Repositories" view.
git stash ["Stash Changes" operation on right-click menu]
git stash list [the stashes are listed directly in this view under "Stashed Commits"]
git stash apply ["Apply stashed changes" from the right-click menu of items in "Stashed Commits"]
git stash show [double-click a listed stash to see it in a commit view]

Thursday, December 20, 2012

EGit: How to resolve a merge conflict


To resolve a merge conflict, two ways.


Using Merge Tool

  • select the top level resource showing the red conflict label decorator
  • click Team > Merge Tool
  • select the merge mode Use HEAD (the last local version) of conflicting files and click OK
Image:Egit-0.10-select-merge-mode.png
  • the merge editor opens showing the working tree version in the left pane and the version to be merged in the right pane
Image:Egit-0.10-merge-tool.png
  • edit the working tree version until you are happy with it
  • Team > Add the merged resource to mark the conflict as resolved
  • commit the merge commit via Team > Commit



Manual conflict resolution
To resolve a conflict you have to do the following steps:
§  Navigate to the conflicting resource
§  Edit the content of the conflicting resource
§  Tell EGit that the conflict is resolved with Team > Add
§  Commit the conflict resolution with Team > Commit

Spring NameSpaces: No version numbers in schema references

No version numbers in schema references

Instead of:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- <bean/> definitions here -->

</beans>

Use this Config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- <bean/> definitions here -->

</beans>

Spring automatically picks the highest version available from the project dependencies (jars). As a project evolves, the Spring version will be updated, we won’t have to maintain all the XML config files to see the new features.

Tuesday, December 18, 2012

Eclipse Configuration: Use spaces for tabs


For the default text editor:
  • General > Editors > Text Editors > Insert spaces for tabs (check it)
For PHP:
  • PHP > Code Style > Formatter > Tab policy (choose "spaces")
  • PHP > Code Style > Formatter > Indentation size (set to 4)
For CSS:
  • Web > CSS > Editor > Indent using spaces (select it)
  • Web > CSS > Editor > Indentation size (set to 4)
For HTML:
  • Web > HTML > Editor > Indent using spaces (select it)
  • Web > HTML > Editor > Indentation size (set to 4)
For XML:
  • XML > XML Files > Editor > Indent using spaces (select it)
  • XML > XML Files > Editor > Indentation size (set to 4)
For Javascript:
  • Javascript > Preferences > Code Style > Formatter > Edit > Indentation (choose "spaces only")
  • Rename the formatter settings profile to save it
For Java:
  • Java > Preferences > Code Style > Formatter > Edit > Indentation (choose "spaces only")
  • Rename the formatter settings profile to save it

Friday, December 14, 2012

Spring Integration:Multiple methods routing




  <int:chain
      input-channel="inboundRequestChannel"
      output-channel="outboundResponseChannel">
    <int:header-enricher>
      <int:header name="service" ref="data-access.service" />
    </int:header-enricher>
    <int:service-activator>
       <int-groovy:script>headers['service']."${headers['METHOD_NAME']}"(payload)</int-groovy:script>
    </int:service-activator>
  </int:chain>

  <!-- The data access services instance -->
  <bean id="data-access.service" class="TestPackagesService" />


  <int:gateway id="gateway"
               service-interface="TestPackagesServiceGateway"
               default-request-channel="inboundRequestChannel"
               default-reply-channel="outboundResponseChannel"
               default-reply-timeout="10000"
               error-channel=“outboundErrorChannel">

    <int:method name="getTestSpec">
      <int:header name="METHOD_NAME" value="getTestSpec" />
    </int:method>
    <int:method name="saveTestSpec">
      <int:header name="METHOD_NAME" value="saveTestSpec" />
    </int:method>

  </int:gateway>






Friday, December 7, 2012

How to define Context-root for a webapp in Eclipse


To define the context-root for a webapp when deplopyed to server on eclipse, specify it by Project -> Properties -> WebProject Settings.

The properties is saved under .settings/org.eclipse.wst.common.component
<property name="context-root" value="test-package.rest-services"/>

When deployed to server, server.xml will contain

<Host ....>
            <Context docBase="test-package.rest-services" path="/test-package.rest-services" ..../>

</Host>


What JRE will a new Maven project in Eclipse use by default and how to change it?

m2eclipse ignores what you configure for the Eclipse default. It will always use 1.5 by default. 

So if you want a Maven project to be configured to use Java 1.6 settings when imported under Eclipse, configure the maven-compiler-plugin appropriately:


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.1</version>
  <configuration>
    <source>1.6</source>
    <target>1.6</target>
  </configuration>
</plugin>


Wednesday, November 21, 2012

Maven Failsafe Plugin

The Failsafe Plugin is designed to run integration tests while the Surefire Plugins is designed to run unit tests.


The Maven lifecycle has four phases for running integration tests:
  • pre-integration-test for setting up the integration test environment.
  • integration-test for running the integration tests.
  • post-integration-test for tearing down the integration test environment.
  • verify for checking the results of the integration tests.
The Failsafe Plugin is used during the integration-test and verify phases of the build lifecycle to execute the integration tests of an application. The Failsafe Plugin will not fail the build during the integration-test phase thus enabling the post-integration-test phase to execute.


The Failsafe Plugin generates reports in 2 different file formats:
  • Plain text files (*.txt)
  • XML files (*.xml)
By default, these files are generated at ${basedir}/target/failsafe-reports.
The Failsafe Plugin has only 2 goals:

    <profile>
      <id>integration-test</id>

      <build>
        <plugins>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>${maven-failsafe-plugin.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

Tuesday, November 13, 2012

"user.home" vs userprofile

Windows 7: user.home =
The Java runtime looks at the Registrykey
"[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersio
n\Explorer\Shell Folders\Desktop]"
and strips the last directory of this value.

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.