Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Sunday, July 28, 2013

How to integrate Spring Security to an existing web application?

Let see how we can integrate a Spring Security to an existing web application. Download the Spring Security from here, from the download add the following jar spring-security-core-3.2.0.M2.jar and spring-security-config-3.2.0.M2.jar from \spring-security-3.2.0.M2\dist, to your project lib folder.

Since this is the existing project, i assume the all the url pattern will be routed through Spring Dispatcher Servlet. Now let's modify our web.xml to add the filter, since spring security uses filter approach, this provides a hook into the Spring Security web infrastructure.


   org.springframework.web.context.ContextLoaderListener               


   contextConfigLocationWEB-INF\applicationContext-security.xml    

   springSecurityFilterChain
   org.springframework.web.filter.DelegatingFilterProxy


   springSecurityFilterChain
   /*


Next we need to create applicationContext-security.xml under WEB-INF

           


    

   

 
  
   
   
  
 
 
   

The element http in the applicationContext-security.xml, says that we want all URLs within our application to be secured, requiring the role ROLE_USER to access them. Thus we are forcing to authenticate ourselves when visiting our pages in the site.

Now to add some test users for a rapid development, we have configured two users here ramanujam and user1, with their password and roles using the authentication-provider and user-service. That's all you have integrated a simple security to your web application. Now if you access any of your web pages, you will redirecting to a default spring login pages.

Happy Programming...!!!

Sunday, January 27, 2013

InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode

If you have enabled the filter OpenSessionInViewFilter, for fetching the lazily loaded data, you can typically see the below error message, when trying to do a persistence operation outside of Spring-managed transaction.

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
org.springframework.orm.hibernate3.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1186)
org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:696)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:694)

OpenSessionInViewFilter has an alternative "deferred close mode", to resolve the issue. This can be activated through setting the singleSession=false. This will use one Session per transaction, but keep each of those open until view rendering has been completed. As no Session will be reused for another transaction in this case, there is no risk of accidentally flushing inconsistent state


  OpenSessionInViewFilter
  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  
     singleSession     false  


Happy Programming !!!

Sunday, December 9, 2012

Hibernate Error : java.lang.NoClassDefFoundError: antlr/ANTLRException

When you are working with the Hibernate Query, you will get the following error
java.lang.NoClassDefFoundError: antlr/ANTLRException
 org.hibernate.hql.ast.ASTQueryTranslatorFactory.createQueryTranslator(ASTQueryTranslatorFactory.java:35)
 org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:74)
 org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56)
 org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
 org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
 org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
 org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
All you need is to download the latest version of antlr jar. You can download this from here antlr-2.7.7.jar, and put it under your web lib folder.

Happy Programming...!!!

Tuesday, October 2, 2012

How to retrieve the auto-generated key after an INSERT in Spring

When you insert a record with a primary key field set as auto_increment in MYSQL, it will generate ID automatically, though Spring's RdbmsOperation class has two methods with encouraging names setGeneratedKeyColumnName and setReturnGeneratedKeys, at the time of writing the child class SqlUpdate doesn't not use them to return the value of the generated keys. If our table has a foreign relation, and related data needs to be inserted at the time of creation, we need the primary key field data of the insert statement.

To get the generated id, we have to use the JdbcTemplate.update method which is overloaded JdbcTemplate.update(PreparedStatementCreator psc, KeyHolder k)
The key returned from the insert is injected into the KeyHolder object. Implementation of this interface KeyHolder can hold any number of keys. In the general case, the keys are returned as a List containing one Map for each row of keys. Below is the sample implementation to get the auto generated ids, this works fine in MYSQL

public int add(BaseObject obj) {
 final Dealer dealer = (Dealer) obj;
 dealerJdbcTemplate.update(psc, generatedKeyHolder)
 KeyHolder keyHolder = new GeneratedKeyHolder();
 dealerJdbcTemplate.update(new PreparedStatementCreator()
  {
   public PreparedStatement createPreparedStatement(Connection connection) throws SQLException 
   {     
    PreparedStatement ps = connection.prepareStatement("INSERT INTO DEALER (NAME, ADDRESS, CITY, STATE, COUNTRY, ZIP, CONTACTPERSONNAME, MOBILENUMBER, PHONENUMBER) VALUES (?,?,?,?,?,?,?,?,?)" , Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, dealer.getName());
    ps.setString(2, dealer.getAddress());
    ps.setString(3, dealer.getCity());
    ps.setString(4, dealer.getState());
    ps.setString(5, dealer.getCountry());
    ps.setInt(6, dealer.getZip());
    ps.setString(7, dealer.getContactPersonName());
    ps.setString(8, dealer.getMobileNumber());
    ps.setString(9, dealer.getPhoneNumber());            
    return ps;
   }    
  },
  keyHolder
 );
 return keyHolder.getKey().intValue(); 
}
Happy Programming...!!

Saturday, September 1, 2012

What is Cross Cutting Concerns in Spring?

The majority of application we design will contain common functionality that spans across tiers and layers, such as Security, Caching, Logging, Transactions and more. These are called crosscutting concerns. "Concern" means logic/functionality. Since it affects the entire application, and should have been in one centralised location rather than scattered across application layers and tiers.

For example: You have application, which spans multiple layers say Controller, Service and DAO. You have a requirement to add the logging code to one of the DAO method, yes that's easy one, just go to that method, and add the logging code at the top of the method, then there is a requirement to add Security code to the same method, where you have added the logging, yes this also seems to easy, you just go to the method, and add the necessary security logic to the method after the logging. Now you got a requirement to extend this logic to all the layers(Controllers and Service) of that method, okay little tedious, but we are expert in copy and paste, we will copy the code from the DAO and paste it in Service and Controller, that's all done. But really what we have done is a dirty job.

Now, if they want this to be done in our entire system, little crazy now, already we have done a dirty job by doing a copy paste of DAO to Service and Controller, our code has been scattered, if we need to change, we have to update all the classes, it will not be a big deal if it is one or two classes, but for entire application it is a pain full job.

That's where we will be using the Aspect Oriented Programming (AOP) . It is a programming technique based on the concept of an Aspect. Aspect encapsulates cross-cutting logic, the basic infrastructure code which all application needs. What we are going to do is, we will take the logging and security code, and encapsulate it into a module for a reusable code.

Will soon publish a post on how to configure the AOP in Spring along with the Cross Cutting Concerns

Happy Programming ...!!!

Monday, August 27, 2012

What is ContextLoaderListener in Spring?

After a very long time, started refresh myself on spring framework, started with some sample web application got held up on the configuration ContextLoaderListener, what it really is, what was the use.
It is the Bootstrap listner to start up the Spring's root WebApplicationContext. All configuration which have been configured and loaded up during the startup, will be available throughout the application.

Mostly DB Configuration will be most one which can be seen
To register the listner, just add the below line to the web.xml
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
The class ContextLoaderListner will be found in the spring.jar, which can be found in the dist folder under spring bundle.

Happy Programming !!