MyArchiBook

Archive for the ‘Java’ Category

Unsatisfied Dependency Exception : CDI 1.1 + Bean Validation + GlassFish 4.0 -> requires jersey-gf-cdi.jar upgrade

with one comment

Recently,  I faced Unsatisfied Dependency Exception, when trying to integrate BeanValidation with CDI 1.1 . Independently (without integration) everything worked fine. Looks like, the present Glassfish version 4.0 doesn’t support CDI 1.1 + Bean Validation together.

To be still clearer, Jersey (reference implementation for JAX-RS)  jar related to CDI  i.e., jersey-gf-cdi.jar in GF-4.0 version, is not supporting this integration .

I made the below changes, for Bean Validation integration with CDI 1.1 in Glassfish 4.0 to work.

Applicaiton Server used : Glassfish 4.0

Technology : JEE-7, CDI 1.1

Exception Trace :

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Foo,parent=Foo,qualifiers={@foo()}),position=-1,optional=false,self=false,unqualified=null,350112977)

at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:771)
at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:790)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$1.inject(CdiComponentProvider.java:316)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)

………………………….

Solution :

  • Download jersey-gf-cdi-2.0.jar . Download specifically 2.0 version for glassfish4.0. If other higher versions 2.10 are used, incompatibilty with other jars (firstly with jersey-server.jar) will arise.

http://repo1.maven.org/maven2/org/glassfish/jersey/containers/glassfish/jersey-gf-cdi/2.0/jersey-gf-cdi-2.0.jar

  • Rename the jar to jersey-gf-cdi.jar
  • Replace it in glassfish4.0/glassfish/modules/
  • Delete osgi-cache folder -> Path : glassfish4.0/glassfish/domains/domain1/osgi-cache
  • Refresh and restart glassfish. New osgi-cache will be created in domain 1 with the latest jersey-gf-cdi.jar. Problem will be solved 🙂

This issue will be resolved in Glassfish-4.0.1 version (not released yet). We’ll have to do the above till GF-4.0.1 is released.

Have a great day 🙂

Reference :
https://java.net/jira/browse/GLASSFISH-20597

CDI – Lifecycle Management by Container

with 3 comments

We know that, CDI Managed Beans are contextual. Their lifecycle management is done by the container. One of its main advantages is type-safe dependency injection.

But how does it do it?
In the below code, during application initialization process, the container checks for Type-Safe Resolution for News bean annotated with @Inject and then instantiates it.

TYPE-SAFE RESOLUTION:

Here the container checks ,

  • if the bean type is equal to the required type(type: News here) at the injection point in Consumer Bean class.
  • if the qualifier of bean is equal to the required qualifier at the injection point.
  • (If no qualifier specified , then default qualifier is @Default)


@Stateless
public class News {
  public String getLatestNews(){
    return "FIFA 2014 WorldCup";
  }
}

@Stateless
@Path(value = "consumer")
public class Consumer {

  @Inject
  private News news;

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("latestNews")
  public String tweetLatestNews(){
    return news.getLatestNews();
  }
}

Any mismatch will result in unsatisfied or ambiguous dependency problem.

CREATION AND DESTRUCTION BY CONTAINER:

 

Reference:

http://www.oracle.com/technetwork/articles/java/cdi-javaee-bien-225152.html
http://docs.jboss.org/weld/reference/latest/en-US/html/injection.html
http://docs.jboss.org/cdi/spec/1.0/html/contexts.html
http://docs.jboss.org/cdi/spec/1.0/html/injectionelresolution.html#ambigdependencies

EJB class able to render REST WebService via Annotation

with 3 comments

Advancements in Java, especially the advent of JEE6 and JEE7  has eased the way we code.
Deployment descriptors for Servlet classes, Entity classes, Web Services are being replaced by annotations, thus advancing towards the concept of Convention over Configuration.

Below is a simple example on how to make a Session Bean class provide a RESTful WebService using annotations.

Here I have used JEE 7 and GlassFish 4 Application Server.
Note: As of now, JEE7 is  compatible only with GlassFish 4.

Here I have considered WebsterPublications example which has,

  •  DictionaryEntity – Entity class
  •  DictionaryResource – EJB+REST Service Provider Class

STEP 1: Create DictionaryEntity.java

@Entity
@Table(name = "WP_DICTIONARY")
public class DictionaryEntity {

    @Id
    @GeneratedValue
    private Long id;

    @NotNull(message = "Enter a word")
    private String word;

    @NotNull(message = "Enter the word's meaning")
    private String meaning;

    //Getters , Setters
}

Attributes can be annotated with constraints like @NotNull, @Pattern and can be made to through message during runtime, when violations occur.

STEP 2: Create DictionaryResource.java

@Path(value = "dictionary")
@Stateless
public class DictionaryResource {

    @PersistenceContext(unitName = "webster")
    private EntityManager em;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path(value = "wordlist")
    public List<DictionaryEntity> getWordList(){
        Query query=em.createQuery("select d from DictionaryEntity d");
        List<DictionaryEntity> wordList=query.getResultList();
        return wordList;
    }
}

Here we can notice that this class apart from acting as a Stateless Bean also provides a RESTful WebService.
i.e., stateless session bean class providing the output object via REST WebService (Here JSON object got as Output).

Mapping the persistence unit and connection pooling in glassfish server is done (default Derby DB used).

STEP 3: Create WebsterRESTConfig.java

Since DictionaryResource acts like a Servlet by providing WebService, it’s essential to provide its entry in web.xml.
But this can also be done through annotation even.

WebsterRESTConfig class is created that extends Application and adds DictionaryResource as its resource class.Like DictionaryResource various other resource class can also be added.

@javax.ws.rs.ApplicationPath("webresources")
public class WebsterRESTConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }

   private void addRestResourceClasses(Set<Class<?>> resources) {
     resources.add(aish.vaishno.websterpublications.resource.DictionaryResource.class);
    }
}

Here @ApplicationPath is equivalent to the servlet-mapping URL-Pattern that we would specify in web.xml.

Also note, while instantiating Set<Class<?>> resources = new java.util.HashSet<>(); I haven’t used generics in HashSet<> but have just used a plane Diamond notation. This is one of the light-weight changes in Java SE 7.

Now when we give the path as:

http://localhost:8080/WebsterPublications/webresources/dictionary/wordlist
URL

The result is obtained as below.

Output

In my this post I wanted to highlight on the concept of Convention Over Configuration which is taking a great leap as the advancements in JEE versions are happening.Without even taking the pain to write the conventional web.xml deployment descriptor, we are now that able to  configure those settings by using simple annotations at the right place.

You can find the above source code in my GitHub repository. 

I wish you all a BLASTFUL 2014 🙂

Reflection – Dynamic Typing

with 4 comments

Today wanted to add some quick notes on my findings on Dynamic Languages.

To start with, lets look into Reflection.

REFLECTION” –  in common generic terms means a Mirror Image of something.

It carries the same meaning in Java. It means getting the mirror image of a class.
The microscopic details of a class can be explored during the runtime by specifying the class name dynamically. During this process the JVM interacts with the object of unknown type.

Let’s see an example,

public static void main(String[] args) {
	try {
		Class class1=Class.forName("aish.vaishno.musicstore.dao.MusicStoreDaoImpl");
		Package package1=class1.getPackage();
		System.out.println("Package Name with Version : "+package1);

		String canonicalName=class1.getCanonicalName();
		System.out.println("\nCanonical/Standard name of Field class: "+canonicalName);

		Method[] methods=class1.getMethods();
		System.out.println("\nMethods present in Field class:");
		for (int i = 0; i < methods.length; i++) {
			System.out.println(methods[i]);
		}

                Class[] classes=class1.getInterfaces();
                System.out.println("Interface implemented: ");
                for (int i = 0; i < classes.length; i++) {
                System.out.println(classes[i]);
                }
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
}

While specifying the className dynamically, the .class file of that particular class is opened and examined during the runtime .By Reflection, the package ,Method , Interface, modifier informations and etc.,can be retrieved.

But the demerits of this is ,

  • It slows down the performance
  • private fields and methods can be accessed.

Reflection concept is used in ,
Spring – while scanning through the packages.
ORM– when data from database is being mapped to the attributes in Entity Bean.
Likewise in Serialisation/Deserialisation, Remote Method Invocation and etc.,

Dynamic Language plays a major role in Rapid Application Development(RAD).

Groovy and Dynamic Language updates coming up.

 

Reference:

http://javarevisited.blogspot.com/2012/04/how-to-invoke-method-by-name-in-java.html

Written by thangaveluaishwarya

August 9, 2013 at 9:48 PM

Spring + JPA – Example with Exception/Error – Fixing

with 8 comments

In this post ,I have given a  simple example on how to use JPA in Spring Framework.
You can find the source code of the below example in my Github link here.

I have considered a MusicStore example, where i just get the list of Songs from the database.

TOOLS USED:

Framework: Spring
Persistence API : JPA 2.0
Build : Maven
Database : MySQL
JPA Provider : Hibernate-JPA Provider

While I was working on integrating JPA into Spring , I felt that, the most important part to concentrate on , is the CONFIGURATION area.

So,let’s get started with application-context.xml and persistence.xml

app-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/jdbc
   http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   
 

<context:component-scan base-package="aish.vaishno.*" />    
 
<tx:annotation-driven transaction-manager="transactionManager"/>
 
<bean id="transactionManager"
  class="org.springframework.orm.jpa.JpaTransactionManager">
     <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

 <bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:persistenceUnitName="simple-jpa">
 </bean>
 
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/MUSIC_STORE"/>
        <property name="username" value="music_store"/>
        <property name="password" value="music_store"/>  
    </bean>
    
</beans>

  • DIFFERENCE BETWEEN <context:annotation-config> AND <context:component-scan base-package=”…..”>

<context:annotation-config> -Enables the usage of JPA annotations(@Service, @Component, @Repository, @Controller  and etc.,)
<context:component-scan base-package=”…..”> – This component-scan tag also enables the usage of JPA annotations.

Then the difference ???

(i) annotation-config —> enables the usage of JPA annotations , only in the beans specified in the context.xml whereas (ii) component-scan —> scans through all the packages specified, records all the  project beans having JPA annotations, into this context.xml. Therefore it enables JPA annotaion usage in (beans specified in context.xml)+(Project Beans).

Inshort, <component-scan> extends <annotation-config>.

When we use <component-scan> in the app-context.xml, it’s not necessary to use  <annotation-config> again.

Even if both  the tags are specified, it’s not a problem because, the spring container would take care of running the process only once.

  • <tx:annotation-driven transaction-manager=”transactionManger”/> – It checks for @Transactional annotation  in any of the classes. This tag is like a Transactional Switch that turns on the transactional behaviour.Here Transaction Manager is being injected .
  • <bean id=”transactionManager”>– Here Transaction Manager is setup.

Here EntityManagerFactory is being injected.

  • <bean id=”entityManagerFactory”>– Here EntityManagerFactory is setup .Data Source reference and Persistence UnitName Reference is specified.
  • <bean id=”dataSource”> – DB connection details are specified.
  • Persistence UnitName Reference – Based on the PersistenceUnit name, the corresponding portion of persistence.xml is accessed (a Project can have multiple persistenceUnitNames)

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="simple-jpa" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>aish.vaishno.musicstorespringjpa.pojo.MusicDetails</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> 
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.max_fetch_depth" value="3"/> 
    </properties>
  </persistence-unit>
</persistence>

Here in persistence.xml,

  • persistence-unitName is declared
  • provider – In this example, I have used Hibernate provider.
  • Entity Bean Class is specified
  • properties- Few settings(like showSQL=true) required are specified.

Configuration part is over. Now that, it’s time to use the annotations in our Dao class to make the Spring – JPA work.

POJO : MusicDetails.java

DaoInterface :

public interface IMusicStoreDao {
   public List getMusicList();
}

DaoImplementation :

@Service(value = "MusicCollections")
@Repository(value = "MusicCollections")
@Transactional
public class MusicStoreDaoImpl implements IMusicStoreDao{

  @PersistenceContext(unitName = "simple-jpa")
    private EntityManager entityManager;

   @Override
     public List getMusicList(){
     List musicDetailsList= entityManager.createQuery("select c from MusicDetails c").getResultList();
     return musicDetailsList;
    }
}

Executer:

public class Executer {
   public static void main(String[] args){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("META-INF/app-context.xml");
        IMusicStoreDao musicStoreDao=(IMusicStoreDao) applicationContext.getBean("MusicCollections");
        System.out.println("MusicList: \n"+musicStoreDao.getMusicList());
    }
}

Now , when you run this main class, for sure , you would only get Errors and Exceptions :-P.
Because, we have not yet added the DEPENDENCY JARS.
Below , I have given a note on the Errors and Exceptions that would arise and the corresponding jars to be added to clear that particular problem.

You can find the Maven dependency tags for the below jars in my Github pom.xml

ERRORS/EXCEPTIONS AND THE CORRESPONDING JARS TO BE ADDED:

  • ERRORException in thread “main” java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/transaction/SystemException. 
  • JAR: javaee5-api.jar . Do not forget to specify the scope as “provided”, otherwise the error will still persist.
  • ERROR: Exception in thread “main” java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/EntityManager.
  • JAR: hibernate-jpa2-api.jar
  • EXCEPTION: ClassNotFoundException : org.hibernate.ejb.HibernatePersistence
  • JAR: hibernate-entitymanager.jar
  • ERROR: NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
  • JARS: slf4j-api.jar, slf4j-jcl-over.jar ( scope-RUNTIME ), slf4j-log4j12.jar ( scope-RUNTIME )
  • Do not forget to add the respective JDBC jar.

Now the program can be executed.

RESULT:

Result

Have a great day 🙂

(Spring – MVC+Hibernate –> Annotation based), MySql , Maven, JSON – Simple Example

with 20 comments

Hi! For the past few days, I have been trying out on Spring – MVC, Hibernate, Maven, MySql and JSON . So I thought, if I could blog about it today with a simple example.

In this post , I have used Hibernate to persist data in the back end  and JSON to display results in the front end.

You can get the below example’s complete source code from my GitHub link here —> https://github.com/AishwaryaThangavelu/Spring-Repository/tree/master/MusicStore.

Let’s take a look at it now.

INFORMATION:

  •  Tool used : NetBeans 7.3
  •  Framework : Spring-mvc-archetype – 3.X
  •  JPA: Hibernate
  •  Build : Maven 2.2
  •  Database Server : MySql
  •  WebApp Server :Tomcat 7

I have considered MusicStore example where I Add Songs and display a list of Songs.

OVERVIEW :

Flow

Flow of Application

STEPS:

1. TO CREATE A TABLE IN MySQL: 

  • Create DB – “CREATE DATABASE MUSIC_STORE;”
  • Create Table 
CREATE TABLE MUSIC_COLLECTIONS(
MC_ID INTEGER(50),
MC_LANGUAGE VARCHAR(50),
MC_TYPE VARCHAR(50),
MC_SONG_NAME VARCHAR(50)
);
  • To give Grant permission for accessing the Database- 

GRANT ALL PRIVILEGES ON MUSIC_STORE.* TO ‘music_store’@’localhost’ IDENTIFIED BY ‘music_store’;

Folder Structure

Folder Structure

2. CREATA A NEW SPRING-MVC PROJECT:

I have used Maven coupled Spring-mvc-archetype.

This Spring-mvc-archetype makes me too comfortable providing me the template as such.My duty is to just to work on the main coding part.

3.CREATE A POJO CLASS(Here MusicDetails.java):

@Entity
@Table(name = "MUSIC_COLLECTIONS")
public class MusicDetails implements Serializable {

 @Id
 @Column(name = "MC_ID")
 private Integer musicID;

@Column(name = "MC_LANGUAGE")
 private String musicLanguage;

 @Column(name = "MC_TYPE")
 private String musicType;

 @Column(name = "MC_SONG_NAME")
 private String songName;

public Integer getMusicID() {
 return musicID;
 }

public void setMusicID(Integer musicID) {
 this.musicID = musicID;
 }

public String getMusicLanguage() {
 return musicLanguage;
 }

public void setMusicLanguage(String musicLanguage) {
 this.musicLanguage = musicLanguage;
 }

public String getMusicType() {
 return musicType;
 }

public void setMusicType(String musicType) {
 this.musicType = musicType;
 }

public String getSongName() {
 return songName;
 }

public void setSongName(String songName) {
 this.songName = songName;
 }
}

Now let’s connect our applicationProject with the database.

4. CONFIGURATION:

Hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/MUSIC_STORE</property>
  <property name="connection.username">music_store</property>
  <property name="connection.password">music_store</property>
  <!-- JDBC connection pool (use the built-in) -->
  <!--<property name="connection.pool_size">20</property>-->
  <property name="hibernate.c3p0.acquire_increment">3</property>
<property name="hibernate.c3p0.idle_test_period">14400</property>
<property name="hibernate.c3p0.timeout">25200</property>
<property name="hibernate.c3p0.max_size">15</property>
<property name="hibernate.c3p0.min_size">3</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.preferredTestQuery">select 1;</property>
  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <!-- Enable Hibernate's automatic session context management, in this case the session will be close after each transaction! -->
  <property name="current_session_context_class">thread</property>
  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  <!-- auto create tables -->
  <property name="hbm2ddl.auto">update</property>
  <!-- Mappings -->
  <mapping class="aish.vaishno.musicstore.pojo.MusicDetails"/>
</session-factory>
</hibernate-configuration>
  • line 8 , connection with the particular DB with specific grant permitted username and password is specified
  • In line 31 POJO class maping is specified.

5.HIBERNATE SESSION MANAGER:

public class HibernateSessionManager {

 private static SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory(){
 try{
   sessionFactory=new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
   return sessionFactory;
 }
 catch(Throwable ex){
   System.err.println("Session Factory Initialization error"+ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static SessionFactory getSessionFactory() {
   return sessionFactory;
 }

 public static void shutdownConnection(){
   getSessionFactory().close();
 }
}

Specify mySql-connector-java.jar and javassist.jar dependency in pom.xml to establish connection with DB

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.15</version>
</dependency>

<dependency>
  <groupId>javassist</groupId>
  <artifactId>javassist</artifactId>
  <version>3.12.0.GA</version>
</dependency>

6.PERSISTENCE LAYER:

    • MusicStore DAO Interface creation:

Here I have created 2 methods as specified earlier,
 One method:  to add new songs
Second method: to get the List of Songs available

public interface IMusicStoreDao {

   public String addSong(MusicDetails musicDetails);
   public List getSongList();

}
  • Music Store Dao Implementation Class:

Here I have specified @Service inorder to inject it into Service Layer class.

@Service
public class MusicStoreDaoImpl implements IMusicStoreDao{

 @Override
 public String addSong(MusicDetails musicDetails) {
   SessionFactory sessionFactory= HibernateSessionManager.getSessionFactory();
   Session session=sessionFactory.openSession();
   Transaction transaction=session.beginTransaction();
   try{
     transaction.begin();
     session.save(musicDetails);
     session.flush();
     transaction.commit();
     return "Music Details has been entered";
   }catch(HibernateException hb){
     transaction.rollback();
     System.err.println("error"+hb);
     return "Sorry some problem has occured. Try Again";
   }finally{
     session.close();
   }
 }

 @Override
 public List getSongList() {
   SessionFactory sessionFactory=HibernateSessionManager.getSessionFactory();
   Session session=sessionFactory.getCurrentSession();
   Transaction transaction=session.beginTransaction();
   try{
     transaction.begin();
     List songList=session.createQuery("from MusicDetails").list();
     return songList;
   }finally{
     session.close();
   }
  }
 }

7.SERVICE LAYER:

  •     Service Layer Interface Creation :
public interface IMusicStoreService {
  public String addSong(MusicDetails musicDetails);
  public List getSongList();
}
  •    Music Service Implemetation Class Creation :

I have annotated this class with @Service because later , in the controller I will be Injecting this class.You can see that IMusicStoreDao is Autowired which means I have injected it in this class and that is why I specified @Service annotation in MusicStoreDao class.

@Service
public class MusicStoreServiceImpl implements IMusicStoreService{

 @Autowired
 private IMusicStoreDao musicStoreDao;

@Override
 public String addSong(MusicDetails musicDetails) {
   return musicStoreDao.addSong(musicDetails);
 }

@Override
 public List getSongList() {
    return musicStoreDao.getSongList();
 }
 }

I have also specified @ComponentScan in Configuration class to scan through the packages containing the respective classes with @Service annotation.

8.PRESENTATION LAYER:

Controller:

I have Autowired IMusicStoreService class

@Controller
public class HomeController {

@Autowired
 private IMusicStoreService musicStoreService;

 @RequestMapping(value="/")
 public ModelAndView test(HttpServletResponse response) throws IOException{
    return new ModelAndView("home","musicDetForm",new MusicDetails());
 }

 @RequestMapping(value="AddSong",method = RequestMethod.POST)
 @ResponseBody
 public String addSong(@ModelAttribute("musicDetForm") MusicDetails musicDetails){
    return musicStoreService.addSong(musicDetails);
 }

 @RequestMapping(value="SongList/",method = RequestMethod.GET)
 @ResponseBody
 public List<MusicDetails> getSongList(){
    return musicStoreService.getSongList();
 }
}

RUNTIME DEPENDENCY JAR’S TO BE ADDED:
Below are few runtime dependencies to be added in pom.xml to avoid Logging Factory and Load Class error.

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>jcl-over-slf4j</artifactId>
   <version>1.6.1</version>
   <scope>runtime</scope>
 </dependency>
 <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.1</version>
    <scope>runtime</scope>
 </dependency>
 <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
    <scope>runtime</scope>
</dependency>

RESULTS:

1.ADD SONG :  I created the form using Simple-Spring Form Handling.You can find details about it in this link, refer to

https://aishwaryavaishno.wordpress.com/2013/06/22/simple-form-handling-and-performing-dependency-injection-in-spring-mvc-framework-using-netbeans/ 

and I have displayed the result .

AddSongResult

AddSongResult

MusicStoreForm

MusicStoreForm

2.SONG LIST DISPLAY :Here I have used JSON format to display result.
JSON:

  •   JSON(Java Script Object Notation) is a data transfer format,used for exchanging data between client and server-side application.
  • It is much like XML. No, actually it is easier than XML bcoz it is easy to understand, language independent and has parsers available for most of the languages(one eg: eval()).
  • It provides me the flexibility of writing just one application and runnning it on any type of application.

For this application, all that u need to know about JSON is, just

  • add the below Jackson Library dependency into the pom.xml
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>
 
  • Specify @ResponseBody JSON-REST Service.
  • Specify the Mapping properly in the Controller .

The “REST” JSON will take care.

Now when you hit the URL link, the JSON result will be as below for SongList.
SongList

That’s it.. 🙂

Hope it’s informative.. Have a great day !!!!

Written by thangaveluaishwarya

July 12, 2013 at 10:09 AM

Simple Form Handling and Performing Dependency Injection in Spring MVC Framework using NetBeans

with 6 comments

  I thought  working on Spring MVC Framework– to handle xml, configurations etc.,was a geeky kindaa job.  But I also recently learnt that , working on it using an IDE like NetBeans which provides the Spring MVC Template(pom.xml, MVC Configurations etc.,) and also the Maven build  has made me focus mainly on the design and coding part of my project , thus saving my time and leaving me unstrained .

Below I have created Simple Form Handling Application using Spring MVC Framwork(3.X).In this sample,I have also implemented Dependency Injection – annotation based .

IDE used:NetBeans 7.3

Build used:Maven 2.2

JspConsider 2 Jsp’s

Jsp 1  : MusicForm.jsp contains the text boxes to be entered.

Jsp 2 : Output.jsp conatins the TEXTS of,

  •          Object transferred from Jsp 1
  •          Object got through DEPENDENCY INJECTION

FLOW:

1.Bean : SongDetails Bean with setters and getters is created

2.Interface : IMusicService Interface is created. It has three unimplemented methods play(), pause(), stop();

3.Service Implementation class :MusicServiceImpl class that implements the above interface and its unimplemented methods is created.

@Service
public class MusicServiceImpl implements IMusicService{
@Override
 public String play() {
 return "Music is played on!!!";
 }

@Override
 public String pause() {
 return "Music has been PAUSED !";
 }

@Override
 public String stop() {
 return "Music Stopped";
 }
}

Note  that there is @Service annotation before the class name… Please have it in mind.Will tell you why, when it’s time of usage has come.

4. Jsp and Controller:

4.a) HomePage(MusicForm) Jsp and Controller :

MusicForm

Here in MusicForm.jsp, the details to be transferred is enclosed in a form.Form has the following attributes,

  • Method type – GET/POST is specified here.
  • commandName -Here we can specify name of the Object , that carries the SongDetails (above commandName is songDetForm )
  • action- Here OutCome jsp name, where the details are to be transferred is specified.

For the above Jsp , controller method has to be written.The flow goes like this,

  • ModelAndView object is created
  • ViewName is set
  • SongDetails Object is initialised and set as songDetForm (must be same as commandName in jsp).

4.b)Output jsp and Controller:

Output

Here in this Controller,

  • Output jsp name is given as the Request mapping value
  • Request method is POST as specified in First Jsp
  • View Name is set.
  • Then Two Objects are set—->1.songDetForm, 2.object got through dependency injection
  • To set songDetForm obj,
  1. Object is got from HomePageController method via @ModelAttribute(“songDetForm”)SongDetails songDetails. This means , object or attribute in the name “songDetForm” is assigned to songDetails object.
  2. This object is then added in a HashMap
  • To set Dependency injection object,
  1. IMusicService private instance is created .It is annotated with @Autowired.
  2. Apart from this, @Service annotation has to be specified on the ServiceImplementation class . This means, MusicServiceImpl class is at Service which can be injected ,when @Autowired annotation is used over its Interface instance.
  3.  In MVC Configuration, the package be scanned is specified and Component Scan is done.
  4. then dependencyObject is  added in the Controller method map.
  • Both these objects along with viewName are set in mv and mv is returned.

The controller sourcecode will look like,

@Controller
public class HomeController {

 @Autowired
 private IMusicService iMusicService;

 @RequestMapping(value="/")
 public ModelAndView homePage(){
 //Method 1:
 ModelAndView mv=new ModelAndView();
 mv.setViewName("MusicForm");
 mv.addObject("songDetForm",new SongDetails());
 return mv;

 //Method 2:                  viewName      Obj Key        Obj Value
 // return new ModelAndView("MusicForm","songDetForm",new SongDetails());
 }

 @RequestMapping(value ="/Output", method = RequestMethod.POST)
 public ModelAndView processSongDetails (@ModelAttribute("songDetForm") SongDetails songDetails){
 Map<String,Object> obj=new HashMap<String,Object>();
 obj.put("songDetails",songDetails);
 obj.put("iMusicService", iMusicService);
//                                            viewName  Obj
 ModelAndView modelAndView = new ModelAndView("Output", obj);
 return modelAndView;
 }
}
  • In the respective Output.jsp , the respective objects are got.

5. Clean the project.

6.Build it using Maven… The most advantageous part about Maven is , I needn’t have to strain myself to provide any dependency jars, specify its classpath etc.,  everytime. Maven took care of that part by itself, thus making my code-writing easy and simple.

7.Run it.

The output will be as follows…

WebPageResult

That’s it about Form Handling and Dependecy Injection in Spring MVC Framework.

You can find and download the above source code from this link.  https://github.com/AishwaryaThangavelu/Spring-Repository

Written by thangaveluaishwarya

June 22, 2013 at 3:49 AM

Hibernate Persistence Context and Object’s LifeCycle

with 4 comments

A Software Industry mainly works on Enterprise Applications. When Persistence Frameworks are being used in the application, then it is better to know about the Persistence Context and Object’s Life Cycle, inorder to deal with the complexities.

BASICS:

  • Object Oriented Programming(OOP)  plays a major central role for developing any application. It is a design concept. It can be imagined as a Collection Of  Interacting Objects.
  • Relational Database Management System helps to store these entity objects into the Database objects(tables).
  • Object Relational Mapping (ORM) relates  objects from Object Oriented domain with relational Data model via mapping.

JPA

    Java Persistence API(JPA exists in JEE5 and higher ) is a specification which  has the features that will make the ORM work.It deals with , how Java Objects(“persistent entites”)are stored in the relational database, how they can be accessed and how the object’s state can be stored so that it can be  restored when the appication is restarted .

Hibernate 3.2,EJB 3 ,TopLink and etc., are frameworks that implement this JPA.

In this post I have briefed on Hibernate’s Persistence Context Pattern and the Object’s LifeCycle.

HIBERNATE PERSISTENCE CONTEXT PATTERN AND OBJECT’S LIFE CYCLE:

  • HIBERNATE is a Simple Persistence Framework . It is a flexible framework even.Flexible, because  it can be used even with or without an application server.
  • Hibernate provides functionality that persists objects of an object-oriented programming environment into some persistent store. These persisted objects are called Persistent Objects.
  • The place where the persistent objects are created,modified and retrieved is called the Persistence Context.
  • The three most importantly used classes of Hibernate’s Persistence API are,
  1. org.hibernate.SessionFactory
  2. org.hibernate.Session
  3. org.hibernate.Transaction

object-life-cycle

  • SessionFactory has the contract to create session instances for the application.Usually one data source has a single session factory instance. In an application, the threads servicing client requests, obtain Session Instances from this factory.
  • Session is THE Hibernate’s Persistence Context.The lifetime of a session is bound between the beginning and the end of a transaction.As said earlier, the persistent objects are created,modified and retrieved only in this session. While carrying out these operations on the objects, they might exist in one of these three states,
  1. transient state
  2. persistent state
  3. detached state
  • Transaction defines the UNIT OF WORK for an application.It is instantiated when Session.beginTransaction() is called.

Let’s get into examples to understand the Object’s life cycle with respect to Persistence Context.Here I have considered an example related to Company and its Chairman.

Attributes: Company Name and Chairman..

CASE 1:

public class CompanyDao {
	public void enterCompanyDetails(){
		Session session=HibernateSessionManager.getInstance().getHibernateSession();
		Transaction transaction=session.beginTransaction();
		try{
			transaction.begin();
			CompanyDetails companyDetails=new CompanyDetails();
			companyDetails.setCompanyName("Apple");
			companyDetails.setCompanyChairman("Steve Jobs");
			session.save(companyDetails);
            EmployeeDetails employeeDetails=new EmployeeDetails();
            employeeDetails.setNoOfEmployees(100000);
            transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
		}finally{
			session.close();
		}
	}
}

Logic:SAVE —> COMMIT

  • Line 8 and 9 – the company name and chairman are set to the CompanyDetails object. Now this object’s instance which is a new one exists in the transient State.
  • Line 10- the object’s instance is being saved, which means it is being persisted in the Persistence Context. Now it is in the persistent state.
  • Line 11- a new employeeInstance is created.
  • Line 12- attribute is set to the instance. The instance now exists in the transient state.
  • When the transaction is committed, only the objects in the Persistence Context gets persisted in the Database as a record.i.e.,Here the persistent object companyDetails gets persisted but employeeDetails does not get persisted because it is in transient state.

Check out if you can answer this question ,

Qn.When you  Insert a data and update the same data in a session , will a new memory object be created in the Persistence Context or will it get Updated in the existing object in the Persistence Context…???

Ans: No, a new object is not created in Persistence Context while updating. Instead , the persistent object created when saving the object in the persistence context gets updated.

The answer is explained with an example below,

CASE 2:

public class CompanyDao {
	public void enterCompanyDetails(){
		Session session=HibernateSessionManager.getInstance().getHibernateSession();
		Transaction transaction=session.beginTransaction();
		try{
			transaction.begin();
			CompanyDetails companyDetails=new CompanyDetails();
			companyDetails.setCompanyName("Infosys");
			companyDetails.setCompanyChairman("K.V.Kamath");
			session.save(companyDetails);
			companyDetails.setCompanyChairman("Narayana Murthy");
			session.update(companyDetails);
            transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
		}finally{
			session.close();
		}
	}
}

Logic: SAVE –> UPDATE –> COMMIT
TRUE 1

  • Line 8,9 – the attributes are set to the object.The object’s instance is in the transient state.
  • Line 10-The instance is saved. So , it moves to the Persistence Context and becomes a persistent object.
  • Line 11- the instance is again set.
  • Line 12- the instance is updated in the Persistence Context. I mean, already an object is created in the persistence context and that object gets modified/updated. New object is not created in the persistence context.
  • Line 13 – The persistent object is committed/persisted to the DB.

Note:Update() can be performed only on Persistent Objects and not on transient/detached objects whereas saveOrUpdate() automatically converts a transient/detached object to persistent object.

CASE 3:

public class CompanyDao {
	public void enterCompanyDetails(){
		Session session=HibernateSessionManager.getInstance().getHibernateSession();
		Transaction transaction=session.beginTransaction();
		try{
			transaction.begin();
			CompanyDetails companyDetails=new CompanyDetails();
			companyDetails.setCompanyName("Infosys");
			companyDetails.setCompanyChairman("K.V.Kamath");
			session.save(companyDetails);
			companyDetails.setCompanyChairman("Narayana Murthy");
			session.saveOrUpdate(companyDetails);
			session.clear();
			System.out.println("Company Details present : "+session.contains(companyDetails));
            transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
		}finally{
			session.close();
		}
	}
}

Logic: SAVE –> UPDATE –> CLEAR –> COMMIT
false

Here in the above code,

  • Line 8,9 -Instance is set.It exists in the transient state.
  • Line 10 -Instance is saved to Persistence Context.It is in the persistent state now.
  • Line 11,12 – instance is set and updated in the Persistence Context
  • Line 13- All instances in the Persistance context are cleared. It has no instance in the context now. This means , the instance is in detached state now.

Like clear() there is also another method evict().The difference is ,evict() detaches a particular instance from the context but clear() detaches all the instances from the Persistence Context.
Hope this post has added an extra feather to your understanding.

Written by thangaveluaishwarya

June 7, 2013 at 9:56 PM

SINGLETON in Multithreaded Environment

with 12 comments

  Most of the time, we are confined to sequential programming.However,several parts of our program can also be executed parallely by concurrent programming. In concurrent programming, the whole program is split into independent running tasks.Using multithreading, each of these independent tasks (also called subtasks) is driven by a thread of execution.The advantages of concurrency is faster execution,improving code design(espeically in Simulation Applications) etc.,

  To be simple, Unless multithreading had been added to Java, any concurrent Java programs wouldn’t have been portable to the Macintosh and similar platforms, thus breaking the “write once/run everywhere” requirement (Eckel,Bruce et al., 2005).

  However the real problem with this concurrency occurs, when each of the tasks begin to interfere with eachother.I mean at times,correct programs can also exhibit incorrect behavior. 

Let’s see what incorrect behaviour, a Singleton Class can execute in a mutithreaded environment.

   I have written the following code with respect to the MusicStore example that I have discussed in my previous blog(https://aishwaryavaishno.wordpress.com/2013/05/17/global-access-point-singleton-design-pattern/).However I have made variations in my Singleton class to signify the importance and disadvantages of each implementation.

private static MusicStre getMusicInstance(){
  if(musicInstance==null){
    musicInstance=new MusicStore();
  }
return musicInstance;

 

  • In the above method, the instance is created via Lazy Initialisation.i.e.,the object is created only when needed.
  • Lazy Initialisation is usually done for Performance Optimisation.

Here let’s consider that two threads are accessing this class.

The flow goes this way,

  • Thread 1 enters the class
  • Thread 1 accesses the method getMusicInstance().
  • Initially the musicInstance is null , so the control goes inside the if()block to create new Music Instance for the class.
  • Consider thread 2 also enters the class parallely with thread 1.Here there are two chances,

         Chance 1:Thread 1 completing its process before thread 2 accesses the getMusicInstance method.If so, the musicInstance for thread 2 will not be null.Thread 2 gets the same Instance as Thread 1.
         Chance 2: Thread 1 has not yet completed its process(getting Instance). If so, musicInstance for thread 2 will be null.Therefore the thread 2 control goes inside the if()block to create new Music Instance for the class.

Result

Result

Here for Chance 2 the result will be as above.Thread 1 has new Instance and thread 2 also has a new Instance.It’s very obvious from the picture that the MusicStore class(supposed to be a Singleton class) cannot be called a singleton class because it has violated the behaviour by giving different instances.Therefore Thread Safety has not been achieved here.

Let’s see how to achieve Thread-safety.

1.Using Synchronized Block- LAZY Initialization:

The above problem of thread-safety can be achieved by using a Synchronized block.

public static MusicStore getMusicInstance(){
synchronized (MusicStore.class) {
   if(musicInstance==null){  musicInstance=new MusicStore();
    }
 }
return musicInstance;
}

Synchronized block allows only one thread to run at a time . The part of method that has to be synchronized is placed inside the block.Here Thread 1 comes in . It acquires the lock. Now the thread 2 has to wait till Thread 1 comes out of the synchronized block and releases the lock.

Here we do synchronisation, to get newMusicInstance object for threads having NULL music Instance.In the above case we can notice that, whether the music Instance of threads is null or not , the thread has to wait. It’s a waste of time for Threads which has musicInstance!=null.

To avoid this we use another null check condition before the synchronized block as shown below.

public static MusicStore getMusicInstance(){
  if(musicInstance==null){
   synchronized (MusicStore.class) {
    if(musicInstance==null){
     musicInstance=new MusicStore();
    }
   }
 }return musicInstance;
}

FLOW:

  • Thread 1 enters the method getMusicInstance(). Here initially musicInstance is null.
  • Now Thread 1 enters the synchronised block and acquires the lock. If no thread has passed the synchronized block earlier, the musicInstance of thread 1 still remains null.
  • Thread 1  gets the new musicInstance.
  • Thread 2 enters the method parallely with the thread 1.(Consider thread 1 has entered the synchronised block and has not finished complete execution)So, the music Instance of thread 2 will also be null.
  • Thread 2 tries entering the synchronized block.Since thread 1 has acquired the lock, thread 2 waits till thread 1 completes it’s execution and releases the lock.
  • Thread 1 releases the lock
  • Thread 2 enters Synchronized block.
  • NewMusicInstance got by thread 1. So musicInstance for Thread2!=null.So,thread 2 does not enter into if() block but will get the same instance as Thread 1,thus achieving thread safety.

This process of double checking is called DOUBLE CHECKED LOCKING PATTERN

Note: Here I have not synchronized the whole method but have synchronized only a part of the code .

Synchronization is useful to control access to resources within the same JVM. If the resources are present in different JVM then synchronized block alone is not sufficient, we will have to get an external lock .

2.Using Lock-LAZY Initialization:

public static MusicStore getMusicInstance(){
 final Lock lockObj=new ReentrantLock();
  if(musicInstance==null){
   lockObj.lock();
   if(musicInstance==null){
     musicInstance=new MusicStore();
   }
   lockObj.unlock();
 }
return musicInstance;
}

This lock is a mutually Exclusive one(MUTEX).i.e, allows only one thread at a time.

Here the execution is the same as the synchronised method. However,this implemetation can used, when multiple JVM’s come into picture.

3. EAGER Initialisation:

private static final MusicStore musicInstance=new MusicStore();

private MusicStore(){
}

public static MusicStore getMusicInstance(){
return musicInstance;
 }
  • Here Instantiation happens once when the class is called.It is a very straight-forward implementation.
  • If the object does not cost too high, then this would be a better approach.But when there are situations where, lazy loading is needed, then this approach cannot be used.

Every coin has its two sides.Likewise,all the above types of implementation has it’s own advantages and disadvantages. So,it’s all left upto the developer/designer to choose the right type of implementation based on the needs.

I would also like to add on that, if the proper designing of the Singleton class is not done and is used in applications related to Banking, DB resource sharing etc., then it would for sure cause a disaster.

Life is Simple just because Design is always around but designing that Design Pattern is not that Simple.

 

Written by thangaveluaishwarya

May 24, 2013 at 11:22 PM

Global Access Point – SINGLETON Design Pattern

with 6 comments

*Click on image to view it better

Slogan

                          Design Patterns provides better recurring solutions for commonly occurring problems says Gang Of Four and SINGLETON is one such DESIGN PATTERNS.

Description:
There must be only one instance to a class and that instance must be the MAIN IMPORTANT GLOBAL POINT OF ACCESS to all other related Classes.

A Singleton Class must have 3 important things,
1. A private static Instance member
2. A private constructor
3. public static getInstance() – to get Instance Member specified in POINT 1

Before entering into Singleton, let us get into a quick discussion on CLASS ACCESS.

Access specifiers in Java are a real gift to the Java Developers because they are much like a CONTROL SYSTEM of our project.It is in our hands to decide what to expose and what not to expose to the world by using the right specifier at the right place.It is generally a good practice to make fields in the class as much PRIVATE as possible, if that field’s need is not outside the class.

Here l also want you to notice that a Class can be either PUBLIC OR DEFAULT and cannot be PRIVATE OR PROTECTED

  • Public Class can be accessed by any class from any Package
  • Default class can be accessed by the classes within the same Package.

Are you with me??? I don’t want to bore you anymore…Let’s go into a SINGLETON example now.

Singleton

Consider , You have a MUSIC STORE in your IPod– That has many categories(as of now in program I have considered Devotional Songs and Pop Songs).

InterfaceImplementation

PopSongs and DevotionalSongs are two classes that implement the Interface IMusicAction .

Consider the interface has a method Play(), that is implemented in both the classes PopSongs and DevotionalSongs, but performing different playAction.

 

Hold On…! Have you noticed that both the classes are of DEFAULT type … and NOT Public.
Can you reason out why……????

Tat’s bacause I do not want these classes to be accessed out anywhere out of this package. i.e., It’s access is only within that package(com.aishu.practice.access).

Now let’s create the MUSICSTORE.We are going to make it Singleton – which means a SINGLE STORE(a SINGLE INSTANCE) having different song types(holding TONS OF INSTANCES)

MusicStoreSteps

Follow these steps,

  1. Create private static Instance member private static final MusicStore musicStoreInstance = new MusicStore();
  2. Create a CONSTRUCTOR and make it PRIVATE– Why PRIVATE ????

Make it Private because I don’t want to create the OBJECT OF MY CLASS anywhere else excepting ONLY INSIDE MY SAME CLASS ITSELF.

  1. Create public static method gets the Instance Member specified in Point 1
  2. Create Instances for the song types, Devotional and Pop Songs and PLAY ON

Here MusicStore class is PUBLIC. So no restrictions..let’s try calling it from a class outside this package and create instance of it to get our desired music played on…

Executor

In the main method , you will not be able to create new Object for MUSICSTORE class.You can only get its instance.How many ever times you try creating a new instance, the Instance still remains the same SINGLE INSTANCE (Marked in Pink).Now after getting this singleInstance, you can get any type of song Played On .

VennDiag

Don’t you think Singleton is much more related to SUBSET FUNCTIONS we learnt in Mathematics by drawing Venn Diagram during our school days….untitled

 

 

 

Okay…….In my next blog I will tell you, how Multi threads work on a Singleton Class.

Written by thangaveluaishwarya

May 17, 2013 at 1:00 PM