Wednesday, September 28, 2011

Pure MVC framework...




Goal of this framework is to impose Model View Controller design pattern on application .
This framework is typically used with adobe flex.This is completely written in action script.

It uses singleton , facade , Observer and MVC design pattern in mixture .

Main components of it are

Core Actors - Model , View , Controller
Central Point to all actors - Facade

Facade (singleton - common gateway for notifications )
Facade is singleton class .This is instantiated from mxml after it has created all of its children components.
Every interaction with application goes through facade .
This class extends Facade class and implements IFacade.as

 ApplicationFacade.as:
package com.me.myapp
{
import org.puremvc.as3.interfaces.*;
import org.puremvc.as3..patterns.facade.*;
import com.me.myapp.view.*;
import com.me.myapp.model.*;
import com.me.myapp.controller.*;
// A concrete Facade for MyApp
public class ApplicationFacade extends Façade implements IFacade
{
// Define Notification name constants
public static const STARTUP:String = "startup";
public static const LOGIN:String = "login";
// Singleton ApplicationFacade Factory Method
public static function getInstance() : ApplicationFacade
{
if ( instance == null ) instance = new ApplicationFacade( );
return instance as ApplicationFacade;
}
// Register Commands with the Controller
override protected function initializeController( ) : void
{
super.initializeController();
registerCommand( STARTUP, StartupCommand );
registerCommand( LOGIN, LoginCommand );
registerCommand( LoginProxy.LOGIN_SUCCESS, GetPrefsCommand );
}
// Startup the PureMVC apparatus, passing in a reference to the application public function startup( app:MyApp ) : void
{
sendNotification( STARTUP, app );
}
}
}


 <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="façade.startup(this)”>
<mx:Script>
<![CDATA[
// Get the ApplicationFacade
import com.me.myapp.ApplicationFacade;
private var facade:ApplicationFacade = ApplicationFacade.getInstance();
]]>
</mx:Script>
<!—Rest of display hierarchy defined here -->
</mx:Application


Notifications -

Used for loose coupling .It is part of observer design pattern.They are like events .
Notifications can be sent by facade and proxies ; listened for and sent by mediators , mapped to send by commands.Many observers can receive same notification and can act on it .
Notification have , notification name , body(it may be any object of action script) , type .

Commands(controller - stateless, Extends Model and implements IModel.as) -
Mapping of command to notification is done in concrete facade exp may be - ApplicationFacade.as
Command is observer for notification for which it is registered.
After getting notification from mxml facade searches for registered command and invokes execute method of it .Commands are stateless means no static reference to them just created and destroyed when notification's work is completed.
They implement Icommand interface.

Mediators (Controller - stateless) -
Agent between view component and other core components .
It can send or receive notifications.
It handles events from view and notifications from rest of puremvc.
It takes name and view object as in constructor of its super class.So it is coupled with view components of flex like data grid.So you can modify view through mediator by accessing view objects.We can cast this view object to desired component like progress bar , grid etc and mutate it.

Proxie (Model - stateless)-
As direct java beans are not accessible in flex they have created surrogate objects in .as as data carriers .These are called as proxies.One can imagine that they are proxies for real java beans.
In proxie depending on your choice of webservice , SAOP, AMF messaging you can talk with real java objects on server .


Simple flow

mxml (Flex View ) ==> On complete create singleton facade ==> send some notification to facade on action ==> Facade looks for mediators , commands registered for that notification ==> registered commands execute method is called ==> command may call some methods of proxies which in turn talk with Java actual objects ==> proxy send response to mediator ==> mediator interpret it and modify view >> proper result is displayed in view or mxml.




References and downloads




Friday, September 9, 2011

Aspect Oriented Programming (AOP) and use in Spring

  1. Concept of AOP
  2. Why to use AOP
  3. How to use in Spring
  4. Simple example

Tuesday, September 6, 2011

Spring/BlazeDS integration

1. What is BlazeDS ?
2. Advantages of using BlazeDS for Spring /Flex
3. Simple Example .
4. Video from adobe

A good video for Flex/BlazeDS greenHorns

Sunday, July 24, 2011

JSF - Facelets - How to call onload java script of body tag from ui:composition

When HEAD and BODY tag are used in <ui:composition>. tag, then this wrong usage will create problem .Because of this html DOM is formed with <body> tag inside <body> tag .Because this DOM crashes in Chrome, Opera and Apple safari browser .

What is facelets ui:composition ?

The UI Composition tag is a templating tag that wraps content to be included in another Facelet. Any content outside of the UI Composition tag will be ignored by the Facelets view handler. Any content inside of the UI Composition tag will be included when another Facelets page includes the page containing this UI Composition tag.

Example –

Template.xhtml

 <html>

<head>
<title><ui:insert name="title" /></title>
<body>
<h2><ui:insert name="header" /></h2>
<ui:insert name="message" />
</body>
</html>


Composition.xhtml

 <html>

<head>
<title>Welcome</title>
</head>
<body>
<h2>Hello World!</h2>
How are you today?
</body>
</html


How to call onLoadBody JS script?

As there is no body tag in <ui:composition> then how to call onBodyLoad function after loading content of template ? We can use <div> tag inside those <ui:include> but there is no reliable way to call function on div onLoad or on div unload .Because of this we have to define a template in header of base template and override it to insert onbodyLoad functions .




How to override a facelets?

Example template for override onBodyLoad and onBodyUnload

• Template.xhtml

 <html xmlns="http://www.w3.org/1999/xhtml"

xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h=http://java.sun.com/jsf/html
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>SALPE TECHNOLOGIES</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<ui:insert name="header">
<script language="JavaScript" type="text/JavaScript">
function bodyLoaded(){
alert("Event bodyLoaded called from base template .. ");
}
</script>
</ui:insert>
<ui:insert name="headerUnLoaded">
<script language="JavaScript" type="text/JavaScript">
function bodyUnLoaded(){
alert("Event bodyUnLoaded called from base template .. ");
}
</script>
</ui:insert>
</head>
<body onload="bodyLoaded();" onUnload ="bodyUnLoaded();">
<f:view locale="#{session.locale}">
<table>
<tr>
<td>
<ui:include id="_header" src="HeaderTemplate.xhtml" />
</td>
</tr>
<tr>
<td>
<ui:insert name="_bodyContent">Insert Body Content</ui:insert>
</td>
</tr>
<tr>
<td>
<ui:include id="_footer" src=FooterTemplate.xhtml"></ui:include>
</td>
</tr>
</table>
</body>


GeneralPage.xhtml

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<ui:composition
template =”Template.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:c="http://java.sun.com/jstl/core" >
<ui:define name="header">
<script type="text/javascript" language="javascript" src=".MyJavascript.js"> </script>
<script type="text/javascript">
function bodyLoaded(){
alert("Event bodyLoaded fucntion from overrriden template");
</script>
</ui:define>
<ui:define name="content">
<f:view locale="#{session.locale}">
<f:loadBundle basename="SALLabel" var="bundle" />
<h:form id="myForm">
<table>
<tr>
<td>
WELCOME TO SALPE Colglomeration !
</td>
</tr>
</table>
</h:form>
</f:view>
</ui:define>
</ui:composition>
</ui:composition>




Standard ways to use facelets.


Do not use <body> tag inside the <ui:composition>. For java script declare source of file before using it .


Tuesday, July 12, 2011

Safari compactibility issue

I got this error while making a JSF page compatible to all browsers including Safari.

Error Details -

This page contains the following errors:

error on line 10 at column 10 : xmlParseEntityRef: no name

Below is a rendering of the page up to the first error.


Solution -

This error comes when speacial characters are used in xhtml for JSF ;

Detailed list

http://www.degraeve.com/reference/specialcharacters.php

More common mistakes



 left single quote           &lsquo;     ‘
right single quote &rsquo; ’
single low-9 quote &sbquo; ‚
left double quote &ldquo; “
right double quote &rdquo; ”
double low-9 quote &bdquo; „
exclamation mark &#33; !
number sign &#35; #
dollar sign &#36; $
percent sign &#37; %
ampersand &#38; &amp; &
Most undectable mistake is that

NOTE

Suppose you have data in data base for example

 &lt;h:outputText styleClass="normal" value="#{testBundle.title}"/>

if this title value from backing bean is like this "Testing & Dev domain"
This value will break XHTML DOM in Safari browser .

Temporary solution is change backing bean /DB value to -"Testing and Dev domain"

Friday, July 8, 2011

Facelets in JSF

JSF is component oriented and event driven web framework to build up web applications.
It is mocking existing technologies like ASP .NET , Apache Tapestry , Java swing etc.
It need some framework to make re-use of XHMTL code and easy way to build pages , composite custom component some what like that of "Apache Tiles" and answer for that is Facelets .
Facelet tag are added in JSF 2.0 as powerful tool to use templates(hence code re-use ) .In jsf 1.2 you have to give facelet handler class but that is not needed in JSF 2.0 .
In JSP we can use page include (static include) and jsp include (dynamic include) for templates .But you have to write all this include tag in all JSPs example header , footer , right , left part of page includes .
As JSF 2.0 has abandoned JSP servlet display technology because it contradicts some phases of JSF life cycle (for more details - improving jsf by dumping jsp ).They have adapted for cleaner appeoch with XHTML and Facelets .
JSP is not true MVC as inexperienced developed may put business logic in java snippets in jsp tags .So there is no imposition of rule .Further more JSP are servlets and they have their phases like translation , compilation and other phases .
JSF facelets with more efficient than JSP because there is no such compilation thing .
With facelets you can create new reusable templates and composite component if you want .

main facelet tags are


I am giving a simple example how to use them -

example template

PageTemplate.xhtml


 <html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:composition>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</meta>
<title>SALPE CORP - INDIA </title>
<LINK rel="shortcut icon" href="icon.ico" />
</head>
<body class="pagebody">
<f:view locale="#{LanguageBean.locale}">
<f:loadBundle basename="Label" var="bundle" />
<table width="98%" border="0" align="center" cellpadding="0" cellspacing="0" ID="Table2">
<tr>
<td>
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" ID="Table3">
<tr>
<td valign="top">
<h:panelGrid width="100%" id="menuBottomZone1" cellpadding="0" cellspacing="0">
<ui:include id="header" src="/template/HeaderTemplate.xhtml" />
</h:panelGrid>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="13" colspan="3" align="center">
<table width="1003px" border="0" align="center" cellpadding="0" cellspacing="0" ID="Table5">
<tr>
<td align="center">
<ui:insert name="bodyContent">Body Content Area</ui:insert>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3">
<h:graphicImage value="../../newimages/general/spacer.gif" width="5" />
</td>
</tr>
<tr>
<td colspan="3" valign="middle">
<ui:include id="footer" src="/template/FooterTemplate.xhtml"></ui:include>
</td>
</tr>
</table>
</f:view>
</body>
</ui:composition>
</html>


Any other pages - like welcomePage.xhtml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<ui:composition
template="/template/PageTemplate.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:define name="content">
<script language="javascript">
doSomeThingOnLoad();
</script>
<f:view locale="#{LanguageBean.locale}" >
<f:loadBundle basename="CATCmaLabel" var="bundle" />
<h:form id="loginForm">
<table>
<tr>
<td>
Hello JSF - I am showing bodyContent Area :)
Insert here XHTML code you like !
</td>
</tr>
</table>
</h:form>
</f:view>
</ui:define>
</ui:composition>

Look like this when you view
welcomePage.xhtml


















HEADER FOM HEADER TEMPLATE XHTML


Hello JSF - I am showing bodyContent Area :)

Insert here XHTML code you like !




©SALPE CORP FOOTER FOM FOOTER TEMPLATE XHTML

Thursday, June 23, 2011

JSF state saving mechanism ..

JSF can save state of component tree in either session or on clients machine inform of serialized data .
While creating component tree JSF creates a key and keep all objects of component tree as UIViewRoot in session with against it.For next JSF request it will use same key to restore that view :)
For client side saving has performance issues like it has to serialize whole tree and write it in response ship in form of gzip to client.Next time when same client make JSF request from same page it de-serialize it and inflate all objects in corresponding state .

Setting for state saving is done in web.xml.

Server side state saving is where the component tree and all component state are stored within the user's session. This entry within the session is tracked by writing a key in the response that is used to lookup the entry on subsequent post-backs.

Client side state saving doesn't leverage the server side session mechanism at all, instead, the component tree and state will be serialized using Java Serialization, GZIP compressed (at least that is the default), Base64 encoded, and written to the response. When a post-back occurs, the encoding process will be reversed which will result in the tree and state we started with.

As to the benefits/drawbacks, review the following table.


State Saving MethodServer Side Memory UsageCPU UsageBandwidth Usage
Server without compressionHighLowLow
Server with compressionLow/MediumHighLow
Client with compressionLowHighMedium
Client without compressionLowMedHigh



Setting in web.xml
  <context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>



1.Server side state saving - following hidden field is added (see the value )

<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="2269033803785808195:-5553424543391650776" autocomplete="off" />


observe >> value="2269033803785808195:-5553424543391650776"



2.Client side state saving - following hidden field is added (see the value )

<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="H4sIAAAAAAAAANVWTWwbRRQeOzFxflryU4UitZC6VSVKuo6TmEJCRZzEaVZxaIRDoCmQjr0Te9Px7mR21l63NCoHBEJCUHFCCuLAhQM9ceGCBOKAhFQQkbjABU6oBxBC4gCHipnxrncTskl6ZCU/z+6+efO975v3Zj/5DcSIRUHPGqxCxWY6VmahVZ6HJNb245df9V/5vgVEZ0AHNqE2A4vMpCpoZ2WKrLKJNYc8MwHE1VWLc9vNfzEGHlhb0TU2alPQdzkn42JolJSLhTVUZOPvfvvih93WYzgKgEP4hKi9DjZAi5hK+OXfbVCgiNmOsgqLyFKKZoWYBjKY8rw65Y1PLVCTIMrqc6huAffq5aEpOOwvnTXsSvAlYaADMkb1gs2QxdPv89PPUArrOd1izmtbx9//Gn7QAiIqaLX0a0jibam1Cssnnd4dXZ5BhmY5O4jmYRXRS998ev69zTvzURDNgfYihpb1LKwgBnolOUmBMJnnYIzSeA50WHyOJmMw0N/w0M1kHlEdYv0aLGA07hBSFTQBS9hDPJtH+PKKZRsuGGExYpaSWVjIqdlp149jToc46hWClWm0Cm3MZhoPT2UIwfVF8yoy/vp48NL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4ttIKntBKMSBBmQWo4wb9UCceXEiYqD+n7IONoYeMUjKepE11cZAF0UGP5MQXawTfrZ0ByVfRA4TbqPCnPNmxAu6ofEdYzW7WUx2s1hIH0z758zgnrUlcworraPNktnhVuu4efnnL+7dirpFMMXXObG9dnbMEKUTfztx7403b3/mlc7LtdOgN0izHN1o8BH8UhHSZ8HU/Um/XexGaFdfcU63eYy6RIm/l6Rd4cdqf3CuLrq30CUE2hxQDwzNXXU7OH+BhOMc9LgL/9SYzzw3t6JON/2OnE2NjAyNjJxLDQ+vjK6OFtLpIbjH54AArMxyo3q49j1HLFbnS4NjRRObdKyOMDZr4wVYvFqipm1oYwUuiHeixClat3WKNFkTwjwpzFjgUImJb4OU3zs4y/8CZd7KiB8LAAA="

Understanding java.util.concurrent package

Using Java Reflection

Tuesday, June 14, 2011

sample DD

It is always a good idea to study servlets using web.xml .It has important inforamtion it should be called as mirror of the application .
It is just a XML with setting which servlet container will use to manage application .

 <?xml version="1.0" encoding="ISO-8859-1"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
version="2.4">
<display-name>Test Webapp</display-name>
<description>This is a sample deployment descriptor that shows the
use
of important elements. </description>
<!-- Presence of this element indicates that this WebApp is distributable. -->
<distributable />
<!-- Defines WebApp initialization parameters. -->
<context-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</context-param>
<context-param>
<param-name>DBName</param-name>
<param-value>Oracle</param-value>
</context-param>
<!-- Defines filters and specifies filter mapping -->
<filter>
<filter-name>Test Filter</filter-name>
<description>Just for test</description>
<filter-class>filters.TestFilter</filter-class>
<init-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Test Filter</filter-name>
<servlet-name>TestServlet</servlet-name>
</filter-mapping>
<!-- Defines application events listeners -->
<listener>
<listener-class>listeners.MyServletContextListener
</listener-class>
</listener>
<listener>
<listener-class>listeners.MySessionCumContextListener
</listener-class>
</listener>
<!-- Defines servlets -->
<servlet>
<servlet-name>TestServlet</servlet-name>
<description>Just for test</description>
<servlet-class>servlets.TestServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlets.HelloServlet</servlet-class>
<init-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<security-role-ref>
<!-- role-name is used in HttpServletRequest.isUserInRole(String role)
method. -->
<role-name>manager</role-name>
<!-- role-link is one of the role-names specified in security-role elements. -->
<role-link>supervisor</role-link>
</security-role-ref>
</servlet>
<!-- Defines servlet mappings -->
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>*.hello</url-pattern>
</servlet-mapping>
<session-config>
<!--specifies session timeout as 30 minutes. -->
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>jar</extension>
<mime-type>application/java-archive</mime-type>
</mime-mapping>
<mime-mapping>
<extension>conf</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>home.html</welcome-file>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>notfoundpage.jsp</location>
</error-page>
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>sqlexception.jsp</location>
</error-page>
<taglib>
<taglib-uri>http://abc.com/testlib</taglib-uri>
<taglib-location> /WEB-INF/tlds/testlib.tld </taglib-location>
</taglib>
<taglib>
<taglib-uri>/examplelib</taglib-uri>
<taglib-location> /WEB-INF/tlds/examplelib.tld </taglib-location>
</taglib>
<security-constraint>
<display-name>Example Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/test/*</url-pattern>
<!-- only POST method is protected -->
<http-method>POST</http-method>
</web-resource-collection>
<web-resource-collection>
<web-resource-name>Another Protected Area</web-resource-name>
<url-pattern>*.hello</url-pattern>
<!-- All methods are protected as no http-method is specified -->
</web-resource-collection>
<auth-constraint>
<!-- Only the following roles can access the above resources. The role
must be defined in security-role. -->
<role-name>supervisor</role-name>
</auth-constraint>
<user-data-constraint>
<!-- Specifies the type of communication between the client and the server.
It can be: NONE, INTEGRAL, or CONFIDENTIAL -->
<transport-guarantee>INTEGRAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<!-- auth-method can be: BASIC, FORM, DIGEST, or CLIENT-CERT -->
<auth-method>FORM</auth-method>
<realm-name>sales</realm-name>
<form-login-config>
<form-login-page>/formlogin.html</form-login-page>
<form-error-page>/formerror.jsp</form-error-page>
</form-login-config>
</login-config>
<!-- Specifies the roles that are defined in the application server. For
example, Tomcat defines it in conf\tomcat-users.xml -->
<security-role>
<role-name>supervisor</role-name>
</security-role>
<security-role>
<role-name>worker</role-name>
</security-role>
</web-app>

Monday, May 9, 2011

Create sample application in android

Introduction to Google Android operating system

Some important UML diagrams and free tools to draw them

Introduction to ORMS

Introduction for Hibernet , Ibatis etc.

Compare Different frameworks

Compare -

Strut 2.0
Spring
JSF
EJB
Seam

JSF - Compoent libraries avaiable

Comparison between

1. Rich faces
2. Apache My faces
3. Ice faces
4. Oracle ADF faces

Creating CAPTCHA component in JSF + Rich faces

JSF/facelets - creating custom components exp - ui:repeat with var in it

Advanced DB 2.0 concepts - JDBC 2.0 + JDBC 4.0

1.DB connection from data source / loading class of driver
2. Types of statements
3.DB Transactions
4.Batch process
5. Stored procedures
6.Types of result sets
7. Data base performance tuning

Thursday, April 28, 2011

How to configure DBCP(DB connection pooling ) using mysql and apache tomcat 6.XX server

Connection pooling is a technique of creating and managing a pool of connections that are ready for use by any thread that needs them.
This technique of "pooling" connections is based on the fact that most applications only need a thread to have access to a JDBC connection when they are actively processing a transaction, which usually take only milliseconds to complete. When not processing a transaction, the connection would otherwise sit idle. Instead, connection pooling allows the idle connection to be used by some other thread to do useful work.
In practice, when a thread needs to do work against a MySQL or other database with JDBC, it requests a connection from the pool. When the thread is finished using the connection, it returns it to the pool, so that it may be used by any other threads that want to use it.
When the connection is "loaned out" from the pool, it is used exclusively by the thread that requested it. From a programming point of view, it is the same as if your thread called DriverManager.getConnection() every time it needed a JDBC connection, however with connection pooling, your thread may end up using either a new, or already-existing connection.

Benefits of Connection Pooling

1. Reduced connection creation time
2. Simplified programming model
3. Controlled resource usage



Implementation of Connection Pooling

Generally, you configure a connection pool in your application server configuration files, and access it via the Java Naming and Directory Interface (JNDI). The following code shows how you might use a connection pool:


 Implementation of Connection Pooling
Generally, you configure a connection pool in your application server configuration files, and access it via the Java Naming and Directory Interface (JNDI). The following code shows how you might use a connection pool:
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class MyServletJspOrEjb {
public void doSomething() throws Exception {
/*
* Create a JNDI Initial context to be able to
* lookup the DataSource
*
* In production-level code, this should be cached as
* an instance or static variable, as it can
* be quite expensive to create a JNDI context.
*
* Note: This code only works when you are using servlets
* or EJBs in a J2EE application server. If you are
* using connection pooling in standalone Java code, you
* will have to create/configure datasources using whatever
* mechanisms your particular connection pooling library
* provides.
*/
InitialContext ctx = new InitialContext();
/*
* Lookup the DataSource, which will be backed by a pool
* that the application server provides. DataSource instances
* are also a good candidate for caching as an instance
* variable, as JNDI lookups can be expensive as well.
*/
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
/*
* The following code is what would actually be in your
* Servlet, JSP or EJB 'service' method...where you need
* to work with a JDBC connection.
*/
Connection conn = null;
Statement stmt = null;
try {
conn = ds.getConnection();
/*
* Now, use normal JDBC programming to work with
* MySQL, making sure to close each resource when you're
* finished with it, which allows the connection pool
* resources to be recovered as quickly as possible
*/
stmt = conn.createStatement();
stmt.execute("SOME SQL QUERY");
stmt.close();
stmt = null;
conn.close();
conn = null;
} finally {
/*
* close any jdbc instances here that weren't
* explicitly closed during normal code path, so
* that we don't 'leak' resources...
*/
if (stmt != null) {
try {
stmt.close();
} catch (sqlexception sqlex) {
// ignore -- as we can't do anything about it here
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (sqlexception sqlex) {
// ignore -- as we can't do anything about it here
}
conn = null;
}
}
}
}
Best Size for Connection Pool

To correctly size a connection pool for your application, you should create load test scripts with tools such as Apache JMeter or The Grinder, and load test your application.
For an example 15to 20 connections which can cater to about 400 to 500 concurrent users over a minute time span .

Connection Pooling Configuration

Apache Tomcat 4.1
Place a copy of mysql-connector-java-[version]-bin.jar in $CATALINA_HOME/common/lib/. Then, follow the instructions in the section MySQL DBCP Example of the Tomcat documentation.
Notice that Connector/J 3.0 and newer work with the same settings: http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html
Tomcat uses the Apache Software Foundation's DBCP libraries, which you can also use in your own non-J2EE code: http://jakarta.apache.org/commons/dbcp/

Sunday, April 24, 2011

How to reduce cyclomatic complexity (part of refactoring ) of java code ?

Database view usage and impact on performance of website

The word View itself suggests that it will be restricted access to some information in database based on privileges and shared summary of information from different tables.

A view is a virtual table.They are just complex query to create abstraction for user .These are not real table because it does not take physical memory more it is like table on fly .View may consists data from many table .
It may be required to show to user on a page from many table with just querying view than dealing with complex queries .

Most of time view are created to simplify interaction with DB and to make faster retrieval of group of data.

Advantages -

1. Grouping data from multiple table in one virtual table
2.Hiding complexity of query
3.They may provide security depending on DB privileges.For example you can create view for admins to see all other information except password .
4. It saves memory as they are not real tables .They are just special group of queries
5. If data in real table is updated then it will reflect in the view .
Suppose very simple a situation there is "employee" with emp_id(pk) and emp_name columns .There is other table with "department" id_emp(fk) , dept_name .
You want to show table in UI with employee name and Department name .Create view for this like view_emp_dept and query that for showing or updating data.



Examples - create view

CREATE OR REPLACE  VIEW view_emp_dept AS
SELECT emp_id ,emp_name , dept_name
FROM employee, department
GROUP BY name
Now query this view to get employee

Example - Get data from view

 SELECT emp_name , dept_name from  view_emp_dept  where emp_id =10;



Example - drop view

 DROP VIEW view_name view_emp_dept

If view are not defined properly then we have to create new view for each situation so define views considering some generic situation .
If view definition is not efficient for example distinct key word, unrefereed tables etc it can kill performance so before defining view we have consider time taken by that query .


So judicious use of view could help to simplify queries in code and could make our life simpler .


Monday, April 11, 2011

MAT for JVM heap dump analysis

Load Testing of web application using Jmeter

Jmeter is open source tool from apache to test performance of application when large number of users access in small amount of time .

This not a browser but it is software which simulated request and response condition which happens at actual time.
Jmeter does not execute your Java scripts , render ajax request etc .It just creates http request object in case of web application and set proper parameter in it.So if you want to analys time taken by each page loading then it would be time difference between request and reposes .Actual browser will take some more time depending on type of browser and its caching mechanisms .
In practice it is very impossible to create scenario in which 1000 users logs in to system and try to play with it .Jmeter virtually creates given numbers of threads which can innudate the server with hhtp request .

Stress testing / Load testing is concept from mechanical engineering in which we test how much requests server can handle without going out of memory :)
Jmeter has pretty long learning curve .


From scratch if you have to do something minimum one week will require to just create a demo .
Lot of problems come in this like cookie manager policy , URL rewriting , creating login and password mapping for say 100 users .


To use you much know main terminologies in it .

Main terminologies


Element

Description

Thread Group

As with any load test, execution is multi-threaded. The thread group element is what controls concurrent connection to your application. In end user terms, it's your group of users.

Samplers

A sampler is the basic type of controller. Very simply, samplers tell JMeter to send requests (HTTP, SOAP, etc…) to a server. There are also Logic Controllers, but we won't be using one in this tip.

Listeners

Listeners are what you use to access to the information JMeter gathers while running. They give you the pretty charts

Timers

Timers are how you set delays in JMeter. Timers fire before each request that a thread makes.

Assertions

Assertions, like in any test tool, allow you to check for specific behavior as your test executes. Assertions provide the standard pass/fail results.




Installation –

Ø Please refer to installation video - Installation video

· Download from

http://jakarta.apache.org/jmeter/

· Download zip file - Unzip it at c: / drive

Ø Please refer video to learn how to use it - You tube video is planned .



Steps to follow -

Scenario -

I am taking general scenario in which you have to log in to system and hit some pages .
Lets consider that 100 users hit the same page in period of one second .

First you have to record all requests and responses using Jmeter then run for 100 users .

Please refer to you tube video lecture for this

How to use Jmeter.


References

1.Jmeter reference book

http://www.doc88.com/p-7040136164.html

2. Apache user manual

http://jakarta.apache.org/jmeter/usermanual/index.html