Monday, August 29, 2011

Loggers in Java, Redirecting Log contents in a Log file in Java

Loggers in Java, Redirecting Log contents in a Log file in Java

Dear reader,
Here is the complete coding where we can configure a logger and redirect the logger contents
into a separate file for proper tracing.

//LoggerTest.java
package com.ewp.services;
import java.util.logging.*;
import java.io.*;

public class LoggerTest {

public static Logger logger;

static {
    try {
      boolean append = true;
      FileHandler fh = new FileHandler("D://Temp//log.properties", append);
      fh.setFormatter(new Formatter() {
         public String format(LogRecord rec) {
            StringBuffer buf = new StringBuffer(1000);
            buf.append(new java.util.Date());
            buf.append("===>");
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
            }
          });
      logger = Logger.getLogger("TestLog");
      logger.addHandler(fh);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
}

public static void main(String args[]) {
    logger.severe("Severe category messages");
    logger.warning("Warning categary messages");
    logger.info("Info level messages");
    }
}

//Output in file "D:\Temp\log.properties"
/*
Mon Aug 29 15:39:48 IST 2011===>Severe category messages
Mon Aug 29 15:39:49 IST 2011===>Warning categary messages
Mon Aug 29 15:39:49 IST 2011===>Info level messages
*/

Monday, August 22, 2011

Stored Procedure in Hibernate

//Calling Stored procedure from Hibernate

XXXX.hbm.xml
<sql-query name="del_logged_users" callable="true">
        {call del_logged_users()}
</sql-query>

//Java code to call the stored procedure
public void deleteAllUsersDAO() throws Exception {
        String sql = "{call del_logged_users()}";
        Object[] inputParams = {};
        try    {    
            QueryInput queryInput = PersistenceHelper.createQuery("del_logged_users");
            PersistenceHelper.executeNamedQuery(queryInput);
            
            DatabaseUtil dbUtil = new DatabaseUtil();   //See this class below
            dbUtil.setup(getDataSourceName());
            dbUtil.runCall(sql, inputParams);
        } catch (Exception e) {
            StringBuffer message = new StringBuffer("Error while updating data. Original error message: ").
                append(e.getMessage());
            LogHelper.error(CLASS_NAME, METHOD_NAME, message.toString());
        
            throw new InternalException(
                    BusinessServiceMessageConstants.INT_ERRCODE_JDBC_QUERY_ERROR,
                    message.toString(), e);
        }
}

//Supporting class DatabaseUtil.java
private static HashMap datasourceCache = null;

public void setup(String datasource Name) throws NamingException {
        try {
            synchronized (this) {
                if( datasourceCache == null ) {
                    datasourceCache = new HashMap();
                }
                datasource = (DataSource)datasourceCache.get(datasourceName);
                if( datasource == null ){
                    InitialContext context = new InitialContext();
                    datasource = (DataSource)context.lookup(datasourceName);
                    datasourceCache.put(datasourceName, datasource);
                }
            }   // end synchronized block
        }
        catch(NamingException e) {
            e.printStackTrace();
            //Rethrow the exception
            throw e;
        }
}

public void runCall(String sql, Object[] params) throws SQLException, PersistenceException, 
                                                               RequiredParameterException {
    CallableStatement statement = null;
    Connection connection = getConnection();    
    try {
        statement = connection.prepareCall(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++)    {
                Object par = params[i];
                if (par == null)
                    statement.setNull(i + 1, Types.VARCHAR);
                if (par instanceof String)
                    statement.setString(i + 1, (String) par);
                else if (par instanceof Long)
                    statement.setLong(i + 1, ((Long) par).longValue());
                else if (par instanceof Timestamp)
                    statement.setTimestamp(i + 1, (Timestamp) par);
                else if (par instanceof java.util.Date)
                    statement.setDate(i + 1, new java.sql.Date(((java.util.Date) par)
                            .getTime()));
                else if (par instanceof Integer)
                    statement.setInt(i + 1, ((Integer) par).intValue());
                else if (par instanceof java.math.BigDecimal)
                    statement.setLong(i + 1, ((java.math.BigDecimal) par).longValue());
                // st.setBigDecimal(i+1, (java.math.BigDecimal)par);
            }
        }
        statement.execute();
      //connection.commit(); 
    }
    catch (SQLException e) {
        throw e;
    }
    finally {
        try {            
            if ( statement != null ) {
                statement.close();
            }
            if ( connection != null ) {
                connection.close();
            }
        }
        catch (SQLException e) {        
        } 
    }
}

-----------------------------END----------------------------------------