Translate

Monday, April 30, 2012

A Simple Colorbox CSS File

After searching around on the Internet for a modal dialog box I settled on ColorBox because out of all of the modal dialog boxes out there it has the most of the the capabilities that I was looking for. The only thing that I did not like about it was the title bar and close button at the bottom. Unfortunately there isn't a setting for ColorBox to not show this section but I did find a way to eliminate it by changing the style sheet.The following CSS will do this for you. Just copy it and use it as your "colorbox.css" file. To simplify things I just used a plain solid box (mborder.png) for the border. All you have to do is supply your own image file.


The CSS:

#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:1111; overflow:hidden;}
#cboxOverlay{position:fixed; width:100%; height:100%;}
#cboxMiddleLeft, #cboxBottomLeft{clear:left;}
#cboxContent{position:relative;}
#cboxLoadedContent{overflow:auto;}
#cboxTitle{margin:0;}
#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%;}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}
.cboxPhoto{float:left; margin:auto; border:0; display:block;}
.cboxIframe{width:100%; height:100%; display:block; border:0;}

#cboxOverlay{background:#222;}
#colorbox{}
#cboxTopLeft{width:8px; height:8px; background:url(images/mborder.png) no-repeat 0 0;}
#cboxTopCenter{height:8px; background:url(images/mborder.png) repeat-x top left;}
#cboxTopRight{width:8px; height:8px; background:url(images/mborder.png) no-repeat 0 0;}
#cboxBottomLeft{width:8px; height:8px; background:url(images/mborder.png) no-repeat 0 0;}
#cboxBottomCenter{height:8px; background-color:black; background:url(images/mborder.png) repeat-x bottom left;}
#cboxBottomRight{width:8px; height:8px; background:url(images/mborder.png) no-repeat 0 0;}
#cboxMiddleLeft{width:8px; background:url(images/mborder.png) repeat-y 0 0;}
#cboxMiddleRight{width:8px; background:url(images/mborder.png) repeat-y 0 0;}
#cboxContent{background:#fff; overflow:visible;} 
#cboxError{padding:50px; border:1px solid #ccc;}
#cboxLoadedContent{margin-bottom:5px;}
#cboxLoadingOverlay{background:url(images/loading_background.png) no-repeat center center;}
#cboxLoadingGraphic{background:url(images/loading.gif) no-repeat center center;}
#cboxTitle{position:absolute; bottom:-25px; left:0; text-align:center; width:100%; font-weight:bold; color:#7C7C7C;}
#cboxCurrent{position:absolute; bottom:-25px; left:58px; font-weight:bold; color:#7C7C7C;}

Using this CSS in my application gave me a modal dialog box like this:

Saturday, April 28, 2012

Internews - A Multimedia Center in Afghanistan Helps People with Disabilities Access Technology

“Before coming to this center, I had little information about the Internet. Now I know how to use it to improve my life and profession. Now it is easy for me to solve my own professional problems and I can connect to the world very easily,” says Mohitullah Mujahid.

Mohitullah, an economics student from Nangarhar University who was born without hands and some of his toes, comes regularly to the Anaar Multimedia Center in Jalalabad to use the computers for his studies.

Read more here.

Saturday, April 21, 2012

Internews - Rapid Growth of Afghanistan’s ICT Sector Paves the Way for New Media and a Stronger Economy

Just ten years ago Afghanistan had a barely functional post-war infrastructure, with no independent media and literally no telecom services. Afghans had to travel to the neighboring countries to make a phone call. Today the story is very different, as outlined in a new independent study conducted by Javid Hamdard, of Internews, under the USAID-funded Afghanistan Media Development & Empowerment Project (AMDEP).

Read the complete report here.

MyBatis - Simple Mapper for Look-up Tables

In the database web application that I am working on there are over 30 look-up tables that are used for pick lists. I simplified reading in the data that I need for my application by using a generic mapper aclled "KeyValueDescriptionMapper". It uses the generic example class, BaseExample, that I describe here. By setting up the SQL statements in the mapper, KeyValueDescriptionMapper, so that the database field and the database table name can be specified by properties in the BaseExample class I am able to just use this one mapper to get me the list of key/value pairs I need for my pick lists!

The "KeyValueDescriptionMapper" mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="KeyValueDescriptionMapper" >
    <!--
      author: Richard Golebiowski
      Generic mapper used to return key/value information
    -->
  <resultMap id="ExtKeyValueMap" type="com.utilSpace.util.ExtKeyValuePair" >
    <result column="ID" property="intKey" jdbcType="INTEGER" />
    <result column="Value" property="value" jdbcType="VARCHAR" />
    <result column="DescValue" property="descValue" jdbcType="VARCHAR" />    
  </resultMap>
  
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  
  <sql id="Base_Column_List" >
    ID, Value, DescValue
  </sql>
  
  <select id="selectByExample" resultMap="ExtKeyValueMap" parameterType="com.interbase.model.BaseExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from ${table}
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  
  <select id="selectByPrimaryKey" resultMap="ExtKeyValueMap" parameterType="com.interbase.model.BaseExample" >
    select 
    <include refid="Base_Column_List" />
    from ${table}
    where ID = #{ID,jdbcType=INTEGER}
  </select>
  
  <delete id="deleteByPrimaryKey" parameterType="com.interbase.model.BaseExample" >
    delete from ${table}
    where ID = #{ID,jdbcType=INTEGER}
  </delete>
  
  <delete id="deleteByExample" parameterType="com.interbase.model.BaseExample" >
    delete from ${table}
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  
  <insert id="insert" parameterType="com.utilSpace.util.ExtKeyValuePair" >
    insert into ${table} (ID, Value, DescValue
      )
    values (#{ID,jdbcType=INTEGER}, #{value,jdbcType=VARCHAR}, #{descValue,jdbcType=VARCHAR}
      )
  </insert>
  
  <insert id="insertSelective" parameterType="com.utilSpace.util.ExtKeyValuePair" >
    insert into ${table}
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="ID != null" >
        ID,
      </if>
      <if test="value != null" >
        Value,
      </if>
      <if test="descValue != null" >
        DescValue,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="ID != null" >
        #{ID,jdbcType=INTEGER},
      </if>
      <if test="value != null" >
        #{value,jdbcType=VARCHAR},
      </if>
      <if test="descValue != null" >
        #{descValue,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.utilSpace.util.ExtKeyValuePair" >
    update ${table}
    <set >
      <if test="value != null" >
        Value = #{value,jdbcType=VARCHAR},
      </if>
      <if test="descValue != null" >
        DescValue = #{descValue,jdbcType=VARCHAR},
      </if>
    </set>
    where ID = #{ID,jdbcType=INTEGER}
  </update>
  
  <update id="updateByPrimaryKey" parameterType="com.utilSpace.util.ExtKeyValuePair" >
    update ${table}
    set Value = #{value,jdbcType=VARCHAR},
      DescValue = #{descValue,jdbcType=VARCHAR}
    where ID = #{ID,jdbcType=INTEGER}
  </update>

<!-- 
 Select records from the database table specified by the string parameter
-->      
  <select id="selectAllKeyValue" resultMap="ExtKeyValueMap" parameterType="java.lang.String">
    select ID, Value from ${value}
  </select>

<!-- 
 Select records from the database table specified by the string parameter
-->    
  <select id="loadDescSelectList" resultMap="ExtKeyValueMap" parameterType="java.lang.String">
    select  ID, Value,  DescValue from ${value} order by DescValue
  </select>
  
<!-- 
 Select records from the database table specified by the string parameter and the  "Value" field returned as "DescValue"
-->     
  <select id="loadValueDescSelectList" resultMap="ExtKeyValueMap" parameterType="java.lang.String">
    select  ID, Value as DescValue from ${value} order by DescValue
  </select>

<!-- 
 Select records from the database with the field specified by the "field" property returned as "Value"
-->    
  <select id="loadFieldAsValue" resultMap="ExtKeyValueMap" parameterType="com.interbase.model.BaseExample">
    select  ID, ${field} as Value from ${table}
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>        
  </select>
  
<!-- 
 Select records from the database with the field specified by the "field" property returned as "DescValue"
-->    
  <select id="loadFieldAsDescValue" resultMap="ExtKeyValueMap" parameterType="com.interbase.model.BaseExample">
    select  ID, ${field} as DescValue from ${table}
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>       
  </select>      
</mapper>

Usage Examples:
Use "selectAllKeyValue" to get a list from the "luMediaType" table:

GenericDataService lstServiceTest = new GenericDataService("KeyValueDescriptionMapper");
List <ExtKeyValuePair> tstList =  (List<ExtKeyValuePair>) lstServiceTest.selectAllKeyValue("luMediaType");


Using BaseExample to get a list from the "Funder" table with the "FunderShortName" database field as the value and sorted by "FunderShortName":

GenericDataService genService = new GenericDataService("KeyValueDescriptionMapper");
BaseExample baseExample = new BaseExample();
baseExample.setTable("Funder");
baseExample.setField("FunderShortName");
baseExample.setOrderByClause("FunderShortName");
List keyList = (List) genService.getFieldAsValue(baseExample);  


The "getFieldAsValue" method for the example above:

public  List getFieldAsValue(BaseExample baseExample){
    SqlSession session = this.sqlSessionFactoryINform.openSession();
    try {
        @SuppressWarnings("unchecked")
        List list = session.selectList(this.dataMapper + ".loadFieldAsValue", baseExample);
        return list;
    }catch(Exception e){
        System.out.println(e.getMessage());
        return null;
    } finally {
        session.close();
    }
}

Wednesday, April 18, 2012

MyBatis Generator - Generic Example Class

One of the things that I like about the mapper files created by MyBatis Generator is the ability to set up some basic query filter using the "Example" class that application creates. You can read more about them here. What I don't like about the "Example" classes is that they are specific to the class file that is created to map to the table. So if you have a large project like I do with around 25 main tables you would have 25 different "Example" classes. To get around this I created the following generic "Example" class. Use it in place of the "Example" classes created by the generator.

BaseExample class:

package com.interbase.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Basic database example class
 * @author Richard Golebiowski
 *
 */
public class BaseExample {
    protected List oredCriteria;    
    protected boolean distinct;
    protected String orderByClause;
    protected String table;//table name
    protected String field;//field name
    protected String queryName;//name of the query
    protected BaseCriteria baseCriteria = new BaseCriteria();
    
    public BaseExample() {
        this.oredCriteria = new ArrayList();
    }
    
    /**
     * Used to clear out current criteria
     */
    public void reset(){
        oredCriteria = new ArrayList();
        this.distinct = false;
        this.orderByClause = null;
        this.baseCriteria = new BaseCriteria();       
    }

    public void resetBase() {
        this.baseCriteria = new BaseCriteria();       
    }
    
    public void orCriteria() {
        oredCriteria.add(this.baseCriteria);
    }

    public void andCriterion(String condition, Object value) {
        baseCriteria.addCriterion(condition, value, condition);    
    }
    
    public void andCommonCriterion(String fieldName, String condition, Object value) {
        if(condition.equals("begins with")) {
            condition = "like";
            value = value + "%";
        }
        else if(condition.equals("contains")){
            condition = "like";
            value = "%" + value + "%";     
        }
        else if(condition.equals("ends with")){
            condition = "like";
            value = "%" + value;
        }
        else if(condition.equals("equals")){
             condition = "=";    
        } 
        condition = fieldName + " " + condition;
        baseCriteria.addCriterion(condition, value, condition);    
    }
    
    public void andCriterion(DataViewCriteria dataViewCriteria) {
        if(dataViewCriteria.getValue1() == null) {
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition());
        }
        else if(dataViewCriteria.getValue2() == null){
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getFieldName());
        }
        else{
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getValue2(), dataViewCriteria.getFieldName());        
        }
    }
    
    public void addCriterion(DataViewCriteria dataViewCriteria) {
        this.baseCriteria = new BaseCriteria();
        if(dataViewCriteria.getValue1() == null) {
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition());
            oredCriteria.add(baseCriteria);
        }
        else if(dataViewCriteria.getValue2() == null){
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getFieldName());
            oredCriteria.add(baseCriteria);
        }
        else{
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getValue2(), dataViewCriteria.getFieldName());
            oredCriteria.add(baseCriteria);
        }
    }

    public void addCriterion(String condition, Object value) {
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition, value, condition);
        oredCriteria.add(baseCriteria);
    }
    
    public void addCriterion(String condition) {
        if (condition == null) {
            throw new RuntimeException("Value for condition cannot be null");
        }
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition);
    }

    public void addCriterion(String condition, Object value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition, value, property);
    }

    public void addCriterion(String condition, Object value1, Object value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition, value1, value2,property);
    }

    public void addCriterionForJDBCDate(String condition, Date value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value.getTime()), property);
    }

    public void addCriterionForJDBCDate(String condition, List values, String property) {
        if (values == null || values.size() == 0) {
            throw new RuntimeException("Value list for " + property + " cannot be null or empty");
        }
        List dateList = new ArrayList();
        Iterator iter = values.iterator();
        while (iter.hasNext()) {
            dateList.add(new java.sql.Date(iter.next().getTime()));
        }
        addCriterion(condition, dateList, property);
    }

    public void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
    }    
    

    public List getOredCriteria() {
        return oredCriteria;
    }

    public void setOredCriteria(List oredCriteria) {
        this.oredCriteria = oredCriteria;
    }
    
    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }
    
    public boolean isDistinct() {
        return distinct;
    }
    
    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getQueryName() {
        return queryName;
    }

    public void setQueryName(String queryName) {
        this.queryName = queryName;
    }

    public BaseCriteria getBaseCriteria() {
        return baseCriteria;
    }

    public void setBaseCriteria(BaseCriteria baseCriteria) {
        this.baseCriteria = baseCriteria;
    }    
}


BaseCriteria class:

package com.interbase.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/**
 * Basic criteria class
 * @author Richard Golebiowski
 *
 */
public class BaseCriteria {
 protected List criteria;
 
    public BaseCriteria() {
        this.criteria = new ArrayList();
    } 
    public boolean isValid() {
        return criteria.size() > 0;
    }

    public List getAllCriteria() {
        return criteria;
    }

    public List getCriteria() {
        return criteria;
    }

    public void addCriterion(String condition) {
        if (condition == null) {
            throw new RuntimeException("Value for condition cannot be null");
        }
        criteria.add(new Criterion(condition));
    }

    public void addCriterion(String condition, Object value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        criteria.add(new Criterion(condition, value));
    }

    public void addCriterion(String condition, Object value1, Object value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        criteria.add(new Criterion(condition, value1, value2));
    }

    public void addCriterionForJDBCDate(String condition, Date value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value.getTime()), property);
    }

    public void addCriterionForJDBCDate(String condition, List values, String property) {
        if (values == null || values.size() == 0) {
            throw new RuntimeException("Value list for " + property + " cannot be null or empty");
        }
        List dateList = new ArrayList();
        Iterator iter = values.iterator();
        while (iter.hasNext()) {
            dateList.add(new java.sql.Date(iter.next().getTime()));
        }
        addCriterion(condition, dateList, property);
    }

    public void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
    }    
}



Example usage:

GenericDataService genService = new GenericDataService("DataViewCriteriaMapper");
BaseExample baseExample = new BaseExample();
baseExample.addCriterion("DataViewID =", this.viewID);
//get the criteria for the view
this.lstDataViewCriteria = (List) genService.getListByExample(baseExample);

GenericDataService Class:

package com.dataSpace.service;

public class GenericDataService extends DataService {
 
 public GenericDataService(String dataMapper){
  this.dataMapper = dataMapper;
 }
 
 public GenericDataService() {

 }

 public void switchDataMapper(String dataMapper){
  this.dataMapper = dataMapper;
 }
 

}
DataService Class:

package com.dataSpace.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;

import com.interbase.mapper.MyBatisConnectionFactory_INform;
import com.interbase.model.BaseExample;
import  com.utilSpace.util.ExtKeyValuePair;
import  com.utilSpace.util.KeyValuePair;

public abstract class DataService {
 private static final Logger logger = Logger.getLogger(DataService.class);
 protected SqlSessionFactory sqlSessionFactoryINform = MyBatisConnectionFactory_INform.getSqlSessionFactory();
 protected String dataMapper;
 protected boolean errorFlag;
 protected String errorMsg;
 
 public List<Object> getAll(){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + ".selectAll");
   return list;
  } finally {
   session.close();
  }    
 }
 
 public List<KeyValuePair> getByMethod(String method){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<KeyValuePair> list = session.selectList(this.dataMapper + "." + method);
   return list;
  } finally {
   session.close();
  }    
 }
 
 public List<ExtKeyValuePair> getExtByMethod(String method){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + "." + method);
   return list;
  } finally {
   session.close();
  }    
 }
 
 public List<?> getListByExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + ".selectByExample", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   this.errorFlag = true;
   this.errorMsg = e.getMessage();
   return null;
  } finally {
   session.close();
  }    
 }
 
 public List<?> getListFromTableByExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + ".selectFromTableByExample", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }    
 }
 
 public List<?> getListByMethodAndExample(String method, BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + "." + method, baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }    
 }  
 
 public Object getRecordByMethodAndExample(String method, BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   Object obj = session.selectOne(this.dataMapper + "." + method, baseExample);
   return obj;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }    
 }
 
 public Object getByMethodWithID(String method, Integer id){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   Object obj = session.selectOne(this.dataMapper + "." + method, id);
   return obj;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }   
 }
  
 public Object getRecordByExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   this.errorFlag = false;
   Object obj = session.selectOne(this.dataMapper + ".selectByExample", baseExample);
   return obj;
  }catch(Exception e){
   this.errorFlag = true;
   return null;
  } finally {
   session.close();
  }    
 } 
 
 public Object getRecordByQueryExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   Object obj = session.selectOne(this.dataMapper + "." + baseExample.getQueryName(), baseExample);
   return obj;
  } finally {
   session.close();
  }    
 } 
 
 public Object getByID(Integer id){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   Object obj = session.selectOne(this.dataMapper + ".selectByPrimaryKey", id);
   return obj;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }   
 }
 
 public void updateByID(Object obj){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   session.update(this.dataMapper + ".updateByPrimaryKey", obj);
   session.commit();
  }catch(Exception e){
   System.out.println(e.getMessage());
  } finally {
   session.close();
  } 
 }
 
 public Object insert(Object obj){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   session.insert(this.dataMapper + ".insert", obj);
   session.commit();
  } catch(Exception e){
   System.out.println(e.getMessage());
  }finally {
   session.close();
  } 
  return obj;  
 }
 
 public void deleteByID(Integer id){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   this.errorFlag = false;
   session.delete(this.dataMapper + ".deleteByPrimaryKey", id);
   session.commit();
  }catch(Exception e){
   this.errorFlag = true;
   logger.error(e.getMessage());
  } finally {
   session.close();
  } 
 } 
 
 public void deleteByExample(BaseExample baseExample){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   this.errorFlag = false;
   session.delete(this.dataMapper + ".deleteByExample", baseExample);
   session.commit();
  }catch(Exception e){
   this.errorFlag = true;
   logger.error(e.getMessage());
  } finally {
   session.close();
  } 
 } 
 
 public List<ExtKeyValuePair> selectAllKeyValue(String source){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + ".selectAllKeyValue", source);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }
 
 public List<ExtKeyValuePair> getFRomTableByMethod(String source, String method){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + "." + method, source);
   return list;
  } finally {
   session.close();
  }    
 }
 
 /**
  * Select records from the database with the field specified by the "field" property returned as "Value"
  * @param baseExample
  * @return
  */
 public ExtKeyValuePair loadFieldAsValue(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   Object kvp = session.selectOne(this.dataMapper + ".loadFieldAsValue", baseExample);
   return (ExtKeyValuePair) kvp;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }
 
 /**
  * Select records from the database with the field specified by the "field" property returned as "Value"
  * @param baseExample
  * @return
  */
 public  List<ExtKeyValuePair> getFieldAsValue(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")   
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + ".loadFieldAsValue", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }
 /**
  * Select records from the database with the field specified by the "field" property returned as "Value"
  * @param baseExample
  * @return
  */
 public  List<ExtKeyValuePair> getFieldAsDescValue(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")   
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + ".loadFieldAsDescValue", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }

 public boolean isErrorFlag() {
  return errorFlag;
 }

 public void setErrorFlag(boolean errorFlag) {
  this.errorFlag = errorFlag;
 }

 public String getErrorMsg() {
  return errorMsg;
 }

 public void setErrorMsg(String errorMsg) {
  this.errorMsg = errorMsg;
 }
 
}

Wednesday, April 11, 2012

TSQL - Date and Formated Count

On the project I'm working on I need to set a field to the to a two digit date and sequential count number when a new record is added. The format is YY-### where YY is the year and ### is the count. So the first record for 2012 would be 12-001, the next is 12-002, and so on.

This is how I did it.

DECLARE @ret int
DECLARE @count int
DECLARE @val varchar(6)
--get the two digit year
SET @ret = (YEAR(GETDATE()) % 100)
--count the number of records where the controlnum begins with the year and add 1
select @count = count(*)+1 from parosc where controlnum like CONVERT(varchar, @ret) + '%'
--combine
set @val = CONVERT(varchar(2), @ret) + '-' + right('00' + CONVERT(varchar, @count), 3)

I just made it into a User Defined Function and set the default value for the ControlNum field to the function.

Afghan National Radio Network Launches as Independent NGO | Internews

Nine years after its establishment, Salam Watandar ("Hello Countrymen") Radio was officially inaugurated April 8 as an independent, non-governmental Afghan organization.

More at Afghan National Radio Network Launches as Independent NGO | Internews

Monday, April 9, 2012

MyBatis - MyBatis Generator

I have been using MyBatis Generator for about a year now on two different projects. It's a great help in building the structures you need in an application for doing database CRUD operations. Read More

Sunday, April 8, 2012

Java, XML - Read/Write a List of Objects

One of the things that I have been doing in my applications is using XML files to store lists. As illustrated by these two short methods, the XStream library makes this very easy to do .

Write a list of class FieldDescriptor to a file:

private static void saveFieldDefinitions(String fieldDescriptorName, LinkedList<FieldDescriptor> list) throws IOException {
    XStream xs = new XStream();
    xs.alias("FieldDescriptor", FieldDescriptor.class); 
    //Write
    try {
        FileOutputStream fs = new FileOutputStream(fieldDefinitionsFilePath + "\\" + fieldDescriptorName + ".xml");
        xs.toXML(list, fs);
        fs.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
}


Reada list of class FieldDescriptor from a file:

protected void loadFieldDefinitions(String fieldDescriptorName) {
    XStream xs = new XStream(new DomDriver());
    xs.alias("FieldDescriptor", FieldDescriptor.class);        
    //Read
    try {
        FileInputStream  fs = new FileInputStream(fieldDefinitionsFilePath + "\\" + fieldDescriptorName + ".xml");
        lstFieldDescriptor = (List<FieldDescriptor>) xs.fromXML(fs);
        fs.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch(Exception e2) {
        e2.printStackTrace();
    }
}

Sunday, April 1, 2012

jQuery, AJAX, Struts - Add a Select Box Option

Here is a quick little example on how to add a new option to a select box and make the new value the selected value.

On my JSP page I have two select boxes that can have new values added. When a new value for an Award or Project is add, the new value will be added as an option to the select box and made the selected value.


A modal dialog box is used to enter a new Award or Project. In this image, you can see a section of the dialog box for adding a new Award. In the dark area you will see a section of the original record edit screen.


Here is the section from the JSP page for the select box. Since the forms are generated dynamically, the id of my select box can have any value so I need to return that value to the server so that it can be used later on as the AJAX target. In the code snippet below you see this value being returned as the "target" parameter.

<s:select name="tableRecord.tblRecord.%{fieldName}" id="disp%{fieldName}" list="selectListMap(fkeyName)" headerKey="" headerValue="Please Select"/>
<s:if test="fkeyPrimaryTableName != null">
 <s:url var="urlFkey" namespace="%{namespace}" action="GotoAddForeignKeyRecord" escapeAmp="false">
  <s:param name="target" >disp${fieldName}</s:param>
  <s:param name="fkeyName" value="fkeyName"/>
  <s:param name="fkeyTableName" value="fkeyPrimaryTableName"/>
 </s:url>
 <s:a href="%{urlFkey}" cssClass='ajax'>
  Add New <s:property value="fkeyPrimaryTableNameLabel"/>
 </s:a>
 <script type="text/javascript">
 $(".ajax").colorbox({width:'800', close:'close'});
 </script>
</s:if>


I use XML files to define the fields for the database tables. Here is the section from the XML file that describes the awardID.

<FieldDescriptor>
    <fieldName>awardID</fieldName>
    <fieldLabel>Award</fieldLabel>
    <fieldType>1</fieldType>
    <fieldSize>0</fieldSize>
    <editable>true</editable>
    <listable>true</listable>
    <required>true</required>    
    <fkeyName>lstAwards</fkeyName>
    <fkeyPrimaryTableName>Award</fkeyPrimaryTableName>
    <fkeyPrimaryTableNameLabel>Award</fkeyPrimaryTableNameLabel>
    <fkeyListEditable>true</fkeyListEditable>
</FieldDescriptor>   


Don't get hung up on this XML structure or the information it contains. The import part follows, getting the new value into the select box.

Here is my GotoAddForeignKeyRecord action method. Notice that the target for my AJAX action is being saved as ajaxTarget.

public String gotoAddForeignKeyRecord(){
 String fkeyName = request.getParameter("fkeyName");
 //save the target for the AJAX action
 this.ajaxTarget = request.getParameter("target");
 this.baseTableDescriptor = TableDescriptorFactory.getFieldDescriptor(table); 
 for(KeyDescriptor kD: this.baseTableDescriptor.getLstKeyDescriptor()){
  if(kD.getName().equals(fkeyName)){
   String tMapper = kD.getMapper();
   if(kD.getTableMapper() != null) {
    tMapper = kD.getTableMapper();
   }
                        //luTableField is used for the display value in the select box on the JSP page
   this.luTableField = kD.getLuTableField();
   //set the Struts namespace for the table we are targeting
   this.redirectNamespace = "/" + tMapper.replace("Mapper", "").toLowerCase();
   //set the page that we will be redirecting to
   this.redirectPage = "AddForeignKeyRecord";
   this.recordID = null;
   return SUCCESS;
  }
 }
 return ERROR;
}


The section from the record add JSP page with the jQuery code for populating the select box. The values that I need for the key and value I get from the "${tablename}ID" and "disp${luTableField}" on the JSP page.

<s:url id="urlCancelRecordAdd" namespace="%{namespace}" action="NoOpp"/>
<sj:submit  value="Cancel" formIds="saveRecordFK" id="cancelFKRecordEdit" href="%{urlCancelRecordEdit}" onclick="parent.$.colorbox.close();return false;" button="true" style="font-size: .7em;"/>
</td>
</tr>
<script type="text/javascript">
//submit the list
$('#cancelFKRecordAdd').click(function() {
 //if we have an ID then we have a record so update the sellect box
 if($('#${tablename}ID').val() != ''){
        //make the markup for the option for the select box
 var option = '<option value=' + $('#${tablename}ID').val() + '>' + $('#disp${luTableField}').val() + '</option>';
        //add the option to the select box
 $('#${ajaxTarget}').append(option);
        //set the added option as the selected value
 $("#${ajaxTarget}").val($('#${tablename}ID').val());
 }
});
</script>