Java Books


Java SE

  1. Online Java Tutorial
  2. HeadFirst Java
  3. Effective Java

Spring

  1. Spring Recipes

You can search in flazx

Advertisements

Configure Log4j in Spring


Di mana kita harus menyimpan log output aplikasi kita? Tentunya kita ingin menggunakan lokasi yang dinamis sesuai dengan lokasi deployment. Misalnya, di Windows kita mungkin mendeploy aplikasi kita di

C:\Program Files\Apache Tomcat\webapps\aplikasi-saya

Sedangkan di Linux, kita mendeploy aplikasi di

/opt/apache-tomcat/webapps/aplikasi-saya

Dengan kemungkinan seperti di atas, bagaimana kita harus menulis konfigurasi log4j?
Mudah, bila kita menggunakan Spring MVC.

Kita bisa menggunakan Log4jConfigListener yang disediakan Spring. Class ini memungkinkan kita menggunakan variabel di konfigurasi log4j kita. Kita mendaftarkan class ini di dalam web.xml, sebelum ContextLoaderListener, seperti ini

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Dengan adanya Log4jConfigListener ini, kita bisa menyebutkan lokasi konfigurasi log4j seperti ini :

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:artivisi-log4j.properties</param-value>
    </context-param>

Isi artivisi-log4j.properties terlihat seperti ini :

# Konfigurasi kategori
log4j.rootLogger=INFO,fileout

# File output
log4j.appender.fileout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileout.file=${webapp.root.path}/WEB-INF/logs/application.log
log4j.appender.fileout.datePattern='.'yyyy-MM-dd
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.conversionPattern=%d [%t] %p (%F:%L) ­ %m%n

Perhatikan konfigurasi log4j.appender.fileout.file. Kita menggunakan variabel ${webapp.root.path} yang akan diisi dengan nilai lokasi deployment aplikasi web kita. Variabel ${webapp.root.path} ini didefinisikan dalam web.xml sebagai berikut :

<context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webapp.root.path</param-value>
</context-param>

Dengan konfigurasi ini, kita dapat meletakkan log output kita di

C:\Program Files\Apache Tomcat\webapps\aplikasi-saya\WEB-INF\logs\application.log

bila kita mendeploy di Windows, dan di

/opt/apache-tomcat/webapps/aplikasi-saya/WEB-INF/logs/application.log

bila kita deploy di Linux.

Konfigurasi di atas bisa disederhanakan lagi bila kita mengikuti nilai default yang disediakan Spring, yaitu cukup seperti ini dalam web.xml :

 

<listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Kemudian memberi nama file konfigurasi logger kita log4j.properties yang berada di top level dalam classpath, dan berisi seperti ini :

# Konfigurasi kategori
log4j.rootLogger=INFO,fileout

# File output
log4j.appender.fileout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileout.file=${webapp.root}/WEB-INF/logs/application.log
log4j.appender.fileout.datePattern='.'yyyy-MM-dd
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.conversionPattern=%d [%t] %p (%F:%L) ­ %m%n

Nilai variabel ${webapp.root} secara default akan diisi dengan lokasi deployment tanpa harus mengkonfigurasi webAppRootKey

http://endy.artivisi.com/blog/java/log4j-spring-mvc/

Get SessionFactory Instance without using hibernate.cfg.xml


Database Config

package co.id.hanoman.btnmw.spp.conf;

import java.util.List;
import java.util.Properties;
import java.util.Vector;

public class DatabaseConfig {
	private static String MYSQL_DBMS = "MYSQL";
	private static String SQLSERVER_DBMS = "SQLServer";

	private static String SQLSERVER_DRIVER = "net.sourceforge.jtds.jdbc.Driver";
	private static String MYSQL_DRIVER = "com.mysql.jdbc.Driver";

	private String host;
	private String port;
	private String dbname;
	private String dbms;
	private String user;
	private String pass;
	private List<Class<?>> mapList;
	private Properties properties;

	public DatabaseConfig(String host, String port, String dbname, String dbms,
			String user, String pass) {
		mapList = new Vector<Class<?>>();
		properties = new Properties();
		this.host = host;
		this.port = port;
		this.dbname = dbname;
		this.dbms = dbms;
		this.user = user;
		this.pass = pass;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public String getDbname() {
		return dbname;
	}

	public void setDbname(String dbname) {
		this.dbname = dbname;
	}

	public String getDbms() {
		return dbms;
	}

	public void setDbms(String dbms) {
		this.dbms = dbms;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public List<Class<?>> getAnnotatedClass() {
		return mapList;
	}

	public void setMapList(List<Class<?>> mapList) {
		this.mapList = mapList;
	}

	public String getDriver() {

		if (dbms.equalsIgnoreCase(MYSQL_DBMS)) {
			return MYSQL_DRIVER;
		} else if (dbms.equalsIgnoreCase(SQLSERVER_DBMS)) {
			return SQLSERVER_DRIVER;
		}

		return null;
	}

	public String getUrl() {
		System.out.println(dbms + MYSQL_DBMS);
		if (dbms.equalsIgnoreCase(MYSQL_DBMS)) {
			return String.format("jdbc:mysql://%s:%s/%s", host, port, dbname);
		} else if (dbms.equalsIgnoreCase(SQLSERVER_DBMS)) {
			return String.format("jdbc:jtds:sqlserver://%s:%s/%s", host, port,
					dbname);
		}

		return null;
	}

	public String getDialect() {
		if (dbms.equalsIgnoreCase(MYSQL_DBMS)) {
			return "org.hibernate.dialect.SQLServerDialect";
		} else if (dbms.equalsIgnoreCase(SQLSERVER_DBMS)) {
			return "org.hibernate.dialect.MySQLDialect";
		}

		return null;
	}

	public void addAnnotatedClass(Class<?> entity) {
		mapList.add(entity);
	}

	public void removeAnnotatedClass(Class<?> entity) {
		mapList.remove(entity);
	}
	
	public Properties getProperties() {
		return properties;
	}
	
	public void addProperty(String k, String v) {
		properties.setProperty(k, v);
	}
	
	public void removeProperty(String k) {
		properties.remove(k);
	}
}

Syncrhonizer Session Factory

package co.id.hanoman.btnmw.spp.dao;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;

import co.id.hanoman.btnmw.spp.conf.DatabaseConfig;
import co.id.hanoman.btnmw.spp.entity.Pembayaran;
import co.id.hanoman.btnmw.spp.entity.Tagihan;


public class SynchronizerSessionFactory {
	private static Logger logger = Logger
			.getLogger(SynchronizerSessionFactory.class);

	public static SessionFactory getSessionFactory(DatabaseConfig conf) {
		logger.debug("getSessionFactory invoked");
		
		try {
			conf.addAnnotatedClass(Pembayaran.class);
			conf.addAnnotatedClass(Tagihan.class);
			conf.addProperty("hibernate.hbm2ddl.auto", "update");
			return HibernateSessionFactory.getSessionFactory(conf);
		} catch (HibernateException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

}

HibernateSessionFactory

package co.id.hanoman.btnmw.spp.dao;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;

import co.id.hanoman.btnmw.spp.conf.DatabaseConfig;
import co.id.hanoman.btnmw.spp.entity.Pembayaran;
import co.id.hanoman.btnmw.spp.entity.Tagihan;


public class SynchronizerSessionFactory {
	private static Logger logger = Logger
			.getLogger(SynchronizerSessionFactory.class);

	public static SessionFactory getSessionFactory(DatabaseConfig conf) {
		logger.debug("getSessionFactory invoked");
		
		try {
			conf.addAnnotatedClass(Pembayaran.class);
			conf.addAnnotatedClass(Tagihan.class);
			conf.addProperty("hibernate.hbm2ddl.auto", "update");
			return HibernateSessionFactory.getSessionFactory(conf);
		} catch (HibernateException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

}

@Test
	public void testGetSessionFactory() {
		DatabaseConfig conf = new DatabaseConfig("localhost", "3306", "btn_usu", "mysql", "root", "root");
		conf.addAnnotatedClass(Tagihan.class);
		conf.addAnnotatedClass(Pembayaran.class);
		conf.addProperty("hibernate.hbm2ddl.auto", "create");
		sf = SynchronizerSessionFactory.getSessionFactory(conf);
		assertNotNull(sf);
		
		ITagihanDao tagihanDao = new TagihanDao(sf);
		tagihanDao.save(tagihan);
		
		IPembayaranDao pembayaranDao = new PembayaranDao(sf);
		pembayaranDao.save(pembayaran);
	}

Convert Date To String and String to Date


String datestring1 = "2009-10-27 14:36:59.580250";
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestring1);
String datestring2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(date1);
System.out.println(datestring2);

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

import org.apache.log4j.Logger;

public class DateHelper {
	private static Logger logger = Logger.getLogger(DateHelper.class);

	public static Date strToDate(String _strDate, String _pattern)
			throws ParseException {
		Date date;
		try {
			date = new SimpleDateFormat(_pattern).parse(_strDate);
			logger.debug("date converted");
			return date;
		} catch (ParseException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	public static String dateToString(Date date, String _pattern) {
		String strDate;

		strDate = new SimpleDateFormat(_pattern).format(date);
		logger.debug("date converted" + strDate);
		return strDate;

	}
}