Sunday, November 28, 2010

Improving the Performance of a JDBC Program

A java program that uses JDBC to connect to a database and retrieve the data from the database may take some time to perform these tasks. To know how much time has been taken by a JDBC program. we can take the help of currentTimeMillis() method of System class. This method gives the current  time in milliseconds since January 1st 1970.

By Reducing the execution time of a JDBC Program, we can improve its performance. The execution time of a JDBC program depends on the Following factors:

  1. The driver used to connect to the database will influence the execution time. Each driver will exhibit different performance and hence, selecting a good driver that gives optimum performance will improve the performance of a JDBC program.
  2. setFetchSize() method of statement interface is useful to tell the driver how many rows at a time to be fetched from the database. By increasing the number of rows to be retrieved at a time, it is possible to improve the performance of a JDBC program.
  3. Sometimes PreparedStatment inteface can be used in place of Statement interface for improving the performance.
 
Affect  of PerparedStatement:

Using the PreparedStatement in place of Statement Interface will improve the performance of a JDBC program.

When a SQL Statement is sent to database, the following tasks are performed:
  • The SQL Statement's Syntax should be verified to know whether it is correct or not. The SQL statement is divided into small pieces called "tokens". These tokens are also verified to know whether they are in SQL format or not.
  • Then another verification is done to know whether the table or view mentioned in the statement exists or not.
The above two statements are called "parsing" and takes some time. When the SQL Statement is executed, Statement interface does parsing every time the statement is executed.

On the Other hand if we use preparedStatement, it does parsing only once.
This saves time and hence PreparedStatement offers better Performance.

Thanks
Vinay Guntaka

Java Database Conntectivity

Stages in JDBC Porgram:

  1. Registering the Driver
  2. Connecting to the Database
  3. Preparing SQL Statements in java
  4. Executing the SQL Statements on the Database
  5. Retrieving the Results.
  6. Closing the Connections.
A List of JDBC Drivers

If you need to access a database with Java, you need a driver. This is a list of the drivers available, what database they can access, who makes it, and how to contact them.

IBM DB2
        jdbc:db2://<HOST>:<PORT>/<DB>
        com.ibm.db2.jdbc.app.DB2Driver

JDBC-ODBC Bridge
        jdbc:odbc:<DB>
        sun.jdbc.odbc.JdbcOdbcDriver
Microsoft SQL Server
        jdbc:weblogic:mssqlserver4:<DB>@<HOST>:<PORT>
        weblogic.jdbc.mssqlserver4.Driver
Oracle Thin
        jdbc:oracle:thin:@<HOST>:<PORT>:<SID>
        oracle.jdbc.driver.OracleDriver
PointBase Embedded Server
        jdbc:pointbase://embedded[:<PORT>]/<DB>
        com.pointbase.jdbc.jdbcUniversalDriver
Cloudscape
        jdbc:cloudscape:<DB>
        COM.cloudscape.core.JDBCDriver
Cloudscape RMI
        jdbc:rmi://<HOST>:<PORT>/jdbc:cloudscape:<DB>
        RmiJdbc.RJDriver
Firebird (JCA/JDBC Driver)
        jdbc:firebirdsql:[//<HOST>[:<PORT>]/]<DB>
        org.firebirdsql.jdbc.FBDriver
IDS Server
        jdbc:ids://<HOST>:<PORT>/conn?dsn='<ODBC_DSN_NAME>'
        ids.sql.IDSDriver
Informix Dynamic Server
        jdbc:informix-sqli://<HOST>:<PORT>/<DB>:INFORMIXSERVER=<SERVER_NAME>
        com.informix.jdbc.IfxDriver
InstantDB (v3.13 and earlier)
        jdbc:idb:<DB>
        jdbc.idbDriver
InstantDB (v3.14 and later)
        jdbc:idb:<DB>
        org.enhydra.instantdb.jdbc.idbDriver
Interbase (InterClient Driver)
        jdbc:interbase://<HOST>/<DB>
        interbase.interclient.Driver
Hypersonic SQL (v1.2 and earlier)
        jdbc:HypersonicSQL:<DB>
        hSql.hDriver
Hypersonic SQL (v1.3 and later)
        jdbc:HypersonicSQL:<DB>
        org.hsql.jdbcDriver
Microsoft SQL Server (JTurbo Driver)
        jdbc:JTurbo://<HOST>:<PORT>/<DB>
        com.ashna.jturbo.driver.Driver
Microsoft SQL Server (Sprinta Driver)
        jdbc:inetdae:<HOST>:<PORT>?database=<DB>
        com.inet.tds.TdsDriver
Microsoft SQL Server 2000 (Microsoft Driver)
        jdbc:microsoft:sqlserver://<HOST>:<PORT>[;DatabaseName=<DB>]
        com.microsoft.sqlserver.jdbc.SQLServerDriver
MySQL (MM.MySQL Driver)
        jdbc:mysql://<HOST>:<PORT>/<DB>
        com.mysql.jdbc.Driver
Oracle OCI 8i
        jdbc:oracle:oci8:@<SID>
        oracle.jdbc.driver.OracleDriver
Oracle OCI 9i
        jdbc:oracle:oci:@<SID>
        oracle.jdbc.driver.OracleDriver
PostgreSQL (v6.5 and earlier)
        jdbc:postgresql://<HOST>:<PORT>/<DB>
        postgresql.Driver
PostgreSQL (v7.0 and later)
        jdbc:postgresql://<HOST>:<PORT>/<DB>
        org.postgresql.Driver
Sybase (jConnect 4.2 and earlier)
        jdbc:sybase:Tds:<HOST>:<PORT>
        com.sybase.jdbc.SybDriver
Sybase (jConnect 5.2)
        jdbc:sybase:Tds:<HOST>:<PORT>
        com.sybase.jdbc2.jdbc.SybDriver

----------------------------------------------
 
Here i am writing a sample code for JDBC.

try
{
  Class.forName("Driver name");
  // DriverManager.registerDriver(new Drivername()); 
   Connection con = DriverManager.getConnenction("jdbcurl","username","password");
   Statement st = con.createStatement();
  ResultSet rs= st.executeQuery("select * from Tablename");
  While(){}
  rs.close();
  st.close(); 
  conn.close(); 
}
catch(Exception e)
{
}
 

Thanks 
Vinay Guntaka

Wednesday, November 17, 2010

Drools 5.0 plugin Installation to Eclipse3.5 Galileo

Drools 5.0 Installation:
------------------------
Drools is a business rule management system (BRMS) with a forward chaining inference based rules engine, more correctly known as a production rule system, using an enhanced implementation of the Rete algorithm.


Drools 5.0 plugin Installation to Eclipse3.5 Galileo

Step 1:

Pls download the eclipse 3.5 Galileo (190mb) from the following link

http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/SR2/eclipse-jee-galileo-SR2-win32.zip


Step 2:

Download the Drools 5.0 workbench from the following link:

http://download.jboss.org/drools/release/5.0.1.26597.FINAL/drools-5.0-eclipse-all.zip

Step 3:


Extract both files to Eclipse-jee-galileo-SR2-win32 and drools-5.0-eclipse-all

copy the FEATURES and PLUG-INS of Drools 5.0 and paste it in the respective Eclipse-jee-galileo-SR2-win32

Step 4:

Just Restart the Eclipse and go to Windows->Prefrences->Drools->Installed Drools Runtime
give the path of the extracted files of the Drools Dir
set ok and plz once again restart the eclipse so that the Drools Perspective will be installed to that
eclipse

Step 5:

Simply You can select the New Project Drools and execute the Drools
and have a great exp with Drools

Thanks
GVK

Generic XML Parsing Method

Vinay  Guntaka
Java Programmer


import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ParseXML {
public Map<List<String>,Integer> parseXMLData(String xmlData,String rootTag,List<String> childTags)
{
Map<List<String>, Integer > xmlMap = new HashMap<List<String>,Integer>();

try {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlData)));
NodeList nodeLst = document.getElementsByTagName(rootTag);
for (int s = 0; s < nodeLst.getLength(); s++) {
List<String> subItems = new ArrayList<String>();
for (int count = 0; count < childTags.size(); count++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(childTags.get(count));
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
subItems.add(((Node) fstNm.item(0)).getNodeValue());
}
}
xmlMap.put(subItems, s);
}
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());

} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();

} catch (Throwable t) {
t.printStackTrace();
}
return xmlMap;
}
public static void main(String[] args) {
ParseXML p = new ParseXML();
String xmlData = "<data><row><Attribute_Name>java</Attribute_Name><VALUE>5656</VALUE><Child_Name>kids</Child_Name></row>"+
"</data>";
String rootTag = "row";
List<String> tagList = new ArrayList<String>();
tagList.add("Attribute_Name");
tagList.add("VALUE");
tagList.add("Child_Name");
Map<List<String>,Integer> myData = p.parseXMLData(xmlData, rootTag, tagList);
System.out.println(myData);
}
}

Tuesday, November 2, 2010

Android Dynamic List with buttons and event listener of each button

Creating a custom list view – a custom layout, a custom row layout and how we bind the custom data holder to these layouts.

So, here we extends simple Activity not ListActivity.

Here i am giving the entire work of my Dynamic List with Button, where we get the event listener of each button from android:onClick="myClickHandler" in one of the layout file. From this event we can get the selected value and pass to other intents.

Here is the program....if you find any concerns or updates let me know will update accordingly....


package com.jit;
/*
 * Vinay Guntaka
 * Desc: Dynamic List with buttons and event listener of each buttons.
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ListViewButtons extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView listView = (ListView)findViewById(R.id.btnOptionList);
        List<HashMap<String, String>> myOptList = getOptionList(EnumTypes.OPTION);
        SimpleAdapter optionList = new SimpleAdapter(getBaseContext(),myOptList,R.layout.btnstablerows,
                new String[]{
                "optnCard"
                },new int[]{
                R.id.btnAddOptn
        });
        listView.setAdapter(optionList);
        listView.setTextFilterEnabled(true);
    }
    /*    myClickHandler() is defined in btnstablerows.xml for
     *  onClick event android:onClick="myClickHandler".
     */
    public void myClickHandler(View v)
    {
    LinearLayout vwParentRow = (LinearLayout)v.getParent();
    /*
     * Based on the row of each field the values of <td> can be
     * get based on the field type and field location
     * just replace with 0,1,2,.... of getChildAt();
     * get the 2nd child of our ParentRow (remember in java that arrays start with zero,
     * so our 2nd child has an index of 1) 
     */
    Button btnChild = (Button)vwParentRow.getChildAt(0);
    Toast.makeText(getBaseContext(), btnChild.getText(), Toast.LENGTH_LONG).show();
    int c = Color.CYAN;
    vwParentRow.setBackgroundColor(c);
    vwParentRow.refreshDrawableState();
    Toast.makeText(getBaseContext(), "Hey event fired", Toast.LENGTH_LONG).show();
   
    }
    private ArrayList<HashMap<String, String>> getOptionList(EnumTypes type){
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map = new HashMap<String, String>();
        switch (type) {
        case OPTION:
            map.put("optnCard", "JAVA");
            mylist.add(map);
            map = new HashMap<String, String>();
            map.put("optnCard", "Eclipse Galileo");
            mylist.add(map);
            map = new HashMap<String, String>();
            map.put("optnCard", "Android 2.2");
            mylist.add(map);
            map = new HashMap<String, String>();
            map.put("optnCard", "Simulator Android");
            mylist.add(map);
            break;

        default:
            break;
        }
        return mylist;
    }
    public enum EnumTypes{
        OPTION
    }
}


-----------------
main.xml
----------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ListView android:id="@+id/btnOptionList"
        android:layout_width="200px" android:layout_height="wrap_content"
        android:drawSelectorOnTop="false" android:paddingLeft="35px"
        android:paddingTop="10px" android:clickable="true" android:scrollbars="none"
        >
    </ListView>
</LinearLayout>

----------------

btnstablerows.xml
--------------

<?xml version="1.0" encoding="utf-8"?>
    <!-- row.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="4dip" android:paddingBottom="6dip"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
   
    >
    <Button android:id="@+id/btnAddOptn" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:clickable="true"     />
</LinearLayout>

-----------------------
Hey.., I am a newbie to Android World
So please have a look at my Program and let me know if any thing missing

Thanks

Android Environment setup with Eclispe3.5 Galileo

Android  Plugin Installation Procedure to Eclispe3.5 Galileo

Minimum requirements for developing a sample android application are as follows:
  • Java 1.6 Eclipse Galileo
  • Android SDK
You can download the Android SDK from the following link with respective OS : 

Install the ADT Plug-in for Eclipse:
               If you are developing in Eclipse, set up a remote update site at https://dl-ssl.google.com/android/eclipse/
Install the Android Development Tools (ADT) Plugin, restart Eclipse, and set the "Android" preferences in Eclipse to point to the SDK install location. For detailed instructions, see ADT Plugin for Eclipse.

Procedure for downloading plugins:


Start Eclipse, then select Help > Install New Software.
 
In the Available Software dialog, click Add....
 
In the Add Site dialog that appears, enter a name for the remote site (for example, "Android Plugin") in the "Name" field.In the "Location" field, enter this URL:
                             https://dl-ssl.google.com/android/eclipse/ 

Note: If you have trouble acquiring the plugin, you can try using "http" in the URL, instead of "https" (https is preferred for security reasons).

Click OK.

Back in the Available Software view, you should now see "Developer Tools" added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools. 

Click Next.In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed. 

Click Next to read and accept the license agreement and install any dependencies, then click Finish.Restart Eclipse.

So you are ready to develop the Android Programs

At first you have to set the Android RunTime :-

Goto Eclipse Window tab-> Preferences ->set the Android SDK location (downloaded of the Android sdk system path).

Android SDK and AVD Manger(Android Emulator):

After Successfull installation of Android plugins you can see a icon with a down arrow (i.e, Android SDK and AVD console)on click it opens the list of existing AVD (Android Virtual Device ) if not you can create a new AVD by selecting the New button.There you can give the AVD name and selecting the target as android version (1.5,2.1,2.2..,)In Hardware there are certain options that supports the Android Emulator.After giving all details mentioned you can start the Device by pressing Launch button to open the Android Emulator.

There is a DDMS(Dalvik Debug Monitoring Service) prespetive to open the LogCat of Android,FileExplorer view etc.,

The above process is to configure the Android Environment.

Thanks

Thursday, October 28, 2010

The Evolution of Java

 The Evolution of JAVA

JDK 1.0 Intial Release

JDK 1.1 
  • an extensive retooling of the AWT event model
  • Inner classes added to the language
  • JavaBeans
  • JDBC
  • RMI
J2SE 1.2 
  • strictfp keyword
  • reflection which supports introspection only, no modification at runtime possible
  • The swing graphical API was integrated into the core classes
  • Sun's JVM was equipped with a JIT Compiler for the first time
  • Java aplug-in
  • Java IDL, and IDL Implementation for CORBA Interoperability.
  • Collection Framework

J2SE 1.3
  • HotSpot JVM Included
  • RMI was modified to support optional compatibilty with CORBA
  • JAvaSound
  • Java Naming and Directory inteface (JNDI) included in core libraries (previously available as an extension)
  • Java platform Debugger Architecture(JPDA)
J2SE 1.4
  • Assesrt Keyword
  • Regular expression modedled after perl regular expressions.
  • exception chaining allows an exception to encapsulate original/ lower-level exception
  • Internet protocal version (IPV6) support
  • non-blocking NIO (new input / output)
  • Logging API
  • Image I/O API for reading and writing images in formats like JPEG and PNG
  • Integrated XML parser and XSLT processor(JAXP)
  • Integrated Security and cryptography
J2SE 5.0
  • Generics
  • Metadata
  • Autoboxing / unboxing
  • Enumerations
  • Swing New skinnable look and feel, called synth
  • Varargs
  • Enchanced "for loop"
  • Fix the previously broken semantics of the java Memory model, which defines how threads interact through memory.
  • Automatic Stud generation for RMI objects
Java SE 6
  • Support for order win9x sessions dropped
  • Scripting Language Support (JSR 223)
  • Dramatic performance improvements for the core
  • platform and swing
  • Improved webservice support through JAX WS
  • JDBC 4.0 support
  • JAva compiler aPI
  • Upgrade of JAXB to version2.0
  • support for pluggable annotations
  • Many GUI improvements
Java SE7
  • JVM support for dynamic languages, following the prototyping work currently done on the Multi language virtual machine
  • A new library for parallel computing pn Multi  core processors

Wednesday, October 27, 2010

The History of Java

The History of JAVA

          Java is related to C++, which is a direct descendant of C. Much of the character of java is inherited from these two languages. From C, Java derives its Syntax. Many of java's Object-Oriented features were influenced by C++. In fact, several of Java's defining characteristics come from or are responses to its predecessors.

The Creation of JAVA

       Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Micro Systems, Inc in 1991. It took 18 moths to develop the first working version. The language was initially called "Oak" but was renamed "Java" in 1995. Between the initial  implementation of Oak in the fall of 1992 and the public announcement of java in the spring of 1995, many more people contributed ti the design and evolution of the language. Bill joy, Arthur van Hoff, Jonathan Payne, Frank Yellin and Tim Lindholm were key contributors to the maturing of the original prototype.

Java's Magic: The Bytecode

     The key that allows Java to solve both the security and the portability problems just described in that the output of a Java compiler is not executable code. Rather it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called Java Virtual Machine(JVM). In essence the original JVM was designed as an interpreted for bytecode.
 
The Java Buzzwords

  • Simple
  • Secure
  • Portable
  • Object-orinted
  • Robust
  • Multithreaded
  • Architecure-neutral
  • Interpreted
  • High performance
  • Distributed
  • Dynamic

Understanding OOP Concepts

 OOPs:


Classes--The "Blueprints" for an object and the actual code that defines the properties and methods.

Objects-- Running instances of a class that contain all the internal data and state information needed for your application to function.

Inheritance-- The ability to define a class of one kind as being a subtype of a different kind of class (much the same way a square is a kind of rectangle)

Polymorphism-- Allows a class to be defined as being a member of more than one category of classes (just a car is a "thing with an engine" and "a thing with wheels")

Interfaces-- A way of specifying that an object is capable of doing something without actually defining how it is to be done (e.g a dog and a human are "things that walk" but they do it very differently )

Encapsulation-- The ability of an object to project access to its internal data.

Why Java is called Java?

Why Java is called Java?

Very interesting question “why java is called java?” isn’t it?
When I was attending the class of Java, we are asked by the teacher. Why Java is called java? We don’t have answer to this question. Later the teacher explain us that:-
Once they were deciding on what to call it. They were at a coffee shop drinking coffee, and somehow they thought of naming it java, which is another word for coffee. As coffee from JAVA island, Indonesia is so famous that sometimes coffee is itself called Java in US slang, the name was a good option for a cool and attractive name.
Note: - Java was originally named Oak, but was changed to Java, in hopes of drawing more interest to the new language.

This article explains how Java got it’s name:
http://www.javaworld.com/jw-10-1996/jw-10-javaname.html

Java 1.7 New Features Over 1.6

Automatic Resource Management Description: A proposal to support scoping of resource usage in a block with automatic resource cleanup. T...