basic Posts

[Java] Algoritma Bilangan Romawi

Berawal dari ngobrol iseng-iseng dengan temen gw ( Kamplenk SKom ) sepulang dari ngopi bareng, beliau kebetulan nanya soal algoritma bilangan romawi untuk digunakan sebagai nomer surat. Kebetulan karena waktu gw agak kosong, iseng-iseng bikin kayak ginian ( setelah dibantu om google juga sih :p ).

package com.edw.main;

public class RomanNumber {
    
    private static final char[] ROMAWI = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
    private static final int MAX = 1000; 
    private static final int[][] DIGITS = {
        {}, {0}, {0, 0}, {0, 0, 0}, {0, 1}, {1},
        {1, 0}, {1, 0, 0}, {1, 0, 0, 0}, {0, 2}}; 
        // konstanta digit modulus 10, 
        // array ke 4(0,1) maksudnya IV, array ke 9(0,2) --> IX

    public static String int2roman(int number) {
        if (number <= 0) {
            return "N";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, m = MAX; m > 0; m /= 10, i += 2) {
            int[] d = DIGITS[(number / m) % 10];
            for (int n : d) {
                sb.append(ROMAWI[i - n]);
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(int2roman(1990));
        System.out.println(int2roman(2012));
        System.out.println(int2roman(231));
    }
}

Oi plenk, udah jadi nih wkkwkwk….

Random String Generator Using Java

This is a simple method to create a random string result, the first method is create string between A-Z and 0-9 while the second one only provide hexadecimal characters.

package com.edw.main;

import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;

public class Main {
    public static void main(String[] args) {
        // one
        System.out.println(RandomStringUtils.randomAlphanumeric(32).toUpperCase());
        
        // two
        System.out.println(UUID.randomUUID().toString().replace("-", "").toUpperCase());
    }
}

This is the screenshot of my Netbeans Project.

and this is the result,

Hope it helped others, good luck.

How to Count Number of Tables and Views from Oracle and DB2

Several days ago i had a project that made me had to do data migration from DB2 to Oracle.
For validity check, i had to count number of tables and views from DB2 before migrated and number of tables and views on Oracle after ive migrate it.

Okay enough chit-chat, this is my queries.
Count DB2’s number of tables

Select Count(*) from syscat.tables
where tabschema = 'YOUR_SCHEMA_NAME' 
AND type = 'T'

And this is how to count DB2’s View numbers

Select Count(*) from syscat.tables
where tabschema = 'YOUR_SCHEMA_NAME' 
AND type = 'V'

This is how to count number of tables from Oracle

select owner, count(*) from dba_tables
where owner = 'YOUR_OWNER_NAME'
group by owner

And this is how to count number of views from Oracle

select owner, count(*) from dba_views
where owner = 'YOUR_OWNER_NAME'
group by owner

Hope it will help others,
cheers (D)

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

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)