Pages

Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Sunday, February 16, 2014

Optimistic locking

What is optimistic locking? Imagine two users read data at the same time and both of them do updates. Then the last to update will win. that is the normal situation.

So how would you handle this situation without compromising the concurrency of the system. The below article gives one solution to this using spring read it carefully.

http://camelcase.com.au/public/jpa/optimistic-locking-with-jpa-and-spring/

Sunday, November 17, 2013

spring webflow Introduction

What issues does spring webflow help overcome?

  1. Visualizing the flow is very difficult.
  2. The application has a lot of code accessing the HTTP session.
  3. Enforcing controlled navigation is important but not possible.
  4. Proper browser back button support seems unattainable.
  5. Browser and server get out of sync with "Back" button use.
  6. Multiple browser tabs causes concurrency issues with HTTP session data.
When spring webflow?
  1. There is a clear start and an end point.
  2. The user must go through a set of screens in a specific order.
  3. The changes are not finalized until the last step.
  4. Once complete it shouldn't be possible to repeat a transaction accidentally

Saturday, November 9, 2013

Object pooling with spring framework

This can be done using the following simple code.

<bean id="simpleBeanTarget" class="com.mad.SimpleBean" scope="prototype">
</bean>

<bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource">               <property name="targetBeanName" value="simpleBeanTarget" />
            <property name="maxSize" value="20" />
</bean>

<bean id="simpleBean" class="org.springframework.aop.framework.ProxyFactoryBean">
           <property name="targetSource" ref="poolTargetSource" />
</bean>

here the simpleBeanTarget is the bean which is pooled. poolTargetSource is the pooling  bean for the simple bean tareget.

Http client library for java

I've been searching for a java http client for one of my projects. then I came across a simple library called jakartha commons client. As it turns out, this library is at it's end of life. So I was wondering a good library implementation of http client. After many tryouts, it seems apache http components is the go to library for general needs of http client.

http://hc.apache.org/

However if you are a spring user, then spring also provides facilities for http client requests.
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/http/client/package-summary.html

Having said that, the scope of this implementation is very limited. So my personal preference is apache http components over spring implementation, unless the requirement is very basic.


Tuesday, November 5, 2013

A spring integration example

Want to get your hands on a spring integration example ? Visit the following link. It guides you to creating a nice spring integration project. This is a tutorial with 2 posts.

http://vrtoonjava.wordpress.com/2013/03/03/spring-integration-developing-application-from-the-scratch-part-1-2/


Monday, November 4, 2013

Reasons for error The matching wildcard is strict, but no declaration can be found for element

This error messages can be found for two reasons.

  1. If you use a trailing slash in the schema location or name space. eg: http://www.springframework.org/schema/beans/       remove the slash to recorrect it
  2. if you do not metion version in it. eg: http://www.springframework.org/schema/integration/spring-integration.xsd instead use http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.2.xsd
This way you can get rid of the above error in the spring xml files.

Thursday, August 29, 2013

Accessing session objects in spring mvc

Yes this is quite simple I know. But I came across a nice article that summarize on how to access session objects spring mvc. The below link explains various methods on how to access session object.

http://www.javaroots.com/2013/08/how-to-get-session-object-in-spring-mvc.html

Tuesday, June 18, 2013

Spring properties place holder configurer example

Often we need to put configuration parameters independently to the code. Because you do not need to lookup the code in order to configure the system and it allows to maintain the system without much trouble.  In such cases it is good to keep a properties file. A good example of the usage of this is, configuration properties of a database.

Now this can be achieved in several methods. One is to use spring's PropertiesLoaderUtils class. Another is to use the spring properties place holder configurer.

Now lets see how you can achieve this using spring properties place holder configurer.

create a database.properties file in your classpath and put the following properties in it.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dbname
jdbc.username=root
jdbc.password=password


Then you need to declare the bean as following PropertyPlaceholderConfigurer

<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>database.properties</value>
  </property>
</bean>

Now you can access the values of the properties as following.

<bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">    <property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

Now what you need to access these properties in your java code too.

then you can simply use @value annotation. something like @Value("${valueKey}")


Tuesday, November 13, 2012

Providing method level security

I showed you how to provide basic security in spring mvc with intercept url patterns in here. Now with that knowledge let's see how to provide method level security.

This can be achieved by using @Preauthorize annotation. First you need to enable it. For that you need to add the following line to your dispatcher servlet.


<global-method-security
pre-post-annotations="enabled" />

Then you can use @Preauthorize annotation.
eg : @PreAuthorize("isAuthenticated() and hasRole('ROLE_ADMIN')")

In the above example the method is allowed to execute if the user is authenticated and has the ROLE_ADMIN role.

How ever you can use @Secure annotation as well. For that you need to add the following line to your dispatcher servlet.

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

How ever the first method gives you more flexibility to handle the permissions as it is based on expressions.

hibernate lazy initialization and jason response to an ajax call

Some days back I was coding and found an interesting problem. It is as follows.

I have two classes called Lecturer and Course. My Lecturer class has a List of Course objects a variable as shown
@OneToMany(mappedBy = "lecturer")
@NotFound(action = NotFoundAction.IGNORE)
private List<Course> courseList = new ArrayList<Course>();

In my course class I have a Lecturer object as a variable as below.

@ManyToOne@JoinTable(name = "course_lecturer", joinColumns = @JoinColumn(name = "course_id"), inverseJoinColumns = @JoinColumn(name = "lecturer_id"))
private Lecturer lecturer;

Now I have a spring Controller method that returns a json object of Lecturer as below.

@RequestMapping(value = "/getlecturerbyid", method = RequestMethod.POST)

public @ResponseBodyObject getLecturer(@ModelAttribute(value = "id") Lecturer lecturer) {

Map<String, Object> response = new HashMap<String, Object>();
    response.put("message", "succeess");
    response.put("lecturer", lecturer);return response;
}

The problem is it throws a lazy initialization exception. Therefore I set fetch type in both variables in Lecturer and Course class to eager. Now the problem is it infinitely tries to fetch objects eagerly(if I unset fetch of either, it raises the same exception).On the other hand if I remove the 

Thursday, October 25, 2012

spring dependencies for maven


Did you spend lots of time searching for maven dependencies for your spring web application? The following page contains the dependencies for each of the spring module.

http://blog.springsource.org/2009/12/02/obtaining-spring-3-artifacts-with-maven/

Sunday, October 21, 2012

mistake when injecting null value to a variable or construct

Say you need to inject null value to a property. How would you do it? Let me guess.

<bean id="youclassid"class="yourclass">
        <property name="distance" value="null" />
</bean>

Sorry to disappoint you. The above code will not work. The correct way is shown below.


<bean id="youclassid"class="yourclass">
<property name="distance"  /><null/></property>
</bean>


Wednesday, September 19, 2012

Spring 3 using ConversionService

Have you come across an exception of the type below?

Field error in object 'student' on field 'courseList': rejected value [mad.nurseryapplication.model.Course@0]; codes [typeMismatch.student.courseList,typeMismatch.courseList,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.courseList,courseList]; arguments []; default message [courseList]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'courseList'

Well this type of exception is usual for spring developers. As the exception clearly suggests, it is a case of spring not being able to convert the data type. Take a look at the below code.
<form:hidden path="id" value="${student.id}"/> <c:forEach items="${avacourses}" var="course" varStatus="status"> <tr><td><form:checkbox path="courseList" value="${course}" /></td> <td>${course.courseName}</td></tr></c:forEach>
Here you can see that the value is ${course} which is an object. How ever spring understands this as 

Monday, September 17, 2012

spring exception

If you come across an exception that has the following in the stack trace, then it is most of the time a problem with the jar file. so remove the jar file and download a new one. Or in maven you can just delete the jar directory from m2 directory and run maven again.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid constant pool reference: 99. Constant pool size is: 25

Friday, September 14, 2012

spring annotation vs xml based configuration

This has been a highly debated topic in spring. In short I will say what I prefer and why.

I recently had a conversation with one of my experienced spring developers. One person said that he  used xml based configuration in a large project sometime back. How ever according to him the number of xml files written went out of hand with the growth of the code base. So in this regard it is good to have annotation driven codes to address this problem.

How ever sometimes using annotations is not good. becase annotations are not a part of the code. So in that regard, yes annotations are bad. Also unlike xml method,  if you want to change a setting, then you have to edit the source and recompile it. Another point is

spring how to load multiple xml files

you can do this in the following way.

ApplicationContext ctx = new ClasspathXmlApplicationContext(String[]{"spring1.xml","spring2.xml"});

Another way to handle this is to put have several xml configuration files. Then export all of them to one file like below

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<import resource="connection/connection.xml"/>
<import resource="common/common.xml"/>
<import resource="moduleA/moduleA.xml"/>
</beans>

Sunday, September 9, 2012

spring el example

The spring Expression Language can be used to set properties to the beans. Note that we can do this also using xml method. Lets see an example.

@Component
public class Computer{

          @Value("#{motherBoard}")// motherBoard bean is referenced to this variable
          private MotherBoard motherBoard;// mother board is a dependency to the computer
}

@Component("motherBoard")//this bean can be taken using name motherBoard in getBean method
public class MotherBoard{

           @Value("asus")//asus is assigned as the property for the variable type in MotherBoard class.
           private String type;
}

This can be also done using Bean declaration in xml files also.

Saturday, September 8, 2012

Handling session details in spring

Storing session details of a specific user session is quite straight forward in spring. The scope variable in the bean identification eliminates the need of using httpsession. That is, using a simple session class with the annotation @Scope("session") and some variables makes it easier to handle session specific details.

@Scope("session")
public class SomeClass {

}

Friday, September 7, 2012

spring @Service @Repository @Controller @Component

@Component is usually used to get a bean of a specific class.

eg:
@Component
public class Vehicle{

}

Now we can get this bean simply by
ApplicationContext context =new ClassPathXmlApplicationContext(new String[] {"Spring.xml"});
then Vehicle vehicle = (vehicle)context.getBean("vehicle");

how ever to work this
<context:component-scan base-package="mad.project.package" /> has to be put in spring.xml
 Note that we can simply get the bean by just calling getBean with the parameter vehicle. That is the parameter's first letter is in lowercase where as class name should begin with capital.

Now another method is putting @Component("beanName") instead of just putting @Component. This way you can get the bean using "beanName"

How ever it is not good to use this annotation.
Instead use @Controller, @Service, @Repository annotations that are specializations of

spring bean scopes

singleton – create and returns a bean instance per Spring IoC container
prototype – creates a new bean instance for every request.
request – creates a single bean instance per HTTP request.
session – create and returns a  bean instance per HTTP session.
globalSession – creates a single bean instance per global HTTP session.

eg:


@Service
@Scope("prototype")
public class Vehicle{
     public void driveVehicle(){
     }
}