Programming

basic programming

How to Handle Jasper Report’s CompilationFailedException

I always use JasperReport for my java projects, but sometimes i found some weird java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException when im trying to get reports from jasper files. This is my full stack trace exception.

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
        at java.lang.Class.getConstructor0(Class.java:2699)
        at java.lang.Class.newInstance0(Class.java:326)
        at java.lang.Class.newInstance(Class.java:308)
        at net.sf.jasperreports.engine.JasperCompileManager.getCompiler(JasperCompileManager.java:472)
        at net.sf.jasperreports.engine.JasperCompileManager.loadEvaluator(JasperCompileManager.java:238)
        at net.sf.jasperreports.engine.fill.JRFillDataset.createCalculator(JRFillDataset.java:416)
        at net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:408)
        at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:74)
        at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:56)
        at net.sf.jasperreports.engine.fill.JRFiller.createFiller(JRFiller.java:143)
        at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:79)
        at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)

Actually it happens because im still using Groovy as my report language, instead of Java. All i have to do is change reporting language to java, as you can see below.

Or adding groovy*.jar to your project’s classpath.

Have fun, cheers. (B)

Set MySQL Connection TimeOut

Sometimes you find a condition where your database connection (MySQL) is time out because of your queries are spending too much time. This is a hint on how you increase your MySQL time out configuration.

First you query your default connection timeout.

SHOW VARIABLES LIKE 'connect_timeout';

As you can see below, i have approximately 10 seconds before my mysql connection time out.

Next is updated it to 60 seconds.

SET GLOBAL connect_timeout=60;

Simple isn’t it. 😉

How to Play MP3 Files with Java

Well, it’s actually very simple, first of all you need to download libraries (mp3spi1.9.4.jar, jl1.0.jar and tritonus_share.jar) from Tritonus and from JLayer.

Here is how i code it,

package com.edw.mp3.main;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import org.apache.log4j.Logger;

public class Main extends Thread {

    private String filename;
    private static Logger logger = Logger.getLogger(Main.class);

    public Main(String filename) {
        super();
        this.filename = filename;
    }


    @Override
    public void run() {
        try {
            File file = new File(filename);

            AudioInputStream in = AudioSystem.getAudioInputStream(file);
            AudioInputStream din = null;
            AudioFormat baseFormat = in.getFormat();
            AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                    baseFormat.getSampleRate(),
                    16,
                    baseFormat.getChannels(),
                    baseFormat.getChannels() * 2,
                    baseFormat.getSampleRate(),
                    false);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);

            // play it...
            rawplay(decodedFormat, din);
            in.close();

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally{
            logger.debug("finish playing "+filename);
        }
    }

    private synchronized void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException {
        byte[] data = new byte[4096];
        SourceDataLine line = getLine(targetFormat);
        if (line != null) {
            // Start
            line.start();
            int nBytesRead = 0, nBytesWritten = 0;
            while (nBytesRead != -1) {
                nBytesRead = din.read(data, 0, data.length);
                if (nBytesRead != -1) {
                    nBytesWritten = line.write(data, 0, nBytesRead);
                }

            }
            // Stop
            line.drain();
            line.stop();
            line.close();
            din.close();
        }

    }

    private synchronized SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info =
                new DataLine.Info(SourceDataLine.class, audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);

        return res;
    }

    public static void main(String[] args) {
        // my relative path file name
        String song = "Bondan ft. Fade2Black-Ya Sudahlah.mp3";
        logger.debug("start playing "+song);
        Main mp3Sound = new Main(song);
        mp3Sound.start();        
    }
}

And my Netbeans’ project structure

Actually i code it a long time ago, Thank God it’s still works. If you have any suggestion, feel free to comment it.
Cheers.. (B)

Beginning MyBatis 3

MyBatis framework is a complete rewrite of iBatis, it’s a data mapper framework that makes it easier to use a relational database with object-oriented applications. The difference from old iBatis is that now everything can now be written in java, from queries, configuration to mappers.

Some people might ask why MyBatis use a different approach from its ancestor, iBatis? iBatis’ code generator use *DAOs while MyBatis use *Mappers. I think they all the same, but then according to Clinton Begin they are, despite their similarity, are not exact in concepts.

DAOs can collect multiple statements and thus aggregate or cohesive data logic into one method. That said, this isn’t necessarily a good thing. After 10 years of writing DAOs, I can say with enough experience that DAOs are a waste of time. They fragment business logic, they’re extra code and the abstraction goes largely unused for the lifetime of most applications that implement it. DAOs were often implemented incorrectly and code would sneak into them that should not.

Mappers on the other hand, are named function that executes a single SQL statement or procedure. There is no extra code, and it eliminates strings in the execution of mapped statements. Mappers also help define the mapped statement.

In a sense, you can also think of it as:

  • DAOs USE mapped statements.
  • Mapper methods ARE mapped statements.

The cohesive grouping or aggregation of related statements that work together to form a business process should now exist in your service layer (be it a Spring bean, or an EJB or a POJO service layer).

Okay enough with the chit-chat, let me show you the code, first as always, a simple mysql database named test, and a table named Contoh.

CREATE TABLE contoh
(
    nama VARCHAR(30) NOT NULL,
    alamat VARCHAR(100),
    PRIMARY KEY (nama)
)

and a java bean

package com.edw.mybatis.bean;

public class Contoh {
    private String nama;
    private String alamat;

    // other setter and getter

    @Override
    public String toString(){
        return nama+" : "+alamat;
    }
}

This is my Contoh table queries, i named it ContohMapper.xml

<?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="com.edw.mybatis.mapper.ContohMapper" >
    
  <resultMap id="ContohMap" type="com.edw.mybatis.bean.Contoh" >
    <id column="nama" property="nama" jdbcType="VARCHAR" />
    <result column="alamat" property="alamat" jdbcType="VARCHAR" />
  </resultMap>

  <insert id="save" parameterType="com.edw.mybatis.bean.Contoh" >
    insert into contoh (nama, alamat)
    values (#{nama,jdbcType=VARCHAR}, #{alamat,jdbcType=VARCHAR})
  </insert>

  <update id="update" parameterType="com.edw.mybatis.bean.Contoh" >
    update contoh
    set alamat = #{alamat,jdbcType=VARCHAR}
    where nama = #{nama,jdbcType=VARCHAR}
  </update>

</mapper>

I register my ContohMapper.xml on Configuration.xml

<?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="xxx"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/edw/mybatis/xml/ContohMapper.xml"/>
    </mappers>
</configuration>

What makes MyBatis different from iBatis, is the ability to put queries on interfaces using annotations. Here is the example.

package com.edw.mybatis.mapper;

import com.edw.mybatis.bean.Contoh;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;

public interface ContohMapper {    
    int save(Contoh contoh);

    @Delete("DELETE FROM contoh WHERE nama = #{nama}")
    int delete(String nama);

    @Select("SELECT * FROM contoh WHERE nama = #{nama}")
    Contoh select(String nama);

    @Select("SELECT * FROM contoh")
    List<Contoh> selectAll();
}

and a factory class to load my configuration

package com.edw.mybatis.config;

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


/**
 *
 * @author edw
 */
public class MyBatisSqlSessionFactory {

    protected static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/mybatis/xml/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 here’s my main class

package com.edw.mybatis.main;

import com.edw.mybatis.bean.Contoh;
import com.edw.mybatis.config.MyBatisSqlSessionFactory;
import com.edw.mybatis.mapper.ContohMapper;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

public class Main {

    private Logger logger = Logger.getLogger(Main.class);

    public Main() {
    }

    private void execute() {
        SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();
        try {
            // select all
            ContohMapper mapper = session.getMapper(ContohMapper.class);
            List<Contoh> contohs = mapper.selectAll();
            for (Contoh contoh1 : contohs) {
                logger.debug(contoh1);
            }

            // delete
            int success = mapper.delete("pepe");
            if (success == 0) {
                logger.debug("failed to delete");
            } else {
                logger.debug("successfully deleted");
            }

            // insert
            Contoh contohExample = new Contoh();
            contohExample.setNama("kacrut");
            contohExample.setAlamat("kacrut alamat");
            int insertSuccess = session.insert("save", contohExample);
            if (insertSuccess == 0) {
                logger.debug("failed to insert");
            } else {
                logger.debug("successfully inserted");
            }

            // check is it inserted yet
            Contoh contoh = (Contoh) mapper.select(contohExample.getNama());
            logger.debug(contoh);

            // update
            Contoh contohExample2 = new Contoh();
            contohExample2.setNama("kacrut");
            contohExample2.setAlamat("kacrut alamat 22");
            int updateSuccess = session.update("com.edw.mybatis.mapper.ContohMapper.update", contohExample2);
            if (updateSuccess == 0) {
                logger.debug("failed to update");
            } else {
                logger.debug("successfully updated");
            }

            session.commit();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            session.close();
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.execute();
    }
}

this is what happen when i run my project,

run:
2010-11-12 15:40:41,804 - DEBUG java.sql.Connection:27 - ooo Connection Opened
2010-11-12 15:40:42,041 - DEBUG java.sql.PreparedStatement:27 - ==>  Executing: SELECT * FROM contoh 
2010-11-12 15:40:42,041 - DEBUG java.sql.PreparedStatement:27 - ==> Parameters: 
2010-11-12 15:40:42,100 - DEBUG java.sql.ResultSet:27 - <==    Columns: nama, alamat
2010-11-12 15:40:42,101 - DEBUG java.sql.ResultSet:27 - <==        Row: edwin, singapore
2010-11-12 15:40:42,103 - DEBUG java.sql.ResultSet:27 - <==        Row: kamplenk, ciledug
2010-11-12 15:40:42,104 - DEBUG java.sql.ResultSet:27 - <==        Row: nugie, pamulang
2010-11-12 15:40:42,105 - DEBUG java.sql.ResultSet:27 - <==        Row: samsu, dago
2010-11-12 15:40:42,120 - DEBUG java.sql.ResultSet:27 - <==        Row: tebek, jayapura
2010-11-12 15:40:42,122 - DEBUG com.edw.mybatis.main.Main:24 - edwin : singapore
2010-11-12 15:40:42,122 - DEBUG com.edw.mybatis.main.Main:24 - kamplenk : ciledug
2010-11-12 15:40:42,123 - DEBUG com.edw.mybatis.main.Main:24 - nugie : pamulang
2010-11-12 15:40:42,123 - DEBUG com.edw.mybatis.main.Main:24 - samsu : dago
2010-11-12 15:40:42,123 - DEBUG com.edw.mybatis.main.Main:24 - tebek : jayapura
2010-11-12 15:40:42,133 - DEBUG java.sql.PreparedStatement:27 - ==>  Executing: DELETE FROM contoh WHERE nama = ? 
2010-11-12 15:40:42,134 - DEBUG java.sql.PreparedStatement:27 - ==> Parameters: pepe(String)
2010-11-12 15:40:42,136 - DEBUG com.edw.mybatis.main.Main:30 - failed to delete
2010-11-12 15:40:42,137 - DEBUG java.sql.PreparedStatement:27 - ==>  Executing: insert into contoh (nama, alamat) values (?, ?) 
2010-11-12 15:40:42,138 - DEBUG java.sql.PreparedStatement:27 - ==> Parameters: kacrut(String), kacrut alamat(String)
2010-11-12 15:40:42,159 - DEBUG com.edw.mybatis.main.Main:43 - successfully inserted
2010-11-12 15:40:42,160 - DEBUG java.sql.PreparedStatement:27 - ==>  Executing: SELECT * FROM contoh WHERE nama = ? 
2010-11-12 15:40:42,160 - DEBUG java.sql.PreparedStatement:27 - ==> Parameters: kacrut(String)
2010-11-12 15:40:42,163 - DEBUG java.sql.ResultSet:27 - <==    Columns: nama, alamat
2010-11-12 15:40:42,163 - DEBUG java.sql.ResultSet:27 - <==        Row: kacrut, kacrut alamat
2010-11-12 15:40:42,164 - DEBUG com.edw.mybatis.main.Main:48 - kacrut : kacrut alamat
2010-11-12 15:40:42,166 - DEBUG java.sql.PreparedStatement:27 - ==>  Executing: update contoh set alamat = ? where nama = ? 
2010-11-12 15:40:42,166 - DEBUG java.sql.PreparedStatement:27 - ==> Parameters: kacrut alamat 22(String), kacrut(String)
2010-11-12 15:40:42,202 - DEBUG com.edw.mybatis.main.Main:58 - successfully updated
2010-11-12 15:40:42,259 - DEBUG java.sql.Connection:27 - xxx Connection Closed
BUILD SUCCESSFUL (total time: 2 seconds)

this is my Netbeans 6.9 project structure

Again, another great framework that i’ll obviously use. Cheers, :-[

ps.
i almost forget, here is my log4j.properties.

# Global logging configuration
log4j.rootLogger=DEBUG,stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d - %-5p %c:%L - %m%n

Creating a Calendar or Date Picker using JQuery

Well, it’s actually quite easy to create a simple calendar or datepicker using jquery. But first you need to download jQuery and jQuery UI libs. This is how you do it,

<html>
    <head>
        <title>JQuery Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="datePicker.css" type="text/css" rel="stylesheet" />
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="jquery-datepicker.js"></script>
        <script type="text/javascript">
            $(function()
            {
                $('#date-pick').datepicker({
                    showOn: "button",
                    dateFormat: "dd/mm/yy",
                    disabled: true,
                    buttonImage: "calendar.png",
                    buttonImageOnly: true
                });
            });
        </script>
    </head>
    <body>
        Enter your birthdate :
        <input name="date1" type="text" id="date-pick" size="10" maxlength="10" />
    </body>
</html>

It will look like this,

For the live example, you can see here. Cheers (B)