Pages

Tuesday, November 27, 2012

Jquery ajax request send json object after binding from a form

This is a common mistakes done by jquery developers. Say you have a form (with form tags) and you extract the form data and create a json object and send it to a url via ajax. Also lets say your action is also the ajax url. Then if you send the content via jquery ajax, pre-request callback will append the form content to the jason object you extracted. So in order to avoid this you can set return to false in the form.

Wednesday, November 21, 2012

Save or Update vs Merge operations in hibernate

Following is from the hibernate documentation.

saveOrUpdate() does the following:
if the object is already persistent in this session, do nothing
if another object associated with the session has the same identifier, throw an exception
if the object has no identifier property, save() it
if the object's identifier has the value assigned to a newly instantiated object, save() it
if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it
otherwise update()

merge() is very different:
if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
the persistent instance is returned
the given instance does not become associated with the session, it remains detached

You should use merge when there is an  object that was detached from the session and a persistence object of it is currently associated with the session.

Tuesday, November 20, 2012

Jackson access node elements and binding sub trees in to java objects

Say you have several types of pojos and you need to send them in json format. Finally you need to deserialize them. In this post lets see how you can access subtrees of the json object and deserialize them in to pojos.

In this example we are using jackson. Another popular json serialize/deserialize library is google's gson library. How ever the gson library does not support maps at the moment. Therefore you cannot use key/value concept to access the json object.
Now let's see how we can do this. In this example, the json string contains lecturer object and an array of subject ids. Say we need to get these two objects separately.

ObjectMapper mapper = new ObjectMapper();//need this to deserialize in to required pojo
JsonNode rootNode = mapper.readTree(json);//json is the json string.
JsonNode lecturerNode = rootNode.path("lecturer");//get the lecturer node from json root node using the related key.
JsonNode subjectIdNode = rootNode.path("selectedSubjects");//get the array from json root node using the related key.
Lecturer lecturer = mapper.readValue(lecturerNode, Lecturer.class);//use the mapper to get the object
String[] subjectIdList = mapper.readValue(subjectIdNode, String[].class);

Monday, November 19, 2012

Managing js, css resources in the maven webapp

external java scrpt files and css files are essential when developing a cool webapp. So how would you manage your files? As far as I know the best way is to put it under webapp folder. That way, all the js and css files will be included in the war file that you will generate. First create a folder named resources in your webapp folder. then put your js files in a folder called js. and css files in a folder called css. Now link your file in the jsp file like below.

<script src="<%=request.getContextPath()%>/resources/js/youfile.js" type="text/javascript">/script>

But still the dispatcher-servlet does not know how to link your file. It will try to get the file in the default manner (Through controller mapping if you use controllers). You need to put the following 2 lines to handle this problem.

 <bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /><mvc:resources mapping="/resources/**" location="/resources/" />

This will easily link you js files. You can link css files in the same manner as well.

Friday, November 16, 2012

hibernate ondelete cascase for generic collection

Well if your are doing a @OnDelete(action=OnDeleteAction.CASCADE) for a generic collection like a list of strings etc... then chances are that hibernate will raise an exception. It cannot initialize the sessionfactory bean. This at the moment, is a bug in hibernate. The easiest method is to clear the collection and saving first, then deleting the entity.
How ever most of the time, if you are doing a bulk deletion using hibernate, then chances are that you are on your own. You will have to handle them rather than expecting hibernate to handle everything with a single annotation.

Tuesday, November 13, 2012

showing and hiding elements based on the user role in spring security


In the previous blog post I showed you how to  provide method level security.  Now let's see how to hide or show elements based on the user role. Well it is quite simple with spring security tag library. just do the following to grant rights to view a specific user role to access some content.

declare the tag lib as follows in the jsp file

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

* Note that in order to use the above library you need to add the spring security tag lib jar file in your class path. you can easily get the dependency from maven repository.

Then go to the element you need to grant rights and surround it with the following block.
<sec:authorize access="hasRole('supervisor')">
</sec:authorize>

Also do not forget to put the following line to your spring security context file.
<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

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>


Friday, October 19, 2012

RPC vs Document based webservices in jax-ws

Yeah I know the SOAP based web services are no longer widely used since REST based web services have decreased the usage of SOAP based services. Today how ever I wanted to talk about the differences in two types of SOAP based web services (RPC and SOAP).

RPC based web service with jax-ws

This type of webservices does marshalling and unmarshalling in the SOAP engine. Therefore if the message is large, then the conversion becomes a huge overhead. Hence implementing coarse grained funtionality becomes a problem. Also inter-operatability of this type is not that good plus the support for custom data types is very low since the restrictions on encoding styles. However on the other hand, the implementation of this type of a web service using jax-ws is very simple. And also is good for fine grained functionality. 

Document based web services are have the qualities exactly opposite to the above mentioned rpc based qualities. They are widely used where you need to transfer lots of data using large xml files. 
By comparison however the document based web services are used than rpc based services.

Friday, October 12, 2012

Map/Reduce with mongodb

Well I am not going  write an article by myself here. Because The concept is brilliantly explained in some other article. Visit the link below to have a good understanding about mongo map/reduce feature.
http://www.mongovue.com/2010/11/03/yet-another-mongodb-map-reduce-tutorial/

The following tutorial has a simple cool tutorial on this feature as well.
http://blog.facilelogin.com/2012/02/mapreduce-with-mongodb.html

Tuesday, October 9, 2012

Cool mongodb admin gui panel

I was looking for a mongodb admin panel to use it. Then I found this cool looking java based mongo admin gui panel called Umong.
You can download it from https://github.com/agirbal/umongo/downloads
Just extract the content and run the .sh file using command line or directly. It will launch the admin panel

How to install from unauthenticated sources

Have you seen the following error when you try to update your ubuntu system?
the action would require installation of packages from not authenticated sources...
Well the error is self explanatory. You need to allow unauthenticated sources to get around this. Use the below command to get it work.
sudo apt-get update && sudo apt-get upgrade --allow-unauthenticated
Now you are good to go.


Monday, October 8, 2012

web server vs web container vs application server

web server : is something that is capable of handling http requests (recieving http requesting, processing them, creating http responses and sending them to the clients). Apache Web Server

web container : is a J2EE compliant implementation which provides an environment for the Servlets and JSPs to run. Tomcat typically a web container

application server : is a complete environment for running business components. It contains the web server capabilities as well as web container capabilities. eg: IBM WebSphere, Oracle Application Server

what is node.js?

This is a new technology(started in 2009). The original goal of node.js is to provide push capabilities (read push technology) to websites and make them highly sacalable. These are written in javascript and it's evendriven, asynchronous I/O nature makes it highly scalable.

These are used by big companies like

  • yahoo
  • microsoft
  • linkedin

what is push technology ?

Push technology or server push is used to send information to the client by itself without requiring a request from the client. It goes under the publish/subscribe paradigm. The other frequently used method is pull method where the client sends a request to initiate the transmission.

Applications include most of the emailing systems like gmail etc.... And the famous smtp protocol uses push technology. This technology removes the requirement of polling which has high overhead.
This can be done in several ways.
  1. Http server push : Here the server does not terminate the connection with the client after serving it's request. There fore it can send information to one or more clients easily. This is implemented using CGI in many systems.
  2. pushlets : This is a java technology. It never terminates the response. That is even if the response is sent to the browser, the response is not terminated. Therefore the browser does not know that the content is fully sent. Whenever the server wants to send information, it sends via javascript and eliminates the requirement of java applet. One draw back is it cannot handle the browser timeout. Therefore need to refresh the page periodically overcome the drawback.
  3. long polling : This is like normal polling in a way. client ask for data and the request is sent to server. How ever the server does not send the response until it has some new data. When ever it has new data, it sends a full response to the client. Then again after that the client needs to poll.
Apart from the above there are some other methods as well like flas xml socket relays, xmpp etc...

Wednesday, October 3, 2012

Using third party library and how to handle exceptions?

I think most of you must have come across situations where you need to use third party classes and you need to do some changes. Sometimes you can do this by decompiling the .class file then modifying it. The point is it works some times. But not always. Specially when the code is  obfuscated, chances are very low of decompilling correctly. So how can you overcome this? Well the most suitable method to do this is to use a wrapper class that extends the third party class.

Eg;
///this is the third party class
public class SomeLibrary{
     public void readBook(){

     }
}


Now you can write the wrapper class like this.

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.

Friday, August 31, 2012

Spring 3 security login example with database help

dependencies
spring 3.x  standard library
spring security web
spring security core
spring security config

First create a mysql database called loginexample. The sql code is as following.

CREATE TABLE `users` (`USER_ID` INT(10) UNSIGNED NOT NULL,`USERNAME` VARCHAR(45) NOT NULL,`PASSWORD` VARCHAR(45) NOT NULL,`ENABLED` tinyint(1) NOT NULL,PRIMARY KEY (`USER_ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user_roles` (`USER_ROLE_ID` INT(10) UNSIGNED NOT NULL,`USER_ID` INT(10) UNSIGNED NOT NULL,`AUTHORITY` VARCHAR(45) NOT NULL,PRIMARY KEY (`USER_ROLE_ID`),KEY `FK_user_roles` (`USER_ID`),CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`USER_ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO users (USER_ID, USERNAME,PASSWORD, ENABLED)VALUES (100, 'madhumal', '123456', TRUE);

INSERT INTO.user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)VALUES (1, 100, 'ROLE_ADMIN')

INSERT INTO users (USER_ID, USERNAME,PASSWORD, ENABLED)VALUES (101, 'user', '123456', TRUE);

INSERT INTO user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)VALUES (2, 101, 'ROLE_USER')

Note that we have two user roles, admin and user.

Create a Dynamic web project with the name SpringLogin

create your mvc-dispatcher-servlet.xml in WEB-INF folder

put the following code in there

Wednesday, August 29, 2012

What is failover?

what is failover?

In computing, failover is automatic switching to a redundant or standby computer server, system, hardware component or network upon the failure or abnormal termination of the previously active application,server, system, hardware component, or network. Failover and switchover are essentially the same operation, except that failover is automatic and usually operates without warning, while switchover requires human intervention.


How ever when the main server recovers, requests are then again sent to the main server.

There are 3 main type of fail overs
  1. clod failover : Should do manually
  2. warm failover : failover happens automatically. But the transaction may abort due to the failure of data synchronization.
  3. hot failover : happens automatically. Data synchronization also happens. Therefore can continue operation without a problem. 

spring jdbc template with mysql

Required Libraries are,

commons-logging
spring-jdbc
spring-beans
spring-core
spring-tx
spring-asm
mysql-connector-java
spring-context
spring-context-support
spring-expression

You can do this simply by using maven. Just google maven dependencies for spring jdbc template and put the dependencies in your pom.xml file and you are good to go.

Let's see how to use jdbc template in spring to communicate with mysql database.

Create a model class named Book.


package mad.library.form;

public class Book {

private String name;
private String author;
private String category;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}

}

Now create the BookDataManager class as following.

Sunday, August 26, 2012

Java Persistence API

What is persistence?

The general objective of persistence is to increase the life span of an object. This could be done by storing it in a disk, file etc... One simple method is to store the object in xml format. Another way of implementing the persistence is to use the databases.

Why do we need JPA?

If you consider about databases, usually it is used in the form of tables that are related in the traditional relational methods. How ever on the other hand objects are entities that has states and can invoke methods that makes it unique. So there is some conflict in objects way of keeping data and keeping data in databases.  JPA is introduced to fulfill this inadequacy.

Java Persistence

The Java Persistence Architecture API is a java specification for accessing, persisting, managing data between java objects, classes and databases. It is considered as the industry approach for object relational mapping (an ORM). That is it helps to retrieve data from the data in the form of java objects. This simplifies the life of a java developer significantly. 

However JPA  is a standard for the java persistence. Probably most of you must have heard about hibernate. Hibernate is a vendor implementation of the JPA and addition to that it provides some additional non JPA facilities as well.

Friday, August 24, 2012

proxy design pattern using java

what is proxy design pattern?
It is a design pattern that uses a proxy to control access to another object. What is the meaning of proxy? It means acting something on behalf of something. In this case, the client access an object through proxy.
So to what kind of objects do we need to provide a proxy?
Usually for objects that takes a lot of memory, files, resources that are expensive or hard to duplicate.

Below a simple implementation of the proxy design pattern.

Interface Game{
   void playGame();
}

public RealGame implements Game{

    private String game;

    public RealGame(String game){
         this.game = game;
         loadGame(game);
    }

    private loadGame(String game){
           System.out.println("loading game : "+game);
    }

    public void playGame(){
         System.out.println("playing game: "+ game);
    }
}

public ProxyGame implements Game{

     private RealGame game;
     private String gameName;
     public ProxyGame(String game){
         this.game = game;
   }
 
   public void playGame(){
      if(game==null)
           game=new RealGame(gameName);
      }
      game.playGame();
}



public DemoProxy{

   public static void main(String[] args){
       Game proxyGame = new ProxyGame("modern warfare");
        proxyGame.playGame();
   }
}

Thursday, August 23, 2012

Facade Design pattern in java

Facade design pattern is a pattern that is used to provide a simple interface to a large amount of code. This makes it very easy to use libraries in programming language. The following example is taken from http://en.wikipedia.org/wiki/Facade_pattern.


/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}

class Memory {
public void load(long position, byte[] data) { ... }
}

class HardDrive {
public byte[] read(long lba, int size) { ... }
}

/* Facade */

class Computer {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}

public void startComputer() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}

/* Client */

class You {
public static void main(String[] args) {
Computer facade = new Computer();
facade.startComputer();
}
}

Tuesday, August 21, 2012

Flyweight design pattern in java

fly weight design pattern is a structural patterns used to improve memory usage and performance. Here, instead of creating a large number of objects, we reuse the objects that are already created.

Lets say we have a MathHelper interface and has doMath method.

public interface MathHelper{
   void doMath(int a , int b);
}

Let's implement two classes that implement MathHelper.

public class Multiplier implements MathHelper{
  @override
  public void doMath(int a , int b){
      System.out.println(a*b);
  }
}


public class Adder implements MathHelper{
  @override
   public void doMath(int a , int b){
      System.out.println(a+b);
  }
}


Now we have the factory class that limits creating the objects.

public class FlyweightFactory{
 
    public FlyweightFactory(){
       Map<String,MathHelper> map = new HashMap<String,MathHelper>();
   }
    public static MathHelper getHelper(String val){
      if(map.containsKey(val))
          return map.get(val);
      if(val.equals("add"))
          map.put(val,new Adder());
     if(val.equals("multiply"))
          map.put(val,new Multiplier());
  }
}


Now the main method in the demo class is like this.
public static void main(String[] args){
   MathHelper helper = FlyweightFactory.getHelper("add")
   helper.doMath(2,3);
}

serialize and deserialize an object with java

We usually use serialization, when we need to store an object with the state to a storage medium so that we can use it later or when we need to transfer an object through the network.
Now lets see how to serialize an object to a file.


ObjectOutputStream o = new ObjectOutputStream(new             FileOutputStream("file.ser"));//saving to a file named file.ser
o.writeObject(ObjectToSerialize);//writing the object
o.close();

Now lets see how to deserialize the saved object.


        FileInputStream fileIn =
                          new FileInputStream("file.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
        try {
            dictionaryMap = (ObjectType) in.readObject();//add cast
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
        }
            in.close();
            fileIn.close();

Saturday, August 18, 2012

Port 8005 required by Tomcat v7.0 Server at localhost is already in use

Well this error message is thrown when another instance of tomcat is running. Basically the Tom cat server requires the ports 8005,8009,8080 by default. Therefore you need to stop the instance in order to run the server. Also it may happen due to, if some other program is using the particular ports. Therefore you need to resolve the port issue to proceed.

How to install tom cat on ubuntu

You can do this in two ways.

  1. Install using : sudo apt-get install tomcat7
  2. You can Install manually which is straight forward. download tomcat 7 binaries from http://tomcat.apache.org/ and extract it to a location you want and go to the bin folder in your extraction using the terminal.  Then type
                                                                             sh startup.sh : to start the server 
                                                                             sh shutdown.sh : to down the server

after you start up the server, you can access the server at the port 8080 (which is the default port for tomcat).

How ever the tomcat server is some what considered light weight compared to servers like glassfish, jboss etc... Therefore if you consider having a server with all the capabilities and features of java, it is better to use a server like glassfish.

Unit testing with java.

First question is what is unit testing?
Well unit testing is a code written by a programmer to test a specific functionality of a program.

Now the question is how can we do this in java? 
There are some libraries in java that helps unit testing. How ever the most popular and the common library used is the JUnit. Actually it is a framework that uses annotations to identify the test methods. Also one thing to remember is JUnit assumes that the tests can be conducted in an arbitrary order. That is the tests we write should not depend on each other.

Setting up JUnit.
You can download JUnit from http://www.junit.org/ and add the junit.jar to your project and classpath.

Using Junit
Create a java project using eclipse. Then right click on the project and create new->source folder and name it as test.
Now create a package inside the src folder and create a class named MyClass inside the package.

Enter the following code inside the MyClass.

public int divide(int x, int y) {
   return x * y;
 }

Now right on the MyClass file and create new->JUnit Test. change the path from src to test in the screen you get after choosing JUnit Test in the menu. Name the file to MyClassTest. Now click next and choose the methods to be tested. click finish.

Now you will see a class called MyClassTest inside test folder. You will see something like below in the class.


@Test
public void testDivide() {

}

Now put the following code inside your testDivide method.


 MyClass tester = new MyClass();
assertEquals("Result", 2, tester.divide(10, 5));

Now right click on the MyClassTest file and run as junit test. You will see a red bar as the result. This is because the result should be 2 but it returns 50. Now correct the code in divide method inside MyClass and rerun the unit test. You will see a green bar. That means the test is ok.

You can create a test suit also. That is you can select several tests and run all the selected methods.


 Now select the Test classes and right click on it. Then new->other and then use Junit ->test suit. Fill the parameters according. After finishing, you will see the Test suit class is created. If you run the file, all the mentioned tests will be run.

Now lets see how you can run tests using your code.
create a class called MyTestRunner inside the test source folder. Then put the following code inside it.

public static void main(String[] args) {
   Result result = JUnitCore.runClasses(MyClassTest.class);
   for (Failure failure : result.getFailures()) {
     System.out.println(failure.toString());
   }
}

Now you will see if there are any errors in the test.

There are some annotations like @Test , @Before, @After, @AfterClass , @BeforeClass, @Ignore, @Test(timeout=100) , @Test(expected=Exception.class). Google and find what these annotations are used for.



Sunday, August 12, 2012

What is a java factory method ?


Java Factory Method is a creational design pattern used by java developers. what it basically does is it instantiates objects from a set of classes by considering a certain logic. That is creating an object without specifying the exact class of object that will be created. This is quite simple. Let's see how we can do this.

Say for an example we have a shape interface

public interface Shape{
      void drawShape();
}

Now lets say we have two classes that implement the interface called Triangle and Square.


public class Triangle implements Shape{

      public void drawShape(){
         System.out.println("drawing three points and joining them");
     }
}



public class Square implements Shape{

      public void drawShape(){
         System.out.println("drawing four points and joining them");
     }
}

Now lets create the ShapeFactory class that is used to instantiate a shape.

public class ShapeFactory{

    public Shape getShape(int numberOfEdges){

               if(numberOfEdges==3)
                     return new Triangle();
               if(numberOfEdges==4)
                     return new Square();
          return null;//just to make the compiler happy ;)
    }
}


Now let's see how to create a new square or a triangle. create a new class ShapeManager.

public class ShapeManager{

    public static void main(String[] args){
           ShapeFactory factory = new ShapeFactory();
           Shape triangle = factory.getShape(3);//note that the object will be a triangle since the //parameter is 3
    }
}


This is simply what happens in a factory method. You do not directly call "new"
 key word to create an instance of shape. Instead you use a factory method to get an instance.

Java UnsupportedClassVersionError

This exception is most likely to be thrown when you compile the program from one version of java and running it on another version of java.
Eg : You compile the code using jdk 7, 6 etc... and run on version 4.

Thursday, August 9, 2012

Maven building and compiling the first App

In the last post I described how to set up maven in linux environment. Now let's see how to create a project structure, compile, package and install.

First open a terminal, then make a directory called TestAppDir and go to the folder. 
  • Now type in the terminal:  mvn archetype:generate Note that when you run this command for the first time it will download the dependency jars and pom files. Now this command will show you a list. The list contains various architectures (spring apps, hibernate etc...).  Lets not input anything and press enter (This will generate a folder structure with default archetype).
  • Now you will be asked the following
Choose org.apache.maven.archetypes:maven-archetype-quickstart version: 
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1

Enter 6 (Latest version). If you run this for the first time this will download the dependencies as well.

Then you will be asked to fill the following


Define value for property 'groupId': : mad.maven.test
Define value for property 'artifactId': : MadTest
Define value for property 'version':  1.0-SNAPSHOT: :
Define value for property 'package':  mad.maven.test: :
Confirm properties configuration:

the values mad.maven.test is given by me and it is like the package name in a normal program. The name I have given for the artifactId is MadTest. So when you package the app, it will  be like MadTest.jar. version refers to the version of the app you are creating. in the test package, you can write all the test cases. 

Now you will see a directory called MadTest in side TestAppDir. Now go to the MadTest directory. There you will see a pom.xml open it using a text editor. You will see something like below.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>mad.maven.test</groupId>
  <artifactId>MadTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MadTest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

The group id, artifact id, version, name are given by you. Packaging tag indicates the type of file you will get after packaging the app. If you have war, it will package app in to a .war file. All the dependencies are mentioned inside dependency tags. By default maven will include junit as a dependency to run unit tests in the test directory within your app.

Now go back to the MadTest directory.  You can enter below commands


  • mvn compile : This will compile your code.
  • mvn test : This will run the unit tests in the app
  • mvn package : This will package your app in to a file you specified in the pom.xml file. In this case it is a .jar file.
Now let's say you need you put a logging code inside your source code, like

Logger logger = LoggerFactory.getLogger(App.class);
        logger.info("Hello World !!!");

Now to work this code you need slf4j jar as a library and import it in the code. 
put,
import org.slf4j.*;

Now with maven, you do not need to download manually and put it in the libraries. Instead go to 


and put slf4j in the search box. Then go to the SLF4J Api module link and choose the version you want and click on the version number. If you choose 1.6.6, you will see something like below in that page.

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>

put this code inside dependencies tags in your pom.xml.
Then in the terminal go to the MadTest directory and type mvn compile. Now the dependent slf4j will be automatically be downloaded at the compile time. Then type mvn package. Now you will see the jar file in the target folder.

Now if you type mvn install in the terminal from the same directory, the app will be available in your local maven repository.

Wednesday, August 8, 2012

How to operate with big integer, big decimal

Sometimes the range of long, double  etc... becomes inadequate for certain mathematical operations. So  java provides a way to handle this problem by introducing BigInteger and Bigdecimal. These are very useful when the programmer needs to calculate big values.  Below examples shows how to work with big integer and big decimal.

First lets see an example of big integer.

BigInteger b1  = new BigInteger("293847293847938798");

BigInteger b2  = BigInteger.valueOf(1298L);
b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

int exponent = 3;
b1=b1.pow(exponent);

Now lets see an example of big decimal.

Bigdecimal b1  = new Bigdecimal("348950394.943859438");

Bigdecimal b2  = Bigdecimal.valueOf(1298L);

b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

An introduction to maven : How to setup maven manually

Maven is a built tool like ant. It is mainly used in building a program and project management. First the question is why do we need maven? below are some of the reasons to why we need maven.

  • It is very much likely that a program use jar libraries. We need to make sure these jars are available at the compile time, when bundling the program. Maven helps us in this regard.
  • Another problem is dependencies. A jar in the program may require another jar. May be the jars needed may need to have specific versions. This can be handled using maven.
  • To set a project structure, we can use maven.
  • To build, publish and to deploy.
Second question is how to set up maven? This is described below. This is very easy.
  • download maven from http://maven.apache.org/download.html
  • Then extract it to some location
  • open a terminal and type:           export MQ_HOME=/home/madhumal/apache-maven-3.0.4
  • Then type:                    export PATH="$PATH":/home/madhumal/apache-maven-3.0.4/bin
  • Now type :                    mvn --version
  • You will get the maven version and that is it. Not that the MQ_HOME is the path where you extracted maven binaries.
Alternatively the NetBeans IDE has inbuilt support for maven as well.

I will post more about maven in later posts.

Saturday, August 4, 2012

Aspect Oriented Programming with spring

In software programming, we meet cross cutting concerns in out app. Security, transaction handling, logging are examples to some of those. So Aspect oriented programming focuses on handling these concerns.
First of all why is it not okay to use a separate class or something to handle these concerns? For example why not logging with a class?

Well there are mainly 3 disadvantages 

1) We have to call methods using references to the class we created. - In logging we will be creating a logging object and calling a method within it when we need to use logging. Now say you modify or remove the logger class, then you will have change a lot of code in your program where you called the methods in the logger class. So it's a lot of mess for one little thing.

2) Too many relationships to the cross cutting concerns - You will have too many relationships to the logger class by referencing it from other classes. In the case of logger, it will be having too many relations from other classes. We do not want that. Simply because logger does not add a lot of business value to the program but only a helper.

3) cannot change all at once. - you will have to change codes in each and every class.

So how are these concerned solved?

Well we handle these by creating aspects (For the moment let's say aspect is a class with special privileges) like and aspect for logging, another for security, and another for Transactions etc...
Now how do we apply these aspects to the code? We do not create objects and call methods from other classes where the aspect is needed. Instead, an aspect configuration is created.
Now the question is how does the configuration handle it? well the configuration contains where to which classes and methods in the program the aspect should be acted upon. Therefore in a way, the aspect configuration is something that glues the aspects and the business logic objects together.


Eg: Say you need to call a security method in classA and classB. What you do is first create the security aspect and implement the methods. Then create classA and classB. Then create the aspect configuration. The configuration says to which methods in classA and classB, the methods in security aspects needs to be called for. It can specifically say which methods in security to call for a certain method in classA , which methods to call for a certain method in classB. aspects can be applied before or/and after the methods.

So if you want to do a bulk change, you can just chang the aspect configuration instead of changing everywhere.

Friday, August 3, 2012

Spring JSR 250 annotations

Below are some commonly used annotations in spring

1) resource annotation

@Resource(name="someBean")
public void setProperty(somebeantype property){
   this.property = property;
}
Here the @Resource annotation is used to locate the resource. The property is set using the .xml file and it should have a bean named "someBean". If the parenthesis and the arguments within it is not given with the annotation, then spring looks for a bean named in the xml file as the same name as the property. If not found you will get an exception.

2) required annotation.

Say you need to set a certain property when you initialized a bean and it is a must. Then you can add the @required annotation for the set method. In this way if the property is not set or the setter is not called for, Spring gives the exception even before running the business logic (That is in the initialization phase).

@required
public void someSetterMethod(Obj obj){
   this.obj  = obj;
}

3) post processor annotations.

@PostConstruct
   You can use this annotation to call a method just after the construction of a bean.

@PreDestroy
   You can use this annotation to call a method just before the bean is destroyed. This will be useful to do some clean up work.

Spring writing a bean post processor

BeanPostProcessor is an interface in Spring which helps the java developer to do some work when each an every bean is initialized. It does not matter weather you have one bean or many. The post processor acts on all of the beans.

First a class that implements the BeanPostProcessor should be created. The BeanPostProcessor implements two methods. One which does work before initializing a bean and another which does work after initializing a bean.

public class MyBeanPostProcessor implements BeanPostProcessor{
        //two methods that the BeanPostProcessor goes here(Use the ide to get the methods)
        // arguments in the methods are the bean itself and the name of the bean
}

Then you need to declare the implemented class in the xml file as a bean

<bean class="package.MyBeanPostProcessor"  />

Note that we have not used an id or a name for the bean. This is because the bean only needs to be declared in the xml file and is not used in any other bean.


Another post processor that is used in spring is the BeanFactoryPostProcessor which does work when the bean factory is initialized. The procedure is same as above except that this time the class extends the BeanFactoryPostProcessor.

One example for a BeanFactoryPostProcessor is the PropertyPlaceholderConfigurer in spring framework.
 You can store values in a filename.properties file and these values can be used in properties of a bean by using the PropertyPlaceholder.






Thursday, August 2, 2012

life cycle call backs of Spring framework

Lets say you need to keep track of life cycle call backs of spring beans.

The first point is if you want to destroy all the beans you created using a certain context, then you need to get the AbstractApplicationContext type of context Object. Then by calling registerShutdownHook method on the instance, all the beans that are created using that context instance is destroyed when the method is finished executing.

AbstractApplicationContext context = new ClassPathApplicationContext("spring.xml");
context.registerShutdownHook();

If you want to do something after the properties are set in a certain bean, you need to implement the InitializingBean interface in the class. The interface implements afterPropertiesSet method.

if you want to do something just before the bean is destroyed, you need to implement DisposableBean interface. The interface implements destroy method and there you can include any cleanup codes.

public class Vehicle implements InitializingBean, DisposableBean{

     public void afterPropertiesSet() throws Exception{

    }
    public void destroy() throws Exception{

   }
}

Another way of handling the life cycle of a bean is to mention the methods in the bean tag

<bean id="car" class="org.Car" init-method="myInit" destroy-method="destroy" ></bean>
Now spring looks for the myInit when initializing and destroy method after finishing in the bean class.

Instead of doing the above we can do the following

<beans default-init-method="myInit" default-destroy-method="destroy" >

As above the default methods can be metioned in the beans tag which covers all the beans. However if the method is not found in the corresponding bean class, then spring will just ignore it.

If we use both the methods together, then the priority goes to the interface implementation. That is interface methods are called first and then the spring configuration methods gets called.


Sunday, July 29, 2012

Setting up spring framework

Setting up spring framework is very easy.

Follow the steps below and you are good to go.

download latest version of spring framework from http://www.springsource.org/download

download apache commons logging binary jars from http://commons.apache.org/

create a java project using eclipse and set the jar file to the build path.

Now you can use the spring framework.

That is it.

spring what is dependency injection?

Dependency injection is a main feature of spring framework. This basically enables the injection of dependencies to a bean.

The example below explains this concept.

Say for an example there is a college class. Then this entity has a list of students, books, lecturers etc... Now we know that the students, books, lecturers are dependencies of college. That is the college class will have to use instances of the above mentioned dependencies. So we can inject these dependencies through an xml configuration file. Now if we call for the college bean through the ApplicationContext class for a bean of college, it will automatically pass the other dependencies as well (a list of student, books and lecturers.). The bean will have initial configured status with the dependencies. Therefore eliminating the requirement of making a list of dependencies by using new keyword for each of the dependency objects.

By default the beans follows the singleton pattern unless you specify the scope to something else. If you specify the scope to prototype, then spring will create object when a new bean is requested from  spring. Other than singleton and prototype, there are 3 other scopes and they are basically for web based applications.

Saturday, July 28, 2012

java apache commons logging

apache commons logging focuses on all aspects of reusable Java components.
It contains 3 main parts




  • The Commons Proper - A repository of reusable Java components.
  • The Commons Sandbox - A workspace for Java component development.
  • The Commons Dormant - A repository of components that are currently inactive.
  • Friday, July 27, 2012

    spring framework charastaristics


    spring is a framework used to make the life of a java programmer easy. Well when you talk about spring framework it has some important characteristics.

    1) Dependancy Injection - When you write a complex java code, you write classes to be as much as independent as possible and DI helps to glue them together while keeping them independent.

    2) Aspect oriented programming (AOP) - This helps you to decouple cross-cutting concerns like security, logging, declarative transactions, caching.

    apache tomcat - how to change the default port


    open your server.xml file (in ubuntu tomcat installation it is /etc/tomcat7/server.xml)
    then locate the code similar to

       < Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />

    or

        <Connector port="8080" maxHttpHeaderSize="8192"
                   maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
                   enableLookups="false" redirectPort="8443" acceptCount="100"
                   connectionTimeout="20000" disableUploadTimeout="true" />


    then change the port number to any number you like.

    adding usesrs to tomcat in linux

    go to the /etc/tomcat7 then type sudo vim tomcat-users.xml then enter the following in the tomcat-users element a role name grants certain privileges to certain users. now you have created a tomcat user and in this case a user with manager privileges.

    computational reflection

    Java is a programming language that has the computational reflection. That is it has the ability to examine and modify the structure of the program at run time. The package java.lang.reflect has the above mentioned facility.

    Tuesday, July 24, 2012

    Java How to change jvm memory settings.


    If you a using ecplise then you can set memory settings for a particular applicartion by simply setting VM arguments in it's run configuration as
    -Xms128m -Xmx512m. 
     In this particular  instance -Xms means the minimum memory and it is 128mb. -Xmx is maximum memory and it is 512mb.

    If you want to change the memory in system jvm then simply run java command in a terminal with -Xms281m -Xmx512m parameters given that the class path variable is set.

    Sunday, July 22, 2012

    Ebook Management software.

    Recently I have been searching for an opensource ebook management software that supports all sorts of document types ( such as pdf, epub,mobi etc...). Then I found a nice ebook library software called calibre. Only weights 32 mb and has a nice interface. more importantly you can store your ebooks based on the genre and has the bookmarking capability. Try it out, you will have a whole library with lots of ebooks that you never imagined. :)

    find pid of a process in linux

    you can simply type
        pidof <programm name>
    or also you can do this
        ps -aux  | grep <programm name>

    you can kill the process by typing as below
    kill -9 <pid>

    some other important linux commands
    create a simlink : ln -s <current directory> <directory to which the link should go>

    providing ownership of a certain directory to a specific user

    sudo chown <user name> <directory to provide ownership> -R

    java block variables

    class A{
      int x = 0;
     {x = 7; int x2=3;} //init block
      void doStuff(){
     //do something
    }

    }

    x2 is an init block variable.

    block variables cannot be accessed after the execution of the code block.

    Tuesday, July 17, 2012

    java singleton, when you want to avoid multiple instances but one.

    Singleton is a creational design pattern used to prevent from creating duplicate objects from a certain class. That is it limits the class to create only one object. Below example shows how to do this.

    static Object o;

    public static Object getObject(){

            if(o==null)
               o= new Object();

          return o;
    }

    This is actually a specialization of java's static factory method design pattern.

    Java how to invoke a static method using a string value

    You can invoke a static method as below

    Let's say you need to call SimpleClass.simpleMethod(int x);

    Method m = SimpleClass.class.getDeclaredMethod("simpleMethod", Integer.TYPE);
    m.setAccessible(true); //if security settings allow this
    Object o = m.invoke(null, 20); //use null if the method is static
    

    java invoke methods by a string name.

    Let's assume that you have a string value and the method name also have the same name as the string value. If you want to invoke the the method using the
    string value you can do it like this,

    Object obj;//object class which the method has
    String methodName = "getName" //string that you need to invoke the method.
     
    THEN GET THE METHOD LIKE THIS
     
    java.lang.reflect.Method method;
    try {
      method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
    } catch (SecurityException e) {
      // ...
    } catch (NoSuchMethodException e) {
      // ...
    }
     
    AFTER THAT YOU CAN INOKE IT LIKE THIS
     
    try {
      method.invoke(obj, arg1, arg2,...);
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    } 
     

    Java associative array

    Today I wanted to use an associative array in java and came to know that java does not have associative aarays. how ever there is a similar data structure you can use instead of an associative array. That is a hash map.

    Map<String, Object> map = new HashMap<>(String, Object);

    to put objects in the map,

    map.put("key","value");

    to retrieve, you can use the key as below.

    map.get("key");

    Jdbc driver time out.

    Recently I deployed an app on glassfish and it worked really well for about half a day and then it threw an exception each time the service was called. Following is the excetion

    com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No 
    operations allowed after statement closed.
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance 
    (NativeConstructorAccessorImpl. java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Deleg
     
    Later found out that the jdbc driver connection automatically 
    expires after 12 hours.  Setting conncetTimeout to 0 in the 
    jdbc connect url as a parameter resolved the problem.

    java split with "."

    String a = "a.jpg";
    String str = a.split(".")[0];
    This will throw ArrayOutOfBoundException
    Why is this?
    This is because "." is a reserved character in regular expression, representing any character.
    Instead, we should use the following statement:
    String str = a.split("\\.")[0];
    When the code is compiled, the regular expression is known as "\.", which is what we want it to be