Programming

Setting Up C3P0 Connection Pooling on Apache Tomcat

My using this configuration on my Apache Tomcat 7 for my heavy-load application, and it runs very well. I put this code on context.xml under Apache Tomcat’s conf folder.

<Resource name="myconnection" auth="Container"
	driverClass="com.mysql.jdbc.Driver"
	jdbcUrl="jdbc:mysql://localhost:3306/mydatabase"
	user="root"
	password="xxxx"                                                      
	factory="org.apache.naming.factory.BeanFactory" 
	type="com.mchange.v2.c3p0.ComboPooledDataSource" 
	maxPoolSize="50" 	
	minPoolSize="15" 
	acquireIncrement="3" 
	acquireRetryAttempts = "0"
	acquireRetryDelay = "3000"
	breakAfterAcquireFailure = "false"
	maxConnectionAge = "60"
	maxIdleTime = "30"
	maxIdleTimeExcessConnections = "10"
	idleConnectionTestPeriod = "15"
	testConnectionOnCheckout = "true"
	preferredTestQuery = "SELECT 1"
	debugUnreturnedConnectionStackTraces = "true"	
	autoCommitOnClose="true"
	/>

I use MySql’s command “SHOW PROCESSLIST” for checking on opened connection to MySql.

I hope it helped others.
:-[

Beginning Sitemesh

In this tutorial, im trying to create a simple application using Sitemesh. According to Wikipedia, Sitemesh is a web-page layout and decoration framework and web application integration framework to aid in creating large sites consisting of many pages for which a consistent look/feel, navigation and layout scheme is required. So basically, Sitemesh is a templating engine or a decorator pattern.

Let’s start with a simple application, first is a maven’s pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.edw</groupId>
    <artifactId>SitemeshExample</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>SitemeshExample Web App</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <netbeans.hint.deploy.server>Tomcat70</netbeans.hint.deploy.server>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>opensymphony</groupId>
            <artifactId>sitemesh</artifactId>
            <version>2.4.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <finalName>SitemeshExample</finalName>
    </build>
</project>

and this is my web.xml file,

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>Sitemesh</display-name>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
    </filter>
 
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

next step is creating decorators.xml under WEB-INF folder

<?xml version="1.0" encoding="UTF-8"?>
<decorators>
    <excludes>
        <pattern>/index.jsp</pattern> <!-- exclude example -->
        <pattern>*.js</pattern> <!-- exclude css files -->
        <pattern>*.css</pattern> <!-- exclude js files -->
    </excludes>
    <decorator name="basic-theme" page="/template/theme.jsp">        
        <pattern>/*</pattern>        
    </decorator>
</decorators>

and a base html template

<?xml version="1.0" encoding="UTF-8" ?>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Title</title>
</head>
<body>
    <h1>Header</h1>
    <p><b>Menu</b></p>
    
    <decorator:body />
    
    <h1>Footer</b></h1>
</body>
</html>

And 2 .jsp files for example, index.jsp and dodol.jsp
index.jsp

<div>
    <h2>Hello WORLD...!! (Without Sitemesh)</h2>
</div>

and dodol.jsp

    <h1>Hello World! (With Sitemesh)</h1>

these is the screenshot when i deploy my application,

and this is my netbeans project structure

Usefull *nix Commands

This is my personal note for my most used *nix commands,
who know perhaps someday someone would find it usefull.

i use this to start apache tomcat, im using nohup command to keep my application running after i logged out.

nohup ./startup.sh 

i use this to kill an application using it’s process id

kill -9 <pid>

but how to find an application’s process id? Im using ps command for it. In this example im searching for “java” process id.

ps -ef | grep java

this is the command i use for checking whether a particular port is open or not. Im using port 8080 for example

netstat -aon | grep 8080

command for reading a rotating log file,

tail -f edw/modules/system.out

check my command history

history | grep java

im using these syntax to see my AIX peformance

topas –P

or

nmon

Create A Database Transaction Using MyBatis

According to Wikipedia, transaction comprises a unit of work performed within a database management system (or similar system) against a database, and treated in a coherent and reliable way independent of other transactions.

Transactions in a database environment have two main purposes:
1. To provide reliable units of work that allow correct recovery from failures and keep a database consistent even in cases of system failure, when execution stops (completely or partially) and many operations upon a database remain uncompleted, with unclear status.
2. To provide isolation between programs accessing a database concurrently. If this isolation is not provided the programs outcome are possibly erroneous.

So basically, the concept of transaction is all-or-nothing. Whether all the query on transaction succesfully executed, or none of them executed.
On this example im trying to insert 5 datas, but on the 5th data i will throw an exception. If the database transaction is running well, none of the datas is on the database.
And dont forget, if you are using MySQL, please make sure that your table engine is InnoDB.

First, as always, i’ll start with a simple MySQL table,

CREATE TABLE `testing` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `address` varchar(255) NOT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `ix` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next is a java bean,

package com.edw.bean;

public class Testing {

    private Integer id;
    private String name;
    private String address;
	
	// other setter and getter
	
    @Override
    public String toString() {
        return "testing{" + "id=" + id + ", name=" + name + ", address=" + address + '}';
    }
}

Next is creating xml file for database configuration,

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
       <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost/test"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>          
    </environments>
    <mappers />        		
</configuration>

A java class to load my database configuration

package com.edw.config;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisSqlSessionFactory {

    private static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;
    }
}

And a java interface for insert queries,

package com.edw.mapper;

import com.edw.bean.Testing;
import org.apache.ibatis.annotations.Insert;

public interface TestingMapper {
    
    @Insert("INSERT INTO testing values(null, #{name},#{address})")
    public void insert(Testing testing);
    
}

This is the main class for my application

package com.edw.main;

import com.edw.bean.Testing;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.TestingMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;

public class Main {

    private Logger logger = Logger.getLogger(Main.class);
    
    public Main(){        
    }

    private void start(){
        logger.debug("==== BEGIN ====");
        SqlSessionFactory sqlSessionFactory = MyBatisSqlSessionFactory.getSqlSessionFactory();
        sqlSessionFactory.getConfiguration().addMapper(TestingMapper.class);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TestingMapper testingMapper = sqlSession.getMapper(TestingMapper.class);
        
        try {
            Testing testing = new Testing();
            testing.setName("Edwin");
            testing.setAddress("Ciledug");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Kamplenk");
            testing.setAddress("Karawaci");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Jeklit");
            testing.setAddress("Cibinong");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Nugie");
            testing.setAddress("Pamulang");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Tebek");
            testing.setAddress("Isvil");
            testingMapper.insert(testing);
            
            // try to create an exception
            if(testing.getName().equals("Tebek"))
                throw new Exception("No Tebek allowed");
            
            sqlSession.commit();
            logger.debug("=== END =====");
        } catch (Exception e) {
            logger.error(e,e);
            sqlSession.rollback();
        } finally{
            sqlSession.close();
        }                
    }
    
    public static void main(String[] args) {
        new Main().start();
    }    
}

It supposed to show exception on your Netbeans console, and your data wont be on your database.

and last but not least, my log4j properties

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %c:%L - %m%n

This is the screenshot for my netbeans project structure,

Cheers (D)

Weird “Unparseable Date” Exception When Using Java’s SimpleDateFormat Class

I found this weird error at my production server, an error which somehow never show up at my testing environment.

java.text.ParseException: Unparseable date: "Thu Oct 11 00:00:00 ICT 2012"
        at java.text.DateFormat.parse(DateFormat.java:337)
        at DateClass.main(DateClass.java:7)

It seems that my application is unable to parse the string i provided. But, what makes me confuse is, i try with the same class on my laptop over and over again but this error is never show up. I tought it has something to do with the server’s JDK version or even the server’s operating system.

This is my java class that i use for testing purpose, it runs very well on both my laptop and development server, but it shows error on my server.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateClass {
    public static void main(String[] args) throws Exception {
        String date = "Thu Oct 11 00:00:00 ICT 2012";
        Date tanggalku = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(date);
        System.out.println(tanggalku);
    }
}

After spend several minutes googling, i found out that it happen because of Java’s Date Localization. This is my workaround,

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateClass {
    public static void main(String[] args) throws Exception {
        String date = "Thu Oct 11 00:00:00 ICT 2012";
        Date tanggalku = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(date);
        System.out.println(tanggalku);
    }
}

Another workaround, if you are using Apache Tomcat, is adding this configuration on your Tomcat’s server parameter.

-Duser.language=en 
-Duser.region=US

Hope it helps others 😉