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());
}
}