Friday, November 27, 2009

MySQL Connect by prior using procedure





MySQL doesn't provide a way to do connect by , so how do you tackle it ? You have to write your own function or procedure that will do the connect by . Here is an example of the skill table that is related to itself by s_parentskillid .

Here is the Code that will get the skills related till it gets to the parent .
Code:

DROP PROCEDURE IF EXISTS getskillpath;
CREATE PROCEDURE `getskillpath`(in skillid int ,in delimiter varchar(5), out v_skillpath varchar(500))
BEGIN

DECLARE v_skill VARCHAR(50); /* variable stores the name */
DECLARE v_skillid INT DEFAULT 0; /* skill id - primary key */
DECLARE v_parentskillid INT DEFAULT 0;
/* parent skill id - foreign key that maps to skill id */

SET v_skillid = skillid; /* assign first skillid to variable */

skill_loop: LOOP

SELECT s_parentskillid,
s_name
INTO
v_parentskillid,
v_skill
FROM skills
where s_id =v_skillid;

SET v_skillpath = CONCAT_WS ( delimiter,v_skill,v_skillpath );
/* set skillpath initially null */


IF v_parentskillid is null THEN
LEAVE skill_loop; /* condition to exit parent found */
else
SET v_skillid = v_parentskillid; /* reset the skill id to loop */
END IF;


END LOOP skill_loop;
SELECT v_skillpath; /* check output */


END;

Example output - sap>SAP Functional>Reports>Reports Sub . if I use 9 as the input skill and > as the delimiter .( rows affected are marked in the image ) .

Friday, October 30, 2009

Why use DOJO



Why Use DOJO ?

Most of us use javascript for validations and js functions for
a variety of taks . Also if you are using AJAX using Xmlhttprequest
you have added a lot of dynamic capabilities in the page . But how
to make it even better ? Do you have to be a great JS expert
to implement single page applications like Gmail ,
Google Reader , Yahoo Mail etc . Answer is NO .

Javascript is complex and cumbersome when it comes to complex applications.
Implementation is different in different browsers and developer has
to worry about memory leakes , browser events etc.

DOJO is a great toolkit that allows the developers to focus on their
needs for the application rather than worry about the complex java script.
Also eliminate the need to write browser specific code . DOJO Toolkit has
taken that burden off developers for the most part .

Following are notes from Alex Russel's ( project lead of dojotool kit )presentation of DOJO.

What does DOJO Provide .

1. Package System / Bootstrap
2. Language Utilities
3. Event System
4. UI utilities
5. Widget System
6. Custom Widgets
7. Utilities

1. Package System - there is no package system in javascript .
No hirearcial way of categorizing js . DOJO solves it by bringing
a package system .
Packages can be included only if required . Lets the developer think about dependencies
Packages can be included dynamically
Once package is included its functions are guranteed work on the next line
code

dojo.require("package.*");
dojo.requireIf(Condition,"package.*");
dojo.kwCompoundRequire
(
{
browser:["foo.bar","baz.*"],
common:("thad.*"]
}
);


2. Language Utilites - Define your own modules using dojo.provide().
Ability to do builds transparently and replace source version.

Example
<script src="path/to/dojo.js">
becomes
<script src="path/to/release/dojo.js">


Normalize javascript acorss browsers with dependable API

dojo.lang.*
* is wrappter for common idioms
has functional programming API
FOWARD - COMPATIBILITY
DOJO.LANG.IS.*


Usual ones

dojo.lang.forEach
dojo.lang.map
dojo.lang.declare
dojo.lang.hitch - scope issues solved
dojo.lang.extend



3.UI Utilities

dojo.io.*
dojo.html.*
dojo.style.*
dojo.dnd.*
dojo.ifx.*



dojo.io.bind - Amazing Library!

handles text encoding
auto-encodes URL
Submits forms
Sync of Async communication
Co-exces return data
Pluggable back-ends


dojo.require("dojo.io.ScriptSrcIo");

- cross-domain and JSON


dojo.require("dojo.io.IframeIO");

background uploads plays right into bind()


dojo.io.UpdateNode()
dojo.io.encodeForm()

Dojo also has ability to Track back button and perform a underlying code before going to previous page.

dojo.ifx.*

includes many effects -fadeIn,fadeOut, fadeShow , fadeHide, wipeIn , wipeOut
slideout, explode,implode , highlight , unhighlight


Example of animation - one play after other

var anim1 = dojo.ifx.wipeOut("foo",300);
var anim2 = dojo.ifx.wipeOut("bar",500);
var composed =dojo.ifx.chain("anim1,anim2);

composed.play(300);

dojo.ifx.fadeOut(
["foo","bar","baz"],
300,
dojo.ifx.easeInOut
).play


4.Event System
Event system is runtime AOP ( aspect oriented programming in script ! )
can use before , after and around advice
Any function can be notified when any other function fires
Code

dojo.event.connect(obj1,"func1",
obj2,"func2");
obj1.func1();


5.Widget system
encapsulated , reusable ,rendering and behavour
most common dojo.widget.HtmlWidget

Other powerful widgets

RichTextEditor
ContentPanel
SplitPanel
Tabs
Fisheye List

Code
<script>
dojo.require("dojo.widget.Editor2");
</script>
<textarea dojoType="Editor2"></textarea>
can include more feauters
<textarea dojoType="Editor2" minHeight="400em" ...></textarea>

6.Custom Widgets
Very easy to create custom widgets


dojo.provide("dojo.widget.Foo");
dojo.require("dojo.widget.*");
dojo.widget.defineWidget(
"dojo.widget.Foo",
dojo.widget.HtmlWidth,
{
"widgetProp
templatesPath:"src/widget/templates/Foo.html
templatesCssPath:"src/widget/css/Foo.css"
}
);


HTML

<div dojoAttachpoint="domNode"
class="DojoFoo">
<em dojoOnClick="hide">Foo!<em>
</div>

CSS
.DojoFoo {
font-weight:bold;
}

7.Utilities ( advanced dojo )
dojo.event.topic
Acts as event bus for client side
decouple components
No worry initialization order
better contracts
ability to use funciton like connect()
arguments are passed as curbs to listener

Code
dojo.event.topic.publish("/name",Foo,Bar);
dojo.event.topic.subscribe(obj , "methodName");
dojo.event.topic.registerPublish(obj,"methodName");


dojo.gfx.Native2D
for native vector graphis


dojo.gfx
Drawing is done on "surfaces"
No declarative markup
shapes are added to surfaces - eclipse, group, image line , polyline, Rect
Matrix and colorspace utilities

x-domain i/0
dojo.io.ScriptSrcIO
support yahoo style JSON callbacks
support JSON-P
always async
plays directly to dojo.io.bind()


dojo.require("dojo.io.*");
dojo.require("dojo.io.ScriptSrcIO");
dojo.io.bind(
{
URI:"http://example.com/json.php"
transport:"scriptsrctransport"
jsonParamName:"callback"
Mimetype:"text/json"
content:{....}
});

dojo.rpc.YahooService
dojo.io.Xhrmlframeproxy
create your own service
doesnt rely on eval()
requires 2 files for cooperativing with external site - Data and Policy
request based enforcement
cross domain dojo
bust 2 connection limit on http
Improve cache-hit rates
load dojo entity asnc
Put dojo in context distributed environment
no copy locally - means less bandwith
Code
<script>
var djconfig ={
use xDomain:true;
baseLoaderUri:"http://foo.com/dojo",
xdWaitSeconds:10
};
</script>
<script src="http://foo.com/dojo/dojo.css"/>
<script>
dojo.setModulePrevix
("dojo","http://foo.com/dojo/src");
dojo.require("dojo.lang.*");
dojo.addonLoad(function1{....});
</script>

can be done by
<script href="download.dojotoolkit.org/dojo-0.4.1.js">
</script>
widget system internal
Event System
Non-browser bootstrap

Tuesday, August 25, 2009

JFreeChart - Easy way to include Graphics






I have used JFreeChart to setup some charts on my Web application . The app was built using J2EE framework . Example from my Project shown above, the code sample below shows the Aggregate image that's generated on the fly based on the input
Green - if percent is less than 33
Orange - if percent is less than 66
red - if percent is over 66


1 . Setting up , is fairly simple . Download the required files from http://www.jfree.org/jfreechart/download.html and include in the WEB-INF/lib directory . I have used 1.0.1 version.

2. Setup your utility class that generates the image on the fly ( Bar chart in this case ) . You have to go through the api's and do a lot of tries to get the image that works as per your specifications.
Here is the example code for the 3D graph , as shown in picture above

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import org.jfree.chart.ChartPanel;


/**
* Creates a 3D Graph bar based on the percent
*/
public class Treepercent extends ChartPanel {



public Treepercent(JFreeChart chart)
{
super(chart);
}


public static Treepercent createChart(String title,double dPercent,String sTree,String sFrac)
{
CategoryDataset dataset = createDataset(dPercent,sTree);
JFreeChart chart1 = createChart(dataset,sTree,dPercent,sFrac);
ChartPanel chartPanel = new ChartPanel(chart1, false);
chartPanel.setSize(new Dimension(50, 27));
chartPanel.setBounds(10,10,15,100);
//setContentPane(chartPanel);
Treepercent tp = new Treepercent(chart1);
return tp;
}


public static CategoryDataset createDataset(double dPercent,String sTree) {

// row keys...
String series1 = "First";

// column keys...
// String category1 = sTree;
String category1 = "";
// create the dataset...

DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(dPercent, series1, category1);
return dataset;

}

/**
* Creates a sample chart.
*
* @param dataset the dataset.
*
* @return The chart.
*/
public static JFreeChart createChart(CategoryDataset dataset, String sTree,double dPercent,String sFrac) {

// create the chart...
JFreeChart chart = ChartFactory.createBarChart3D(
"", // chart title
"", // domain axis label
"Aggregate "+String.valueOf(dPercent)+" Percent ("+ sFrac+")", // range axis label
dataset, // data
PlotOrientation.HORIZONTAL, // orientation
false, // include legend
true, // tooltips?
false // URLs?
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

// set the background color for the chart...
chart.setBackgroundPaint(Color.white);

// get a reference to the plot for further customisation...
CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setDomainGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.white);

// set the range axis to display integers only...
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setRange( 0.0D, 100D );
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

// disable bar outlines...
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(true);

//renderer.setLegendItemToolTipGenerator( new StandardCategorySeriesLabelGenerator( "Tooltip: {0}" ) );
// renderer.setBaseItemLabelsVisible(false);
// set up gradient paints for series...

GradientPaint gpGreen = new GradientPaint(
0.0f, 0.0f, new Color(0, 64, 0),
0.0f, 0.0f, new Color(0, 64, 0)
);

GradientPaint gpOrange = new GradientPaint(
0.0f, 0.0f, new Color(220, 124, 9),
0.0f, 0.0f, new Color(220, 124, 9)
);
GradientPaint gpRed= new GradientPaint(
0.0f, 0.0f, Color.red,
0.0f, 0.0f, Color.red
);

if (dPercent <= 33) renderer.setSeriesPaint(0, gpGreen); else if(dPercent <= 66) renderer.setSeriesPaint(0, gpOrange); else renderer.setSeriesPaint(0, gpRed); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLabel(""); domainAxis.setCategoryLabelPositions( CategoryLabelPositions.STANDARD ); // OPTIONAL CUSTOMISATION COMPLETED. return chart;
}

}


3. Next is to setup a servlet or a screen class that would generate the image . Remember the servlet the image itself as bytes .

import org.jfree.chart.ChartUtilities;
....

public class generatechart extends ... {

screenmethod (....)
{
ChartUtilities.writeChartAsJPEG( os, 100, Treepercent.createChart("Aggregate",dPer,"",sFrac).getChart(), 300, 75 );
// this create a chart based on the numbers sFranc
}
}


4. Setup a template a JSP or Velocity template , It will be a empty file .

5. Test if the image is generated