Friday, July 8, 2011

To Every Mother

This was written by one of my friends(Deepak chhabra). He wrote for his mother to gift her on Mother's Day. Sorry Deepak, I am copying your poem. I am dedicating this to for all mothers from their children.

It follows like below....


You were there when I first opened my eyes,
And also when I needed you to shun my cries.

You are the gift which every child gets,
You are the one who makes us learn the alphabets.

The first word which I spoke was you,
I pray to god that this love shall accrue.

I took my first step with your hand and your support,
And whenever I thought I can not do, you won’t let me abort.

Every time I had fallen, I have seen the pain you had,
I always looked into your eyes though I was surrounded by dad.

I have seen you sleeping on wet bed sheets, just to give me dry.
You taught me everything from why monkeys jump and why birds fly.

You can hear my cry from millions of miles away,
I remember all your kisses, as if it was yesterday.

When I started walking, I always made you run,
Without your company all those homeworks would not have been fun.

You packed my lunch box, combed my hair and filled my water bottle.
You were the one who made even the worse class of school days gentle.

When I come home with dirty clothes and bruises all over,
I got hugs, kisses, chocolates and you will eat the food leftover.

No one liked my silly jokes but you always laughed,
There is only string by which my injury and your pain are attached.

When my days were dull and evenings were boring,
You gave me the love, the affection and made me feel like a king.

You have witnessed me growing inch by inch.
Every time I had fallen, you were the one who got the pinch.

With your nutrition I grew tall like a bamboo,
And that brought all the happiness in the world to you.

My board exams came and you burned the midnight’s oil with me,
I did mistakes, Dad shouted at me but you handled the situation aptly.


Amidst the love, the time came when I left the city for my education,
You cried in the bath room and told me “go ahead my champion”.

It was tough for me to adjust in the new city without your presence.
You gave me all the support and told me that good days will shortly commence.

Each visit from my college to home would give me some extra pound,
I was hard to say you goodbye but I knew that you were always around.

Soon I graduated from the college with a job,
You were the happiest person in the earth and told me never to snob.

Years have passed after that and I am still away,
But your love for me is long like an infinite array.

I owe you so much that even the nine planets are less,
For your love was always in excess.

When I asked for a drop you gave me the sea.
But never expected anything in return from me,

These few words cannot describe what I fell for you,
Maa, because you know how much I love you.






















Friday, November 19, 2010

How smartphone users view each other !



Please check with Manuals. Author is NOT responsible for any misinformation / incorrect information or typographical errors. NOTE: If you would like to share any useful info, please mail to the authors.

Monday, October 26, 2009

Indian Scientists Develop a New Variety of Rice



After tremendous amount of research, Indian scientists claim to have developed a rice variety that requires no cooking; only soaking in water.

The rice variety developed at the government-run Central Rice Research Institute (CRRI) at Cuttack in Orissa is characterised by low amylase content and becomes soft on soaking in water.

Indian Production of rice is massive considering the last year’s figure of 98.5 million tones. The new variety of rice can serve specific niche consumers and make rice cooking a hassle free affair.

The new variety, named Aghanibora, tested by the institute is of 145 days duration with a yield of 4-4.5 tonnes per hectare and is at par with the currently grown rice varieties in the country. It is like any other rice variety grown and consumed in India.

The initial experimentation was to test whether the rice variety could be grown in the hot and humid climate of Orissa and still retain the property of softness.

Scientists at the institute have done extensive research over the past three years and tested its nutritional properties and other biochemical parameters. The experiment has proved successful and can be grown more in the eastern states of India

Do you think such a experimentation in Agricultural sector would increase the number of exports and thereby help the Indian economy?

Tuesday, June 30, 2009

Logging framework: Log4j

Log4j is an essential logging framework for Java. It helps you debug your application (with minimal impact on performance) by means of logging statements inserted in specific points of your code. Logging can be configured or even turned off at runtime via method calls or with a configuration file, all without changing the application binary.
Logging equips the developer with detailed context for application failures, thus it gets easier to correct them.


You can download the current version of log4j from the project home page.
http://logging.apache.org/log4j/
Make sure that you use use md5sum to check that the downloaded file is not hacked.
In a linux console you can type the following and compare the number to that from the home page:
md5sum logging-log4j-1.2.14.zip
There are md5sum tools for windows as well. For Firefox you can install the md hash tool extension and check directly from the download windows.
First example

log4j.properties example

Create a Java project.
Add the log4j.jar to the build path of the project.
Create a file named log4j.properties in the src folder with the following content.
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout
Create a class with the following content:
package de.laliluna.logexample;
import org.apache.log4j.Logger;

public class LogClass {
private static org.apache.log4j.Logger log = Logger
.getLogger(LogClass.class);

public static void main(String[] args) {

log.trace("Trace");
log.debug("Debug");
log.info("Info");
log.warn("Warn");
log.error("Error");
log.fatal("Fatal");

}
}
Run it. You should see the log messages in the console.
08:50:49,661 DEBUG LogClass:29 - Debug
08:50:49,663 INFO LogClass:30 - Info
08:50:49,663 WARN LogClass:31 - Warn
08:50:49,663 ERROR LogClass:32 - Error
08:50:49,664 FATAL LogClass:33 - Fatal
Change the line
log4j.rootLogger=debug, stdout
to
log4j.rootLogger=warn, stdout
and run your java application again.
What did we learn?
Log4j does look for a file named log4j.properties in the src folder.
We get a Logger by calling Logger.getLogger
Do not use Category.getCategory to get a logger. This is deprecated.
You can influence what is logged by setting the log level.
How to log messages with the following levels: trace, debug, info, warn, error and fatal
log4j.xml example

log4j.xml example


Create
a file named log4j.xml with the following content in your src folder:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/>
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>

Copy the log4j.dtd into the source folder as well. You can find it in the download of log4j. The XML requires a dom4j.jar which might not be included in older Java versions. You do not need it with Java 5
You can test your configuration the same way as the former example.
Log level

The following Levels are available. But you can define custom levels as well. Examples are provided with the log4j download.
Level
Description
all
All levels including custom levels
trace
developing only, can be used to follow the program execution.
debug
developing only, for debugging purpose
info
Production optionally, Course grained (rarely written informations), I use it to print that a configuration is initialized, a long running import job is starting and ending.
warn



Production, simple application error or unexpected behaviour. Application can continue. I warn for example in case of bad login attemps, unexpected data during import jobs.
error
Production, application error/exception but application can continue. Part of the application is probably not working.
fatal
Production, fatal application error, application cannot continue, for example database is down.
no
Do not log at all.
Log4j configuration

Layout of the log file

The layout specifies how a log message looks like.
First you define the layout.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
The pattern layout requires another parameter, i.e. the pattern.
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
The best up-to-date documentation about available layouts can be found in the API documentation:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/Layout.html
There you can see that we have DateLayout, HTMLLayout, PatternLayout, SimpleLayout, XMLLayout as options.
SimpleLayout has no properties to be set. It is simple.
We used PatternLayout in our example and we set a property named ConversionPattern. This property allows us to define the log output.
%d{ABSOLUTE}
Date in Format Absolute
%5p
%5 defines a right justified print with 5 characters, p prints the priority of the log message
%c{1}:%L - %m%n
And the other settings. Very simple. They are all explained in the API.

The options to influence the layout are explained perfectly in the API documentation:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
Custom Layout

If the configuration options does not suite your needs, you can define custom layouts as well. Examples for custom layout are provided with the log4j download. Have a look in the examples directory.
Types of log appender

An appender specifies where your log messages are written to. There is a wide choice of appenders available. All appenders are direct or indirect subclasses of the AppenderSkeleton. Therefore we can find all options on the following API page:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/AppenderSkeleton.html
The console and the file appender are a subclass of WriterAppender.
Later on, we are going to choose examples for the following appenders.
ConsoleAppender
Logs to console
FileAppender
Logs to a file
SMTPAppender
Logs by email
RollingFileAppender Logs to a file, starts a new file once the max size is reached. (An alternative is the DailyRollingFileAppender which creates on file per day)
But there are as well:
AsyncAppender, JDBCAppender, JMSAppender, LF5Appender, NTEventLogAppender, NullAppender, NullAppender, SMTPAppender, SocketAppender, SocketHubAppender, SyslogAppender, TelnetAppender, DailyRollingFileAppender, RollingFileAppender.
Custom appenders can be created as well. The log4j download comes with a whole bunch of samples in the examples directory.
log4j.xml versus log4j.properties

Properties can be defined by a properties file or by an XML file. Log4j looks for a file named log4j.xml and then for a file named log4j.properties. Both must be placed in the src folder.
The property file is less verbose than an XML file. The XML requires the log4j.dtd to be placed in the source folder as well. The XML requires a dom4j.jar which might not be included in older Java versions.
The properties file does not support some advanced configuration options like Filters, custom ErrorHandlers and a special type of appenders, i.e. AsyncAppender. ErrorHandlers defines how errors in log4j itself are handled, for example badly configured appenders. Filters are more interesting. From the available filters, I think that the level range filter is really missing for property files.
This filter allows to define that a appender should receive log messages from Level INFO to WARN. This allows to split log messages across different logfiles. One for DEBUGGING messages, another for warnings, ...
The property appender only supports a minimum level. If you set it do INFO, you will receive WARN, ERROR and FATAL messages as well.
Here are two logfiles examples for a simple configuration:
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.rootLogger=debug, stdout
and











<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.SimpleLayout"></layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>

5.5 Loading the configuration

Log4j will first check for a file log4j.xml and then for a log4j.properties file in the root directory of the classes folder (= src folder before compilation).
You can load other configurations as well. Here are some examples:
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.Loader;
import org.apache.log4j.xml.DOMConfigurator;

............. snip ...........

// use the loader helper from log4j
URL url = Loader.getResource("my.properties");
PropertyConfigurator.configure(url);

// use the same class loader as your class
URL url = LogClass.class.getResource("/my.properties");
PropertyConfigurator.configure(url);

// load custom XML configuration
URL url = Loader.getResource("my.xml");
DOMConfigurator.configure(url);
In a web application you might configure a servlet to be loaded on startup to initialize your configuration.
Keep in mind that this is not required, if you use the default names and folders for the configuration file.
Reconfigure a running log4j configuration

If you analyse a problem you frequently want to change the log level of a running application server. This chapter explains how you can do this. I used Tomcat as example server but you can use any application server you like.
The XML actually offers a method to watch changes in config files.
http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/DOMConfigurator.html#configureAndWatch(java.lang.String)
The problem is that it seems not to work in some situations. But this is no problem as it is quite easy to develop a short tool by yourself. We have two options. We could change the log level during runtime:
Logger root = Logger.getRootLogger();
root.setLevel(Level.WARN);
or we can reload the configuration:
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);
The following example will check the configuration file in defined intervals and reconfigure log4j if any changes are found.
We need to create three things:
a) a monitor thread, monitoring the configuration file and reconfiguring log4j if needed
b) a servlet starting and stopping the monitor thread
c) an entry in the web.xml, to initialize the servlet
The following class monitors the logj4 configuration file and checks with the last change date has changed:
package de.laliluna.logexample;

import java.io.File;
import java.net.URL;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class MonitorThread implements Runnable {

private static Logger log = Logger.getLogger(MonitorThread.class);

boolean interruped;

private long checkIntervalMillis = 10000;

private URL url;

private File file;

// stores the last modification time of the file
private long lastModified = 0;

public void run() {
System.out.println("Initialize " + url.getPath());
file = new File(url.getPath());
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);
lastModified = file.lastModified();

monitor();
}

private void monitor() {
log.info("Starting log4j monitor");

while (!interruped) {

// check if File changed
long temp = file.lastModified();
if (lastModified != temp) {
log.info("Initialize log4j configuration " + url.getPath());
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);

lastModified = temp;

} else
log.debug("Log4j configuration is not modified");
try {
Thread.currentThread().sleep(checkIntervalMillis);
} catch (InterruptedException e) {
interruped = true;
}
}
log.info("Shutting down log4j monitor");

}

public URL getUrl() {
return url;
}

public void setUrl(URL url) {
this.url = url;
}

public long getCheckIntervalMillis() {
return checkIntervalMillis;
}

/**
* Sets the interval for checking the url for changes. Unit is
* milliseconds, 10000 = 10 seconds
*
* @param checkIntervalMillis
*/
public void setCheckIntervalMillis(long checkIntervalMillis) {
this.checkIntervalMillis = checkIntervalMillis;
}

public boolean isInterruped() {
return interruped;
}

public void setInterruped(boolean interruped) {
this.interruped = interruped;
}

}
The servlet starts and stops the monitor thread:
package de.laliluna.logexample;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class Log4jConfigLoader extends HttpServlet {

private Thread thread;

@Override
public void destroy() {
thread.interrupt();
super.destroy();
}

public void init() throws ServletException {
super.init();
MonitorThread monitorThread = new MonitorThread();
monitorThread.setCheckIntervalMillis(10000);
monitorThread.setUrl(Log4jConfigLoader.class.getResource("/log4j.xml"));
thread = new Thread(monitorThread);
thread.start();
}

}
We add the servlet to the web.xml to initialize it.



log4j-init
de.laliluna.logexample.Log4jConfigLoader
10



Examples


Rolling File and errors to email


Log
messages with Level info to fatal to a file and send messages from
error to fatal by email. The file should be rolled every 100 KB.


You
need mail.jar and activation.jar libraries from J2EE to send emails.
Further properties of the SmtpAppender are described here:


http://logging.apache.org/log4j/docs/api/org/apache/log4j/net/SMTPAppender.html



log4j.properties


### file appender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=100KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=test.log
log4j.appender.file.threshold=info
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

#email appender
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#defines how othen emails are send
log4j.appender.mail.BufferSize=1
log4j.appender.mail.SMTPHost="smtp.myservername.xx"
log4j.appender.mail.From=fromemail@myservername.xx
log4j.appender.mail.To=toemail@myservername.xx
log4j.appender.mail.Subject=Log ...
log4j.appender.mail.threshold=error
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=warn, file, mail


log4j.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="file"
class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="5" />
<param name="File" value="test.log" />
<param name="threshold" value="info"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
</appender>
<appender name="mail" class="org.apache.log4j.net.SMTPAppender">
<param name="SMTPHost" value="smtp.myservername.xx" />
<param name="From" value="email@fromemail.xx" />
<param name="To" value="toemail@toemail.xx" />
<param name="Subject" value="[LOG] ..." />
<param name="BufferSize" value="1" />
<param name="threshold" value="error" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
<appender-ref ref="mail"/>
</root>
</log4j:configuration>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
<appender-ref ref="mail"/>
</root>
</log4j:configuration>


Separate file


I
want to have debugging messages to one file and other messages to
another file. This can only be done with XML because we need a
LevelRange filter.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="file"
class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="5" />
<param name="File" value="test.log" />
<param name="threshold" value="info" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
</appender>
<appender name="debugfile"
class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="5" />
<param name="File" value="debug.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="debug" />
<param name="LevelMax" value="debug" />
</filter>
</appender>

<root>
<priority value="debug"></priority>
<appender-ref ref="debugfile" />
<appender-ref ref="file" />
</root>
</log4j:configuration>

Other examples

The log4j download provides further examples as well.
Log4j and Tomcat

The configuration of log4j in tomcat is well described in the Tomcat documentation:
http://tomcat.apache.org/tomcat-5.5-doc/logging.html
Libraries are placed in common library directory. The configuration file for Tomcat is in common/classes directory, the configuration file for a application is placed in the WEB-INF/classes folder of the application.
If you do not want Tomcat to use log4j to log but only your application, you can place log4j in the WEB-INF-lib directory of your application as well.
Best practices for exception logging

I present some basic tips here. Further information can be found here:
http://today.java.net/lpt/a/280#throwingException
http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html
Do not use e.printStackTrace

e.printStackTrace prints to the console. You will only see this messages, if you have defined a console appender. If you use Tomcat or other application server with a service wrapper and define a console appender, you will blow up your wrapper.log.
try {
......... snip .......
} catch ( SomeException e) {
e.printStackTrace();
}
You can use log.error(e,e). The second parameter passed an exception and will print the stack trace into the logfile.
try {
......... snip .......
} catch (SomeException e) {
log.error("Exception Message", e);
// display error message to customer
}
Don't log and throw again

try {
......... snip .......
} catch ( SomeException e) {
log.error("Exception Message", e);
throw e;
}
Do not catch an exception, log the stacktrace and then continue to throw it. If higher levels log a message as well, you will end up with a stacktrace printed 2 or more times into the log files.
Don't kill the stacktrace

try{
... some code
}catch(SQLException e){
throw new RuntimeException(?DB excpetion? +e.getMessage());
}
This code will erase the stacktrace from the SQLException. This is not recommended, because you will loose important information about the exception. Better do the following.
try{
... some code
}catch(SQLException e){
throw new RuntimeException("My Exception name", e);
}
That's all for this tutorial.

O/R persistence: Hibernate

Hibernate is a solution for object relational mapping and a persistence management solution or persistent layer. This is probably not understandable for anybody learning Hibernate.


What you can imagine is probably that you have your application with some functions (business logic) and you want to save data in a database. When you use Java all the business logic normally works with objects of different class types. Your database tables are not at all objects.


Hibernate provides a solution to map database tables to a class. It copies one row of the database data to a class. In the other direction it supports to save objects to the database. In this process the object is transformed to one or more tables.











Saving data to a storage is called persistence. And the copying of tables to objects and vice versa is called object relational mapping.

Create a Java Project

Using Eclipse press the keys Ctrl+n (Strg+n) to create a new project. Select a Java project. We will call it FirstHibernateExample.

Prepare the project for Hibernate using MyEclipse

When you are using MyEclipse, right click on your project in the package explorer and choose Add Hibernate capabilities.




Continue the wizard and create a new hibernate.cfg.xml in the src directory.

In the last step you can create a Hibernate SessionFactory. I prefer to create my own. You can find it below.

Prepare the project for Hibernate for anybody

If you do not use MyEclipse, you can use the ant build to retrieve the libs using Ivy or alternatively just download Hibernate from the website http://www.hibernate.org/

You will need at least Hibernate Core. If you want to use Annotations you need Hibernate Annotations and if you want to use Hibernate Search, you need to download Hibernate Search as well.

Extract the file. Hibernate comes with a long list of libraries. You do not need all of them. There is a REAME file in the lib directory explaining what is required. Open your project properties, select “Java Build Path”, click on “Add External Jars” and add the libaries shown below to your project path.

The following list includes the libraries to use Hibernate with XML or annotations, EHCache, PostgreSQL and logging over log4j.

  • antlr.jar

  • backport-util-concurrent.jar

  • hibernate-commons-annotations.jar

  • hibernate-annotations.jar

  • postgresql.jar

  • hibernate-ehcache.jar

  • log4j.jar

  • ejb3-persistence.jar

  • slf4j-log4j12.jar

  • slf4j-api.jar

  • javassist.jar

  • commons-collections.jar

  • dom4j.jar

  • lucene-core.jar

  • commons-logging.jar

  • hibernate-search.jar

  • jta.jar

  • hibernate-core.jar

  • ehcache.jar

  • xml-apis.jar


Create a SessionFactory

A session factory is important for Hibernate. It implements a design pattern, that ensures that only one instance of the session is used per thread. You should only get your Hibernate session from this factory.


Create a class named InitSessionFactory in the package de.laliluna.hibernate and add the source code below.

/**
*
* @author Sebastian Hennebrueder
* created Feb 22, 2006
* copyright 2006 by http://www.laliluna.de
*/
package de.laliluna.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
* @author hennebrueder This class garanties that only one single SessionFactory
* is instanciated and that the configuration is done thread safe as
* singleton. Actually it only wraps the Hibernate SessionFactory.
* You are free to use any kind of JTA or Thread transactionFactories.
*/
public class SessionFactoryUtil {

/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;

/**
* disable contructor to guaranty a single instance
*/
private SessionFactoryUtil() {
}

static{
// Annotation and XML
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
// XML only
// sessionFactory = new Configuration().configure().buildSessionFactory();
}

public static SessionFactory getInstance() {
return sessionFactory;
}

/**
* Opens a session and will not bind it to a session context
* @return the session
*/
public Session openSession() {
return sessionFactory.openSession();
}

/**
* Returns a session from the session context. If there is no session in the context it opens a session,
* stores it in the context and returns it.
* This factory is intended to be used with a hibernate.cfg.xml
* including the following property * name="current_session_context_class">thread This would return
* the current open session or if this does not exist, will create a new
* session
*
* @return the session
*/
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}

/**
* closes the session factory
*/
public static void close(){
if (sessionFactory != null)
sessionFactory.close();
sessionFactory = null;

}
}


Configuring Log4J

As you can see above we added the log4j library. This library does like a configuration file in the source directory or it welcomes you with the following error.

log4j:WARN No appenders could be found for logger (TestClient).
log4j:WARN Please initialize the log4j system properly.

Create a file named log4j.properties in the root directory and insert the following:

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout

log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=info

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
log4j.logger.org.hibernate.cache=info

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

Add the database driver

Even Hibernate needs a database driver to access a database. Open the project properties, click on “Java Build Path”, select “Add External Jars” and add your database driver. If you use PostgreSQL you can find your database driver on http://jdbc.postgresql.org if you use MySQL have a look here http://www.mysql.de/products/connector/j

Create database and tables.

Create a database with MySql or PostgreSQL or anything you like. Call it “firsthibernate”.

Using PostgreSql use the following script to create your table:

CREATE TABLE "public"."honey" (
id SERIAL,
name text,
taste text,
PRIMARY KEY(id)
);


Using MySql use the following script:

CREATE TABLE `honey` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(250) default NULL,
`taste` varchar(250) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Create the class

Create a new class named “Honey” in the package “de.laliluna.example”. Add three fields id, name and taste and generate (Context menu -> Source -> Generate Getter and Setter) or type the getters and setters for the fields. Then create an empty constructor.

package de.laliluna.example;

public class Honey {
private Integer id;
private String name;
private String taste;

public Honey(){

}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTaste() {
return taste;
}

public void setTaste(String taste) {
this.taste = taste;
}

public String toString() {
return "Honey: "+getId()+" Name: "+getName()+" Taste: "+getTaste();
}
}



Create the Hibernate configuration

Create a new file named “hibernate.cfg.xml” in your root directory if it is not already created.

Insert the following in your hibernate file. Do not forget to change the username and the password to suit your database configuration.

PostgreSQL
Version:


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost/firsthibernate</property>
<property name="connection.username">postgres</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.password">p</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- thread is the short name for
org.hibernate.context.ThreadLocalSessionContext
and let Hibernate bind the session automatically to the thread
-->
<property name="current_session_context_class">thread</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="de/laliluna/example/Honey.hbm.xml" />
</session-factory>
</hibernate-configuration>





MySQL
Version:





<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost/firsthibernate</property>
<property name="connection.username">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.password">r</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- thread is the short name for
org.hibernate.context.ThreadLocalSessionContext
and let Hibernate bind the session automatically to the thread
-->
<property name="current_session_context_class">thread</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>

<!-- mapping files -->
<mapping resource="de/laliluna/example/Honey.hbm.xml" />

</session-factory>
</hibernate-configuration>





This
file includes the configuration of the database in our case a
PostgreSQL database and all mapping files. In our case it is only the
file Honey.hbm.xml. The tag


<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>


configures the
dialect. Change this to fit your database. Have a look in the chapter
“SQL Dialects” of the Hibernate reference to find the dialect for
your database.


XML Mapping


You can use XML or annotations to define, how to
map your class attributes to a database table.


Create
the Honey.hbm.xml in the package de.laliluna.example and change it
to the following:





PostgreSQL
Version:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="de.laliluna.example.Honey" table="honey">
<id name="id" column="id" >
<generator class="sequence">
<param name="sequence">honey_id_seq</param>
</generator>

</id>

<property name="name" column="fooname" />
<property name="taste" column="bartaste" />
</class>
</hibernate-mapping>





MySQL
Version:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="de.laliluna.example.Honey" table="honey">
<id name="id" column="id" >
<generator class="increment"/>
</id>
<property name="name" column="fooname" />
<property name="taste" column="bartaste" />
</class>
</hibernate-mapping>




In this file the mapping from our class Honey to the database table honey is configured.

Annotation based mapping

If you use annotation, you can define the mapping in the class.

package de.laliluna.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;

@Entity
public class Honey {

@Id
@GeneratedValue
private Integer id;

private String name;

private String taste;
// ......... snip .........

Create a Test Client

Create a Java Class “TestClient” in the package “de.laliluna.example”.


Add the following source code. It includes methods to create entries in the database, to update and to list them.


package de.laliluna.example;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.laliluna.hibernate.SessionFactoryUtil;

public class TestExample {

final static Logger logger = LoggerFactory.getLogger(TestExample.class);

/**
* @param args
*/
public static void main(String[] args) {
Honey forestHoney = new Honey();
forestHoney.setName("forest honey");
forestHoney.setTaste("very sweet");
Honey countryHoney = new Honey();
countryHoney.setName("country honey");
countryHoney.setTaste("tasty");
createHoney(forestHoney);
createHoney(countryHoney);
// our instances have a primary key now:
logger.debug("{}", forestHoney);
logger.debug("{}", countryHoney);
listHoney();
deleteHoney(countryHoney);
listHoney();
forestHoney.setName("Norther Forest Honey");
updateHoney(forestHoney);

}

private static void listHoney() {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
List honeys = session.createQuery("select h from Honey as h")
.list();
for (Iterator iter = honeys.iterator(); iter.hasNext();) {
Honey element = (Honey) iter.next();
logger.debug("{}", element);
}
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
logger.debug("Error rolling back transaction");
}
// throw again the first exception
throw e;
}


}
}

private static void deleteHoney(Honey honey) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.delete(honey);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
logger.debug("Error rolling back transaction");
}
// throw again the first exception
throw e;
}
}
}

private static void createHoney(Honey honey) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.save(honey);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
logger.debug("Error rolling back transaction");
}
// throw again the first exception
throw e;
}
}
}

private static void updateHoney(Honey honey) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.update(honey);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
logger.debug("Error rolling back transaction");
}
// throw again the first exception
throw e;
}
}
}
}


Congratulations. You have finished your first steps in the Hibernate world.

How To Break a Weight Loss Plateau


No matter how efficient your diet & workout plan, you are bound to face a weight-loss plateau at one point or another. But this does not mean your weight-loss trend has ended, it just means that you need to revise your tactics and fitness routine to overcome the plateau and march ahead! Plateaus are common to anybody who's been on the same diet and exercise plan for a while, which is the reason why you don't see the same results you saw at the beginning. But its not as scary or difficult to break a weight-loss plateau. I've done it myself, and I hope my ideas help you achieve similar results too!

If you've been eating right and exercising often, you've probably been losing weight at a rate of one or two pounds a week. However, as you get closer to your optimum weight, it usually gets harder to lose those last few pounds. You know you've hit a weight-loss plateau when more than two weeks have gone by without any further change in your weight, while you still follow the same regimen! So the first thing you do is review your exercise and diet program, find out what's wrong and make amendments. Here are a few helpful tips to get you started!

Calorie Intake & Diet Plan
As you probably know by now, weight loss is all about burning more calories than you consume. A healthy diet plan is the key, so take a quick look at your food diary, or calorie intake.

Are you still keeping track of your portion sizes, even when you are dining out?
Are you spacing your meals 5 times a day, dividing daily calories between them?
have you recently sneaked in a few desserts or carbs thinking a piece won't hurt much?
Did you switch to sodas instead of smoothies and juices?
Are you drinking enough water?

It's easy to increase your calorie intake accidentally, without realizing how its hurting your diet plan. Remember, a baked potato is not the same as a baked potato with gravy and butter! So evaluate your calorie consumption; maintain a diet hhournal if you like; if you are well above the 1200(for women) or 1500 (for men) daily intake level, you can try cutting down a couple hundred calories to break the plateau. However, if you are consuming less than 1,200 calories a day (1,500 for a man), your body may react by slowing down as a self-preservation measure. This means your metabolism rate falls, and you actually store fat even if you're working out consistently.

Eat 5-6 Times a Day
Eating frequently stabilizes your blood sugar, controls appetite, and keeps your energy up. Ideally, you shouldn't go more than three or four hours without eating something. Doing so slows down your metabolism and makes your body burn fat at a slower rate. Its also very important to eat as soon as you feel hungry - a feeling of hunger indicates your blood sugar is going down, which makes you prone to craving simple sugars. If you're eating three times a day, eat five. If you're already eating five times, upgrade to six or seven. This doesn't necessarily mean you'll be eating more food; just divide your calories into 6 meals per day.

Change Your Workout Routine
"Variety is the spice of life" - and this phrase has never been so fitting to a scenario! It takes your body only four weeks to get used to a workout. Once something becomes a routine for your metabolism, plateaus are likely. The most efficient way to break a plateau is to shake up your fitness routine. Join an online weight loss program to find tips and ideas. If you are used to 30 mins on the treadmill, switch to cycling or kick-boxing instead. Instead of the stationary bike, switch to a Stepper or a StairMaster. Instead of running in the morning, try playing tennis or do some swimming. Use Interval Training to your advantage; short bursts (30-60 sec)of higher-intensity movement, such as sprint, followed by 2-3 mins of less intense exercise like walking. Adding variety to your routine brings revs up your metabolism as the body has to start adapting again.

Add More Strength Training
If you are not doing so already, start lifting weights now to boost your metabolism and burn fat! When you lift weights, your muscle fibers suffer tiny tears which causes you to experience soreness for a couple days; but that's normal. Changing the intensity of the workout helps a lot. Try to increase the amount of weights you lift, or try changing the number of repetitions. Whenever you change a workout routine your body responds by burning fat. Do not under-estimate the power of strength-training; in fact, lifting weights is the best way to conquer that plateau! Challenge your muscles with harder exercises or heavier weights (every 6 to 8 weeks), adding a set of risers during your step class, increasing the incline on the treadmill, the duration of your run/walk, etc… It might seem tough at first as your newly challenged muscles will have to work harder but you will burn more calories and build more lean muscle mass in the process. its always a good idea to do a combination of resistance machines and free-weights, as the latter can increase metabolic rate as high as 10% in one session!

Avoid Alc0hol & Drink Water
Thirst is often mistaken for hunger. Every time you feel the urge to snack, drink a glass of water first and see if the urge goes away. Coffee, tea or any other juices count as liquids, but add an extra glass of pure water for each cup of coffee you drink, as caffeine tends to dehydrate the body. Research has shown that BMR increase by 30%, not to mention flushing out all toxins from your body, thereby contributing to a healthy weight-loss. As for Alcohol, it is a known fact that it contains a large amount of calories, but hardly any other nutrients, and some of these are also high in sugars and fat. Alc0hol consumption slows down the fat burning capabilities of the body, as the body focuses on using the alcohol (a toxin) as fuel, rather than burning fat for energy. Alc0hol also dehydrates, which in turn, makes you hungry. So avoid Alc0hol, and start drinking more Water instead!

Losing weight requires exercise or controlled caloric intake . While its important to maintain a healthy weight, do not get obsessed by it! And plateaus in weight loss are very common; it only means you've successfully lost a lot of weight, and now you need to re-evaluate your regimen to overcome the weight-loss plateaus. Just follow the simple steps above, and you'll be ready to drop a couple more sizes the next time you buy yourself a new dress!

Weight Loss Just By Drinking Water


Make A Successful Weight Loss Just By Drinking Water - Maybe The Easiest Weight Loss Method
Well, you may have heard it before - you can lose weight just by drinking pure plain water. Do you think it is like that? Yes, it is, you can lose weight just by drinking water. I will explain why it is so.
There are studies that show that just by drinking water your metabolism will increase with up to 30 percentages. That is quite impressive, isn't it? To make your weight loss possible you need to drink eight glasses of water every day, and if you have lots of overweight you need to drink a few glasses more. If you live in a warm climate or if you exercise very intensive you need to drink more than the eight glasses. You maybe think that eight glasses is much water to drink, but you shouldn't drink it at the same time; instead you need to spread it out throughout the day.

Drinking water is not only great for your weight loss. Just by drinking lots of water you will look better because and your skin will become more glowing. Your muscles will work more effective when you exercise which will lead to a better shaped body.
A few tips about how you should act when you decide to lose weight just by drinking water:
  • Start every morning with a glass of water.
  • Drink a glass of water before every meal.
  • Drink lukewarm water, it may be easier to drink lots of water when it isn't cold.
  • Add a slice of lemon if you don't like the taste of the water.
  • Avoid drinking just before you go to bed.

Drinking water is a cheap and very effective way to lose weight, but often you need to add some diet and exercise to make your weight loss effective.