Monday, December 26, 2016

Design Patterns in Java

Design patterns provide architectural solutions to common software design problems. These patterns have emerged over time through the experience and insights of developers. This section introduces some basic patterns that might prove helpful in the context of developing web applications.
You can also find information on these patterns by visiting the following website, which is part of the Java Developer Connection:
The patterns listed below are of particular relevance to the building of web applications. More details are provided in the sections that follow:
  • Front Controller. Coordinates handling of incoming requests. See Front Controllers for more information.
    • Dispatcher. A subpattern of the Front Controller, describing how to control which view the user sees. See Dispatchers for details.
    • View Helper. A subpattern, in this case, to the Front Controller, encapsulating the processing functions, or business rules, such as data access or business logic. See Helpers for more.
  • Composite View. (also called a template) Creates an aggregate view from subcomponents. See Composite Views for additional information.
A full treatment of the use of design patterns in web applications can be found in Core J2EE Patterns by Deepak, Crupi, and Malks. See for more on this book.

Front Controllers

Front Controllers are responsible for routing incoming user requests. In addition, they can enforce navigation in web applications. When users are in sections of a web application where they can browse freely, the Front Controller simply relays the request to the appropriate page. For example, in an e-commerce application, the customer browses through a product catalog. In controlled sections in which users must follow a specific path through the application, the Front Controller can validate the incoming requests and route them accordingly. For example, a customer wants to buy the items in a shopping cart. That customer is required to follow a particular route to complete the purchase successfully.
A Front Controller provides a single entry point through which requests for several resources in a web application pass. One Front Controller might handle all requests to the application. Several Front Controllers might handle requests for portions of the application. Typically implemented as servlets, Front Controllers are frequently used for the following tasks:
  • Controlling page flow and navigation
  • Accessing and managing model data
  • Handling business processing
  • Accessing relevant data to GUI presentation, for example a user profile
Front Controllers can reduce duplication of code in JSP pages, especially in cases where several resources require the same processing. Examples might include ensuring that the user's profile has been found, obtaining the data corresponding to a product ID, and so forth.
You can maintain and control a web application more effectively if you funnel all client requests through a Front Controller. Functions such as view selection, security, and template creation can be centralized in this design pattern. The Front Controller applies these functions consistently across all pages or views. Consequently, when the behavior of these functions needs to change, only the Front Controller and its helper classes need to be changed. They constitute a relatively small portion of the application.
In the two-tier form of a web application, shown in FIGURE 3-1, the recommended approach is for the Front Controller to deal with user requests. The Front Controller also determines which presentation element is to be shown to users and which data is to be used for the chosen presentation. This strategy contrasts to the traditional approach in which each user request must be mapped to a separate view.
Note that Front Controllers do not have to route requests directly to Views. You can chain them so that, for instance, one Front Controller accesses user profile information. Then it could forward that profile to another Front Controller.
 FIGURE 3-1 Determining the User View With a Front Controller
Figure showing contrast between traditional and recommended approaches to determining user views.[ D ]
For information on creating a servlet as a Front Controller using the Forte for Java IDE, see Using the Servlet as a Front Controller.

Dispatchers

Typically, the Front Controller coordinates user navigation, using the Dispatcher subpattern for this purpose. As shown in FIGURE 3-2, the Front Controller processes a request. Perhaps the user might want to check out items in a shopping cart of an e-commerce application.
 FIGURE 3-2 Dispatching as a Function of a Front Controller
Figure showing dispatcher communication with Front Controller to route user requests to appropriate view.[ D ]
Dispatcher code could be contained within the Front Controller servlet, or in a separate class. In practice, the Dispatcher instructs the Front Controller where to forward the request. In the Front Controller design pattern, the Dispatcher encapsulates the behavior that controls which views the user sees.
View Mappers
When web resources differ based on the type of client, you can use a View Mapper to assist the Dispatcher mechanism. Such clients could include a web browser, personal desktop assistant, or cell phone. For instance, you might be developing a web application that retrieves information about waves and tides. In this situation, your users might want to view this data from desktop personal computers or cell phones. Instead of dispatching to a single JSP page, your web application might use the View Mapper to send a different JSP page, depending on the type of client.
1. For example, when your web application receives incoming requests, it routes them to a Front Controller servlet.
2. The Front Controller retrieves the appropriate data using a Helper bean.
3. It then determines the appropriate view type based on the client within the View Mapper.
4. Based on input from the View Mapper, the Dispatcher returns the view information to the Front Controller.
5. The application subsequently forwards the request to the specific view intended for the user's client, as shown in FIGURE 3-3.
 FIGURE 3-3 Using View Mappers
In your wave and tide application, you might not initially know whether you wanted to display the information on a PDA or on a phone. In this case, the View Mapper would enable you to create alternative objects or families of objects.
Use View Mappers not only to redirect information to different devices, but to different locales or different views.

Helpers

The Front Controller servlet can easily become quite large and unwieldy. Therefore, use Helper classes to break out specific features and make the application easier to build and maintain. Here are some tasks that can be encapsulated as Helper classes:
  • Retrieval of content from a file, another website, or even a web service
  • Validation of user-entered information
  • If the Front Controller needs to delegate processing of business logic, it can use Helpers for this purpose, as shown in FIGURE 3-4.
  • Data processing
 FIGURE 3-4 Delegating Processing of Business Logic With Helpers
You can implement Helpers as regular Java classes. See Using Additional Classes or Beans for details.

Composite Views

Composite View is a design pattern that creates an aggregate view from component views. Component views might include dynamic, modular portions of the page. This design pattern pertains to web application design when you are creating a view from numerous subviews. Complex web pages frequently consist of content derived from various resources.The layout of the page is managed independently of the content of its subviews. For instance, a view might have subviews like Navigation, Search, Feature Story, and Headline. An included view is a subview that is one portion of a greater whole. The included view might, in turn, consist of subviews, as shown in FIGURE 3-5.
 FIGURE 3-5 Managing Content Independently From Layout With a Composite View


When creating a Composite View, you can include static content and dynamic content. Static content might consist of an HTML file. Dynamic content might be something like a JSP page. You can also include content at JSP translation time and runtime.
For information on using the Forte for Java IDE to implement a Composite View pattern, see Creating a Composite View Template.

View Creation Helpers

Typically, web pages need to be reused and maintained over time. Use View Creation Helper beans when you need to display data as it is received. Examples of such information might be tables or sets of links. A View Creation Helper can be any bean or Java class. However, since they are specifically geared toward presentation in JSP pages, View Creation Helpers are typically tag handler classes.
The View Creation Helper class provides a way to avoid placing Java code related to specific presentation features directly in the JSP file or Front Controller servlet. For instance, your web application might contain a catalog search that results in certain display results. In this situation, encapsulate the behavior into JSP tags, as shown in FIGURE 3-6:
 FIGURE 3-6 Using View Creation Helpers
Similarly, your web application might require that logic to format data within its views. View Creation Helper beans can be obtained and used in the same manner as any other beans from within a JSP file. See Using Additional Classes or Beans for more information on using the IDE with beans.

Model Objects

Model objects are Java objects that encapsulate application data inside a web application. For instance, in a shopcart e-commerce application, a model object might be an abstraction for a plush toy. Examples of the data would include the toy's name, description, price, stock on hand, and so forth. This information is typically retrieved from database data is inefficient. Hence, you must design session data carefully. For additional information on accessing databases with JDBC, see Using Java DataBase Connectivity, a volume in the Forte for Java Programming Series.
The model object can be passed to the JSP file from a Front Controller servlet two ways:
  • Through a request attribute
  • By placement in the web application's session data
If it makes sense for the application to store product data for a term longer than a single request, then this information can be placed in the application's session.
Typically, all requests from a single user go to a single server where the session information is stored. In a load-balancing system, a single user's requests might be routed to different servers. Hence, session information for a particular user must be shared among servers. This situation can result in slower performance if the web application must synchronize access to the session data.
If the application is to be deployed on a load-balancing system, distributing session data is inefficient. Hence, you must design session data carefully.


Frameworks

Frameworks are sets of design patterns, APIs, and runtime implementations intended to simplify the design and coding process for building new applications. Examples of frameworks are Struts, JATO, and JavaServer Faces, described in the subsequent sections.
Framework designers factor out common functions from existing applications and implement them using appropriate design patterns. A framework enables application developers to concentrate on the unique feature set required by their applications.
Web application frameworks typically provide support for functions such as:
  • Navigating among the application's pages
  • Building forms that accept input from the end user
  • Creating views to display information to the end user
  • Providing access to processing and data with JavaBeans and Enterprise JavaBeans
  • Supplying database access to incorporate information directly from database systems
  • Using directory services such as JNDI (Java Naming and Directory Interface) and LDAP (Lightweight Directory Access Protocol)
  • Providing secure and non-secure access through authentication mechanisms

Java Interview Latest Questions

      1) How hash map works internally.
Refer homeshop 18 post

2) Hbm cache – difference
First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.


First-level cache - First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

3) What is Connection pooling?
Ans:
import java.sql.*;
import javax.sql.*;

public class JDBCServlet extends HttpServlet {

  private DataSource datasource;

  public void init(ServletConfig config) throws ServletException {
    try {
      // Look up the JNDI data source only once at init time
      Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
      datasource = (DataSource) envCtx.lookup("jdbc/MyDataSource");
    }
    catch (NamingException e) {
      e.printStackTrace();
    }
  }

  private Connection getConnection() throws SQLException {
    return datasource.getConnection();
  }

  public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
    Connection connection=null;
    try {
      connection = getConnection();
      ..<do JDBC work>..
    } 
    catch (SQLException sqlException) {
      sqlException.printStackTrace();
    }
    finally {
      if (connection != null) 
        try {connection.close();} catch (SQLException e) {}
      }
    }
  }
}

4) Explain Spring bean life cycle.

Here is the content of HelloWorld.java file:
package com.dev21century;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}
Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.
package com.dev21century;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {

      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}
Following is the configuration file Beans.xml required for init and destroy methods:
<?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-3.0.xsd">

   <bean id="helloWorld"
       class="com.dev21century.HelloWorld"
       init-method="init" destroy-method="destroy">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:
Bean is going through init.
Your Message : Hello World!
Bean will destroy now.
Default initialization and destroy methods:
If you have too many beans having initialization and or destroy methods with the same name, you don't need to declare init-method and destroy-methodon each individual bean. Instead framework provides the flexibility to configure such situation using default-init-method and default-destroy-methodattributes on the <beans> element as follows:
<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-3.0.xsd"
    default-init-method="init"
    default-destroy-method="destroy">

   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

</beans>

5) XmlBeanFactory uses
Ans: ApplicationContext is a sub-interface of BeanFactory.You can use this way
public class SpringHelloWorldTest {
    public static void main(String[] args) {
        ApplicationContext context= new ClassPathXmlApplicationContext("SpringHelloWorld.xml");
        Spring3HelloWorld myBean= (Spring3HelloWorld) context.getBean("Spring3HelloWorldBean");
        myBean.sayHello();
    }
}

6) Data format used in restful. – json,text plain etc.
7) What is Db deadlock
Ans:

 In a database, a deadlock is a situation in which two or more transactions are waiting for one another to give up locks. For example, Transaction A might hold a lock on some rows in the Accounts table and needs to update some rows in the Orders table to finish.



8) Restful and soap difference.
Ans:


No.
SOAP
REST
1)
SOAP is a protocol.
REST is an architectural style.
2)
SOAP stands for Simple Object Access Protocol.
REST stands for REpresentational State Transfer.
3)
SOAP can't use REST because it is a protocol.
REST can use SOAP web services   because it is a concept
and can use any protocol like HTTP, SOAP.
4)
SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business logic.
5)
JAX-WS is the java API for SOAP web services.
JAX-RS is the java API for RESTful web services.
6)
SOAP defines standards to be strictly followed.
REST does not define too much standards like SOAP.
7)
SOAP requires more bandwidth and resource than REST.
REST requires less bandwidth and resource than SOAP.
8)
SOAP defines its own security.
RESTful web services inherits security measures from
 the underlying transport.
9)
SOAP permits XML data format only.
REST permits different data format such as Plain text,
HTML, XML, JSON etc.
10)
SOAP is less preferred than REST.
REST more preferred than SOAP.













































      9) Explain Cookie and request data?
     10) 
Spring security implementation:
Web.xml entries:
Spring security implementation:
applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
       
      <!-- Scan this package for all config annotations -->
<context:component-scan base-package="com.ge.aviation.scit.supplier360.rest,com.ge.aviation.scit.supplier360.model,com.ge.aviation.scit.userservice.data,com.ge.aviation.scit.supplier360.util" />
<context:annotation-config />
<security:http use-expressions="true" auto-config="false" entry-point-ref="http403EntryPoint" >
<security:intercept-url pattern="/rest/supplier/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/details/**" access="hasRole('S_PROFILE_USER')"/>
<security:intercept-url pattern="/rest/supplier/update/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/reCalculateRating/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/finalSupplierRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/finalMetricRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/metricDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/updateMetric/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplierProfile/supplierInfo/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/yellowPage/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/sprofileUserAuth/userAuth/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/GEAEPQEReport/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersNonQmReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/DSQRReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOrganizationData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedProcessCodes/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCountryData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersStateData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCityData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersZipData/**" access="hasRole('S_PROFILE_USER')" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</security:http>
   
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
        <property name="principalRequestHeader" value="SM_USER"/>
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>   
   
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService">
            <bean id="userDetailsServiceWrapper"  class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="supplierUserDetailsService"/>
</bean>
</property>
</bean>
   
<bean id="supplierUserDetailsService" class="com.ge.aviation.scit.supplier360.security.SupplierUserDetailsService">  
       <property name="emf" ref="emf"></property>
</bean>
   
   
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></bean>
<!--  tried options  -->
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
       <property name="defaultTargetUrl" value="/home.do" />
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="jpaSupplier360"/>
</bean>

<!--<jee:jndi-lookup id="emf" jndi-name="java:jboss/datasources/nmsDS"/>
  -->
 <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="emf"/>
 </bean>
</beans>
applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
        <!-- Scan this package for all config annotations -->
<context:component-scan base-package="com.ge.aviation.scit.supplier360.rest,com.ge.aviation.scit.supplier360.model,com.ge.aviation.scit.userservice.data,com.ge.aviation.scit.supplier360.util" />
    
<context:annotation-config />
      
<security:http use-expressions="true" auto-config="false" entry-point-ref="http403EntryPoint" >
       
<security:intercept-url pattern="/rest/supplier/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/details/**" access="hasRole('S_PROFILE_USER')"/>
<security:intercept-url pattern="/rest/supplier/update/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/reCalculateRating/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplier/finalSupplierRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/finalMetricRating/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/metricDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplier/updateMetric/**" access="hasRole('S_PROFILE_USER') and hasRole('PQE')" />
<security:intercept-url pattern="/rest/supplierProfile/supplierInfo/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/search/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/supplierProfile/yellowPage/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/sprofileUserAuth/userAuth/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/GEAEPQEReport/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/suppliersNonQmReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/SupplierQMReport/DSQRReportDetails/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOrganizationData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedProcessCodes/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCountryData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersStateData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersCityData/**" access="hasRole('S_PROFILE_USER')" />
<security:intercept-url pattern="/rest/preloadedDataAdvanceSearch/preloadedOthersZipData/**" access="hasRole('S_PROFILE_USER')" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</security:http>

   
<bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
        <property name="principalRequestHeader" value="SM_USER"/>
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>
   
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>   
   
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService">
            <bean id="userDetailsServiceWrapper"  class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="supplierUserDetailsService"/>
</bean>
</property>
</bean><bean id="supplierUserDetailsService" class="com.ge.aviation.scit.supplier360.security.SupplierUserDetailsService">  
       <property name="emf" ref="emf"></property>
</bean>
   
   
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></bean>
<!--  tried options  -->
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
       <property name="defaultTargetUrl" value="/home.do" />
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="jpaSupplier360"/>
</bean>

<!--<jee:jndi-lookup id="emf" jndi-name="java:jboss/datasources/nmsDS"/>
  -->
 <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="emf"/>
 </bean>
</beans>



import java.util.LinkedList;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ge.aviation.scit.supplier360.util.LDAPAppUser;
import com.ge.aviation.scit.supplier360.util.NmsConstants;
import com.ge.aviation.scit.supplier360.util.UserSSONTSingleton;
import com.ge.aviation.scit.userservice.data.AZLdapUserDao;
import com.ge.aviation.scit.userservice.model.AZLdapUser;
@Service("SupplierUserDetailsService")
public class SupplierUserDetailsService implements UserDetailsService
{
       EntityManagerFactory emf;
       @Inject
       LDAPAppUser ldapAppUser  ;
       @Inject
       AZLdapUserDao ldapRepository  ;
       @Autowired
       public void setEmf(EntityManagerFactory emf){
              this.emf = emf;
       }
       @Override
       @Transactional(readOnly=true)
       public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException
    {
              System.out.println("Check...Inside loadUserByUsername username:"+username);
              GrantedAuthority authority[] = new GrantedAuthority[2];
       authority[0] = new GrantedAuthorityImpl("NONE_PROFILE_USER");
       authority[1] = new GrantedAuthorityImpl("NONE_PROFILE_USER");
      
       UserSSONTSingleton  userSSONTSingleton  = UserSSONTSingleton.getInstance();
      
       AZLdapUser ldapUser = ldapRepository.findBySSO(username);

       //Get this user details from database and set its roles also here
              if(ldapUser != null)
              {
                     String userId = ldapUser.getUserId();
                     //Gupendra 11202014 - added last parameter
                     userSSONTSingleton.setSSONTMap(username, userId, ldapUser.getFirstName() + " " + ldapUser.getLastName());
                     if(ldapAppUser.isValidUser(ldapUser)){
                           authority[0] = new GrantedAuthorityImpl("S_PROFILE_USER");
                     userSSONTSingleton.setSsoAppAccessMap(username, true);
                     if(isPqeRoleUser(userId)){
                            authority[1] = new GrantedAuthorityImpl("PQE");
                     }
                     //To check logged user is supplier or not
                     LinkedList<String> listSupplerIds = new LinkedList<String>();
                     boolean isSupplier = false;
                     listSupplerIds = ldapUser.getGeaeaeecsupplierid();
                     isSupplier = ldapAppUser.checkGeaeaeecsupplierid(listSupplerIds);
                     if(isSupplier)
                     {
                            userSSONTSingleton.setNtIDSupplierMap(userId,isSupplier);
                            userSSONTSingleton.setNtIDSupplierIdsMap(userId,listSupplerIds);
                     }else{
                            userSSONTSingleton.setNtIDSupplierMap(userId,isSupplier);
                     }
                    
                     }else{
                           userSSONTSingleton.setSsoAppAccessMap(username, false);      
                     }
              }
        @SuppressWarnings("deprecation")
       UserDetails user = new User(username, "password", truetruetruetrue,authority);
      return user;
    }
       private boolean isPqeRoleUser(String username){
              try{
              if(emf== null){
                     return false;
              }
              EntityManager em = emf.createEntityManager();
              if(em== null){
                     return false;
              }
              Query query = em.createNativeQuery(NmsConstants.QUERY_CHECK_USER_ELIGIBILITY);
              query.setParameter(1, username);
              query.setParameter(2, username);
              int count = ((Number) query.getSingleResult()).intValue();
                     if (count > 0) {
                           return true;
                     } else {
                           return  false;
                     }
             
              }catch (Exception e) {
                     e.printStackTrace();
                     return false;
                     // TODO: handle exception
              }
       } //end spring security

What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like Counting SemaphoreBlockingQueueConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch which we have seen in last article  What is CountDownLatch in Java and allows multiple threads to wait for each other (barrier) before proceeding. Difference between CountDownLatch and CyclicBarrier is a also very popular multi-threading interview question in Java. CyclicBarrier is a natural requirement for concurrent program because it can be used to perform final part of task once individual tasks  are completed. All threads which wait for each other to reach barrier are called parties, CyclicBarrier is initialized with number of parties to be wait and threads wait for each other by calling CyclicBarrier.await() method which is a blocking method in Java and  blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on barrier. await() is a blocking call but can be timed out orInterrupted by other thread. In this Java concurrency tutorial we will see What is CyclicBarrier in Java  and  an example of CyclicBarrier on which three Threads will wait for each other before proceeding further.

Difference between CountDownLatch and CyclicBarrier in Java
In our last article we have see how CountDownLatch can be used to implement multiple threads waiting for each other. If you look at CyclicBarrier it also the does the same thing but there is a different you can not reuse CountDownLatch once count reaches zero while you can reuse CyclicBarrier by calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is good for one time event like application start-up time and CyclicBarrier can be used to in case of recurrent event e.g. concurrently calculating solution of big problem etc. If you like to learn more about threading and concurrency in Java you can also check my post on When to use Volatile variable in Java  and How Synchronization works in Java.
CyclicBarrier in Java – Example
Now we know what is CyclicBarrier in Java and it's time to see example of CyclicBarrier in Java. Here is a simple example of CyclicBarrier in Java on which we initialize CyclicBarrier with 3 parties, means in order to cross barrier, 3 thread needs to call await() method. each thread calls await method in short duration but they don't proceed until all 3 threads reached barrier, once all thread reach barrier, barrier gets broker and each thread started there execution from that point. Its much clear with the output of following example of CyclicBarrier in Java:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate how to use CyclicBarrier in Java. CyclicBarrier is a
 * new Concurrency Utility added in Java 5 Concurrent package.
 *
 * @author Javin Paul
 */
public class CyclicBarrierExample {

    //Runnable task for each thread
    private static class Task implements 
Runnable {

        private CyclicBarrier barrier;

        public Task(CyclicBarrier barrier) {
            this.barrier = barrier;
        }
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            } catch (BrokenBarrierException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args[]) {

        //creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await()
        final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                //This task will be executed once all thread reaches barrier
                System.out.println("All parties are arrived at barrier, lets play");
            }
        });

        //starting each of thread
        Thread t1 = new Thread(new Task(cb), "Thread 1");
        Thread t2 = new Thread(new Task(cb), "Thread 2");
        Thread t3 = new Thread(new Task(cb), "Thread 3");

        t1.start();
        t2.start();
        t3.start();
   
    }
}

Output:
Thread 1 is waiting on barrier
Thread 3 is waiting on barrier
Thread 2 is waiting on barrier
All parties are arrived at barrier, lets play
Thread 3 has crossed the barrier
Thread 1 has crossed the barrier
Thread 2 has crossed the barrier


When to use CyclicBarrier in Java
Given the nature of CyclicBarrier it can be very handy to implement map reduce kind of task similar to fork-join framework of Java 7, where a big task is broker down into smaller pieces and to complete the task you need output from individual small task e.g. to count population of India you can have 4 threads which counts population from North, South, East and West and once complete they can wait for each other, When last thread completed there task, Main thread or any other thread can add result from each zone and print total population. You can use CyclicBarrier in Java :

1) To implement multi player game which can not begin until all player has joined.
2) Perform lengthy calculation by breaking it into smaller individual tasks, In general to implement Map reduce technique.

Important point of CyclicBarrier in Java
1. CyclicBarrier can perform a completion task once all thread reaches to barrier, This can be provided while creating CyclicBarrier.

2. If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier.
3. Thread will block on await() until all parties reaches to barrier, another thread interrupt or await timed out.
4. If another thread interrupt the thread which is waiting on barrier it will throw BrokernBarrierException as shown below:

java.util.concurrent.BrokenBarrierException
        at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
        at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)

5.CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException.

That's all on  What is CyclicBarrier in Java , When to use CyclicBarrier in Java and a Simple Example of How to use CyclicBarrier in Java . We have also seen difference between CountDownLatch and CyclicBarrier in Java and got some idea where we can use CyclicBarrier in Java Concurrent code.

java.util.concurrent.CountDownLatch is a concurrency construct that allows one or more threads to wait for a given set of operations to complete.
CountDownLatch is initialized with a given count. This count is decremented by calls to the countDown() method. Threads waiting for this count to reach zero can call one of theawait() methods. Calling await() blocks the thread until the count reaches zero.
Below is a simple example. After the Decrementer has called countDown() 3 times on theCountDownLatch, the waiting Waiter is released from the await() call.
CountDownLatch latch = new CountDownLatch(3);
Waiter      waiter      = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);
new Thread(waiter)     .start();
new Thread(decrementer).start();

Thread.sleep(4000);
public class Waiter implements Runnable{

    CountDownLatch latch = null;

    public Waiter(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Waiter Released");
    }
}

public class Decrementer implements Runnable {

    CountDownLatch latch = null;

    public Decrementer(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {

        try {
            Thread.sleep(1000);
            this.latch.countDown();

            Thread.sleep(1000);
            this.latch.countDown();

            Thread.sleep(1000);
            this.latch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}