Search This Blog

Something on Everything

Wednesday, June 23, 2010

Loading resources from classpath


The following java code snippet can be used to load all resources with “.properties” as extension under path specified in “resourceLoc”. The getDotReplaced() method will replace the ‘\’ or ‘/’ to ‘.’ Which the ResourceBundle requires for loading the resource.

try {

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader == null){
classLoader = getClass().getClassLoader();                     
}
Enumeration resPaths = classLoader.getResources(resourceLoc);
String loc = getDotReplaced(resourceLoc);
while(resPaths.hasMoreElements()) {
     
InputStream inputStream =  resPaths.nextElement().openStream();
                       
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String fileName;
      while((fileName = reader.readLine()) != null) {
            fileName = fileName.trim();
            if(fileName.length() == 0) {
                  continue; //blank line ignored
            }
                             
            if(isProperties(fileName))
            {
            String bundleKey = getBundleKey(fileName);
            if(bundleKey!=null)
            {
                  ResourceBundle resourceBundle = ResourceBundle.getBundle(loc+"."+bundleKey,locale);
            }
      }
}
}                      
} catch (Exception exep) {
                  LOGGER.error(exep.getMessage(), exep);
}


and the code for getDotReplaced() is as follows,

private String getDotReplaced(String resourceLoc) {
String loc = null;
      loc = resourceLoc.replace('\\', '/');
      loc = resourceLoc.replace('/', '.');
      return loc;
}
isProperties(fileName) checks whether the file is a property file.
private boolean isProperties(String fileName) {
int index = fileName.indexOf(PROPERTYFILE);
      if (index > 0) {
            return true;
      }
      return false;
}

Wednesday, May 19, 2010

Eclipse-Maven-iBatis-Derby

Got to work with this combination and I wanted to share the steps, so that followers can save time and effort..
Let me put up the versions that I am using.
Versions:
Eclipse : Galileo 3.5.2
Maven 2.2.1
iBatis 2.3.4.726
Derby 10.5.3.0
If you are completely new to all these tools and have to start afresh. Here I have briefed on the download links and installation steps.

1.1       Install JDK 1.6 Update 20

Download and install Java JDK 1.6 update 20, from the provided URL

1.2       Install Eclipse IDE

Download and install eclipse IDE – Galileo 3.5 IDE for java developers, from the provided URL

1.3       Install Maven

And follow the installation instruction in the same page for the OS (Windows XP). Make sure the mvn –version returns indented version and other information correctly.

1.4       IDE Integration – Maven and Eclipse

1.4.1     Install m2eclipse core components

Follow the instruction provided in this link to complete installation of the plugin.

1.4.2     Install m2eclipse extras

Follow the reference book in this link to download m2eclipse extras which includes SCM integration.
As a prerequisite subclipse installation need to be done before installing the extras. This is integrator of subversion and eclipse. The link has the instructions for the same.

1.4.3     Configuration in Eclipse

The Maven Integration requires that Eclipse be running in a JDK, because a number of Maven core plug-ins are using jars from the JDK.

Hence a warning message occurs,
“Please make sure the -vm options in eclipse.ini is pointing to a JDK and verify that Installed JREs are also using JDK installs.”
To solve this update the eclipse.ini file to include vm param in the first line and it should point to JDK.
Example:
-vm
c:/java/jdk1.6.0_20/bin/javaw.exe

1.5       Download ibatis

Download ibatis 2.3.4 for java from this link,
It is available under Old stuff in the page.

1.6       Install Apache Derby

Download the binary zip 10.5.3.0 (db-derby-10.5.3.0-bin.zip) from the below link.
And follow instruction in this link for installing, configuring it as an embedded DB.
Instructions to work with Derby DB:
After completing the installation of all the required tools, we can directly jump to the sample implementation.
I have a table called Sample with following attributes,
CREATE TABLE sample
(
                document_id VARCHAR(40) NOT NULL,
                res_name VARCHAR(99) NOT NULL
)

Create a Maven project from archetype ‘maven-archetype-quickstart’ version 1.1. This in turn will create folder structure for source, test.

Include the following dependency in the pom.xml file the project, 

  <dependencies>
     <dependency>  
       <groupId>org.apache.ibatis</groupId>
       <artifactId>ibatis-sqlmap</artifactId>
       <version>2.3.4.726</version>
     </dependency>
    
      <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derbyclient</artifactId>
        <version>10.2.2.0</version>
      </dependency>
     
       <dependency>
         <artifactId>org.apache.derby</artifactId>
         <groupId>derby</groupId>
         <version>10.5.3.0</version>
       </dependency>                   
  </dependencies>    
iBatis requires the following components to complete the persistence and retrieval of data,
vo -  which is the object that maps to the entity in DB.
xml – mapping xml that maps the vo to the entity.
So for every entity in DB you have corresponding vo and xml.
The final one is xml config file that has information about the data source. This config file is one for any valid connection.
Lets see all of these components for our sample table,
SampleData.java
package xx.xy.vo;

public class Sample {

      private String documentId;
      private String fullName;
     

      public Sample(){

      }

      public void finalize() throws Throwable {

      }

      public String getDocumentId() {
            return documentId;
      }

      public void setDocumentId(String documentId) {
            this.documentId = documentId;
      }

      public String getFullName() {
            return fullName;
      }

      public void setFullName(String fullName) {
            this.fullName = fullName;
      }

}
SampleData.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap     
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"     
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="SampleData">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="SampleData" type="xx.xy.vo.PreEnrolmentData"/>

  <!-- Result maps describe the mapping between the columns returned
       from a query, and the class properties.  A result map isn't
       necessary if the columns (or aliases) match to the properties
       exactly. -->
  <resultMap id="SampleDataResult" class="SampleData">
    <result property="documentId" column="document_id"/>
    <result property="fullName" column="res_name"/>   
  </resultMap>

  <!-- Select with no parameters using the result map for Account class. -->
  <select id="selectAllSampleData" resultMap="SampleDataResult">
    select * from sample
  </select>

  <!-- A simpler select example without the result map.  Note the
       aliases to match the properties of the target result class. -->
  <select id="selectSampleDataById" parameterClass="string" resultClass="SampleData">
    select
      document_id as documentId,
      res_name as fullName,     
    from sample
    where document_id = #documentId#
  </select>
  
  <!-- Insert example, using the Account parameter class -->
  <insert id="insertSampleData" parameterClass="SampleData">
    insert into sample (
      document_id,
      res_name)
    values (
      #documentId#, #fullName#
    )
  </insert>

  <!-- Update example, using the Account parameter class -->
  <update id="updateSampleData" parameterClass="SampleData">
    update sample set
      res_name = #fullName#     
    where
      document_id = #documentId#
  </update>

  <!-- Delete example, using an integer as the parameter class -->
  <delete id="deleteSampleDataById" parameterClass="string">
    delete from sample where document_id = #documentId#
  </delete>

</sqlMap>

sql-map-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
   "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <settings cacheModelsEnabled="true" enhancementEnabled="true"
        lazyLoadingEnabled="true" maxRequests="32" maxSessions="10" maxTransactions="5"
        useStatementNamespaces="false" />
    <transactionManager type="JDBC">
        <dataSource type="SIMPLE">
            <property name="JDBC.ConnectionURL" value="jdbc:derby:./derbyDB"/>
            <property name="JDBC.Driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
            <property name="JDBC.Username" value="app"/>
            <property name="JDBC.Password" value="app"/>                       
        </dataSource>
    </transactionManager> 
  <sqlMap resource="PreEnrolmentData.xml"/>
</sqlMapConfig>

Create a helper class that loads the config file and provides a valid connection to perform CRUD operations to the underlying database.
MyAppSqlConfig.java
package xx.xy;

import java.io.Reader;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class MyAppSqlConfig {
      private static final SqlMapClient sqlMap;
      static {
      try {
      String resource = "sql-map-config.xml";
      Reader reader = Resources.getResourceAsReader (resource);
      sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
      } catch (Exception e) {
      // If you get an error at this point, it doesn’t matter what it was. It is going to be
      // unrecoverable and we will want the app to blow up hard so we are aware of the
      // problem. You should always log such errors and re-throw them in such a way that
      // you can be made immediately aware of the problem.
      e.printStackTrace();
      throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: " + e);
      }
      }
      public static SqlMapClient getSqlMapInstance () {
      return sqlMap;
      }
}


Now using this helper class try to execute the query that you have declared in the xml map file,
        …..
        SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance();
        ….
To insert data into DB,
        …..
        SampleData sampleData = new SampleData();
        preEnrolmentData.setDocumentId("1");
        preEnrolmentData.setFullName("Kanmani");
        try {
                                                sqlMap.update("insertPreEnrolmentData",preEnrolmentData);
                                                sqlMap.delete("deletePreEnrolmentDataById","2");                                     
                                } catch (SQLException e) {
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                }
        …..

That’s it!! You are ready with your first sample implementation and ready to explore.

Thursday, May 13, 2010

First Post

Long decided and into action today :)