Spring Basics

Framework:
A framework is a collection of components that can used to build well organized applications.

Spring Framework:
Spring is a framework, because it provides components to build common parts of applications, such as data access support, MVC support, and many others.

The core of the Spring Framework is based on the principle of Inversion of Control (IoC). Applications that follow the IoC principle use configuration that describes the dependencies between its components. It is then up to the IoC framework to satisfy the configured dependencies. The “inversion” means that the application does not control its structure; it is up to the IoC framework to do that.

IoC:
IoC provides services through which a component can access its dependencies and services for interacting with the dependencies throughout their lives. In general, IoC can be decomposed into two subtypes: DI and dependency lookup

DI:
Dependency Injection (DI) in computer programming refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.
Three types
1. interface injection
2. setter injection
3. constructor injection

Dependency Lookup:
It’s the reverse process of DI where a component must acquire a reference to a dependency, whereas with DI, the dependencies are literally injected into the component by the IoC container
two types are
1. Dependency pull
2. Contextualized dependency lookup (CDL

AOP:
Aspect-oriented programming (AOP) is one of the technologies of the moment in the programming space. AOP lets us to implement crosscutting logic—that is, logic that applies to many parts of your application—in a single place, and then have that logic automatically applied right across the application

there are two types of AOP

1. Static AOP, such as AspectJ.
2. Dynamic AOP, such as that in Spring, allows crosscutting logic to be applied arbitrarily to any other code at runtime


Swing application for Windows CE and CrE-ME

This is same as Writing Applet Application. The Only thing we need to the followings

Step1:
Take the javax.swing package from http://www.nsicom.com/Default.aspx?tabid=295.

You will get a CAB file, put it on the PDA device and click on it to install. It will fire a dialog box. Select the root folder of the CrE-ME.

Step2:
The write a sample Swing program:

Bellow program also shows how to set a user defined icon left most of the Title bar.

import javax.swing.*;
import java.awt.*;

public class Sample
{

public static void main(String[] args)
{

JFrame frame = new JFrame("Setting an Icon for a frame");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("icon_confused.gif"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}

NB: keep your image icon in the same package where the program is.

Finally produce the jar file and keep it in the PDA and run it.

Java in Windows CE with CrE-ME

Developing CDC application with CrE-ME VM’s:
Recently I just worked with PDA devices and got to develop an application for that PDA which holding Windows CE Operating System. Let us know all that steps to be followed for this circumstance.

NB: For CDC devices there are two JV’s are well known which requires license to work. Both are

  • IBM J9
  • CrE-ME
CrE-ME can be used for a month of trial. IBM J9 does not give trial any more but earlier it used to.

Step 1:
Download Microsoft Active Sync from the bellow link, You may need to sign in to your MSN id to download

http://www.microsoft.com/windowsmobile/en-us/help/synchronize/activesync45.mspx

Step 2:
Install the Active Sync then connect the PDA and try to access the PDA device.

Step 3:
Download JVM CrE-ME 4.12 and CrEme 3.29 from http://nsicom.com/, free evaluation. And install both with having PDA connected to the PC . U will get confirmation in the PDA while installed

Step4:
Write your Applet and produce the .jar of it.
Here is my sample program

//MainTest.java
import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;


public class MainTest extends Frame implements ComponentListener
{

private Label StepLabel ;

private MenuBar mbar;

private Menu menu;
private MenuItem mitem, msolve;

AboutGSL about;
NewForm newForm;


public void init ()
{

setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());

setLayout (null);

about=new AboutGSL();
newForm=new NewForm();

mbar = new MenuBar();
menu = new Menu("File");
mbar.add(menu);

mitem = new MenuItem("New");

menu.add(mitem);

mitem = new MenuItem("Update");

menu.add(mitem);

msolve = new MenuItem("Delete");

menu.add(msolve);
mitem = new MenuItem("Exit");
menu.add(mitem);
menu = new Menu("Help");

mbar.setHelpMenu(menu);

mitem = new MenuItem("About");
menu.add(mitem);
setMenuBar(mbar);

show();

start();

}


public void start () {}

public void stop () {}

public MainTest (String s) { super(s);
}


public synchronized boolean handleEvent (Event event)
{

if (event.id == Event.ACTION_EVENT)
{

if ("About".equals (event.arg))

about.setVisible(true);
if ("New".equals (event.arg))

newForm.setVisible(true);
if ("Exit".equals (event.arg))

System.exit(0);
else{
}
}

else if (event.id == WindowEvent.WINDOW_CLOSING)

System.exit(0);

return true ;
}

public void componentResized(java.awt.event.ComponentEvent e)
{

if (e instanceof java.awt.event.WindowEvent)
{

setVisible(false);

stop();

init();
}

}

public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}

public void componentHidden(ComponentEvent e) {}


public static void main(String args[]) {

MainTest app = new MainTest(" GSL Sample Application");
app.init();
app.addComponentListener(app);
}

}

//
NewForm.java
import java.awt.*;
import java.awt.event.*;

class NewForm extends Frame
{

Button save=new Button(" Save ");

Button OK = new Button (" Close ") ;

Label nameL = new Label ("Enter Name",Label.LEFT) ;

TextField nameT = new TextField (30) ;

Label fnameL = new Label ("\nEnter Father Name",Label.LEFT) ;
TextField fnameT = new TextField (30) ;
Label addL = new Label ("Enter Address") ;

TextField addT = new TextField (30) ;

Label contactL = new Label ("Enter Contact Number") ;

TextField contactT = new TextField (30) ;


public NewForm ()
{

super ("About Grameen Solutions") ;

setSize (Toolkit.getDefaultToolkit().getScreenSize().width/2, Toolkit.getDefaultToolkit().getScreenSize().height /2) ;
setResizable (false) ;

setLayout (new FlowLayout ()) ;

add(nameL);

add(nameT);

add(save);

add (OK) ;

}


public synchronized boolean handleEvent (Event event)
{

System.out.println( event);

if (event.id != Event.ACTION_EVENT)
{

if (event.id == WindowEvent.WINDOW_CLOSING)
{

dispose ();
return true;

}
else
return false ;
}

if (" Close ".equals (event.arg))

dispose () ;
return true ;

}

}


//
AboutGSL.java
import java.awt.* ;
import java.awt.event.* ;

class AboutGSL extends Frame
{

Button OK = new Button (" Close ") ;
Label Caption = new Label ("Passbook V1.0", Label.CENTER) ;

Label c1 = new Label ("developed for Sample Demo", Label.CENTER) ;

Label c2 = new Label (" ", Label.CENTER) ;

Label c3= new Label (" ", Label.CENTER) ;


public AboutGSL ()
{

super ("About Grameen Solutions") ;

setSize (Toolkit.getDefaultToolkit().getScreenSize().width/2, Toolkit.getDefaultToolkit().getScreenSize().height /4) ;

setResizable (false) ;

setLayout (new FlowLayout (FlowLayout.CENTER, 500, 0)) ;
add (c2);

add (c3);

add (Caption);

add (c1);

add (OK) ;

}

public synchronized boolean handleEvent (Event event)
{

System.out.println( event);

f (event.id != Event.ACTION_EVENT)
{

if (event.id == WindowEvent.WINDOW_CLOSING)
{

dispose ();

return true;

}
else
return false ;
}

if (" Close ".equals (event.arg))

dispose () ;
return true ;

}

}


Step5:
Put yor .jar file inside the
Windows\creme\demos\ directory of your PDA and try to run it by double clicking on it.

Its worked fine for me.

JSP Live Validation

Its being interesting to have the validation of web application with each tab movement which also called Live Validation. The concept natively came with Ruby on Rails frame work. I felt to do the same for a JSP page.

What we need?
1. Download livevalidation_standalone.js file from bellow location
http://www.livevalidation.com/javascripts/src/1.3/livevalidation_standalone.js

2. Download consolidated_common.css file from bellow location
http://docman.cn/docs/livevalidation/css/consolidated_common.css

3. keep both the file in the context of your web application

4. And link both .js and css file to the Jsp page with in tag

<head>
<link rel="stylesheet" type="text/css" href="css/consolidated_common.css">
<script type="text/javascript" src="jscript/livevalidation_standalone.js"></script>
</head>

then beside the text box have the given code as given bellow.

Required Validation:
<tr>
<td width="462"><span class="style5">Required Validation:</span></td>
<script type="text/javascript">
var sayHello = new LiveValidation('sayHello', { validMessage: 'Thanks!', wait: 500});
</script> </td>
</tr>

same way follow other code for several validation

Numeric Only :
var f3 = new LiveValidation('f3');
f3.add(Validate.Numericality);

Integer Only:
var f4 = new LiveValidation('f4');
f4.add(Validate.Numericality, { onlyInteger: true } );

Specific 2000 Only:
var f5 = new LiveValidation('f5');
f5.add(Validate.Numericality, { is: 2000 } );

Higher than or equal to 2000:
var f6 = new LiveValidation('f6');
f6.add(Validate.Numericality, { minimum: 2000 } );

Lower than or equal to 2000:
var f7 = new LiveValidation('f7');
f7.add(Validate.Numericality, { maximum: 2000 } );

Within a range of 2000 - 3000:
var f8 = new LiveValidation('f8');
f8.add(Validate.Numericality, { minimum: 2000, maximum: 3000 } );

Should be between 2000 and 2003, and also be an integer:
var f9 = new LiveValidation('f9');
f9.add(Validate.Numericality, { minimum: 2000, maximum: 2003, onlyInteger: true } );

Should be 4 or more characters in length:
var f11 = new LiveValidation('f11');
f11.add(Validate.Length, { minimum: 4 } );

Confirm password:
var f19 = new LiveValidation('f19');
f19.add(Validate.Confirmation, { match: 'myPasswordField'} );

Should be an email address:
var f20 = new LiveValidation('f20');
f20.add(Validate.Presence);
f20.add(Validate.Email );

output of the page look like with each event like this



Building Blocks of Android Applications

There are four building blocks to an Android application:
• Activity
• Intent Receiver
• Service
• Content Provider

Its of course not necessary each application need all these 4 block but some how some of these will be followed
The XML file AndroidManifest.xml contains all components to be used in the application. All the componets need to declare here before used.

Activity:
Each function or activity that happens in a screen of the application is party of activity.
All the Android class extends a base class Activity. In screens we see are Activity class

Intent and Intent Filters:

Android uses a special class called an Intent to move from screen to screen. An intent describes what an application wants.
There is a related class called an IntentFilter. While an intent is effectively a request to do something, an intent filter is a description of what intents an activity (or intent receiver, see below) is capable of handling.

Intent Receiver:
It’s a some kind of background process. IntentReceiver to receive the data from external events.

Content Provider:
Applications can store their data in files, an SQLite database, or any other mechanism that makes sense. A content provider, however, is useful if we want our application's data to be shared with other applications. A content provider is a class that implements a standard set of methods to let other applications store and retrieve the type of data that is handled by that content provider.

Life Cycle of Android Activity: Life cycle methods sequence are
  1. onCreate()
  2. onStart()
  3. onResume()
  4. onFreeze()
  5. onPause()
  6. onStop()
  7. onDestroy()


Ref:
http://www.anddev.org/lifecycle_of_an_activity-t81.html

Android Simple Login Demo

This demo gives an idea of designing Relative Layout. Its a simple Log In demonstration. Which looks pretty as shown here.







main.xml looks as





Source code as comes here

package my.com.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MyAndroid extends Activity implements OnClickListener
{

private EditText tName;

private EditText tPass;
private Button btnEnter, btnExit;
private AlertDialog.Builder alert;

@Override
public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initComponents();
}

private void initComponents()
{

tName = (EditText) findViewById(R.id.tName);
tPass = (EditText) findViewById(R.id.tPass);
btnEnter = (Button)findViewById(R.id.btnEnter);
btnExit = (Button)findViewById(R.id.btnExit);
btnEnter.setOnClickListener(this);
btnExit.setOnClickListener(this);
}

@Override
public void onClick(View v)
{

if(v == btnEnter) { alert = new AlertDialog.Builder(this); alert.setTitle("Welcome"); alert.setMessage("Your Name: " + tName.getText().toString()+ "\nYour Pass:"+tPass.getText().toString());
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{

public void onClick(DialogInterface dialog, int whichButton)
{

setResult(RESULT_OK);

}
});
alert.show();
}
else if(v == btnExit)
{

finish();
}
}
}

Java SE from sketch - Part 2

Java Primitive Data Types:

Data types are to define various types of data in the program to be used, there are 8 primitive data types in java.



Java Variable or Identifier:
  • Variables are to hold different type of data to be used in the program
  • Java is strict case sensitive language
  • Identifiers must start with a letter, a currency character ($), or a connecting
  • character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters,currency characters, connecting characters, or numbers.
  • Key words should be ignored to be an identifier
Legal Identifiers:
int _a;
int $c;
int ______2_w;
int _$;
int this_is_a_very_detailed_name_for_an_identifier;

Illegal Identifiers:
int :b;
int -d;
int e#;
int .f;
int 7g;


Java Code conventions:
Sun defined a coding standard and style programmer. Here are the naming standards that Sun recommends as follow,

Classes:
The first letter should be capitalized, and if several words are linked together to form the name, both the words should have first letter uppercases. Classes, the names should typically be nouns like,
System
Account
StudentProfile

Interfaces:
The names should be adjectives like,
Runnable
Serializable

Methods:
The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs like,
getName ()
setFullName()
validateUser()

Variables:
Like methods, the camelCase format should be used, starting with
a lowercase letter like,
maxWidth
accountBalance
formName

Constants:
They should be named using uppercase letters with underscore characters as separators like,
YEAR_RATE
FINAL_VALUE




Writing First Java Program:

Being an OOP language each Java Program has to be written with a class. Let us write a simple program to begin,

public class MyFirst
{
public static void main(String[] args)
{
System.out.println("New Line");
System.out.print("After New Line");
System.out.println("Not in new Line");
}
}
output:
New Line
After New LineNot in new Line


Here we created a public class called MyFirst having a main method,

public static void main(String[] args) {
}

This main method happens to be the starting point of the program and also all other methods will be called from this method.

System.out.println("New Line");

Here System is a built-in class, out is an Object of output Stream and println(); is the method to display data in the console.

Println(); prints data in a line and moves the cursor to new line. Please remember it never starts in a new line.

Print(); print along with current line.

Output of the program should give the complete idea.

NB: about public, static, void and String[] we will discuss soon.

to be continued...

J2ME from Sketch - Part 1

J2ME Historical events:
1998:

  • Sun refocused on mobile and entertainment devices (Java's original intention)
  • Released pJava to be used for resource constrained devices.
  • pJava was based on core set of JDK1.1.8 and some new API’s specific to mobile devices.
  • Though pJava fit bigger devices such as setboxes better, it did a poor job on other smaller devices.
1999:
  • Sun creates a VM for Palm Pilots.
  • The project was called "Spotless", and the VM created became KVM.
  • KVM together with Spotlet demo was released for early access at JavaOne.
  • It was standardized via JCP, and came out as a set of configurations and profiles, with a new name J2ME.
  • J2ME release overcame the inefficiencies of pJava.
2000:
  • Sun extends pJava for handsets (PDAs and SmartPhones) with a JavaPhone API which found its way into several Symbian OS 6 implementations.
  • These extensions became new classes in J2ME via PP and the PBP.
2001:
  • Nextel Communications, Inc. introduces first java enabled wireless phone in North America.
  • The i85s, manufactured by Motorola, is pre-loaded with Java apps, including specialized business calculators and an expense pad.Allows download of J2ME applications.

What is J2ME:
A separate Java platform optimized for small devices. Stands for Java 2 Micro Editions.

The Computing resources of J2ME are:
  • Memory (Persistent & Volatile).
  • Processing speed
  • Output device
  • Input device
  • Network connectivity
  • Power supply

J2ME Architecture:
J2ME Architecture divided into three parts as Configurations, Profiles and Optional Packages known as MIDP.



Configuration:
  • It defines the minimum platform required for a group of devices.
  • It defines a lowest common denominator J2ME Runtime Environment.
  • It includes VM and a set of common API derived primarily from J2SE.
  • Each configuration is geared for a family of devices with similar capabilities.
  • Two configurations have been defined:
  • Connected Device Configuration (CDC).
  • Connected, Limited Device Configuration (CLDC)
CDC:
  • Designed for devices with a min of 512KB of memory (ROM) and 256KB of RAM.
  • Specifies a full Java Virtual Machine called CVM.
  • Total memory budget range may extend
  • up to 16MB.
  • CDC compliant devices may have 16 or 32 bit CPUs.
  • E.g. TV Set-top boxes, Car navigation systems, RTS, Washing Machine etc.



CLDC:
  • 128kb memory for Java
  • 32kb for runtime allocation
  • Restricted UI
  • Low bandwidth network connectivity, intermittent access
  • KVM is reference implementation
  • E.g. Mobile Devices, PDA



KVM for CLDC:
  • Kilo Virtual Machine (KVM) a minimal and almost complete JVM, small enough to fit in tens of kilobytes.
  • Lots of features eliminated
  • floating point, finalize(), JNI, etc.
  • Change in classfile verification
  • Preverifier, verifier
  • Classfile format: JAR
CVM for CDC:
  • Compack Virtual Machine
  • JVM with J2SE 1.3 VM specification compliancy.
  • Supports almost all advanced features of J2SE VM, including low-level debugging and native programming interfaces.
  • It is more portable, more efficient, and smaller than J2SE VM.
  • CVM was written in C and uses a portability layer to abstract underlying OS dependencies.
  • CVM improves garbage collectors, native-thread support, synchronization, and stack usage.

Profile:
It addresses the specific needs of a certain device family

MIDP:
Mobile Information Device Profile which is upper layer part of the J2ME architecture comes with the Profile specification. MIDP characteristics are
  • 128 kb non-volatile memory
  • 32 kb volatile memory
  • 8 kb of non-volatile memory for persistency
  • A screen of at least 96 x 54 pixels
  • Some capacity for input
  • Two-way network connection, possibly intermittent

Life cycle of J2ME Midlets:
  • Instantiation
  • pauseApp()
  • startApp()
  • destroyApp()
  • Deallocation


Simple Midlet Skeliton:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class LifeCycleDemo extends MIDlet
{

LifeCycleDemo() { }
public void startApp() { }
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }

}

Java SE from sketch - Part 1

History at a glance:
  • In the year around 1990James Gosling along with 13 team members started planning for of computing and formed a team called Green Team.
  • Their primary goal was to control over handheld devices like cable set-top boxes,VCR's, toasters, *7-type of device, and also for personal data assistants (PDA).
  • They came up with a language named OAK with having features with Platform independent, Extremely reliable, Compact.
  • Internet and Web explosion began, so Sun shifted the target market to Internet applications and changed the name of the project OAK to Java.
  • Having passed a bad time since 1991 – 1993, In 1994 Sun's HotJava browser appeared.
  • HotJava illustrated the power of applets, programs that run within a browser, and also the capabilities of Java for speeding program development.
  • In 1995, Netscape Navigator Internet browser incorporated Java technology officially.
  • And Java alpha version Java1.0a2 introduced in the market.
  • Since then now we have Java 6 with 12 update so far
What is Java:
Java is a OOP language which refers with several others language like C, C++ or Pascal having different new perception as

  • Pure OOP language
  • Java byte code
  • JVM (Java Virtual Machine)
  • JRE (Java Runtime Environment)
Java’s ideal features:
Java has incorporated plenty of exiting features to buzz the programming myth, some of are
  • Platform Independency
  • Compiler/Interpreter Pack
  • Automatic Memory Management
  • Architecture neutrality
  • Security

Plaform Independent vs Architecture Neutral:
PI refers to running the programs written in one platform (Operating System) will be the same for other platform. Software specific

AN refers to writing a program for a Machine (e.g. Pentium) will be the same for any other machine architecture. Hardware specific

Byte Code and Binary Machine Code:
Byte code is alternative form of Machine code which is understood only by the JVM generated by java compiler orally known as .class file. When JVM loads a .class file in fact it loads stream of byte code for each method there in the class. And finally execute by java interpreter, JIT (just-in-time) or JVM specific techniques.

Binary code falls a hidden mechanism here in Java where JVM act smart o generate neutral machine code against all Byte Code stream taken from a class file. Mr. Cute JVM act as a Microprocessor here!!!


JVM as Microprocessor:
As name says JVM is a Virtual Machine which has its own instruction sets as Microprocessors does. Each instruction consists of a one-byte opcode followed by zero or more operands. The opcode indicates the action to be taken. If more information is required before the JVM can take the action, that information is encoded into one or more operands that immediately follow the opcode. For each kind of data to be handled either logically or arithmetically JVM does with its own separate instruction a set.

Sample instruction opcodes of JVM :
iconst_m1, iconst_0 , iconst_1
, iconst_1

Sample Byte code Stream :
03 3b 84 00 01 1a 05 68 3b a7 ff f9


Sample Machine code by JVM:
iconst_0 = 03
istore_0 = 3b
iinc 0, 1 = 84 00 01
iload_0 =1a
iconst_2 = 05
imul = 68
istore_0 = 3b
goto -7 = a7 ff f9

Finally to say Java is smart because it has JVM. All praises Java but JVM the hero. Sorry to say JVM not Platform independent because each platform needs a separate JVM.


JDK vs JRE vs JVM:
  • JDK to compile Java Program and generate bytecode
  • JRE to run the Java Program with the help of JVM
  • JVM to interpret Java bytecode to machine code for low level execution.

JDK: Java Development Kit holds all the tools needed to develop the Java programs. These tools are compiler i.e. javac, Java application launcher i.e.java.exe, Appletviewer, etc. If wejust needed to write a Java program and compile then JDK is enough.

JRE: Java Runtime Environment contains JVM, class libraries, and other supporting files. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE.

JVM: Java Virtual Machine interprets the bytecode into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc.


Java Exceution processes:
Compiling (JDK part):
My.java--->javac My.java (Compiling)--->My.class (Bytecode)

Executing (JRE part):
java My (Interpreting)--->JVM---> Machine Code--->Microprocessor---> Output

Hibernate Annotations and Spring

Let us make the previous Hibernate Application to Spring application with the same entity class Item.java and Sale.java

Step 1:

Let us make DAO classes MyDAO.java and MyDAOImpl.java

//MyDAO.java
package me.gs.dao;
import me.gs.model.Item;

import me.gs.model.Sale;

public interface MyDAO
{
public void saveItem(Item item);

public void saveSale(Sale sale);

}


//MyDAOImpl.java

package me.gs.dao;

import me.gs.model.Item;

import me.gs.model.Sale;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository("MyDAO")
public class MyDAOImpl implements MyDAO
{

private HibernateTemplate hibernateTemplate;


@Autowired

public void createHibernateTemplate(SessionFactory sessionFactory)
{

this.hibernateTemplate = new HibernateTemplate(sessionFactory);

}


public void saveItem(Item item)
{

hibernateTemplate.save(item);
}

public void saveSale(Sale sale)
{

hibernateTemplate.save(sale);
}

}


Step 2:

Add jdbc.properties file inside the WEB-INF directory with bellow code

jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/my jdbc.username=root jdbc.password=

Step 3:
we may remove bellow code from hibernate.cfg.xml or comment or let it be exist in fact its not needed as we added jdbc.properties file

< property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect < /property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my</property> <property name="hibernate.connection.username">root</property>

Step 4:
Locate the applicationContext.xml and edit with the bellow code inside the WEB-INF folder




Step 5:
Let us make a jUnit test class to test the application this time.

import me.gs.dao.MyDAO;

import me.gs.model.Item;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class TestSpring
{

public TestSpring()
{

}

@Test

public void testSpringHB()
{

ApplicationContext context = new FileSystemXmlApplicationContext("web/WEB-INF/applicationContext.xml");


MyDAO idao = (MyDAO) context.getBean("MyDAO");
Item item = new Item();

item.setName("item3");

item.setCode("code3");

idao.saveItem(item);
}

}
Output comes as bellow:


Hibernate Annotations and Relationships

Hibernate Annotation brings up a concept of transferring data from POJO (Plain Old Java Object) to database tables in the form of Metadata. which replaces earlier hibernate versions which uses XML files to work with metadata.

Java 5 on words metadata can be handled by JVM itself, this technique is called as Annotation. Annotation is the Java class which is read through reflection mechanism during the runtime by JVM and does the processing accordingly. Here Hibernate Annotation is to providing raw metadata for mapping Object and Relational Tables. All metadata comes with an Entity class containing table structure so that programmer simultaneously can hook up with required structure and relationships without having lengthy XML mapping files.

The current Hibernate Annotation release is based on the EJB 3 and JPA specification.

Let us see an example of this topic:

What needed before you proceed?
  1. Java 5.0 or Higher installed in your system.
  2. Download Hibernate Core 3.3.1.GA then extract and set all jar files to your classpath.
  3. Download Hibernate Annotations 3.4.0 GA.
  4. You should also have hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your classpath.
  5. Better if you know hibernate already.

Preface of Application:
We will make an application which shows the Item and its Sale relationships. So here tables are item and sale, there will be another table for Item and Sale relationship sale_item. All these three tables will be generated by Hibernate Annotation core automatically without our intricacy.

Database Name :my
User Name : root
Password :


Step 1: Create an Entity Class Item.java this is the POJO class for Items

package me.gs.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String name;

@Column
private String code;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

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

public Long getId() {
return id;
}

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

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
fields are not set
if (!(object instanceof Item)) {
return false;
}
Item other = (Item) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "me.gs.model.Item[id=" + id + "]";
}

}

Here @Entity declares the class as an entity bean i.e. a persistent POJO class and @Id declares the identifier property of this entity bean which is also Primary Key of the tables. @Column is used to map the entities with the column in the database.We can also define the table name as bellow

@Entity
@Table(name="item")
public class Item implements Serializable {
...

Step 2 : Create another entity class Sale.java which is same as Item.java class

package me.gs.model;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Sale implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column
private String refNo;

@OneToMany
private List items;

public List getItems() {
return items;
}

public void setItems(List items) {
this.items = items;
}

public String getRefNo() {
return refNo;
}

public void setRefNo(String refNo) {
this.refNo = refNo;
}

public Long getId() {
return id;
}

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

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
fields are not set
if (!(object instanceof Sale)) {
return false;
}
Sale other = (Sale) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "me.gs.model.Sale[id=" + id + "]";
}

}


Bellow two statements make the OneToMany relationship between Item and Sale class.

@OneToMany
private List items;


Step 3: The Hibernate.cfg.xml is the configuration file for the datasource in the Hibernate. Our file will look something like this.

<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my</property>
<property name="hibernate.connection.username">root</property>

<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="me.gs.model.Item"></mapping>
<mapping class="me.gs.model.Sale"></mapping>

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

Step 4: This following program we can use to test the entire application we have designed so far.

import java.util.ArrayList;
import java.util.List;
import me.gs.model.Item;
import me.gs.model.Sale;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class HiberTestMain {


public static void main(String args[])
{
System.out.println("start");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Item item = new Item();
item.setName("item1");
item.setCode("code1");

Item item1 = new Item();
item1.setName("item2");
item1.setCode("code2");
session.save(item);
session.save(item1);

Sale sale = new Sale();
sale.setRefNo("refNo1");
List items = new ArrayList();
items.add(item);
items.add(item1);
sale.setItems(items);
session.save(sale);
transaction.commit();
session.close();
System.out.println("end");
}

}

Output:
start
Hibernate: insert into Item (code, name) values (?, ?)
Hibernate: insert into Item (code, name) values (?, ?)
Hibernate: insert into Sale (refNo) values (?)
Hibernate: insert into Sale_Item (Sale_id, items_id) values (?, ?)
Hibernate: insert into Sale_Item (Sale_id, items_id) values (?, ?)
end


Finally in our MySQL database we will find three tables created with given data,
item
sale
sale_item

here sale_item defines the OneToMany relationship of item and sale.

Thanks.
Special Thanks to Mehrab Ferdous

Android Step by Step...

Android is the most exiting open platform which covers operating system, middleware and powerful applications for all types of mobile devices.


This Android platform is the outcome of different top technology leading companies like Google, T-Mobile, Intel, HTC and 30 other companies under the Open Handset Alliance (OHA).

The main intension is to have a new Operating System for hand held devices in which new colorful rich mobile application and services can be developed for the end users.

Configuring your eclipse for android in WindowsXP or Vista:
What we need before we proceed?
  • Java 5 or 6
  • Eclipse 3.3 (Europa), 3.4 (Ganymede)
  • Then Download the SDK for android and extract in any drive (e.g. in C:\ )
  • Getting ready with eclipse by intalling android plugin.
For Eclipse 3.4 (Ganymede):
  1. Start Eclipse, then select Help > Software Updates > Find and Install....
  2. In the dialog that appears, select Search for new features to install and click Next.
  3. Click New Remote Site.
  4. In the resulting dialog box, enter a name for the remote site (e.g. Android Plugin) and enter this as https://dl-ssl.google.com/android/eclipse/ or http://dl-ssl.google.com/android/eclipse/
  5. Click OK.
  6. You should now see the new site added to the search list (and checked). Click Finish.
  7. In the subsequent Search Results dialog box, select the checkbox for Android Plugin > Developer Tools. This will check both features: "Android Developer Tools", and "Android Editors". The Android Editors feature is optional, but recommended. If you choose to install it, you need the WST plugin mentioned earlier in this page. Click Next.
  8. Read the license agreement and then select Accept terms of the license agreement. Click Next.
  9. Click Finish.
  10. The ADT plugin is not signed; you can accept the installation anyway by clicking Install All.
  11. Restart Eclipse.
For Eclipse 3.4 (Ganymede):
  1. Start Eclipse, then select Help > Software Updates....
  2. In the dialog that appears, click the Available Software tab.
  3. Click Add Site...
  4. Enter this as the Location:https://dl-ssl.google.com/android/eclipse/ or http://dl-ssl.google.com/android/eclipse/
  5. Click OK.
  6. Back in the Available Software view, you should see the plugin. Select the checkbox next to Developer Tools and click Install...
  7. On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. The Android Editors feature is optional, but recommended. If you choose to install it, you need the WST plugin mentioned earlier in this page. Click Next.
  8. Accept the license agreement and click Finish.
  9. Restart Eclipse.
Now, you just need to modify your Eclipse preferences to point to the Android SDK directory:
  1. Select Window > Preferences... to open the Preferences panel.
  2. Select Android from the left panel.
  3. For the SDK Location in the main panel, click Browse... and locate the SDK directory where you kept Android SKD (e.g. C:\android-sdk-windows-1.0_r2)
  4. Click Apply, then OK.
Done eclipse is ready now to start with a HelloWorld Andorid application.

Step 1:
Create a new Android project as shown bellow.




Step 2:
Enter project name, package name, activity name and application name then click onfinish.




Step3:
we get project directory structure as given bellow



Step4:
Locate the java source HelloAndroid.java code file and change the new code as given here.



package com.hello.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
tv.setText("My First Android");
this.setContentView(tv);
}
}

Step 5:
Save the code and run the project. Select given option bellow



Step 6:
The android emulator will come, it would be bit slow and gradually one menu button will come then click on it. We get a menu as shown bellow and Hello Android icon will appear, click on it




Step 7:

Final out put will be here




we can also work with main.xml and strings.xml for designing user interface then steps are as follows



Step1:
Edit the main.xml as bellow



Step2:
Edit the strings.xml as bellow



here strings.xml used for Label values and main.xml used for layout the interface. and finally see the code of HelloAndroid.java will be like this. which actualy load the main.xml.

package com.hello.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

save and run the project and verify the output.

NB: R.java actually generates automatically. you can design the project either way.


Java Best Practice.

It’s been a long time we have been moving with a traditional way of Java programming which makes the programs tightly coupled and also leads the program a hassled one to be modified or to make generic.

Let us see a traditional program followed by a modern programming techniques to make programs more generic and expendable… we also call it best practice of Java programming in oppose to traditional style of programming.

Traditional:

package traditional;
public class Traditional {
public static void main(String[] args) {
System.out.println("Traditional Programming!!!");
}
}


Modern:

package modern;

import java.io.PrintStream;

final class Source {
private final String message;
public Source(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}

class Destination {
public void write(PrintStream out, String message) {
out.println(message);
}
}

public class Mordern {
public static void main(String[] args) {
Source source = new Source("Modern Programming!!!");
Destination destination = new Destination();
destination.write(System.out, source.getMessage());
}
}