Programming

How to Log Log4J’s Message Logs Into Database

Today im going to do a simple log4j logging into mysql database, the only reason i want to log into database instead of into file is so that i could query the logs i have.

This is my java class that i use to do my testcase,

package com.edw.main;

import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class Main {

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

    private void doSomething() {
        logger.debug("im doing something");
        logger.error("im doing something - error -");
    }

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

and my simple table, to store all my log messages

CREATE TABLE `logs` (
  `thread_id` varchar(20) NOT NULL,
  `tanggal` datetime NOT NULL,
  `kelas` varchar(50) NOT NULL,
  `level` varchar(10) NOT NULL,
  `pesan` varchar(1000) NOT NULL,
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

This is my log4j.properties,

# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB

# Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender

# Set JDBC URL
log4j.appender.DB.URL=jdbc:mysql://localhost/test

# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver

# Set database user name and password
log4j.appender.DB.user=root
log4j.appender.DB.password=password

# Set the SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOGS VALUES('%x',now(),'%C:%L','%p','%m', null)

# Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout

And this is what the contents of my database

This is my Netbeans; Project structure, as you can see, i only need 2 jars, mysql driver and log4j jar.

A Simple AES Encryption – Decryption Using Java

Several days ago, my friend asked me how to create a simple AES encryption – decryption using java. Well, here is your answer, hope it will helped you.

package com.edw.testing;

import java.security.AlgorithmParameters;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

public class TestingAES {

    public TestingAES() {
    }

    private void execute() throws Exception {
        
        String password = "mypassword";
        String salt = "salt";
        String cipherText = "Hello, World!";
        
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        // encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] ciphertext = cipher.doFinal(cipherText.getBytes("UTF-8"));
        
        System.out.println("password : "+password);
        System.out.println("salt : "+salt);
        System.out.println("cipherText : "+cipherText);
        System.out.println("iv : "+new BASE64Encoder().encode(iv));
        System.out.println("ciphertext : "+new BASE64Encoder().encode(ciphertext));
        
        // decrypt
        Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipherDecrypt.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        String plaintext = new String(cipherDecrypt.doFinal(ciphertext), "UTF-8");
        System.out.println("decrypted text : "+plaintext);
        
    }

    public static void main(String[] args) throws Exception {
        TestingAES testingAES = new TestingAES();
        testingAES.execute();
    }
}

And this is what is written on my netbeans console,

Oh and if you ever found this kind of error

Caused by: java.security.InvalidKeyException: Illegal key size or default parameters

it means that you need to install Java Cryptography Extension (JCE). You will find it here,

http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

Have fun 😀

Changing JAX-WS Webservice Client’s Target Endpoint Url

Let say you have a wsdl that you get from an url, but you want to fire the webservice generated from it to a different url, see my code below for example,

<service name="TestingService">
	<port name="TestingServicePort" binding="tns:TestingServicePortBinding">
		<soap:address location="http://localhost:8084/WSDLTest/TestingService" />
	</port>
</service>

as you can see, my wsdl is pointing at “http://localhost:8084/WSDLTest/TestingService”. But what if i want to fire my webservice client into another url, without changing the original wsdl. For example, my new url would be http://192.168.0.101/WSDLTest/TestingService.

Well, it’s actualy quite easy. All you need to do is only casting the service interface into interface BindingProvider, and add a new url property. This is what my code would look like,


             TestingService_Service tss = new TestingService_Service();
             TestingService testingService = tss.getTestingServicePort();
             ((BindingProvider) testingService).getRequestContext()
                .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://192.168.0.101/WSDLTest/TestingService");

If you fire your service again, it will point to a new url (http://192.168.0.101/WSDLTest/TestingService) instead of the old one (http://localhost:8084/WSDLTest/TestingService).

How to Create A Simple Captcha Using Java Servlet

On this article im going to create a simple image captcha that will show a 5-random alphanumeric letters, im using SimpleCaptha library to help me creating images and validating user’s input.

First is a simple java servlet, it will build random images and store its value on httpsession.

package com.edw.captcha;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.Captcha;
import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.renderer.DefaultWordRenderer;

public class EdwCaptcha extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Color> colors = new ArrayList<Color> ();
        colors.add(Color.black);
        colors.add(Color.red);
        
        List<Font> fonts = new ArrayList<Font>();
        fonts.add(new Font("Arial", Font.ITALIC, 40));
        
        Captcha captcha = new Captcha.Builder(120, 50)
                .addText(new DefaultWordRenderer(colors, fonts))
                .addBackground(new GradiatedBackgroundProducer(Color.white, Color.white))
                .gimp()
                .addBorder()
                .build();

        // display the image produced
        CaptchaServletUtil.writeImage(response, captcha.getImage());

        // save the captcha value on session
        request.getSession().setAttribute("simpleCaptcha", captcha); 
    }
}

And now im registering my servlet on my 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">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <servlet>
        <servlet-name>Captcha</servlet-name>
        <servlet-class>com.edw.captcha.EdwCaptcha</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Captcha</servlet-name>
        <url-pattern>/Captcha.jpg</url-pattern>
    </servlet-mapping>    
</web-app>

Here is the result image generated from my servlet,

You can validate the submitted captcha values by comparing it with the values that you store in httpsession.

[Book Review] Packt Publishing’s Ebook, Java Persistence with MyBatis 3

Among lots of java frameworks, MyBatis is a very popular especially because it is a database-centric-framework and it has a shallow and short learning curve, and today im trying to do a book review for it. The book that i want to review is Packt Publishing’s Java Persistence with MyBatis 3. You can see the ebook on this link, http://www.packtpub.com/java-persistence-with-mybatis-3/book.

This book’s author, K. Siva Prasad Reddy, really show the reasons of why MyBatis is very popular by providing with various code samples, from simple “down to earth” codes to a much more complicated codes, such as Spring Framework integration and Caching strategy.

These are the Table of Contents of the book,
Chapter 1: Getting started with MyBatis
Chapter 2: Bootstrapping
Chapter 3: SQL Mappers using XML
Chapter 4: SQL Mappers using Annotations
Chapter 5: Integration with Spring

So needless to say, this is the kind of ebook that i wish i had read since long time ago.