Wednesday, December 28, 2011

Open Session In View Filter Usage

Open Session In View Filter of Spring framework takes care of hibernate session management of a web application.  The integration of it is done at the web.xml.

Firstly, the spring beans ought to be loaded to the application context. This is done with a 'context-param' element. Secondly, define a filter with a 'filter' element (here my filter class is com.shyarmal.filter.MyOpenSessionInViewFilter which extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter).  Thirdly, define a filter mapping to the filter appropriately using 'filter-mapping' element. Notice the init parameter (sessionFactoryBeanName) passed to the filter. It is the id of the session factory defined in spring beans xml configurations.

web.xml elements of interest are as follows.
===================================================================
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</context-param>

<filter>
   <filter-name>openSessionInViewFilter</filter-name>
   <filter-class>com.shyarmal.filter.MyOpenSessionInViewFilter</filter-class>
   <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
   </init-param>
</filter>

<filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
===================================================================

Following are the spring bean definitions related to session factory used for the integration of open session in view filter.
===================================================================

<bean id="hibernateConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <property name="location">
       <value>classpath:hibernate.properties</value>
   </property>
</bean>

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driver.class.name}"/>
   <property name="url" value="${jdbc.url}"/>
   <property name="username" value="${jdbc.username}"/>
   <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>Accounts.hbm.xml</value>
             .....
            .....
            .....
        </list>
    </property>
    <property name="hibernateProperties" ref="hibernateConfigProperties"/>
</bean>

===================================================================

thanks,
Shyarmal.

Sunday, December 11, 2011

Read and display image - Java Swing


package com.shyarmal.image.display;

import java.awt.Color;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.border.LineBorder;

/**
 *
 * @author  shyarmal
 * An external image file is read, re-sized and rendered in a
 * JLabel.
 */
public class ImageForm extends extends javax.swing.JFrame {

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;


/**
This is the default constructor of the JFrame. This can not be used to render an image. Basically the initialization of components are done here. 
*/
    public ImageForm() {
        initComponents();
        this.setLocation(100, 150);
        jLabel1.setBorder(new LineBorder(Color.DARK_GRAY, 5));
        this.setResizable(false);
    }


/**
This is the constructor to be used to set an image. Path of the image file is passed as an argument, which is used to get an image icon from the method, createImageIcon(path) below. The image icon is set to the JLabel. Further the tile of the JFrame is set here. The default constructor is called first to initialize the components of the JFrame.
*/
    public ImageForm(String path) {
        this();
        this.setTitle("Image: " + path.substring(
                           path.lastIndexOf("\\") + 1));
        jLabel1.setIcon(createImageIcon(path));
//        jLabel1.setIcon(new ImageIcon(readFile(path)));
        getContentPane().add(jLabel1);
    }
/**
CREATING AND RESCALING OF AN IMAGE
An image is created from the byte data obtained by reading the image file (refer to the method, readImageFile(String path)). The image created is rescaled to the dimensions of the label in which it is to be rendered. An image icon is created from the rescaled image and returned.
*/
    private ImageIcon createImageIcon(String path) {
        Image image = new ImageIcon(
                readImageFile(path)).getImage();
        Image rescaledImage = image.getScaledInstance(
               jLabel1.getWidth(), jLabel1.getHeight(),
                      Image.SCALE_DEFAULT);
        return new ImageIcon(rescaledImage);
    }


/**
READING IMAGE DATA FROM (EXTERNAL) FILE
File path is passed into this method and a file input stream is created using the same. Length of byte data available in the input stream is obtained [fis.available()]. A byte array of the length, determined by this means is subsequently created. All the data is read into the byte array from the input stream [while ((i = fis.read(data)) != -1);] and returned.
*/
    private byte[] readImageFile(String path) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            int length = fis.available();
            byte[] data = new byte[length];
            int i = 0;
            while ((i = fis.read(data)) != -1);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }               
   
    //  auto generated codes for the JFrame are not shown.              
}




thanks,
Shyarmal.

Detached Criteria - Hibernate

The following is an example usage of DetachedCriteria in hibernate. CoinTrxLedger is the domain class which is to be queried and it consists of a set of CoinBuckets. Detached Criteria is used to prepare a sub-query using CoinBuckets (which is not the main query class).
CoinTrxLedger entities are to be selected, which are having CoinBucket entities having the CoinBucket.PROPERTY_ACCOUNT set to An entity, account (passed in to the method).

===================================================================

    public List<CoinTrxLedger> getTransactionEntries(Account account) {
        Session session = getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(CoinTrxLedger.class);
        DetachedCriteria dCriteria = DetachedCriteria.forClass(CoinBucket.class);
        dCriteria.add(Restrictions.eq(CoinBucket.PROPERTY_ACCOUNT, account));
        dCriteria.setProjection(Projections.property(CoinBucket.PROPERTY_ID));
        criteria.add(Subqueries.propertyEq(CoinTrxLedger.PROPERTY_COIN_BUCKET, dCriteria));
        return criteria.list();
    }

===================================================================

Create a criteria of the query entity;
          Criteria criteria = session.createCriteria(CoinTrxLedger.class);

Create the sub-query, define restrictions and projections as required:
         DetachedCriteria dCriteria = DetachedCriteria.forClass(CoinBucket.class);
     dCriteria.add(

Restrictions.eq(CoinBucket.PROPERTY_ACCOUNT, account));
     dCriteria.setProjection(Projections

.property(CoinBucket.PROPERTY_ID));

Add the sub-query to the main criteria:
        criteria.add(
Subqueries.propertyEq(CoinTrxLedger.PROPERTY_COIN_BUCKET, dCriteria));

thanks,
Shyarmal