Monday, June 30, 2008
Simple RSS Reader
<html> <title>RSS Reader</title> <head> <script language="JavaScript">
var xmlHttp = null; var t_channel = 'channel'; var t_title = 'title'; var t_link = 'link'; var t_description = 'description';
var t_pubDate = 'pubDate' var t_lastBuildDate = 'lastBuildDate'
var t_item = 'item';
var t_tableHTML;
var objChannelNodeList;
// messages var NOT_A_VALID_RSS_FEED = 'Not a valid RSS Feed'; var GOT_ERROR = 'Got error please try again'; var GETTING_DATA = 'Getting Data Please wait';
// colors var CLR_PROCESSING="orange"; var CLR_ERROR="red"; var CLR_SUCCESS="green"; var CLR_BORDER="skyblue";
function getFirstChildText(objNode,tag){ if(objNode.getElementsByTagName(tag).length>0){ return objNode.getElementsByTagName(tag)[0].firstChild.nodeValue; }else{ return ' '; } }
function getRSSData(){ try{ if(xmlHttp.readyState==4){ t_tableHTML = '<table cellspacing="0" cellpadding="3" border="1" bordercolor='+CLR_BORDER+'>'; var resXML = xmlHttp.responseXML; if(!resXML){ throw NOT_A_VALID_RSS_FEED; } var objChannelNodeList = resXML.getElementsByTagName(t_channel); if(objChannelNodeList.length==0){ throw NOT_A_VALID_RSS_FEED; }
for(i=0;i<objChannelNodeList.length;i++){
var titleText = getFirstChildText(objChannelNodeList[i],t_title); var linkText = getFirstChildText(objChannelNodeList[i],t_link); var descText = getFirstChildText(objChannelNodeList[i],t_description); var publishDate = getFirstChildText(objChannelNodeList[i],t_pubDate); if(publishDate==''){ publishDate = getFirstChildText(objChannelNodeList[i],t_lastBuildDate); } if(publishDate!=''){ titleText = titleText + '[ <font color='+CLR_SUCCESS+'>' + publishDate + '</font> ]'; } constructRows(titleText,linkText,descText); for(j=0;j<objChannelNodeList[i].getElementsByTagName(t_item).length;j++){ var itemTitleText = getFirstChildText(objChannelNodeList[i].getElementsByTagName(t_item)[j],t_title); var itemLinkText = getFirstChildText(objChannelNodeList[i].getElementsByTagName(t_item)[j],t_link); var itemDescText = getFirstChildText(objChannelNodeList[i].getElementsByTagName(t_item)[j],t_description); constructRows(itemTitleText,itemLinkText,itemDescText);
}// end of : item for }// end of channel for
t_tableHTML = t_tableHTML + '</table>';
setText(t_tableHTML);
}else{// end of xml http ready state gettingDataPleaseWait(xmlHttp.readyState); } }catch(e){ gotErrorPleaseTry(e); } } function gettingDataPleaseWait(state){ t_tableHTML = '<table cellspacing="0" cellpadding="0" border="0">'; var t_txtMsg = GETTING_DATA; for(msgDots=0;msgDots<state;msgDots++){ t_txtMsg = t_txtMsg + ' ...'; } t_tableHTML = t_tableHTML + '<tr><td><font color='+CLR_PROCESSING+'>' + t_txtMsg + '</font></td></tr>'; t_tableHTML = t_tableHTML + '</table>';
setText(t_tableHTML); } function gotErrorPleaseTry(e){ t_tableHTML = '<table cellspacing="0" cellpadding="0" border="0">'; t_tableHTML = t_tableHTML + '<tr><td><font color='+CLR_ERROR+'>'; if(e){ if(e.message){ t_tableHTML = t_tableHTML + GOT_ERROR + ' [<b>' + e.message + '</b>]'; }else{ t_tableHTML = t_tableHTML + GOT_ERROR + ' [<b>' + e + '</b>]'; } }else{ t_tableHTML = t_tableHTML + GOT_ERROR; } t_tableHTML = t_tableHTML + '</font></td></tr>'; t_tableHTML = t_tableHTML + '</table>';
setText(t_tableHTML); } function constructRows(itemTitleText,itemLinkText,itemDescText){ t_tableHTML = t_tableHTML + '<tr>'; t_tableHTML = t_tableHTML + '<td><a href="' + itemLinkText + '">' + itemTitleText + '</a></td>'; if(!document.theForm.chkDebug.checked){ // trim images var t_tempDes = new String(itemDescText); itemDescText = t_tempDes.replace('<img','<imge'); }
t_tableHTML = t_tableHTML + '<td>' + itemDescText + '</td>'; t_tableHTML = t_tableHTML + '</tr>'; } function setText(strHtmlText){
document.getElementById('DisplayArea').innerHTML=''; document.getElementById('DisplayArea').innerHTML=strHtmlText;
} function startProcess() { try{ gettingDataPleaseWait(1); var runningUserAgent = new String(navigator.userAgent);
var URL=''; if(document.theForm.selURL.selectedIndex>0){ URL = document.theForm.selURL[document.theForm.selURL.selectedIndex].value; }else{ URL = document.theForm.txtURL.value; } // append some random number to avoid cache if(URL!=''){ URL = new String(URL) var curDate = new Date(); if(URL.indexOf("?")!=-1){ URL = URL + '&date=' + curDate.getTime(); }else{ URL = URL + '?date=' + curDate.getTime(); } }else{ throw 'Invalid URL' }
if(runningUserAgent.indexOf('MSIE')!=-1){//IE xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); if(!xmlHttp){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } else if(runningUserAgent.indexOf('Firefox')!=-1){ netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); xmlHttp=new XMLHttpRequest(); }else{ throw 'Currently supports only IE or Firefox' }
xmlHttp.open("GET",URL,true); xmlHttp.send(null);
if(xmlHttp!=null){ xmlHttp.onreadystatechange=getRSSData; }
}catch(e){ gotErrorPleaseTry(e) } }// end of : ajaxFunction function </script> </head> <body> <form name="theForm"> <div id="RSS Source Area">
<table cellspacing="0" cellpadding="0" border="0"> <tr> <td align="left"> <select name="selURL"> <option value="">Select RSS Feed</option> <option value="http://www.ibnlive.com/xml/top.xml">IBN Top Stories</option> <option value="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/latest_published_stories/rss.xml">BBC Latest</option>
<option value="http://www.ndtvprofit.com/RSS/SectionRssfeed.aspx?ts=Markets">NDTV Profit Business</option> </select> </td> <td> or </td> <td><input type="text" name="txtURL"></td> <td> </td> <td>Images : </td>
<td align="left"><input type="checkbox" name="chkDebug" value="1"></td> <td> </td> <td align="left"><input type="button" name="getRSS" value="Get Data" onClick="javaScript:startProcess();"/> </tr> </table> </div> <br/> <div id="DisplayArea"> </div>
</form> </body></html>
var xmlHttp = null; var t_channel = 'channel'; var t_title = 'title'; var t_link = 'link'; var t_description = 'description';
var t_pubDate = 'pubDate' var t_lastBuildDate = 'lastBuildDate'
var t_item = 'item';
var t_tableHTML;
var objChannelNodeList;
// messages var NOT_A_VALID_RSS_FEED = 'Not a valid RSS Feed'; var GOT_ERROR = 'Got error please try again'; var GETTING_DATA = 'Getting Data Please wait';
// colors var CLR_PROCESSING="orange"; var CLR_ERROR="red"; var CLR_SUCCESS="green"; var CLR_BORDER="skyblue";
function getFirstChildText(objNode,tag){ if(objNode.getElementsByTagName(tag).length>0){ return objNode.getElementsByTagName(tag)[0].firstChild.nodeValue; }else{ return ' '; } }
function getRSSData(){ try{ if(xmlHttp.readyState==4){ t_tableHTML = '<table cellspacing="0" cellpadding="3" border="1" bordercolor='+CLR_BORDER+'>'; var resXML = xmlHttp.responseXML; if(!resXML){ throw NOT_A_VALID_RSS_FEED; } var objChannelNodeList = resXML.getElementsByTagName(t_channel); if(objChannelNodeList.length==0){ throw NOT_A_VALID_RSS_FEED; }
for(i=0;i<objChannelNodeList.length;i++){
var titleText = getFirstChildText(objChannelNodeList[i],t_title); var linkText = getFirstChildText(objChannelNodeList[i],t_link); var descText = getFirstChildText(objChannelNodeList[i],t_description); var publishDate = getFirstChildText(objChannelNodeList[i],t_pubDate); if(publishDate==''){ publishDate = getFirstChildText(objChannelNodeList[i],t_lastBuildDate); } if(publishDate!=''){ titleText = titleText + '[ <font color='+CLR_SUCCESS+'>' + publishDate + '</font> ]'; } constructRows(titleText,linkText,descText); for(j=0;j<objChannelNodeList[i].getElementsByTagName(t_item).length;j++){ var itemTitleText = getFirstChildText(objChannelNodeList[i].getElementsByTagName(t_item)[j],t_title); var itemLinkText = getFirstChildText(objChannelNodeList[i].getElementsByTagName(t_item)[j],t_link); var itemDescText = getFirstChildText(objChannelNodeList[i].getElementsByTagName(t_item)[j],t_description); constructRows(itemTitleText,itemLinkText,itemDescText);
}// end of : item for }// end of channel for
t_tableHTML = t_tableHTML + '</table>';
setText(t_tableHTML);
}else{// end of xml http ready state gettingDataPleaseWait(xmlHttp.readyState); } }catch(e){ gotErrorPleaseTry(e); } } function gettingDataPleaseWait(state){ t_tableHTML = '<table cellspacing="0" cellpadding="0" border="0">'; var t_txtMsg = GETTING_DATA; for(msgDots=0;msgDots<state;msgDots++){ t_txtMsg = t_txtMsg + ' ...'; } t_tableHTML = t_tableHTML + '<tr><td><font color='+CLR_PROCESSING+'>' + t_txtMsg + '</font></td></tr>'; t_tableHTML = t_tableHTML + '</table>';
setText(t_tableHTML); } function gotErrorPleaseTry(e){ t_tableHTML = '<table cellspacing="0" cellpadding="0" border="0">'; t_tableHTML = t_tableHTML + '<tr><td><font color='+CLR_ERROR+'>'; if(e){ if(e.message){ t_tableHTML = t_tableHTML + GOT_ERROR + ' [<b>' + e.message + '</b>]'; }else{ t_tableHTML = t_tableHTML + GOT_ERROR + ' [<b>' + e + '</b>]'; } }else{ t_tableHTML = t_tableHTML + GOT_ERROR; } t_tableHTML = t_tableHTML + '</font></td></tr>'; t_tableHTML = t_tableHTML + '</table>';
setText(t_tableHTML); } function constructRows(itemTitleText,itemLinkText,itemDescText){ t_tableHTML = t_tableHTML + '<tr>'; t_tableHTML = t_tableHTML + '<td><a href="' + itemLinkText + '">' + itemTitleText + '</a></td>'; if(!document.theForm.chkDebug.checked){ // trim images var t_tempDes = new String(itemDescText); itemDescText = t_tempDes.replace('<img','<imge'); }
t_tableHTML = t_tableHTML + '<td>' + itemDescText + '</td>'; t_tableHTML = t_tableHTML + '</tr>'; } function setText(strHtmlText){
document.getElementById('DisplayArea').innerHTML=''; document.getElementById('DisplayArea').innerHTML=strHtmlText;
} function startProcess() { try{ gettingDataPleaseWait(1); var runningUserAgent = new String(navigator.userAgent);
var URL=''; if(document.theForm.selURL.selectedIndex>0){ URL = document.theForm.selURL[document.theForm.selURL.selectedIndex].value; }else{ URL = document.theForm.txtURL.value; } // append some random number to avoid cache if(URL!=''){ URL = new String(URL) var curDate = new Date(); if(URL.indexOf("?")!=-1){ URL = URL + '&date=' + curDate.getTime(); }else{ URL = URL + '?date=' + curDate.getTime(); } }else{ throw 'Invalid URL' }
if(runningUserAgent.indexOf('MSIE')!=-1){//IE xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); if(!xmlHttp){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } else if(runningUserAgent.indexOf('Firefox')!=-1){ netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); xmlHttp=new XMLHttpRequest(); }else{ throw 'Currently supports only IE or Firefox' }
xmlHttp.open("GET",URL,true); xmlHttp.send(null);
if(xmlHttp!=null){ xmlHttp.onreadystatechange=getRSSData; }
}catch(e){ gotErrorPleaseTry(e) } }// end of : ajaxFunction function </script> </head> <body> <form name="theForm"> <div id="RSS Source Area">
<table cellspacing="0" cellpadding="0" border="0"> <tr> <td align="left"> <select name="selURL"> <option value="">Select RSS Feed</option> <option value="http://www.ibnlive.com/xml/top.xml">IBN Top Stories</option> <option value="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/latest_published_stories/rss.xml">BBC Latest</option>
<option value="http://www.ndtvprofit.com/RSS/SectionRssfeed.aspx?ts=Markets">NDTV Profit Business</option> </select> </td> <td> or </td> <td><input type="text" name="txtURL"></td> <td> </td> <td>Images : </td>
<td align="left"><input type="checkbox" name="chkDebug" value="1"></td> <td> </td> <td align="left"><input type="button" name="getRSS" value="Get Data" onClick="javaScript:startProcess();"/> </tr> </table> </div> <br/> <div id="DisplayArea"> </div>
</form> </body></html>
Tuesday, June 17, 2008
Maven + Eclipse Java Project Setup Quick Steps
How to create a project .jar , .war file structure using Maven
1) Create a folder D:\mavenProject
2) Traverse to that Directory : CD D:\ mavenProject
3) Execute (for .jar): mvn archetype:create -DgroupId=com.abc.example -DartifactId=exampleLogic
4) Execute (for .war): mvn archetype:create -DgroupId=com.abc.example -DartifactId=exampleWeb -DarchetypeArtifactId=maven-archetype-webapp
Now we can independently build .jar and .war files by excecuting mvn celan install , command on respective folders.
i.e on D:\mavenProject\exampleLogic and D:\mavenProject\exampleWeb
The .jar file and .war file will be installed in the maven local repository.
Note : the maven local repository is configured in settings.xml located @ <maven Installaion directory>\conf
Say suppose our exampleLogic .jar is used in exampleWeb then we can add that as dependency in the .pom file of exampleWeb as follows
<dependency>
<groupId>com.abc.example</groupId>
<artifactId>exampleLogic</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
In this case first we have to build the .jar file and then we have to build the .war file
If the .jar file is not installed in the local maven repository and mvn clean install is executed on exampleWeb then we will receive an error.
If we want to run a single command to clean and install both the logic and web project we can create a .pom file in the D:\mavenProject as follows
<project>
<name>Maven Example</name>
<url>http://localhost:8080/</url>
<modelVersion>4.0.0</modelVersion>
<groupId>com.abc.example</groupId>
<version>1.0</version>
<artifactId>mavenExample</artifactId>
<packaging>pom</packaging>
<modules>
<module>exampleLogic</module>
<module>exampleWeb </module>
</modules>
</project>
How to configure the created project to work with eclipse.
1) Create a folder D:\workspaceExample
2) CD D:\mavenProject\exampleLogic : the following commands have to be executed from a folder having .pom file
3) Execute : mvn eclipse:add-maven-repo -Declipse.workspace=D:\workspaceExample
Note : This will create M2_REPO variable for the given workspace
4) Execute mvn -Dwtpversion=1.0 eclipse:eclipse from D:\mavenProject\exampleLogic
Note : This will create .class and .project files for Eclipse for ExampleLogic project.
5) Execute mvn -Dwtpversion=1.0 eclipse:eclipse from D:\mavenProject\exampleWeb
Note : This will create .class and .project files for Eclipse for ExampleLogic project.
6) Open the workspace (D:\workspaceExample) from eclipse
7) Select File > Import > General > Existing Projects into workspace
1) Create a folder D:\mavenProject
2) Traverse to that Directory : CD D:\ mavenProject
3) Execute (for .jar): mvn archetype:create -DgroupId=com.abc.example -DartifactId=exampleLogic
4) Execute (for .war): mvn archetype:create -DgroupId=com.abc.example -DartifactId=exampleWeb -DarchetypeArtifactId=maven-archetype-webapp
Now we can independently build .jar and .war files by excecuting mvn celan install , command on respective folders.
i.e on D:\mavenProject\exampleLogic and D:\mavenProject\exampleWeb
The .jar file and .war file will be installed in the maven local repository.
Note : the maven local repository is configured in settings.xml located @ <maven Installaion directory>\conf
Say suppose our exampleLogic .jar is used in exampleWeb then we can add that as dependency in the .pom file of exampleWeb as follows
<dependency>
<groupId>com.abc.example</groupId>
<artifactId>exampleLogic</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
In this case first we have to build the .jar file and then we have to build the .war file
If the .jar file is not installed in the local maven repository and mvn clean install is executed on exampleWeb then we will receive an error.
If we want to run a single command to clean and install both the logic and web project we can create a .pom file in the D:\mavenProject as follows
<project>
<name>Maven Example</name>
<url>http://localhost:8080/</url>
<modelVersion>4.0.0</modelVersion>
<groupId>com.abc.example</groupId>
<version>1.0</version>
<artifactId>mavenExample</artifactId>
<packaging>pom</packaging>
<modules>
<module>exampleLogic</module>
<module>exampleWeb </module>
</modules>
</project>
How to configure the created project to work with eclipse.
1) Create a folder D:\workspaceExample
2) CD D:\mavenProject\exampleLogic : the following commands have to be executed from a folder having .pom file
3) Execute : mvn eclipse:add-maven-repo -Declipse.workspace=D:\workspaceExample
Note : This will create M2_REPO variable for the given workspace
4) Execute mvn -Dwtpversion=1.0 eclipse:eclipse from D:\mavenProject\exampleLogic
Note : This will create .class and .project files for Eclipse for ExampleLogic project.
5) Execute mvn -Dwtpversion=1.0 eclipse:eclipse from D:\mavenProject\exampleWeb
Note : This will create .class and .project files for Eclipse for ExampleLogic project.
6) Open the workspace (D:\workspaceExample) from eclipse
7) Select File > Import > General > Existing Projects into workspace
Sunday, December 23, 2007
range validation in javascript
function rangeObject(minValue,maxValue){
this.minValue = minValue;
this.maxValue = maxValue;
this.getMinValue = function(){
return this.minValue;
}
this.getMaxValue = function(){
return this.maxValue;
}
this.validate = function(){
t_str_min = new String(this.minValue);
t_str_max = new String(this.maxValue);
t_str_min = t_str_min.replace(' ','');
t_str_max = t_str_max.replace(' ','');
if(t_str_min.length==0 ||
t_str_max.length==0){
return false;
}else if(isNaN(this.minValue) || isNaN(this.maxValue)){
return false;
}else{
this.minValue = parseInt(this.minValue);
this.maxValue = parseInt(this.maxValue);
if(this.minValue>this.maxValue){
return false;
}else{
return true;
}
}
}
this.isOverlaped = function(tRangeObject){
var secondMinValue = tRangeObject.getMinValue();
var secondMaxValue = tRangeObject.getMaxValue();
if((secondMinValue <= this.minValue &&
this.minValue <= secondMaxValue)
|| (secondMinValue <= this.maxValue &&
this.maxValue <= secondMaxValue)
|| (secondMinValue <= this.maxValue &&
this.maxValue <= secondMaxValue)
|| (this.minValue<=secondMinValue &&
this.maxValue >=secondMaxValue )){
return true;
}else{
return false;
}
}
this.getValues = function(){
return this.minValue + ' : ' + this.maxValue;
}
}
function checkOverlap(noOfRows){
var rangeObjectArray = new Array();
for(i=1;i<=noOfRows;i++){
var t_min = eval('document.theForm.' + 'rMIN_' + i).value;
var t_max = eval('document.theForm.' + 'rMAX_' + i).value;
var tempRangeObject = new rangeObject(t_min,t_max);
rangeObjectArray.push(tempRangeObject);
}
for(j=0;j < rangeObjectArray.length;j++){
var t_validStr='';
if(!rangeObjectArray[j].validate()){
t_validStr = t_validStr + 'values entered in row ' + (j+1) + ' not valid \n';
}
if(t_validStr!=''){
alert(t_validStr);
return false;
}
}
for(j=0;j < rangeObjectArray.length;j++){
for(k=j+1;k < rangeObjectArray.length;k++){
if(rangeObjectArray[j].isOverlaped(rangeObjectArray[k])){
alert(rangeObjectArray[j].getValues() + ' ::: ' + rangeObjectArray[k].getValues() + ' are overlapped');
return false;
}
}
}
return true;
}
this.minValue = minValue;
this.maxValue = maxValue;
this.getMinValue = function(){
return this.minValue;
}
this.getMaxValue = function(){
return this.maxValue;
}
this.validate = function(){
t_str_min = new String(this.minValue);
t_str_max = new String(this.maxValue);
t_str_min = t_str_min.replace(' ','');
t_str_max = t_str_max.replace(' ','');
if(t_str_min.length==0 ||
t_str_max.length==0){
return false;
}else if(isNaN(this.minValue) || isNaN(this.maxValue)){
return false;
}else{
this.minValue = parseInt(this.minValue);
this.maxValue = parseInt(this.maxValue);
if(this.minValue>this.maxValue){
return false;
}else{
return true;
}
}
}
this.isOverlaped = function(tRangeObject){
var secondMinValue = tRangeObject.getMinValue();
var secondMaxValue = tRangeObject.getMaxValue();
if((secondMinValue <= this.minValue &&
this.minValue <= secondMaxValue)
|| (secondMinValue <= this.maxValue &&
this.maxValue <= secondMaxValue)
|| (secondMinValue <= this.maxValue &&
this.maxValue <= secondMaxValue)
|| (this.minValue<=secondMinValue &&
this.maxValue >=secondMaxValue )){
return true;
}else{
return false;
}
}
this.getValues = function(){
return this.minValue + ' : ' + this.maxValue;
}
}
function checkOverlap(noOfRows){
var rangeObjectArray = new Array();
for(i=1;i<=noOfRows;i++){
var t_min = eval('document.theForm.' + 'rMIN_' + i).value;
var t_max = eval('document.theForm.' + 'rMAX_' + i).value;
var tempRangeObject = new rangeObject(t_min,t_max);
rangeObjectArray.push(tempRangeObject);
}
for(j=0;j < rangeObjectArray.length;j++){
var t_validStr='';
if(!rangeObjectArray[j].validate()){
t_validStr = t_validStr + 'values entered in row ' + (j+1) + ' not valid \n';
}
if(t_validStr!=''){
alert(t_validStr);
return false;
}
}
for(j=0;j < rangeObjectArray.length;j++){
for(k=j+1;k < rangeObjectArray.length;k++){
if(rangeObjectArray[j].isOverlaped(rangeObjectArray[k])){
alert(rangeObjectArray[j].getValues() + ' ::: ' + rangeObjectArray[k].getValues() + ' are overlapped');
return false;
}
}
}
return true;
}
Saturday, September 01, 2007
small sorting example in oralce pl/sql
PROCEDURE prc_test(a VARCHAR2)
IS
TYPE v_test IS TABLE OF VARCHAR2(2) INDEX BY VARCHAR2(2);
v_v_test v_test;
i VARCHAR2(2);
BEGIN
v_v_test('AB') := 'A';
v_v_test('AA') := 'C';
v_v_test('BA') := 'B';
--DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.COUNT);
--DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.FIRST);
--DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.LAST);
-- DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.NEXT(1));
-- DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.NEXT(2));
i := v_v_test.FIRST; -- get subscript of first element
DBMS_OUTPUT.PUT_LINE('test .... ' || i);
WHILE i IS NOT NULL LOOP
-- do something with courses(i)
i := v_v_test.NEXT(i); -- get subscript of next element
DBMS_OUTPUT.PUT_LINE('test .... ' || i);
END LOOP;
NULL;
END;
IS
TYPE v_test IS TABLE OF VARCHAR2(2) INDEX BY VARCHAR2(2);
v_v_test v_test;
i VARCHAR2(2);
BEGIN
v_v_test('AB') := 'A';
v_v_test('AA') := 'C';
v_v_test('BA') := 'B';
--DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.COUNT);
--DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.FIRST);
--DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.LAST);
-- DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.NEXT(1));
-- DBMS_OUTPUT.PUT_LINE('test .... ' || v_v_test.NEXT(2));
i := v_v_test.FIRST; -- get subscript of first element
DBMS_OUTPUT.PUT_LINE('test .... ' || i);
WHILE i IS NOT NULL LOOP
-- do something with courses(i)
i := v_v_test.NEXT(i); -- get subscript of next element
DBMS_OUTPUT.PUT_LINE('test .... ' || i);
END LOOP;
NULL;
END;
Saturday, March 17, 2007
oracle table , sys ref cursor usage in procedure
---------------------------------------------
getting values from a cursor to a table type
--------------------------------------------
-- following things can be defined in package specification
-- define record
TYPE studentDetails IS RECORD(
v_student_id NUMBER(8),
v_student_name VARCHAR2(25));
-- define table [nested table]
TYPE studentDetailsTab IS TABLE OF studentDetails INDEX BY BINARY_INTEGER;
-- followng things will be inside package body and inside a procedure in a declaration section
-- define a cursor
CURSOR cur_student_details(p_class_id NUMBER)
IS
SELECT student_id,
student_name
FROM student_table
WHERE class_id = p_class_id;
-- define a variable of type studentDetailsTab
v_t_studentDetailsTab studentDetailsTab;
-- follwoing things comes in the procedure body
-- open the cursor and fetch the values into the table type
OPEN cur_student_details(v_t_classid);
FETCH cur_student_details BULK COLLECT INTO v_t_studentDetailsTab;
CLOSE cur_student_details;
-- looping throgh the table type
IF v_t_studentDetailsTab.COUNT > 0 THEN
FOR tempIter IN v_t_studentDetailsTab.FIRST..v_t_studentDetailsTab.LAST
LOOP
DBMS_OUTPUT.PUT_LINE('student id ' || v_t_studentDetailsTab(tempIter).v_student_id);
DBMS_OUTPUT.PUT_LINE('student name ' || v_t_studentDetailsTab(tempIter).v_student_name);
END LOOP;
END IF;
--------------------------------------------------
getting values from a SYS_REFCURSOR to table type
--------------------------------------------------
-- cosider there is a function returnting the sys_refcursor in some other package
FUNCTION FNC_STUDENTDETAILS(p_class_id NUMBER,
p_sql_code OUT PLS_INTEGER,
p_sql_errm OUT VARCHAR2) RETURN sys_refcursor IS
v_cur_studentdetails sys_refcursor;
BEGIN
open v_cur_studentdetails FOR
SELECT student_id,
student_name
FROM student_table
WHERE class_id = p_class_id;
return v_cur_studentdetails;
END;
EXCEPTION
WHEN OTHERS THEN
p_sql_code := SQLCODE;
p_sql_errm := SQLERRM;
RETURN v_cur_studentdetails;
END FNC_STUDENTDETAILS;
-- how to use it
-- following things can be defined in package specification
-- define record
TYPE studentDetails IS RECORD(
v_student_id NUMBER(8),
v_student_name VARCHAR2(25));
-- define table [nested table]
TYPE studentDetailsTab IS TABLE OF studentDetails INDEX BY BINARY_INTEGER;
--- define the following in package body , package declaration section
v_t_student_details SYS_REFCURSOR;
v_t_studentDetailsTab studentDetailsTab;
-- call the following in the procdure body
v_t_student_details :=.FNC_STUDENTDETAILS(v_t_classid,p_errcd,p_errm);
-- fetch student details
FETCH v_t_student_details BULK COLLECT INTO v_t_studentDetailsTab;
-- we can check
IF v_t_student_details%NOTFOUND THEN
null; -- do some thing
END IF;
getting values from a cursor to a table type
--------------------------------------------
-- following things can be defined in package specification
-- define record
TYPE studentDetails IS RECORD(
v_student_id NUMBER(8),
v_student_name VARCHAR2(25));
-- define table [nested table]
TYPE studentDetailsTab IS TABLE OF studentDetails INDEX BY BINARY_INTEGER;
-- followng things will be inside package body and inside a procedure in a declaration section
-- define a cursor
CURSOR cur_student_details(p_class_id NUMBER)
IS
SELECT student_id,
student_name
FROM student_table
WHERE class_id = p_class_id;
-- define a variable of type studentDetailsTab
v_t_studentDetailsTab studentDetailsTab;
-- follwoing things comes in the procedure body
-- open the cursor and fetch the values into the table type
OPEN cur_student_details(v_t_classid);
FETCH cur_student_details BULK COLLECT INTO v_t_studentDetailsTab;
CLOSE cur_student_details;
-- looping throgh the table type
IF v_t_studentDetailsTab.COUNT > 0 THEN
FOR tempIter IN v_t_studentDetailsTab.FIRST..v_t_studentDetailsTab.LAST
LOOP
DBMS_OUTPUT.PUT_LINE('student id ' || v_t_studentDetailsTab(tempIter).v_student_id);
DBMS_OUTPUT.PUT_LINE('student name ' || v_t_studentDetailsTab(tempIter).v_student_name);
END LOOP;
END IF;
--------------------------------------------------
getting values from a SYS_REFCURSOR to table type
--------------------------------------------------
-- cosider there is a function returnting the sys_refcursor in some other package
FUNCTION FNC_STUDENTDETAILS(p_class_id NUMBER,
p_sql_code OUT PLS_INTEGER,
p_sql_errm OUT VARCHAR2) RETURN sys_refcursor IS
v_cur_studentdetails sys_refcursor;
BEGIN
open v_cur_studentdetails FOR
SELECT student_id,
student_name
FROM student_table
WHERE class_id = p_class_id;
return v_cur_studentdetails;
END;
EXCEPTION
WHEN OTHERS THEN
p_sql_code := SQLCODE;
p_sql_errm := SQLERRM;
RETURN v_cur_studentdetails;
END FNC_STUDENTDETAILS;
-- how to use it
-- following things can be defined in package specification
-- define record
TYPE studentDetails IS RECORD(
v_student_id NUMBER(8),
v_student_name VARCHAR2(25));
-- define table [nested table]
TYPE studentDetailsTab IS TABLE OF studentDetails INDEX BY BINARY_INTEGER;
--- define the following in package body , package declaration section
v_t_student_details SYS_REFCURSOR;
v_t_studentDetailsTab studentDetailsTab;
-- call the following in the procdure body
v_t_student_details :=
-- fetch student details
FETCH v_t_student_details BULK COLLECT INTO v_t_studentDetailsTab;
-- we can check
IF v_t_student_details%NOTFOUND THEN
null; -- do some thing
END IF;
using a oracle array type as out parameter in a stroed procedure and using that in java program
create types in oracle
1) create or replace TYPE IDHolderList IS TABLE OF NUMBER;
2) create public synonym S_IDHOLDERLIST for IDHOLDERLIST; -- incase of multiple schemas create this public synonym
3) write the procedure
PROCEDURE prc_test(v_IDList OUT s_IDHolderList)
IS
BEGIN -- START OF PROCEDURE
v_IDList.EXTEND;
v_IDList(v_IDList.COUNT) := 1;
v_IDList.EXTEND;
v_IDList(v_IDList.COUNT) := 2;
END prc_test;
4) java code
// sepcial imports needed
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import java.math.BigDecimal;
// sample code
Connection objConnection = getConnection();
OracleCallableStatement objCall = null;
objCall = (OracleCallableStatement)objConnection.prepareCall("call prc_test(?)");
objCall.registerOutParameter(3,OracleTypes.ARRAY,"S_IDHOLDERLIST");
objCall.execute();
ARRAY simpleArray = objCall.getARRAY(3);
if(simpleArray!=null){
BigDecimal[] values = (BigDecimal[])simpleArray.getArray();
}
few clarifications about oracle collection types
------------------------------------------------
PL/SQL offers these collection types:
Index-by tables, also known as associative arrays, let you look up elements using arbitrary numbers and strings for subscript values. (They are similar to hash tables in other programming languages.)
Nested tables hold an arbitrary number of elements. They use sequential numbers as subscripts. You can define equivalent SQL types, allowing nested tables to be stored in database tables and manipulated through SQL.
Varrays (short for variable-size arrays) hold a fixed number of elements (although you can change the number of elements at runtime). They use sequential numbers as subscripts. You can define equivalent SQL types, allowing varrays to be stored in database tables. They can be stored and retrieved through SQL, but with less flexibility than nested tables.
Arrays in other languages become VARRAYs in PL/SQL.
Sets and bags in other languages become nested tables in PL/SQL.
Hash tables and other kinds of unordered lookup tables in other languages become associative arrays in PL/SQL.
-------------
Choosing Between Nested Tables and Associative Arrays
Both nested tables and associative arrays (formerly known as index-by tables) use similar subscript notation, but they have different characteristics when it comes to persistence and ease of parameter passing.
Nested tables can be stored in a database column, but associative arrays cannot. Nested tables are appropriate for important data relationships that must be stored persistently.
Associative arrays are appropriate for relatively small lookup tables where the collection can be constructed in memory each time a procedure is called or a package is initialized. They are good for collecting information whose volume is unknown beforehand, because there is no fixed limit on their size. Their index values are more flexible, because associative array subscripts can be negative, can be nonsequential, and can use string values instead of numbers when appropriate.
PL/SQL automatically converts between host arrays and associative arrays that use numeric key values. The most efficient way to pass collections to and from the database server is to use anonymous PL/SQL blocks to bulk-bind input and output host arrays to associative arrays.
Choosing Between Nested Tables and Varrays
Varrays are a good choice when the number of elements is known in advance, and when the elements are usually all accessed in sequence. When stored in the database, varrays retain their ordering and subscripts.
Each varray is stored as a single object, either inside the table of which it is a column (if the varray is less than 4KB) or outside the table but still in the same tablespace (if the varray is greater than 4KB). You must update or retrieve all elements of the varray at the same time, which is most appropriate when performing some operation on all the elements at once. But you might find it impractical to store and retrieve large numbers of elements this way.
Nested tables can be sparse: you can delete arbitrary elements, rather than just removing an item from the end. Nested table data is stored out-of-line in a store table, a system-generated database table associated with the nested table. This makes nested tables suitable for queries and updates that only affect some elements of the collection. You cannot rely on the order and subscripts of a nested table remaining stable as the table is stored and retrieved, because the order and subscripts are not preserved when a nested table is stored in the database.
1) create or replace TYPE IDHolderList IS TABLE OF NUMBER;
2) create public synonym S_IDHOLDERLIST for IDHOLDERLIST; -- incase of multiple schemas create this public synonym
3) write the procedure
PROCEDURE prc_test(v_IDList OUT s_IDHolderList)
IS
BEGIN -- START OF PROCEDURE
v_IDList.EXTEND;
v_IDList(v_IDList.COUNT) := 1;
v_IDList.EXTEND;
v_IDList(v_IDList.COUNT) := 2;
END prc_test;
4) java code
// sepcial imports needed
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import java.math.BigDecimal;
// sample code
Connection objConnection = getConnection();
OracleCallableStatement objCall = null;
objCall = (OracleCallableStatement)objConnection.prepareCall("call prc_test(?)");
objCall.registerOutParameter(3,OracleTypes.ARRAY,"S_IDHOLDERLIST");
objCall.execute();
ARRAY simpleArray = objCall.getARRAY(3);
if(simpleArray!=null){
BigDecimal[] values = (BigDecimal[])simpleArray.getArray();
}
few clarifications about oracle collection types
------------------------------------------------
PL/SQL offers these collection types:
Index-by tables, also known as associative arrays, let you look up elements using arbitrary numbers and strings for subscript values. (They are similar to hash tables in other programming languages.)
Nested tables hold an arbitrary number of elements. They use sequential numbers as subscripts. You can define equivalent SQL types, allowing nested tables to be stored in database tables and manipulated through SQL.
Varrays (short for variable-size arrays) hold a fixed number of elements (although you can change the number of elements at runtime). They use sequential numbers as subscripts. You can define equivalent SQL types, allowing varrays to be stored in database tables. They can be stored and retrieved through SQL, but with less flexibility than nested tables.
Arrays in other languages become VARRAYs in PL/SQL.
Sets and bags in other languages become nested tables in PL/SQL.
Hash tables and other kinds of unordered lookup tables in other languages become associative arrays in PL/SQL.
-------------
Choosing Between Nested Tables and Associative Arrays
Both nested tables and associative arrays (formerly known as index-by tables) use similar subscript notation, but they have different characteristics when it comes to persistence and ease of parameter passing.
Nested tables can be stored in a database column, but associative arrays cannot. Nested tables are appropriate for important data relationships that must be stored persistently.
Associative arrays are appropriate for relatively small lookup tables where the collection can be constructed in memory each time a procedure is called or a package is initialized. They are good for collecting information whose volume is unknown beforehand, because there is no fixed limit on their size. Their index values are more flexible, because associative array subscripts can be negative, can be nonsequential, and can use string values instead of numbers when appropriate.
PL/SQL automatically converts between host arrays and associative arrays that use numeric key values. The most efficient way to pass collections to and from the database server is to use anonymous PL/SQL blocks to bulk-bind input and output host arrays to associative arrays.
Choosing Between Nested Tables and Varrays
Varrays are a good choice when the number of elements is known in advance, and when the elements are usually all accessed in sequence. When stored in the database, varrays retain their ordering and subscripts.
Each varray is stored as a single object, either inside the table of which it is a column (if the varray is less than 4KB) or outside the table but still in the same tablespace (if the varray is greater than 4KB). You must update or retrieve all elements of the varray at the same time, which is most appropriate when performing some operation on all the elements at once. But you might find it impractical to store and retrieve large numbers of elements this way.
Nested tables can be sparse: you can delete arbitrary elements, rather than just removing an item from the end. Nested table data is stored out-of-line in a store table, a system-generated database table associated with the nested table. This makes nested tables suitable for queries and updates that only affect some elements of the collection. You cannot rely on the order and subscripts of a nested table remaining stable as the table is stored and retrieved, because the order and subscripts are not preserved when a nested table is stored in the database.
struts validation
using struts validation frame work as well as the validation method in validatorform
=====================================================================================
1) add the validation rules in the validation framework
2) for more validations override the validation method of the ValidatorForm as follows
public ActionErrors validate(ActionMapping map,HttpServletRequest req){
// get the validation errors from the frame work
ActionErrors objActionErros = super.validate(map,req);
// start custom validations
String strPageNumber = req.getParameter("page");
if(strPageNumber!=null && !strPageNumber.eqlus("2")){
if(objActionErros==null){
objActionErros = new ActionErrors();
}
objActionErros.add("errors",new ActionError("errors.wrongpage"));// this key will be in the message resource file
}
return objActionErros;
}
=====================================================================================
1) add the validation rules in the validation framework
2) for more validations override the validation method of the ValidatorForm as follows
public ActionErrors validate(ActionMapping map,HttpServletRequest req){
// get the validation errors from the frame work
ActionErrors objActionErros = super.validate(map,req);
// start custom validations
String strPageNumber = req.getParameter("page");
if(strPageNumber!=null && !strPageNumber.eqlus("2")){
if(objActionErros==null){
objActionErros = new ActionErrors();
}
objActionErros.add("errors",new ActionError("errors.wrongpage"));// this key will be in the message resource file
}
return objActionErros;
}
Quality process
------------------
A) Proposal STAGE
------------------
1) proposal
2) Estimation [can use functional point estimation] [consider fixed bid , time and management]
-------------------------------------------------------
B) Once Proposal/Estimation is approved start Analysis
-------------------------------------------------------
1) prepare the document for project [called as PDSP] , which contains details about harware requirements,
configuration management tool , Quaility person ,Quality audit frequencey, other trimmings for the quality
policy of the company in specific to the project
2) should start maintaining the Trancebility matrix [horizantal , vertical tracebility matrix]
horizantal will contain functional points against deliverables [HLD,SRS,LLDs,UTCs,ITCs,STCs]
Vertical will contain functional points against functional points to get an idea of impact of change
in one functionality on other
3) preparing check lists for variuos artifacts
4) Software requirement specification [SRS]
----------------------------------------------
C) Once architecture is approved start Design
----------------------------------------------
1) High Level Document [Architecture] [HLD]
2) If one have to choose between technologies one has to prepare a sheet for comparing them for taking a decision
the reoport is called Decision Analysis Report [DAR]
3) Low Level Document [should be done for all the use cases]
4) Unit Test Cases
5) Integration Test Cases[integrating modules or with other projects]
6) System Test Cases [functionality test cases]
----------------------------------------------
D) Once Design is approved start Construction
----------------------------------------------
1) coding , code review
2) unit testing , capturing unit test results
------------------------------------------
D) Once construction is done start testing
------------------------------------------
1) integration testing , capture results , raise defects , fix and release
2) system testing , capture results , raise defects , fix and release
3) user acceptance testing , capture results , raise defects , fix and release
Each one of the above should follow the following steps
i) Preparation
ii) each artifcat will have a check list, the check list has to be filled with self review
iii)external Review [in some cases it will goto SME (System Mater Expert) review ]
iv) all the review/testing defects should be captured and fixed
v) Rework [again goes back to review/testing until every thing is ok]
vi) Each deliverable should go after FIR (Final Inspection Report) from Quality person
Vii) after each page there will be a casual analysis meeting for discussing where more
defects are coming and how to reduce them [training or adding items to check lists etc]
and the strategy for the upcoming phase
Viii) every discussion either with customer or internal should have Minutes of Meeting and open items for action captured
ix) every artifact , evidence (like customer mail , Minutes of meeting) should be in configuration management tool
x) In the above Phases one should ensure to get the best practices , resuable components.
-------------------------------------------------------
E) Once UAT (user acceptence) is done start Maintanance
-------------------------------------------------------
1) raising tickets , closing , tracking time
A) Proposal STAGE
------------------
1) proposal
2) Estimation [can use functional point estimation] [consider fixed bid , time and management]
-------------------------------------------------------
B) Once Proposal/Estimation is approved start Analysis
-------------------------------------------------------
1) prepare the document for project [called as PDSP] , which contains details about harware requirements,
configuration management tool , Quaility person ,Quality audit frequencey, other trimmings for the quality
policy of the company in specific to the project
2) should start maintaining the Trancebility matrix [horizantal , vertical tracebility matrix]
horizantal will contain functional points against deliverables [HLD,SRS,LLDs,UTCs,ITCs,STCs]
Vertical will contain functional points against functional points to get an idea of impact of change
in one functionality on other
3) preparing check lists for variuos artifacts
4) Software requirement specification [SRS]
----------------------------------------------
C) Once architecture is approved start Design
----------------------------------------------
1) High Level Document [Architecture] [HLD]
2) If one have to choose between technologies one has to prepare a sheet for comparing them for taking a decision
the reoport is called Decision Analysis Report [DAR]
3) Low Level Document [should be done for all the use cases]
4) Unit Test Cases
5) Integration Test Cases[integrating modules or with other projects]
6) System Test Cases [functionality test cases]
----------------------------------------------
D) Once Design is approved start Construction
----------------------------------------------
1) coding , code review
2) unit testing , capturing unit test results
------------------------------------------
D) Once construction is done start testing
------------------------------------------
1) integration testing , capture results , raise defects , fix and release
2) system testing , capture results , raise defects , fix and release
3) user acceptance testing , capture results , raise defects , fix and release
Each one of the above should follow the following steps
i) Preparation
ii) each artifcat will have a check list, the check list has to be filled with self review
iii)external Review [in some cases it will goto SME (System Mater Expert) review ]
iv) all the review/testing defects should be captured and fixed
v) Rework [again goes back to review/testing until every thing is ok]
vi) Each deliverable should go after FIR (Final Inspection Report) from Quality person
Vii) after each page there will be a casual analysis meeting for discussing where more
defects are coming and how to reduce them [training or adding items to check lists etc]
and the strategy for the upcoming phase
Viii) every discussion either with customer or internal should have Minutes of Meeting and open items for action captured
ix) every artifact , evidence (like customer mail , Minutes of meeting) should be in configuration management tool
x) In the above Phases one should ensure to get the best practices , resuable components.
-------------------------------------------------------
E) Once UAT (user acceptence) is done start Maintanance
-------------------------------------------------------
1) raising tickets , closing , tracking time
Sunday, September 17, 2006
General Talk about Java Memory
Basically Heap and Stack are the same thing. The difference is how they are used/accessed. They both are an area of memory where you store something. With a heap, you access what you are storing in any order you want and they stay there until you remove them.
With a stack, you normally access them in the reverse order you put them on the stack and they are automatically removed as you access them.
Both of 'em are sources from which memory is allocated. Stack is automatic, which is created when memory is in scope, and destroyed when it is out of scope. Heap is manual and created and destroyed when requested. On stack, the local variables (unless they are static or register data members), function parameters are stored on stack. On heap normally global variables, static local variables, any data allocated by using calls like new will be stored.
---------------------
jre=jvm+some classes(like awt,swing...)
and if u wonder what is the use of providing jre...the answer is if u develop an application in java and u want to give it to the client then u also need to provide runtime environment also so jre is given for redistribution to the clients to whoom u make a s/w product...
jre= targeted for execution i.e. jvm+some classes(like awt,swing...)+runtime libraries.
jdk= mainly targeted for java development i.e. compilation (javac+others) + jvm + libraries.
u can find jvm in both jre and jdk.
-----------------------
We conclude our discussion of storage class and scope by breifly describing how the memory of the computer is organized for a running program. When a program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment, and heap segment. The text segment (sometimes also called the code segment) is where the compiled code of the program itself resides. This is the machine language representation of the program steps to be carried out, including all functions making up the program, both user defined and system.
The remaining two areas of system memory is where storage may be allocated by the compiler for data storage. The stack is where memory is allocated for automatic variables within functions. A stack is a Last In First Out (LIFO) storage device where new storage is allocated and deallocated at only one ``end'', called the Top of the stack.
When a program begins executing in the function main(), space is allocated on the stack for all variables declared within main(). If main() calls a function, func1(), additional storage is allocated for the variables in func1() at the top of the stack. Notice that the parameters passed by main() to func1() are also stored on the stack. If func1() were to call any additional functions, storage would be allocated at the new Top of stack. When func1() returns, storage for its local variables is deallocated, and the Top of the stack returns to to position. If main() were to call another function, storage would be allocated for that function at the Top. As can be seen, the memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage.
The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.
------------------------------------------------------------------------------------------------
ref : http://java.sun.com/docs/books/vmspec/2nd-edition/html/Overview.doc.html
Runtime Data Areas
------------------
The Java virtual machine defines various runtime data areas that are used during execution of a program. Some of these data areas are created on Java virtual machine start-up and are destroyed only when the Java virtual machine exits. Other data areas are per thread. Per-thread data areas are created when a thread is created and destroyed when the thread exits.
The pc Register
---------------
The Java virtual machine can support many threads of execution at once. Each Java virtual machine thread has its own pc (program counter) register. At any point, each Java virtual machine thread is executing the code of a single method, the current method for that thread. If that method is not native, the pc register contains the address of the Java virtual machine instruction currently being executed. If the method currently being executed by the thread is native, the value of the Java virtual machine's pc register is undefined. The Java virtual machine's pc register is wide enough to hold a returnAddress or a native pointer on the specific platform.
Java Virtual Machine Stacks
---------------------------
Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread.A Java virtual machine stack stores frames.it holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java virtual machine stack does not need to be contiguous.
The Java virtual machine stack size limit may be set on virtual machine start-up using the "-oss" flag. The Java virtual machine stack size limit can be used to limit memory consumption or to catch runaway recursions.
The following exceptional conditions are associated with Java virtual machine stacks:
If the computation in a thread requires a larger Java virtual machine stack than is permitted, the Java virtual machine throws a StackOverflowError.
If Java virtual machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java virtual machine stack for a new thread, the Java virtual machine throws an OutOfMemoryError.
Heap
----
The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated.
The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.
A Java virtual machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size(start-up using the "-ms" and "-mx")
The following exceptional condition is associated with the heap:
If a computation requires more heap than can be made available by the automatic storage management system, the Java virtual machine throws an OutOfMemoryError.
Method Area
-----------
The Java virtual machine has a method area that is shared among all Java virtual machine threads. The method area is analogous to the storage area for compiled code of a conventional language or analogous to the "text" segment in a UNIX process.
The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it.
The following exceptional condition is associated with the method area:
If memory in the method area cannot be made available to satisfy an allocation request, the Java virtual machine throws an OutOfMemoryError.
Runtime Constant Pool
---------------------
A runtime constant pool is a per-class or per-interface runtime representation of the constant_pool table in a class file.
It contains several kinds of constants, ranging from numeric literals known at compile time to method and field references that must be resolved at run time. The runtime constant pool serves a function similar to that of a symbol table for a conventional programming language, although it contains a wider range of data than a typical symbol table.
Native Method Stacks
--------------------
An implementation of the Java virtual machine may use conventional stacks, colloquially called "C stacks," to support native methods, methods written in a language other than the Java programming language.
Frames
------
A frame is used to store data and partial results, as well as to perform dynamic linking , return values for methods, and dispatch exceptions.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception). Frames are allocated from the Java virtual machine stack of the thread creating the frame. Each frame has its own array of local variables,its own operand stack, and a reference to the runtime constant pool of the class of the current method.
Note that a frame created by a thread is local to that thread and cannot be referenced by any other thread.
The ClassFile Structure
-----------------------
A class file consists of a single ClassFile structure:
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
u2 constant_pool_count;
cp_info constant_pool[constant_pool_count-1];
u2 access_flags;
u2 this_class;
u2 super_class;
u2 interfaces_count;
u2 interfaces[interfaces_count];
u2 fields_count;
field_info fields[fields_count];
u2 methods_count;
method_info methods[methods_count];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
Virtual Machine Start-up
------------------------
The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader. The Java virtual machine then links the initial class, initializes it, and invokes its public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.
Threads
-------
To synchronize threads the language uses monitors, a mechanism for allowing one thread at a time to execute a region of code. The behavior of monitors is explained in terms of locks. There is a lock associated with each object.
The synchronized statement performs two special actions relevant only to multithreaded operation:
After computing a reference to an object but before executing its body, it locks a lock associated with the object.
After execution of the body has completed, either normally or abruptly, it unlocks that same lock. As a convenience, a method may be declared synchronized; such a method behaves as if its body were contained in a synchronized statement.
Threads
-------
A variable is any location within a program that may be stored into. This includes not only class variables and instance variables, but also components of arrays. Variables are kept in a main memory that is shared by all threads. Because it is impossible for one thread to access parameters or local variables of another thread, it does not matter whether parameters and local variables are thought of as residing in the shared main memory or in the working memory of the thread that owns them.
Every thread has a working memory in which it keeps its own working copy of variables that it must use or assign. As the thread executes a program, it operates on these working copies. The main memory contains the master copy of every variable. There are rules about when a thread is permitted or required to transfer the contents of its working copy of a variable into the master copy or vice versa.
check the link : http://java.sun.com/docs/books/vmspec/2nd-edition/html/Threads.doc.html
Book : The JavaTM Virtual Machine Specification, Second Edition
With a stack, you normally access them in the reverse order you put them on the stack and they are automatically removed as you access them.
Both of 'em are sources from which memory is allocated. Stack is automatic, which is created when memory is in scope, and destroyed when it is out of scope. Heap is manual and created and destroyed when requested. On stack, the local variables (unless they are static or register data members), function parameters are stored on stack. On heap normally global variables, static local variables, any data allocated by using calls like new will be stored.
---------------------
jre=jvm+some classes(like awt,swing...)
and if u wonder what is the use of providing jre...the answer is if u develop an application in java and u want to give it to the client then u also need to provide runtime environment also so jre is given for redistribution to the clients to whoom u make a s/w product...
jre= targeted for execution i.e. jvm+some classes(like awt,swing...)+runtime libraries.
jdk= mainly targeted for java development i.e. compilation (javac+others) + jvm + libraries.
u can find jvm in both jre and jdk.
-----------------------
We conclude our discussion of storage class and scope by breifly describing how the memory of the computer is organized for a running program. When a program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment, and heap segment. The text segment (sometimes also called the code segment) is where the compiled code of the program itself resides. This is the machine language representation of the program steps to be carried out, including all functions making up the program, both user defined and system.
The remaining two areas of system memory is where storage may be allocated by the compiler for data storage. The stack is where memory is allocated for automatic variables within functions. A stack is a Last In First Out (LIFO) storage device where new storage is allocated and deallocated at only one ``end'', called the Top of the stack.
When a program begins executing in the function main(), space is allocated on the stack for all variables declared within main(). If main() calls a function, func1(), additional storage is allocated for the variables in func1() at the top of the stack. Notice that the parameters passed by main() to func1() are also stored on the stack. If func1() were to call any additional functions, storage would be allocated at the new Top of stack. When func1() returns, storage for its local variables is deallocated, and the Top of the stack returns to to position. If main() were to call another function, storage would be allocated for that function at the Top. As can be seen, the memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage.
The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.
------------------------------------------------------------------------------------------------
ref : http://java.sun.com/docs/books/vmspec/2nd-edition/html/Overview.doc.html
Runtime Data Areas
------------------
The Java virtual machine defines various runtime data areas that are used during execution of a program. Some of these data areas are created on Java virtual machine start-up and are destroyed only when the Java virtual machine exits. Other data areas are per thread. Per-thread data areas are created when a thread is created and destroyed when the thread exits.
The pc Register
---------------
The Java virtual machine can support many threads of execution at once. Each Java virtual machine thread has its own pc (program counter) register. At any point, each Java virtual machine thread is executing the code of a single method, the current method for that thread. If that method is not native, the pc register contains the address of the Java virtual machine instruction currently being executed. If the method currently being executed by the thread is native, the value of the Java virtual machine's pc register is undefined. The Java virtual machine's pc register is wide enough to hold a returnAddress or a native pointer on the specific platform.
Java Virtual Machine Stacks
---------------------------
Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread.A Java virtual machine stack stores frames.it holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java virtual machine stack does not need to be contiguous.
The Java virtual machine stack size limit may be set on virtual machine start-up using the "-oss" flag. The Java virtual machine stack size limit can be used to limit memory consumption or to catch runaway recursions.
The following exceptional conditions are associated with Java virtual machine stacks:
If the computation in a thread requires a larger Java virtual machine stack than is permitted, the Java virtual machine throws a StackOverflowError.
If Java virtual machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java virtual machine stack for a new thread, the Java virtual machine throws an OutOfMemoryError.
Heap
----
The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated.
The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.
A Java virtual machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size(start-up using the "-ms" and "-mx")
The following exceptional condition is associated with the heap:
If a computation requires more heap than can be made available by the automatic storage management system, the Java virtual machine throws an OutOfMemoryError.
Method Area
-----------
The Java virtual machine has a method area that is shared among all Java virtual machine threads. The method area is analogous to the storage area for compiled code of a conventional language or analogous to the "text" segment in a UNIX process.
The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it.
The following exceptional condition is associated with the method area:
If memory in the method area cannot be made available to satisfy an allocation request, the Java virtual machine throws an OutOfMemoryError.
Runtime Constant Pool
---------------------
A runtime constant pool is a per-class or per-interface runtime representation of the constant_pool table in a class file.
It contains several kinds of constants, ranging from numeric literals known at compile time to method and field references that must be resolved at run time. The runtime constant pool serves a function similar to that of a symbol table for a conventional programming language, although it contains a wider range of data than a typical symbol table.
Native Method Stacks
--------------------
An implementation of the Java virtual machine may use conventional stacks, colloquially called "C stacks," to support native methods, methods written in a language other than the Java programming language.
Frames
------
A frame is used to store data and partial results, as well as to perform dynamic linking , return values for methods, and dispatch exceptions.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception). Frames are allocated from the Java virtual machine stack of the thread creating the frame. Each frame has its own array of local variables,its own operand stack, and a reference to the runtime constant pool of the class of the current method.
Note that a frame created by a thread is local to that thread and cannot be referenced by any other thread.
The ClassFile Structure
-----------------------
A class file consists of a single ClassFile structure:
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
u2 constant_pool_count;
cp_info constant_pool[constant_pool_count-1];
u2 access_flags;
u2 this_class;
u2 super_class;
u2 interfaces_count;
u2 interfaces[interfaces_count];
u2 fields_count;
field_info fields[fields_count];
u2 methods_count;
method_info methods[methods_count];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
Virtual Machine Start-up
------------------------
The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader. The Java virtual machine then links the initial class, initializes it, and invokes its public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.
Threads
-------
To synchronize threads the language uses monitors, a mechanism for allowing one thread at a time to execute a region of code. The behavior of monitors is explained in terms of locks. There is a lock associated with each object.
The synchronized statement performs two special actions relevant only to multithreaded operation:
After computing a reference to an object but before executing its body, it locks a lock associated with the object.
After execution of the body has completed, either normally or abruptly, it unlocks that same lock. As a convenience, a method may be declared synchronized; such a method behaves as if its body were contained in a synchronized statement.
Threads
-------
A variable is any location within a program that may be stored into. This includes not only class variables and instance variables, but also components of arrays. Variables are kept in a main memory that is shared by all threads. Because it is impossible for one thread to access parameters or local variables of another thread, it does not matter whether parameters and local variables are thought of as residing in the shared main memory or in the working memory of the thread that owns them.
Every thread has a working memory in which it keeps its own working copy of variables that it must use or assign. As the thread executes a program, it operates on these working copies. The main memory contains the master copy of every variable. There are rules about when a thread is permitted or required to transfer the contents of its working copy of a variable into the master copy or vice versa.
check the link : http://java.sun.com/docs/books/vmspec/2nd-edition/html/Threads.doc.html
Book : The JavaTM Virtual Machine Specification, Second Edition
MS SQL SERVER PROCEDURE FOR TREE STRUCTURE
This MS SQL SERVER procedure is used to get the list of all children , childrens children so on... for a given parent
CREATE PROCEDURE TEST
@id numeric(10)
AS
begin
create table #temp(parentid numeric(10) , level int,process bit,root numeric(10))
-- 0 level
insert into #temp values(@id,0,0,0)
declare @level int
set @level=0
select top 1 @id = parentid from #temp where level = @level and process=0;
while(@id is not null)
begin
update #temp set process =1 where parentid = @id and level = @level and process = 0;
insert into #temp select GRP_ID_N,@level+1,0,@id from USR_GRPS where parent_grp_id_n = @id
select top 1 @id = parentid from #temp where level = @level and process=0;
if @@rowcount = 0
begin
set @id = null
set @level = @level + 1
select top 1 @id = parentid from #temp where level = @level and process=0;
end
end
select * from #temp
end
CREATE PROCEDURE TEST
@id numeric(10)
AS
begin
create table #temp(parentid numeric(10) , level int,process bit,root numeric(10))
-- 0 level
insert into #temp values(@id,0,0,0)
declare @level int
set @level=0
select top 1 @id = parentid from #temp where level = @level and process=0;
while(@id is not null)
begin
update #temp set process =1 where parentid = @id and level = @level and process = 0;
insert into #temp select GRP_ID_N,@level+1,0,@id from USR_GRPS where parent_grp_id_n = @id
select top 1 @id = parentid from #temp where level = @level and process=0;
if @@rowcount = 0
begin
set @id = null
set @level = @level + 1
select top 1 @id = parentid from #temp where level = @level and process=0;
end
end
select * from #temp
end
Monday, August 07, 2006
Working with Oracle , JAVA Array Types
1) create an array type in oracle
----------------------------------
create or replace type NUM_ARRAY as table of number(10);
2)create oracle procedure
--------------------------
CREATE OR REPLACE PROCEDURE TEST_procedure(p_array in num_array,ERR_MSG OUT VARCHAR2)
IS
BEGIN
for i in 1 .. p_array.count
loop
insert into TESTTABLE values('T' || i,'TEST');
end loop;
commit;
EXCEPTION
WHEN OTHERS THEN
BEGIN
ROLLBACK;
ERR_MSG := SQLERRM(SQLCODE);-- send the error message back if there any exeptions.
END;
END;
3)java program
---------------
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.driver.OraclePreparedStatement;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import org.hibernate.HibernateException;
public class CallSP{
public static void main(String args[]){
try {
int intArray[] = { 1,2,3,4,5,6 };
// from any connection pool get the connection
Connection conn =HibernateUtil.currentSession().connection();
OraclePreparedStatement ps =
(OraclePreparedStatement)conn.prepareStatement
( "begin TEST_procedure(:x,:outparam); end;" );
ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor( "NUM_ARRAY", ps.getConnection());
ARRAY array_to_pass = new ARRAY( descriptor, conn, intArray );
ps.setARRAY( 1, array_to_pass );
ps.registerOutParameter(2,Types.VARCHAR);
ps.execute();
String strResult = ps.getString(2);
} catch (HibernateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}// end of : CallSP class
----------------------------------
create or replace type NUM_ARRAY as table of number(10);
2)create oracle procedure
--------------------------
CREATE OR REPLACE PROCEDURE TEST_procedure(p_array in num_array,ERR_MSG OUT VARCHAR2)
IS
BEGIN
for i in 1 .. p_array.count
loop
insert into TESTTABLE values('T' || i,'TEST');
end loop;
commit;
EXCEPTION
WHEN OTHERS THEN
BEGIN
ROLLBACK;
ERR_MSG := SQLERRM(SQLCODE);-- send the error message back if there any exeptions.
END;
END;
3)java program
---------------
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.driver.OraclePreparedStatement;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import org.hibernate.HibernateException;
public class CallSP{
public static void main(String args[]){
try {
int intArray[] = { 1,2,3,4,5,6 };
// from any connection pool get the connection
Connection conn =HibernateUtil.currentSession().connection();
OraclePreparedStatement ps =
(OraclePreparedStatement)conn.prepareStatement
( "begin TEST_procedure(:x,:outparam); end;" );
ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor( "NUM_ARRAY", ps.getConnection());
ARRAY array_to_pass = new ARRAY( descriptor, conn, intArray );
ps.setARRAY( 1, array_to_pass );
ps.registerOutParameter(2,Types.VARCHAR);
ps.execute();
String strResult = ps.getString(2);
} catch (HibernateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}// end of : CallSP class
Subscribe to Comments [Atom]