Monday 28 November 2011

Java with mysql


1. To connect java into database, we need some driver to connect. I have used jdbc driver.

2. In java.sql package contain DriverManager class, it handles driver.

3. After this driver successfully connected to data base, it returns connection object.

   DriverManager.getConnection(String databaseUrl, String username, String password);

   datbaseUrl  -   Url which represents database connection

                   Example, jdbc:mysql://localhost:3306/Uma

                   Uma - Data base name

   username   -    username of the mysql

   password   -    Password of the mysql


4.  Use this connection object, we can create a statement for executing mysql queries.

    Statement st = Conn_object.createStatement()  -   create a statement with out any specification

    [ We can create statement with some specification like resultset scrollable, etc ]


5. statement class contains methods to run queries. We can get the query result using ResultSet.

  
   ResultSet rs = st.exceuteQuery(String query)  -   Simply returns the result, not update in datbase

                  st.updateQuery(String query)   -   Update the query result into database



Some methods in ResultSet :

    We can get values from ResultSet using some methods in ResultSet.


1. To get the column value using getXXX()

   Here XXX is the column data type like getInt(), getString()

2. To check wheather or not a column is null, using wasNull()

      if (rs.wasNull()) {
          // resultset contains null value
      }

3.  Use JDBC operation inside try block and catch the exception which is thrown. TO get more details about exception,

JDBC provides some methods,  e.getMessage(), e.getErrorCode()

    catch (Exception e) {
        // print error message using  e.getMessage()
        // print error number using e.getErrorCode()   
    }


More Info :

http://www.kitebird.com/articles/jdbc.html

Difference between JDK, JRE and JVM

JDK:

1. Java development kit contains tools for developing java programs such as compiler (javac.exe) whihc converts source code inro byte code,
Interpreter, Java Application launcher (java.exe) which converts byte coe into mechine code.


JRE :

1. Java Runtime Environment contains JVM, class libraries and other supported files. It does not contain any developer tools such as compiler, interpreter. Actually JVM runs the program using library files and other supported files that are provided by JRE.

JVM :

1. JVM is in both JRE and JDK.

2. JVM runs the java program using library files in jre.

3. JVM interpretes the byte code into machine code.

4. JVM is called "virtual" because it creates machine interface which does not depend on underlying operatiog system and machine hardware architecture.

[ JVM interpretes byte code into machine code which does not depend on underlying operating system ]



-

Wednesday 16 November 2011

Enhanced for loop

Enhanced for loop:

1. This new feature added in Java1.5

2. Also callied as "for each loop".

3. It allows as to iterate through collection without having to create a iterator or without having to calculate beginning and end conditions for counter variable.

For example, 

In normal for loop,

class sample {
    public static void main(String args) {
        int[] var = {1, 9, 18, 27 };
        for( int i = 0; i < var.length; i++) {
            System.out.println("values :" +var[i]);
        }
    }
}
       
For each loop,

class sample {
    public static void main(String args) {
        int[] var = {1, 9, 18, 27 };
        for( int i : var) {
            System.out.println("values :" +var[i]);
        }
    }
}

Here, no need to check var length. Its easy to adapt for loop to for each loop.


But, It contains some disadvantages, follows

1. for each loop iterate only sequencialy. cant get first and third value using for each. [ Step value can not be incremented ]

2. Backward traversal is not possible.



Reference :

http://www.javabeat.net/articles/32-new-features-in-java-50-1.html

Wednesday 9 November 2011

Flex Basics

Flex basics:

Use of Name space in mxml :

1. To specify language version

2. To provide scope for mapping XML tag name to ActionScipt class name or CSS style tag to ActionScript class name

3. And provide details to compiler, where local sources located for custom component.


Name space :

1. Flex 2 and 3 -> MXML 2006  which contains language version and mapping for flex framework component

2. In Gumbo, new language features are added and updated to MXML 2009 [ xmlns:fx="http://ns.adobe.com/mxml/2009" ]

3. Components are described in their own namespaces,

    -> Flex 3 or MX components are in mxml library namespace. [ xmlns:mx="library://ns.adobe.com/flex/mx" ]

    -> New Gumbo spark components are in spark component name space. [ xmlns:s="library://ns.adobe.com/flex/spark" ]


For flex 3,

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://ns.adobe.com/mxml/2006">


For flex 4, Gumbo spark component,

<?xml verison="1.0" encoding="utf-8"?>

<s:Applicaiton xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx">


                                                                                - will continue in next post..

Monday 17 October 2011

Flex Event life cycle

Flex Instantiation Life Cycle and Event Flow

DIGG IT!     Published Thursday, February 08, 2007 at 8:41 AM . Flex is an event driven programming model, everything (and I mean everything) happens due to an event. When developers first take a look at MXML it is often difficult to see the event flow or instantiation life cycle of an application given the XML markup. This is especially confusing to HTML and Flash developers because the development paradigm of Flex does not match what they are used to. HTML instantiates top to bottom where Flash executes across frames starting at Frame0. Flex is a bit different.

When I learned Flex, I struggled with understanding event flow and instantiation in MXML. I was puzzled because I really didn't understand what event would kick start the logic or when events would fire. The key is understanding the event basics and seeing the initialization and event flow for yourself.

So lets look at a simple application in MXML.

Sample Application

Sample Application Source



When this application runs it dumps the instantiation and event flow into the TextArea via a binding. This allows us to see all events within the application occur independent of component instantiation order. As you can see in the application output there is a consistent order of events when this application starts. Here is the basic output up to the applicationComplete event. (The EventFlow0 object is the Application tag of the base app. The times to the left are the from the execution clock of the Flash Player.)

167ms >> EventFlow0.preinitialize
183ms >> EventFlow0.outTextArea.initialize
187ms >> EventFlow0.HelloButton.initialize
188ms >> EventFlow0.GoodByeButton.initialize
189ms >> EventFlow0.ClearButton.initialize
189ms >> EventFlow0.initialize
243ms >> EventFlow0.outTextArea.creationComplete
243ms >> EventFlow0.HelloButton.creationComplete
243ms >> EventFlow0.GoodByeButton.creationComplete
244ms >> EventFlow0.ClearButton.creationComplete
244ms >> EventFlow0.creationComplete
246ms >> EventFlow0.applicationComplete


Once the applicationComplete event it triggered, the components fire events when mouseEvents are dispatched to the components individually.

1807ms >> EventFlow0.HelloButton.rollOver
2596ms >> EventFlow0.HelloButton.rollOut
2954ms >> EventFlow0.HelloButton.rollOver
3170ms >> EventFlow0.HelloButton.rollOut
3543ms >> EventFlow0.HelloButton.rollOver
4052ms >> EventFlow0.HelloButton.click > Hello!
4267ms >> EventFlow0.HelloButton.click > Hello!
4474ms >> EventFlow0.HelloButton.click > Hello!
4569ms >> EventFlow0.HelloButton.rollOut
4907ms >> EventFlow0.GoodByeButton.click > Goodbye!
5130ms >> EventFlow0.GoodByeButton.click > Goodbye!


There is also some great documentation on the instantiation life cycle located here. Understanding this instantiation process is very important for Flex development. The example posted contains view source so feel free to take a peek and play with the events yourself.

So now you know the instantiation life cycle and event flow! I will be covering DOM events and event flow next. Event do not just happen at the component but they flow across the displaylist in phases.

Wednesday 12 October 2011

Clear explanation about Connection pooling in java

Connection Pooling - what is it and why do we need it?

It's a technique to allow multiple clinets to make use of a cached set of shared and reusable connection objects providing access to a database. Connection Pooling feature is supported only on J2SDK 1.4 and later releases.

Opening/Closing database connections is an expensive process and hence connection pools improve the performance of execution of commands on a database for which we maintain connection objects in the pool. It facilitates reuse of the same connection object to serve a number of client requests. Every time a client request is received, the pool is searched for an available connection object and it's highly likely that it gets a free connection object. Otherwise, either the incoming requests are queued or a new connection object is created and added to the pool (depending upon how many connections are already there in the pool and how many the particular implementation and configuration can support). As soon as a request finishes using a connection object, the object is given back to the pool from where it's assigned to one of the queued requests (based on what scheduling algorithm the particular connection pool implementation follows for serving queued requests). Since most of the requests are served using existing connection objects only so the connection pooling approach brings down the average time required for the users to wait for establishing the connection to the database.

How is it used?

It's normally used in a web-based enterprise application where the application server handles the responsibilities of creating connection objects, adding them to the pool, assigning them to the incoming requests, taking the used connection objects back, returning them back to the pool, etc. When a dynamic web page of the web-based application explicitily creates a connection (using JDBC 2.0 pooling manager interfaces and calling getConnection() method on a PooledConnection object ... I'll discuss both the JDBC 1.0 and JDBC 2.0 approaches in a separate article) to the database and closes it after use then the application server internally gives a connection object from the pool itself on the execution of the statement which tries to create a connection (in this case it's called logical connection) and on execution of the statement which tries to close the connection, the application server simply returns the connection back to pool. Remember you can still use JDBC 1.0 / JDBC 2.0 APIs to obtain physical connections. This of course is used very rarely - probably in the cases where connection to that particular database is needed once in a while and maintaining a pool of connection is not really needed.

How many connections the Pool can handle? Who creates/releases them?

These days it's pretty configurable - the maximum connections, the minimum connections, the maximum number of idle connections, etc. these all parameters can be configured by the server administrator. On start up the server creates a fixed number (the configured minimum) of connection objects and adds them to the pool. Once all of these connection objects are exhausted by serving those many clinet requests then any extra request causes a new connection object to be created, added to the pool, and then to be assigned to server that extra request. This continues till the number of connection objects doesn't reach the configured maximum number of connection objects in the pool. The server keep on checking the number of idle connection objects as well and if it finds that there are more number of idle connection objects than the configured value of that parameter then the server simply closes the extra number of idle connections, which are subsequently garbage collected.

Traditional Connection Pooling vs Managed Connection Pooling

Connection Pooling is an open concept and its certainly not limited to the connection pooling we normally notice in the enterprise application i.e., the one managed by the Application Servers. Any application can use this concept and can manage it the way it wants. Connection Pooling simply means creating, managing, and maintaining connection objects in advance. A traditional application can do it manually, but as we can easily observe that as the scalability and reach of the application grows, it becomes more and more difficult to manage connections without having a defined and robust connection pooling mechanism. Otherwise it'll be extremely difficult to ensure the maintainability and availability of the connections and in turn the application.