Archive for the “Java Enterprise Edition” Category

Hibernate Criteria – SELECT DISTINCT and while loop (A[i] && B[i]) || (A[i+1] && B[i+1])

Here is the case: I need to get the distinct SX-Number from list of shipment of each shipment data of selected HUB, on SoftONE Logistic Database using Hibernate Criteria.

The scenario will be:

  1. User will select the HUB from combo box UI element
  2. From selected HUB, system will pick up the JCode Name and Consignee Account
  3. Using those destination and consignee account data, system will retrieve the shipment data
  4. On the shipment data, there is SX-Number data
  5. System need to list unique SX-Number from the filtered shipment data

 

Here is the implementation of the scenario above, skip the getting hub data from UI

// Open Hibernate Session

sessionFactory.getCurrentSession().beginTransaction();

// Based on selected HUB, system will retrieve

Criteria jCodeCriteria = sessionFactory.getCurrentSession().createCriteria(MasterJCode.class);
if(category.compareToIgnoreCase("HUB") == 0){
       jCodeCriteria.add(Restrictions.eq("destination", value));
}
listJCode = jCodeCriteria.list();

// Check the list of jcode whether it is null or empty, if not continue the process

if((listJCode != null) && (listJCode.size()>0)){

// Create new criteria to get distinct SX-Number based on jcode name and consignee account stated above

Criteria fastCriteria = sessionFactory.getCurrentSession().createCriteria(FASTData.class);

// Implementation of SELECT DISTINCT(a.refDesc)
fastCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
fastCriteria.setProjection(Projections.distinct(Projections.property("refDesc")));

// implementation of WHERE while loop (A[i] && B[i]) || (A[i+1] && B[i+1])
// Use disjunction to implement OR logic between Restriction.and

Disjunction disjunction = Restrictions.disjunction();

// Use Restriction.and to implement (A[i] && B[ii])
               
for(MasterJCode masterJCode:listJCode){
              disjunction.add(Restrictions.and(Restrictions.eq("destination", masterJCode.getJcodeName()), Restrictions.eq("consigneeAccount", masterJCode.getConsigneeAccount())));
}
fastCriteria.add(disjunction);

 

// Execute the criteria              
List data = fastCriteria.list();

You will get the list of OBJECT as a result. Here is the thing, even though in the beginning of Criteria, the used

Criteria fastCriteria = sessionFactory.getCurrentSession().createCriteria(FASTData.class);

Logically the result will be list of FASTData, and we will use for loop to retrieve FASTData object from the result list. Since in the criteria, there is no method .iterate() unlike query, we can not use iterator to iterate the list of object. We will use for loop instead

for(Object obj:data){
         System.out.println(String.valueOf(obj));
}

 Lastly, commit the transaction

sessionFactory.getCurrentSession().getTransaction().commit();

 

Jul 15, 2010 Posted Under: Hibernate   Read More

Calling MS SQL Server 2005 Stored Procedure from Spring JDBCTemplate

 

The idea came from DotNetNuke design pattern, based on experience on DNN based project, SoftONE Logic’s team try to find the easier way to use Stored Procedure on the Spring JDBCTemplate . SoftONE Logic’s team has used iBatis to call stored procedure. Due to the ‘complexity’ of XML, the team start to do research to find other way to implement it.

Here are the outcome of the research.

  •     DB Server : MS SQL Server 2005
  •     Spring Framework 2.5 (JDBCTemplate features).
Get Object from DB

Create Stored Procedure named hr_GetRequisitionForm, has one input parameter.

USE [hr]
    GO
SET ANSI_NULLS ON
    GO
SET QUOTED_IDENTIFIER ON
    GO
CREATE procedure [dbo].[hr_GetRequisitionForm]
    @id int
as
    select
*
    from hr_vw_RequisitionForm
where
   id = @id

Create Method to call above stored procedure by using Spring JDBC Template.

public RequisitionFormVO getRequisitionDataByRequisitionId(int id){
     String queryString = "{call hr_GetRequisitionForm(?)}";
     Object args []= new Object[] {id};
     return (RequisitionFormVO)jdbcTemplate.queryForObject(queryString, args, new RequisitionFormMapper());
}

I assume reader has already familiar with Spring JDBC Tempalte. The hr_GetRequisitionForm stored procedure has one input parameter (id). Pass the value of id to the stored procedure with hr_GetRequisitionForm(?) statement, and Object args []= new Object[] {id}; . Cast the returned object from jdbcTemplate and use the method queryForObject as shown below:

(RequisitionFormVO)jdbcTemplate.queryForObject(queryString, args, new RequisitionFormMapper());

Get List from DB

Create Stored Procedure named hr_GetApprovedRequisitionForm

USE [hr]
   GO
SET ANSI_NULLS ON
   GO
SET QUOTED_IDENTIFIER ON
   GO
CREATE procedure [dbo].[hr_GetApprovedRequisitionForm]
   as
SELECT
   *
FROM
   hr_vw_RequisitionForm
WHERE
   HRManagerVerifiedStatus = 'verified' AND
   SGManagerApprovedStatus = 'approved' AND
   ManagingDirectorApprovedStatus = 'approved'

Create Method to call above stored procedure by using Spring JDBC Template.

public List getApprovedRequisitionData(){
     String queryString = "{call hr_GetApprovedRequisitionForm}";
     return jdbcTemplate.query(queryString, new RequisitionFormMapper());
}

The MapperClass is to map the Database column with ValueObject class.

package com.softonelogic.project.smoe.hr.utils.persistence.sqlmapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.softonelogic.project.smoe.hr.utils.vo.RequisitionFormVO;
public class RequisitionFormMapper implements RowMapper {
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
     RequisitionFormVO obj = new RequisitionFormVO();
     obj.setId(rs.getInt("ID"));
     obj.setPositionVacant(rs.getString("PositionVacant"));
     ...
     return obj;
     }
}

 

Sep 6, 2009 Posted Under: Java Enterprise Edition, Spring Framework   Read More

Role based implementation in RichFaces with Spring Security

 

This article will explain how to implement role based system in the user control panel page. The login process is required to enter the page. The authentication process will be handled by the Spring Framework. I assume the reader understand how the Spring Security authentication works.
 
In the RichFaces page:
Page contain list of menu by implementing <rich:toolBar/> RichFace tag. The menu will be rendered based on user credential. The rendering process will be controled by bean class via rendered parameter in <rich:toolBar/> tag.
 
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:rich="http://richfaces.org/rich">

<rich:toolBar itemSeparator="line">
     <rich:toolBarGroup rendered="#{managerControlBean.menuSubscriber}">
          <rich:dropDownMenu value="Subscriber">
               <rich:menuGroup value="Manage Subscription" direction="right">
                    <rich:menuItem submitMode="ajax" value="Current Subscription">
                    </rich:menuItem>
                            …
                </rich:dropDownMenu>
            </rich:toolBarGroup>

In the bean class:

Declare the property of menuSubscriber in the class as a boolean type.

private boolean menuSubscriber = false;

Declare a final string type for the ROLE type. User can declare more than 1 role type, please ensure the role type in the bean class is the same as the role type declared in database.

private final String role_subscriber = "ROLE_SUBSCRIBER";

In the <rich:toolBar/> the rendered parameter will get the value of menuSubcriber property via isMenuSubcriber() method

public boolean isMenuSubscriber() {
        this.menuSubscriber = validateAuthorization(role_subscriber);
        return menuSubscriber;
}

Method isMenuSubcriber() will call method validateAuthorization(String) to validate the user credential. Spring Framework method is used to validate the user credential.

private boolean validateAuthorization(String authorizationString){
        boolean authStatus = false;
       
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if(securityContext != null){
            Authentication authentication = securityContext.getAuthentication();
           
            GrantedAuthority[] authorities = authentication.getAuthorities();
           
            for(GrantedAuthority authStr : authorities){
                if((authStr.toString()).compareToIgnoreCase(authorizationString) == 0){
                    authStatus = true;
                }
            }
        }
        return authStatus;
    }

 

Aug 30, 2009 Posted Under: JavaServer Faces, Spring Framework   Read More

Installing multiple tomcat instances on the Apache 2 webserver

 

This article will explain how to install tomcat webserver as a extension of Apache 2 webserver. Apache webserver will act as a proxy for n tomcat instances installed in the machine. This articles is written based on the need of installing multiple instances of tomcat webserver in the one physical server. We assume there are existing Apache 2 webserver already installed in the machine, JVM has been installed as well. We also assume that we have registered domain softonelogic.com and our aim is installing tomcat for main softonelogic.com and sub domain funds.softonelogic.com.

The steps required for tomcat installation will be divided into 2 section, setting in Apache 2 side and setting in the tomcat side

Apache 2 setting

Register new domain name in to Apache 2

Register domain to the DNS system in the machine. In our lab, we are using tinydns to handle DNS in our machine. The command to add new domain in the apache are:

# cd /service/tinydns/root
# ./add-ns new-domain.org 192.168.0.2
# make

Replace new-domain.org with the desired domain. In our case will be funds.softonelogic.com. And change the 192.168.0.2 to the correct IP Address.

The /var/tinydns/root/data file is where all your DNS entries are stored. There are a number of scripts inside /var/tinydns/root that will help you add various lines to your data file. Whenever you edit the data file,  run ’make’ in the root dir to "compile" the data file into a tinydns readable file.

You can use the scripts to add nameservers, aliases, childns servers, mx servers, and regular hosts. After using the scripts, and seeing what they do, you might be comfortable enough to edit the data file directly. Hence, to make it easy, adding a new domain quickly, just add these 4 lines to the end of the file:1

.new-domain.org:203.211.130.159:a:259200
.new-domain.org:203.211.130.158:b:259200
@new-domain.org:203.211.130.159:a::86400
+new-domain.org:203.211.130.159:86400

Virtual Host

To add a new virtual host, create a file with .conf extension in the /etc/apache2/vhosts.d/ you can copy one of the conf file in it to get started with, and then edit the file. The conf file is self explanatory. Please refer to Apache Virtual Host Documentation8 for more details. If you specify the ErrorLog in the conf file, make sure you create an empty file for the log.

Once you have finished editing the conf file, restart the apache.

Edit /etc/apache2/workers.properties.

This file contains the details about how each process is linked to Tomcat by defining workers that communicate through the ajpv13 protocol. Refer to the Workers HowTo
for more detail.

(a) Add more worker entry in the worker.list. This variable is comma separated without containing any space. Tip: You can add it right away after the equal sign (=) since the order doesn’t matter.

worker.list=ajpnewapp,ajpexistingapp

(b) Add at least the type, host and port properties of the worker somewhere after the worker.list. The combination of host and port values between applications must not be the same. The easiest way is to use different host (or ip) and use the same port.

worker.ajpnewapp .type=ajp13
worker.ajpnewapp .host=127.0.0.n*
worker.ajpnewapp .port=8009

* Where n is a number between 1 to 254. Your system has been pre-set to all these IPs.

Create the apache vhost configuration file in the /etc/apache2/vhosts.d/

The difference with the regular apache vhost is that you need to specify the mount point. This is where JkMount parameter comes in.

JkMount /a_folder* ajpnewapp

Restart the apache.

Tomcat Setting

Unzip compressed tomcat folder in the path /opt/

rename the unzipped file to any name that easy to remember, example apache-tomcat-softonelogic-portal

mv apache-tomcat-6.0.20 apache-tomcat-softonelogic-portal

Since the tomcat will be run by non-root user, we need to change the ownership of the tomcat.

syntax: chown -[option] [user].[group] target-folder-ownership-to-be-changed

Assume we have user called softonelogic and group tomcat, so the command will be

chown -R softonelogic.tomcat apache-tomcat-softonelogic-portal

-R recursively

Then create symbolic link the apache-tomcat-softonelogic-portal at the /home directory or any other directory you want. This article, the symbolic link will be placed at /home/softonelogic

login as user softonelogic

ln -s /opt/apache-tomcat-softonelogic-portal ./tomcat

to test the symbolic link

ls -l

You should see tomcat->/opt/apache-tomcat-softonelogic-portal

Next, go to tomcat directory at /opt/ go to directory conf, edit the server.xml

vi server.xml

Fine <Connector by using command

/Connector

in command mode of vi

Find the Connector that define the AJP 1.3 connector. Compare the address and port with the worker.properties

Next, run the tomcat. Go to the bin folder in the tomcat, run

./startup.sh

You should get the tomcat homepage or any other defined page.

Jul 5, 2009 Posted Under: Java Enterprise Edition, UNIX   Read More