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

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...