Pages

Friday, September 28, 2012

what is mongodb?

MongoDB, an implementation of c++,  belogs to NOSQL category(Non-relational operational stores) also most knows this as Not only SQL.

It doesn't have

  • joins
  • complex transactions
Because of the above reasons, scaling becomes easy. But the side effect is we need to have new data models (Have to stop using relational models).


Well most of you have used relational database. That is one way of modelling databases. Another way of modelling data is document oriented data modelling.

If you are unfamiliar with document oriented databases, read the following link.

http://en.wikipedia.org/wiki/Document-oriented_database

Mongodb saves data as documents.
You can try issuing mongodb commands online in the following link. It also guides you how to use mongodb.
http://try.mongodb.org/

Sunday, September 23, 2012

what's the difference between forward and sendRedirect?

forward happens in server and does not make the browser to redirect.
sendRedirect actually redirects the browser and makes another httpRequest.

builder pattern

Builder pattern is an object creation design pattern and it is used to build complex objects.
The builder design pattern has four elements

  1. Director : responsible for managing the creation of the object. It actually delegates the process to builder interface.
  2. Builder : An interface that describe how the parts of the objects are created.
  3. Product : The complex object to be created.
  4. Concrete Builder : implements the builder. Can have several builders that each describe how different type of object is created. 
The following example is taken from Wikipedia (http://en.wikipedia.org/wiki/Builder_pattern).

Thursday, September 20, 2012

Ant Vs Maven

Well this has been a highly debated topic among java developers. Some prefer ant while other maven. So what is the better build tool.

Imho i think both have their advantages and disadvantages. if you use ant

  • your project directories are not predefined, therefore flexible. You can build the project in your own way.
  • Unlike maven you do not need internet to work.
  • Unlike maven there will be no conflicting jar downloads or broken dependencies since developer him/her self mentions adds the libraries.
  • But you need to manage the dependencies of the dependencies which sometimes is a headache.
  • Easy setup and usage.
  • Not the best tool if the project is huge.
  • Support for managing versions of dependencies and the project it self is not good.
Let's see the maven facts
  • You can just put dependencies in the pom.xml file and maven will download it for you.
  • You do not need to manage dependencies of dependencies, since maven automatically handles it.
  • You can manage versions of the project, dependency versions easily.
  • Good if the project is large.
  • Project structure is not flexible. You will have to go with default maven structure.
  • You have to have internet to work with.
  • There may have broken dependencies.
yes as you see both has it's own advantages and disadvantages. However as a java developer I believe you need to learn both the build tools since the type of tool you need to work with will vary from project to project. In my case it's 50-50. So I wouldn't fancy only one build tool but both.

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

Saturday, September 15, 2012

How to get a maven web project work or run in eclipse

I must confess you that it had been a real waste of time. I literally had to search the whole web to find a descent tutorial to get a maven built project work with eclipse.

That is when you create a maven web application in eclipse (obviously after setting up maven in eclipse. you can find many online tutorials on how to setup maven  in eclipse) you won't be able to run the project by just right clicking on the project and select run on server.

Finally after spending several hours, I found a nice tutorial.

In order to do that you need to do some stuff. The following link has a nice simple video tutorial on how to do this very easily. Hope this is useful.

http://www.youtube.com/watch?v=Q14WkL9mw5o&feature=related

Friday, September 14, 2012

what is the difference between mvc and mvp

what mvc does:

view: takes user inputs, displays the content to the user
model:contains the business logic, also responsible for communicating with the database
controller: is merely an assistant to the view module. It sends user data, input to the correct model.

Now lets see what mvp is

view: as usual it takes user inputs, displays the content to the user
presenter: is some what a thick layer. unlike controller in mvc it handles the business logic required to respond to the user event.
model: here the model can be considered as the interface to the data.

what is jms?

JMS also known as java messaging service is an api intended to make the component loosely couple  by providing a mechanism to communicate among java clients. Note that JMS  is a peer to peer facility.

It allows distributed applications to be loosely coupled, reliable and asynchronous. This technology is widely used in java based message oriented middleware.

In essence JMS has two qualities.

  1.  reliable : JMS makes sure the message is delivered and delivered only once.
  2. asynchronous : A JMS provider can deliver messages to a client as they arrive; a client does not have to request messages in order to receive them
JMS can be a candidate over a tightly couple technology like RPC. These are the desirable qualities of JMS.
  1.  Does not depend on the information of interfaces of other clients.
  2. Can operate even when one or more other peers are down
  3. A component can send a message to another and continue it's operation even without an immediate response
How ever above is just a little introduction of jms. You can see more information at

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>

Thursday, September 13, 2012

hibernate no class found exception

Exception in thread "main" java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;at java.lang.Class.getDeclaredFields0(Native Method)at java.lang.Class.privateGetDeclaredFields(Class.java:2308)

The above exception usually happens when we use hibernate4 with spring 3. look at the below sping xml bean declaration.

<bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="mad.springnhibernate.model" />
<property name="hibernateProperties">
<props><prop key="dialect">org.hibernate.dialect.MySQLDialect</prop></props>
</property>

</bean>

The error happens because of the class of the bean. If you are using hibernate4 then there is no such class. If you are using hibernate4 then you need to change it to org.springframework.orm.hibernate4.LocalSessionFactoryBean. The the code will stop giving you the above exception.


Wednesday, September 12, 2012

Hibernate configuration for mysql in hibernate 4.0

this is the normal configuration of a hibernate.cfg.xml in hibernate 4

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

<!-- Database connection settings. hibernatedb is my database name. you can choose anything you want -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
<property name="connection.username">root</property>
<property name="connection.password">pass</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

Sunday, September 9, 2012

What does hibernate do?

Hibernate is an Object relational mapping tool. We normally say it as ORM

say we have an Item object now we have these member variables.

  1. itemPrice
  2. itemName
  3. itemId
Now we need to have a table for this entity. Say the table name is Item then the following columns should be there
  1. item_price
  2. item_name
  3. item_id
If we use normal method

We need to write boiler plate codes for the classes and need to write code to map models with databases.

Another problem is mapping relationships. If we have a Computer class and a MotherBoard class then we need to map MotherBoard object to the computer class as a member variable of computer class.

Also data type conversion has to be done. Say we have a boolean and database stores it as integers. This conversion is also a problem.

It is hard to manage code changes. say we have change in object status. Then we have to write queries for each of the column value  changes. 

what does hibernate do?

Well in simple hibernate removes the inadequacies mentioned above. In simple what hibernate does is it removes the gap between the object and the database. we can persist the object into a database without much effort.

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

what is java internationalization

In general internationalization in making the software usable by multiple languages. By using this we can make application to support languages like english, french, latin etc...

The way to tackle this problem is to use  .properties file.

The link below provides a nice simple tutorial on how to do this.

http://www.roseindia.net/java/example/java/swing/internationalization.shtml

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(){
     }
}

Monday, September 3, 2012

Spring AOP Error : Cannot Proxy Target Class Because CGLIB2 Is Not Available error in spring

This is a common error in spring development

The solution is

put the cglib.jar as a library to your project. you can obtain this from Cglib official web site
http://cglib.sourceforge.net/

example with spring jdbctemplate with transactions.

If you want to use aop of spring and do a transaction with database you can use @Transaction annotation.  this is how you do it.

Note that this works only with non MyISAM tables. MyISAM does not handle transactions.

Say there is a function you want to have the transaction. then you simply add the @Transaction annotation above the method.
public class BeverageModel{
private DriverManagerDataSource dataSource;
private JdbcTemplate jdbcTemplate;

public void setDataSource(DriverManagerDataSource dataSource){
this.dataSource = dataSource;
}

public DriverManagerDataSource getDataSource() {
return dataSource;
}

public JdbcTemplate getJdbcTemplate() {

return jdbcTemplate;

}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

Sunday, September 2, 2012

spring transaction management


recently I wrote a spring code.

JdbcTemplate insert = new JdbcTemplate(dataSource);

insert.update("INSERT INTO item (price, item_category) VALUES(?,?)",new Object[] { beverage.getPrice(), beverage.getItemCategory() });

int id = insert.queryForInt( "SELECT last_insert_id()" );

System.out.println(id);return insert.update("INSERT INTO beverage (id, name, quantity,size) VALUES(?,?,?,?)", new Object[] { id,beverage.getName(), beverage.getQuantity(),beverage.getSize() });

How ever the id was always 0. There reason has been,

whole code above must be wrapped in a transaction. Otherwise JdbcTemplate can use a different connection from the pool for all statements and last_insert_id() is tied to a transaction.
Threfore @Transactional can be used to avoid this error.

How ever this solution can be applied only to non MyISAM type of tables. Because MyISAM type does not support transactions.