Pages

Showing posts with label java-ee. Show all posts
Showing posts with label java-ee. Show all posts

Tuesday, July 1, 2014

Java EE singleton pitfall

If you implement a singleton class with the @Singleton annotation, then it is  considered all the method level access is read and write. Therefore a write lock is established automatically. Which is not good. Since when a method required a read lock its default setting is a write lock. So when you are programming, then you should always keep that in mind.

Thursday, November 28, 2013

Multi tenent applications with java

Want to know about some main considerations in multi tenent application development in java ee technologies? Have look at the following article.

http://www.javacodegeeks.com/2013/11/architecting-a-multi-tenant-application.html

Tuesday, November 5, 2013

Integration with apache camel

Want to get your hands on apache camel ? 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/10/20/apache-camel-developing-application-from-the-scratch-part-1-2/

Another detailed project tutorial could be found in the following link.
http://camel.apache.org/tutorial-example-reportincident.html

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.

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>


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

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.

Friday, September 14, 2012

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>

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

Monday, September 3, 2012

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