Reality is a perception. Perceptions are not always based on facts, and are strongly influenced by illusions. Inquisitiveness is hence indispensable

Thursday, December 4, 2008

Kick starting with hibernate

ORM is no rocket science, it is a very useful tool though. The idea of a tool to help manage transactions and bean bindings is a developer's paradise. So how do we start off? Download hibernate from internet, along with it the not so obvious slf4j-simple-xxx.jar and slf4j-api-xxx.jar files are needed.

Place these in you project class path. The next step is writing the mapping files. The file hibernate.cfg.xml is the one which spells out the all encompassing details like those of the database, connection pool etc. The < entity >.hbm.xml files contain the object mapping information along any operation specific information.

A sample hibernate config xml for MySQL


<?xml version="1.0" encoding="UTF-8"?>

<!--
Document : hibernate.cfg.xml.xml
Created on : 02 November 2008, 19:31
Author : Kanthi Swaroop Rongala
-->

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hospital_care</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
-->

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup
<property name="hbm2ddl.auto">create</property>
-->

<!--
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
-->
<mapping resource="model/resources/Doctor.hbm.xml"/>
<mapping resource="model/resources/Patient.hbm.xml"/>
<mapping resource="model/resources/Appointment.hbm.xml"/>
</session-factory>

</hibernate-configuration>




Note that I have placed all my xmls in a different package called model.resources. What about the hibernate.cfg.xml location? We can move it as well.

See the following:
public class HibernateUtil {

private static SessionFactory sessionFactory = null;
private String CONFIG_FILE_PATH = "/model/resources/hibernate.cfg.xml";

private HibernateUtil(){
}

private SessionFactory create() {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure(CONFIG_FILE_PATH).buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
return sessionFactory;
}

public static SessionFactory getSessionFactory() {
if(sessionFactory == null){
HibernateUtil utils = new HibernateUtil();
utils.create();
}
return sessionFactory;
}
}


Hope this helps in giving you that well deserved push

Dynamic proxy

Every one knows compiled code is type safe and is static. It is not possible to dynamically type the behaviour in such cases. C, C++, Java … they all fit the bill. Java has this interesting feature called Dynamic proxies which promises what it spells. Now how the hell can… well it is not exactly dynamic!. There is a provision for plugging functionality (not just behaviour) at run time without major code changes. So should we really be calling it Dynamic?

As life goes on, let’s see an example. Suppose I have come legacy code/tested code/production code/my own kitchen sink code/tutorial code…Tan(90). The purpose of the code can be as simple as that of a logger. Now I want to impart some extra functionality (not just behaviour), say an actionlistener, whoa!! On a logger!! (Bear with me for the sake of example). Now how would be do that:
  1.  Implement the interface
  2.  Create a wrapper class which uses composition
Not bad?, and where would be place this? In our code base of course! Dynamic proxies offer yet another way of doing things.

Think of a utility that creates a wrapper for the interfaces you want and lets you inspect the calls being made. Armed with this knowledge the lone ninja developer can render a killer app, well that is the idea at least. This utility is part of java since jdk1.3 and is called the Proxy.

Starring…coming to your nearest desktop…
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

What exactly are these? Proxy helps you by creating the implementing class alias proxy and InvocationHandler helps you with the inspection/introspection. Proxy needs a set of interfaces and InvocationHandler needs to be hand coded.

Some code snippets


public interface IAppLogger {

void logError(String txt);

void logInfo(String txt);

void logWarning(String txt);

}

public class GenericInvocationHandler implements InvocationHandler {


public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
StringBuilder sb = new StringBuilder();
sb.append(" Calling ---> ");
sb.append(method.getName());
sb.append("(");
sb.append(")");
System.out.println(sb.toString());
//donothing proxy
//return method.invoke(obj, args);
return null;
}

}

public class ProxyGen {

public Object createProxy(Class[] interfaces, InvocationHandler handler){
ClassLoader cl= ProxyGen.class.getClassLoader();
return Proxy.newProxyInstance(cl, interfaces , handler);
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
GenericInvocationHandler handler = new GenericInvocationHandler(new AppLogger());
ProxyGen factory = new ProxyGen();
ActionListener proxyObj2 = (ActionListener) factory.createProxy(new Class[]{IAppLogger.class, ActionListener.class}, handler);
proxyObj2.actionPerformed(null);
IAppLogger proxyObj = (IAppLogger) proxyObj2;
proxyObj.logError("abc");
proxyObj.logInfo("abc");
proxyObj.logWarning("abc");
}

}

As the whims of the butterfly go, in a flap of wing the requirements change. We now have a new technique under our belt.

I have seen a generic logging example on net as part of my learning, thank you Google, once again!

Thursday, November 6, 2008

Top 25 Geek Blogs

The title says it all.
http://cellphones.org/blog/news/top-25-geek-blogs

Thursday, October 30, 2008

HTML - Buttons as Links

UI designers pursue their job with the idea of getting a clean and pleasing finish. That is their job, however this single focus causes them to ignore the periphery. Accessability and Technical realisation take a back seat. A really good designer would provide a solution that is solvable and not some thing which is impossible.

What is an impossible design? Think of cramping a list of names into a horizontal row without any due consideration for 'screen estate', now if anyone does a Ctrl++ to increase the font size what would happen? It is impossible to support all resolutions, but most often the min and max constraints can be frozen, not having them defined causes even more confusion.

What is a solvable problem then! The unfortunate truth about web-dev is lack of standard environment. The browsers, CSS, java script all tend to vary. Removing backward compatibility is a sin, but that is the burden these age old browsers have to carry. The new kids on the block (Chrome), Good luck!.

Nuf of cribbing and coming to point, one of our teams was given this task of submitting forms using links. Now HTML supports form submissions on buttons and images alone! So what did they do, went ahead and used images. Not bad unless you think of resizing text. Like most puzzles which we face, I happened to run into this conversation and started twiddling with the source. Look where we are Maa.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
/* Works on Firefox2+ but not on IE6 :(*/
.link a>input{
background:none;
border:0;
border-bottom:1px blue solid;
padding:0;
height:1.2em;
cursor:pointer;
}

.link a>input:hover{
background:none;
border:0;
border-bottom:1px red solid;
padding:0;
height:1.2em;
cursor:pointer;
font-weight:600;
}


</style>
</head>

<body>
<div class="link"> <a> <input type="button" value="submit"/> </a> </div>
<div class="link"> <a> <input type="button" value="crap"/> </a> </div>
</body>
</html>

Wednesday, October 22, 2008

Stack Overflow

StackOveflow: A new preoccupation and time killer! Explains a slump in my blogging activities.

Nuf said, the real reason why I fell in love with SO cannot be explained, it has to be experienced. Have a look at this post (warning java script knowledge is mandatory)

Sunday, September 28, 2008

Religion for me 2

Now when I read about, people fighting eachother for their beliefs, I was surprised. Infact I was depressed. I feared some of my friends and neighbours would be hurt. So I started paying more attention to the differences. The differences were those I never cared for. They were the most superficial ones. I don't know why and how they became so important, so as usual started asking others. The answer, it was told so in the books.

As a student of logic, I found religion unexplicable. The most difficult thing to comprehend was the irrepressible quest to force ones own ideals on others. Then I found that the books actually force certains aspects on individuals. For me, Religion was no longer a way of life, it was a totalitarian structure with helped individuals intrepret things in many ways. It became a abhorence, more like a power structure or political structure. My knowledge of history didn't help here.

My angst was targeted towards the religious symbols. I started to interpret things in a different fashion. Religion was set out as a means of bringing social order to a society. When these isolated societies started to come in contact, they had to fend themselves and religion became a voice and power. God had nothing to do with it. God, wouldn't even care if people worshipped him or not. Religion says that God is the most powerful one and he saves the people. They don't give out compelling reasons why God would do so, what binds God to carry out the obligation and the consequences of not doing so. God wouldn't be hurt by things I do or don't do. Individuals are incapable of causing any harm, are do they? All they are capable of doing is hurt others.

Does God exists? I don't know, frankly I don't even care. I even wonder, what would the believers of respective religions do, if God himself tells them that they need to change their beliefs, they may call it a bluff/fraud and attack. So what do I want to do, I find some aspects of life appealing, like enjoying a nice laugh/conversation. Showing appreciation towards others and caring for others in my own capacity. I wouldnt' want this silly religion thing to interfere in any of these.

Religion for me

I grew up in a family which observed reverence to GOD. I remember the early days when my mom and dad used to take me to holy shrines and asked me to pray, they infact used to prompt me to ask for blessings!! My normal prayer was 'God, give me good conscience, help me with my studies, I will behave myself'. I am not going to spell out the religious order which my family belongs for it defies the purpose of this blog. When I grew up, I used to see people who never had any consideration to the ideals promoted by my family, I also saw people who went throught the strict regimen. As a kid, I once bychance went into a neighbour's house, they belonged to a different religious order, I saw the people over there uttering their prayers and I followed them with my own words - quoted above. I could see the lady of the house smiling in agreement.

One another time, I happened to step into the prayer room of a different neighbours. I used to enjoy the stories told by the elders and asked them if I could have the book of stories. They told me I couldn't and I wouldn't' understand the writing as well. I asked why? They told me it was the holy book and even they wouldn't touch it normally. I didn't feel bad as I remember my mom warning me with the books in our house. (Technically speaking, those were scriptures, but for a 11 year old they are all books!). The best part of all the religions was the festivals we used to have. We could jump of school and enjoy the sweets. My mother never objected! I even used to help our neighbours with the preperations. The same was the case in our school. I used to observe that some of our teachers/students used to take a special eatery. Once I joined the line just to try that. Later my friends asked me when we converted! I said no!! I just wanted to eat what you guys are having.

For me all the stories had the same moral, all my friends and their parents taught the same. Later when I found what others saw as reigion, I was in for a shock. Will continue rest in my next posting...

Popular Posts

Labels

About Me

Well for a start, I dont' want to!. Yes I am reclusive, no I am not secretive; Candid? Yes; Aspergers? No :). My friends call me an enthusiast, my boss calls me purist, I call myself an explorer, to summarise; just an inquisitive child who didnt'learn to take things for granted. For the sake of living, I work as a S/W engineer. If you dont' know what it means, turn back right now.