Web Developmet Articles: Recent Technologies and Concepts

by JustEtc Publications Ltd




Distributed by justEtc

Layouts with CSS: Layout without tables



Two column webpage layout with CSS

create twocol.css. Then, add the following code to the file:

div#topBanner { text-align: center; padding-bottom: 10px; }
div#bodyLeft { position: absolute; width: 25%; }
div#bodyRight { margin: 5px 25px 25px 225px; width: 75%; }

Your two column webpage will look like

<head>

<link rel="stylesheet" href="twocol.css" type="text/css">

</head>

<body>

<div id="topBanner">Page Title</div>
<div id="bodyLeft">Add menu items here</div>
<div id="bodyRight">Add your content here</div>
</body>

Three column webpage with CSS

Create a file like threecol.css. Put the following code

div#bodyLeft { position: absolute; padding-left: 10px; width: 25%; }
div#bodyCenter { margin-left: 190px; margin-right: 190px; width: 50%; position: absolute; }
div#bodyRight { position: absolute; padding-right: 10px; width: 25%; right: 0%; }
div#topBanner { text-align: center; padding-bottom: 15px; }

Your three column webpage will look as follows

<div id="topBanner">Page Title</div>
<div id="bodyLeft">Add menu items here</div>
<div id="bodyCenter">Add your content here</div>
<div id="bodyRight">Add your content here</div>

Then, add your text and/or graphics to the file.



Table Less Design: Layouts with CSS



A three column webpage with CSS positioning
    
<div id="leftnavigation"></div> <div id="rightnavigation"></div> <div id="content"></div>
The CSS should look like this:
#leftnavigation { position : absolute; left : 0; width : 150px; margin-left : 10px; margin-top : 20px; color : #000000; padding : 3px; } #rightnavigation { position : absolute; left : 80%; top : 20px; width : 140px; padding-left : 10px; z-index : 3; color : #000000; padding : 3px; } #content { top : 0px; margin : 0px 25% 0 165px; padding : 3px; color : #000000; }
----------

More CSS Layouts:



Three Column layout with header and footer: The CSS
html, body { margin: 0; padding: 0; }
#header {
  width: 800px;
  float: left;
}
#maincontainer {
  width: 800px;
  float: left;
}
#nav {
  width: 200px;
  float: left;
}
#main {
  float: right;
  width: 600px;
}
#footer {
  width: 800px;
  float: left;
}


The XHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>2 Column Header and Footer Layout</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div id="header"><h1>Header</h1></div>
<div id="maincontainer">
<div id="main">
<p>Whee</p>
<p>
</div>
<div id="nav">
<ul>
<li><a href="">Link</a></li>
<li><a href="">Link</a></li>
<li><a href="">Link</a></li>
<li><a href="">Link</a></li>
</ul>
</div>
</div>
<div id="footer"><h4>Footer</h4></div>
</body>
</html>


Web page design standards



Try to follow the following rules while creating a web-page.
1. Decide what you want to use HTML or XHTML. Better to go
with XHTML. Which XHTML? Strict or transitional? Go for
strict one, that way you will be in the most standard way.

2. If you are new into XHTML try transitional first, when you are
comfortable in Transitional style, switch to Strict.
Rememebr, strict will not support many non-standard tags
and coding you usually use, so it may sound a bit difficult.

3. Some XHTML rules
a. Simply use a Doctype.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> b. Use lower case for all tags
c. enclose all attribute values
d. close all tags even <hr/> <br/>
e. Try to use css for layout
f. Even assign values to empty attributes like checked='checked', readonly='true'
g. nest attributes correctly

4. Page Layout
Most recent and most standard way is to use pure css (div,span tags) to create page layouts
However, not all browsers are that advanced. With css layout horizontal alignment is problemetic.
Also, placing page footers in the right place becomes difficult.

A good way is, try css first. If you face problems use tables for the outer layout and for internal layout (under the table) never use tables just use css(div). Use table internally only to display tabular data not for layout.

5. Always use both id and name tags. use id tag before name tag.
6. For javascript use Use the Document.getElementById DOM that is compatible in all browsers
7. Always use attributes or set properties in div tag not in the td tag when you use div inside td. But use valign on the td, it does not work with div

Page layout with minimal use of table

<table>
	<tr>
		<td colspan="2">
			<div class="header">
			Header
			</div>
		</td>
	</tr>
	<tr>
		<td>
			<div class="navigation">
			Navigation
			</div>
		</td>
		<td>
			<div class="content">
			Content
			</div>
		</td>
	</tr>
	<tr>
		<td colspan="2" style="vertical-align: bottom">
			<div class="footer">
			Footer
			</div>
		</td>
	</tr>
</table>
8. <center> is deprecated and centering a block in css is difficult. So rather use the following css



div.container {
text-align: center;
}

div.text {
margin-left: auto;
margin-right: auto;
text-align: left; /* overrule inheritance */

}





What you really need to learn in Javascript?



What you really need to learn in Javascript? 
1. Where you can place JavaScript codes?
2. Some basic programming:
<script language="javascript" type="text/javascript">
</script>
<script language="javascript" type="text/javascript">
document.write('<b>Hello World</b>');
</script>
This will only be displayed in javascript enabled browsers.
<script language="javascript" type="text/javascript">
document.write('<a href="script.htm">Page Requiring Javascript</a>');
</script>
3. Variables and their scopes
<script language="javascript" type="text/javascript">
var hello = 'Hello World';
document.write(hello);
</script>
var mynum = 5;
var smokes = false;
var riches = null;
var today = new Date;
Example use of variables:
<script language="javascript" type="text/javascript">
var questions = '<p>If you have any questions about this
please <a href="mailto:me@myaddress.com">email me</a>.</p>';
document.write(questions);
</script>
Another block can refer to questions variables without reassigning the value
<script language="javascript" type="text/javascript">
document.write(questions);
</script>
variables declared within a function is recognized only withing that function. Variables declared outside of a function is recognized anywhere in the webpage within javascript code from the declaration place.
4. Operators
Assignment operators
<script language="javascript" type="text/javascript">
var rich = 5000;
var lotsOfMoney = 100000;
rich = lotsOfMoney;
document.write(rich);
</script>
Arithmetic and concatenation operators
five = two + three;
profit = income - expenses;
income = sales * price;
payment = total / instalments;
option = randnum % choices;
b = ++a;
c = a++;
d = --a;
e = a--;
Combination of Operators like c/c++
joy += happiness;
price -= discount;
capital *= interest;
pie /= slices;
options %= choice;
Example use:
<script language="javascript" type="text/javascript">
var singlePrice = 8;
var bulkPrice = singlePrice * 9;
document.write('<p>Buy our Widgets $'
+singlePrice+' for one, $'+bulkPrice+' for ten</p>');
</script>
5. Comparing Variables, Logical statements
<script language="javascript" type="text/javascript">
var red = 5;
var blue = 3;
var match = null;
if (red == blue)
{
match = 'equal';
}
else
{
match = 'unequal';
}
document.write(red + ' and ' + blue + ' are ' + match);
</script>
Other comparison operators:
if (red > blue)
if (red >= blue)
if (red < blue)
if (red <= blue)
if (red != blue)
Combining more than one comparison
if ((red == blue) || (red == green))
<script language="javascript" type="text/javascript">
var red = 5;
var blue = 3;
var green = 3;
var match = null;
if ((red == blue) && (red == green))
{
match = 'equal';
}
else
{
purple = 'unequal';
}
document.write(red + ' and ' + blue + ' are ' + match);
</script>
Comparison in short
red == blue ? match = 'equal' : match = 'unequal';
instead of
if (red == blue)
{
match = 'equal';
}
else
{
match = 'unequal';
}
Example Use:

<script language="javascript" type="text/javascript">
var discPrice = 25;
var regPrice = 25;
var discount = regPrice - discPrice;
if (discount > 0)
document.write('<p>Save $'+discount+ ' off the normal price of $' +regPrice+ 'now only $'+discPrice+'.</p>');
else
document.write('<p>Buy now at our regular cheap price of $' + regPrice+'.</p>' );
</script>
6. Switch statement in Javascript, very similar to C/C++/Java
use switch instead of multiple if/else if
<script language="javascript" type="text/javascript">
var red = 1;
var result = null;
switch (red)
{
case 1: result = 'one'; break;
case 2: result = 'two'; break;
default: result = 'unknown';
}
document.write(result);
</script>
Example:
<script language="javascript" type="text/javascript">
var message = 0;
switch (message)
{
case 1: document.write('Merry Christmas'); break;
case 2: document.write('Happy New Year'); break;
case 3: document.write('Happy Easter'); break;
case 4: document.write('Happy Holidays'); break;
default: document.write('Welcome');
}
</script>
7. Function
Defining a function
function myCode()
{
document.write('<b>Hello World</b>');
}
calling a function
myCode()
Example:
function displayMessage()
{
switch (message)
{
case 1: document.write('Merry Christmas'); break;
case 2: document.write('Happy New Year'); break;
case 3: document.write('Happy Easter'); break;
case 4: document.write('Happy Holidays'); break;
default: document.write('Welcome');
}
}
var message = 0;
displayMessage();
parameter passing
function writeSentence(argument1,argument2)
{
document.write('The '+argument1+' is '+argument2+'.<br />');
}
var a = 'table';
var b = 'chair';
var c = 'red';
var d = 'blue';
writeSentence(a,c);
writeSentence(b,c);
b = 'other ' + b;
writeSentence(b,d);
writeSentence('table',b); //passing the value directly
Example:
function displayMessage(m)
{
switch (m)
{
case 1: document.write('Merry Christmas'); break;
case 2: document.write('Happy New Year'); break;
case 3: document.write('Happy Easter'); break;
case 4: document.write('Happy Holidays'); break;
default: document.write('Welcome');
}
}
In Javascript functions can also return values
function validField(fld)
{
if (fld == '') return false;
return true;
}
function validField(fld)
{
return (fld != '');
}
How to receive returned values and process
document.write(myField + ' is ');
if (!validField(myField))
{
document.write('not ');
}
document.write('empty');
8. Alert and confirm
alert('Alert Message');
Will display a message box with the message. Very useful in debugging javascript applications.
use confirm(), when you need user agreement on an issue. like:
if (confirm('Select a button'))
{
alert('You selected OK');
}
else
{
alert('You selected Cancel');
}
9. comments
// Scrolling Ad Javascript
// copyright 3rd September 2004, by Stephen Chapman
// permission to use this Javascript on your web page is
// granted provided that all of the code in this script (including
// these comments) is used without any alteration
or
/* Scrolling Ad Javascript
copyright 3rd September 2004, by Stephen Chapman
permission to use this Javascript on your web page is
granted provided that all of the code in this script (including
these comments) is used without any alteration */

10. Debugging JavaScript
Test in different browsers like IE, Mozilla, Firfox, Netscape
Enable Javascript and script debugging
Script debugging usually reside under tools menu under browsing or web development sub-options

Using alert to check variable values or if you can reach to a particular point of your code
use bookmarklets, these are small scripts that can be used as plug in into browsers to provide error information.
Use firebug in firefox, also use error console under tools menu to debug javascript error.
Visual interdev provides Javascript debugging you may also enable external debugging by such programs
11. External javascript

You can place all of your javascript codes to an external file. and use the file scripts/functions from any webpage.
You just need to provide a reference to that external file.
You can provide reference as follows:
<script language="javascript" type="text/javascript"
src="hello.js">
</script>
Note: do not include any <script> or </script> in the external file.
12. Using <noscript> tag: this tag may help you to provide some information to the visitors
when javascript is disabled or not supported by the browsers.
<script language="javascript" type="text/javascript">
document.write('<b>Hello Javascript World</b>');
</script>
<noscript>Hello World Without Javascript</noscript>
<noscript>
This page uses Javascript. Your browser either
doesn't support Javascript or you have it turned off.
To see this page as it is meant to appear please use
a Javascript enabled browser.
</noscript>
13. Objects and properties in Javascript
var strlen = myField.length;
var str = mynum.toString();
function theLetter(num)
{
var str = 'abcdefghijklmnopqustuvwxyz';
return str.substr(num-1,1);
}
document.write(theLetter(5));
14. Arrays in Javascript
var myArray = new Array();
var myArray = new Array('message one',
'message two','message three');
document.write(myArray[0]);
myArray[3] = 'message four';
function displayMessage(m)
{
var greeting = new Array('Welcome','Merry Christmas',
'Happy New Year','Happy Easter','Happy Holidays');
if (m < 0 || m > greeting.length) m = 0;
document.write(greeting[m]);
}
15. Loops
for (var i=0; i<10; i++)
{
document.write(i);
}
var x = 0;
while (x<10)
{
document.write(x);
x++;
}
var x = 12;
do
{
document.write(x);
x++;
} while (x<10)
16. Date and Time in Javascript
//current date
var myDate = new Date;
myDate.setDate(15);
myDate.setMonth(3); // January = 0
myDate.setFullYear(2006);
myDate.setDate(myDate.getDate()+7);


How to implement multiple tab webpages in Ajax and Javascript



The following two examples will demonstrate how to use javascript and/or ajax to implement multiple tab webpages. http://www.dynamicdrive.com/dynamicindex17/ajaxtabscontent/

http://www.barelyfitz.com/projects/tabber/example2.html

I hope to be familiar with these concepts and use them in my work soon.

Handling Checkbox arrays with Javascript::GetElementsByName:XHTML supported



The following code demonstrates how to handle checkboxes with javascript. Note the names of all check boxes are same myInput[]. It could also be myInput. Both works as an array to contain the controls' values. I prefer myInput[] as you can handle this control in PHP as an array. If you use $arr=$_POST['myInput'], $arr will contain the values of the controls.

Note the use of getElementsByName(). It is easy to manipulate javascript controls using this name. You do not need to send a value/control to the function. And in many times, document.myform.control, does not work right, specially if you want to main XHTML standard[i need to check more on this]. getElementById is also very useful. You may use getElementById for most times, but with checkbox arrays getElementsByName is better choice.

Also, note that when a form is submitted only the values of the checked check boxes are submitted to the server. You may wish to use hidden controls to keep the values, so that all values are submitted and based on the checked/non-checked you can ..control your work

<html>
	<head>
		<script type="text/javascript">
			function getElements()
			  {
			  var x=document.getElementsByName("myInput[]");
			  alert(x.length);
			  alert(x[0].value);
			  alert(x[1].value);
			  alert(x[2].value);


			  }
		</script>
</head>

<body>
	<input name="myInput[]" type="checkbox" size="20" value='10'/>10 
<input name="myInput[]" type="checkbox" size="20" value='20' />20
<input name="myInput[]" type="checkbox" size="20" value='30' />30

Want to check how the code works, check below

10
20
30



Javascript by Example



Java Script by Example:

Please check the URL:

http://examples.oreilly.com/jscript2/

Javascript - Form validation



The code will be helpful in validating data entry forms such as: user registration, user creation. validate_required is used by all other functions

function validate_required(field,alerttxt)
	{
		with (field)
		{
			if (value==null||value=='')
			{
				alert(alerttxt);return false
			}
			else {return true}
		}
	}
	
	function validateTicketCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(type,'Type must be filled out!')==false)
			{type.focus();return false}
			
			if (validate_required(subject,'Subject must be filled out!')==false)
			{subject.focus();return false}
						
		}
	}

	function validate_customer_create_form(thisform)
	{
		with (thisform)
		{
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(phone,'Phone must be filled out!')==false)
			{phone.focus();return false}
			
		}
	}
	
	
	function validateUserCreateForm(thisform)
	{
		with (thisform)
		{
						
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(shortName,'Short name must be filled out!')==false)
			{shortName.focus();return false}
			
			if (validate_required(username,'Username must be filled out!')==false)
			{username.focus();return false}
			
			
			if (validate_required(password,'Password must be filled out!')==false)
			{password.focus();return false}
			
			if (password.value.length < passwordLength.value) {alert("Password must be at least "+ passwordLength.value +" char long");	password.focus();return false}
			
			if (validate_required(password2,'Please re-enter password!')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Password did not match");
				password2.focus();
				return false			
			}
			
			
		}
	}



JavaScript - Miscellaneous Validations



	function validateDomainName(strValue) 
	{
		return /www\.[a-z0-9_\-]+\.[a-z]{2, 3}/ig.test(strValue);		
	}

	function validateDomainName(strValue) 
	{
		return /www\.[a-z0-9_\-]+\.[a-z]{2, 3}/ig.test(strValue);		
	}


	//not 100% right, will fix later
	function checkDateFormat()
	{
		var pattern = new RegExp(0|1[0-9]/[0-3][0-9]/[0-9][0-9]);
		if(document.getElementById('timestampStarted').value.match(pattern))
		{
			var date_array = document.getElementById('timestampStarted').value.split('/');
			
			var month = date_array[0];
			var day = date_array[1];
			var year = date_array[2];

			// This instruction will create a date object
			source_date = new Date(year,month,day);
	
			if(month != source_date.getMonth())
			{
				alert('Month is not valid!');
				return false;
			}
	
			if(day != source_date.getDate())
			{
				alert('Day is not valid!');
				return false;
			}
			
			if(year != source_date.getYear())
			{
				alert('Year is not valid!');
				return false;
			}
		}
		else
		{
			alert('Date format is not valid!');
			return false;
		}
	
		return true;
	}



	function validateEmail( strValue) 
	{
		var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  		//check for valid email
  		return objRegExp.test(strValue);
	}


//AJAX Example
function ajaxFunctionGeneral()
	{
		var page_request = false

		if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
			page_request = new XMLHttpRequest()
		else if (window.ActiveXObject)
		{ // if IE
			try 
			{
				page_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e)
			{
				try
				{
					page_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e)
				{
				}
			}
		}
		else		
			return false
		return page_request;
	}

	function reboot(deviceId)
	{
		var response=confirm('Are you sure to reboot');
		
		if(!response)
			exit;
		
		page_request = ajaxFunctionGeneral();
		if (!page_request) return false;
		
		page_request.onreadystatechange=function()
      {
      	if(page_request.readyState==4)
        	{
        		var response=page_request.responseText;
        		var displayArea = document.getElementById('showDiagnosticsResults');
        		displayArea.value = response;
        	}
      }
		page_request.open('GET', '/Inventory/Diagnostics/reboot.php?deviceId='+deviceId, true)
		page_request.send(null)
	}



Javascript Codes



Javascript is a very powerfull scripting language for web-site development. Also, it is in much demand. In Europe Javascript experts earn 29-58 pound/hour [ref: Internet]

	var serviceInstancesArrAtLoad = Array();
	var serviceInstancesArrAtSubmit = Array();
	var tempArr=Array();	
	
	function validate_required(field,alerttxt)
	{
		with (field)
		{
			if (value==null||value=='')
			{
				alert(alerttxt);return false
			}
			else {return true}
		}
	}
	
	function validateTicketCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(type,'Type must be filled out!')==false)
			{type.focus();return false}
			
			if (validate_required(subject,'Subject must be filled out!')==false)
			{subject.focus();return false}
						
		}
	}

	function validate_customer_create_form(thisform)
	{
		with (thisform)
		{
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(phone,'Phone must be filled out!')==false)
			{phone.focus();return false}
			
		}
	}
	
	
	function validateUserCreateForm(thisform)
	{
		with (thisform)
		{
						
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(shortName,'Short name must be filled out!')==false)
			{shortName.focus();return false}
			
			if (validate_required(username,'Username must be filled out!')==false)
			{username.focus();return false}
			
			/*
			if (validate_required(password,'Password must be filled out!')==false)
			{password.focus();return false}
			
			if (password.value.length < passwordLength.value) {alert("Password must be at least "+ passwordLength.value +" char long");	password.focus();return false}
			
			if (validate_required(password2,'Please re-enter password!')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Password did not match");
				password2.focus();
				return false			
			}
			*/
			
		}
	}

	function validate_assign_group_form(thisform)
	{
		with (thisform)
		{
			if (validate_required(groupId,'Group name must be filled out!')==false)
			{groupId.focus();return false}
			
			if (validate_required(userId,'Action on invalid user!')==false)
			{userId.focus();return false}		
		}
	}
	
	function validateGroupCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Group name must be filled out!')==false)
			{name.focus();return false}
			
		}
	}
	
	function validateAssignGroupPermissionForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(taskId,'Task module name must be filled out!')==false)
			{taskId.focus();return false}
			
		}
	}
	
	function validateAssignTaskPermissionForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(groupId,'Group name must be filled out!')==false)
			{groupId.focus();return false}
			
		}
	}
	
	function validateUserEditForm(thisform)
	{
		with (thisform)
		{
						
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(shortName,'Short name must be filled out!')==false)
			{shortName.focus();return false}
			
			if (validate_required(username,'Login id must be filled out!')==false)
			{username.focus();return false}
						
			if (password.value.length>0)
			{
				if (password.value.length < passwordLength.value) {alert("Password must be at least "+ passwordLength.value +" char long");	password.focus();return false}
				
				if (validate_required(password2,'Please re-enter password!')==false)
				{password2.focus();return false}
			}
			
			if (password.value != password2.value)
			{
				alert("Password did not match");
				password2.focus();
				return false
			}
			
		}
	}
	
	function validateInventoryCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(serial,'serial must be filled out!')==false)
			{serial.focus();return false}
			
			if (validate_required(hardwareAddress,'Hardware Address must be filled out!')==false)
			{hardwareAddress.focus();return false}
		}
	}
	
	function validateInventoryTypeCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validateInventoryModelCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
			
			if (validate_required(manufacturerId,'Manufacturer must be filled out!')==false)
			{manufacturerId.focus();return false}
			
			if (validate_required(typeId,'Type must be filled out!')==false)
			{typeId.focus();return false}
			
			
		}
	}
	
	function validateInventoryManufacturerCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	
	function validateServiceCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
			
			if (validate_required(typeId,'Type must be filled out!')==false)
			{typeId.focus();return false}
			
			
		}
	}
	
	function validateHostingCreateForm(thisform)
		{
			with (thisform)
			{
				if (validate_required(serviceId,'Service must be filled out!')==false)
				{serviceId.focus();return false}
				
				if (validate_required(storageSpace,'Storage space must be filled out!')==false)
				{storageSpace.focus();return false}
			}
		}
		
	function validateDomainName(strValue) 
	{
		return /www\.[a-z0-9_\-]+\.[a-z]{2, 3}/ig.test(strValue);
		
		//var objRegExp  = /^\w+([\.-]?\w+)*(\.\w{2,3})/;

  		//check for valid domain
  		//return objRegExp.test(strValue);
	}
	
	function validateDomainServiceCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Domain name must be filled out!')==false)
			{name.focus();return false}
			
			/*if (validateDomainName(name.value)==false)
			{alert('Please enter valid domain name');name.focus();return false;}*/
			
			if (validate_required(registrar,'Registrar must be filled out!')==false)
			{registrar.focus();return false}
			
			if (validate_required(registrationTimestamp,'Registration timestamp must be filled out!')==false)
			{registrationTimestamp.focus();return false}
			
			if (validate_required(expiryTimestamp,'Expiry timestamp must be filled out!')==false)
			{expiryTimestamp.focus();return false}
			
			if (validate_required(username,'User name must be filled out!')==false)
			{username.focus();return false}
			
			if (validate_required(password,'Password must be filled out!')==false)
			{password.focus();return false}
			
			if (password.value.length < passwordMinLength.value || password.value.length>passwordMaxLength.value)
			{alert('Password must be '+ passwordMinLength.value+ '-'+ passwordMaxLength.value +' chars long');password.focus();return false;}
			
			if (password.value != password2.value)
			{alert('Password must match');password2.focus();return false;}
		}
	}
	
	
	
	
	function validateCommunityCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validatePostalCodeCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(postalCode,'Postal code must be filled out!')==false)
			{postalCode.focus();return false}
			
			if (validate_required(communityId,'Community must be filled out!')==false)
			{communityId.focus();return false}
		}
	}
	
	function validateStreetTypeCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validateStreetCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
			
			if (validate_required(typeId,'Type must be filled out!')==false)
			{typeId.focus();return false}
			
			if (validate_required(communityId,'Community must be filled out!')==false)
			{communityId.focus();return false}
		}
	}
	
	function validateUnitCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(streetId,'Street must be filled out!')==false)
			{streetId.focus();return false}
			
			if (validate_required(communityId,'Community must be filled out!')==false)
			{communityId.focus();return false}
			
			if (validate_required(number,'Number must be filled out!')==false)
			{number.focus();return false}
			
			if (validate_required(nodeId,'Node must be filled out!')==false)
			{nodeId.focus();return false}
			
		}
	}
	
	function validatePlantCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validateCreateTicketCategoryForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	
	function validateStartWorkOnTicketForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(startTimestamp,'Start Timestamp must be filled out!')==false)
			{startTimestamp.focus();return false}
		}
	}
	
	function validateTicketReportForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(date,'Date must be filled out!')==false)
			{date.focus();return false}
		}
	}
	
	
	function validateCloseTicketForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(date,'Date must be filled out!')==false)
			{date.focus();return false}
			
			if (validate_required(time,'Time must be filled out!')==false)
			{time.focus();return false}
			
		}
	}

	function validateCreateWorkOrder(thisform)
	{
		with (thisform)
		{
			if (validate_required(inventoryId,'Inventory must be filled out!')==false)
			{inventoryId.focus();return false}
			
			if (validate_required(assignedTo,'Assigned to must be provided!')==false)
			{assignedTo.focus();return false}
			
			if (validate_required(scheduledDate,'Scheduled date must be provided!')==false)
			{scheduledDate.focus();return false}
			
			if (validate_required(scheduledTime,'Scheduled time must be provided!')==false)
			{scheduledTime.focus();return false}
			
		}
	}
	
	
	
	
	function addService(services,serviceId)
	{
		for (var i = 0; i < services.length; i++) 
		{
			if (services.options[i].selected) 
			{
				serviceIdLength = serviceId.length++;
				serviceId.options[serviceIdLength].text = services.options[i].text;
				serviceId.options[serviceIdLength].value = services.options[i].value;
				
			}
		}
	}
	
	
	function removeService(serviceId)
	{
		for (var i = 0; i < serviceId.length; i++) 
		{
			if (serviceId.options[i].selected) 
			{
				
				serviceId.options[i].text = '';
				serviceId.options[i].value = '';
				serviceId.options[i].selected = false;
				serviceId.options[i].remove();
			}
			
		}
		
	}
	
	function validateAssignInventoryForm()
	{
		
		var serviceArr=document.getElementsByName("serviceArr[]");
		length=serviceArr.length;
		isAnySelected = false;
		
		for (var i=0;i 0)
			   isServiceRequested = 1;
			   
			if (serviceArr[i].checked == true)
			{
			   if (inventoriesHavingSameService[service] >= 0)
			   	inventoriesHavingSameService[service]=inventoriesHavingSameService[service]+1;
			   else 
			   	inventoriesHavingSameService[service]=1;
			   
			   if (servicesHavingSameInventory[inventory] > 0)
			   	servicesHavingSameInventory[inventory]=servicesHavingSameInventory[inventory]+1;
			   else
			   	servicesHavingSameInventory[inventory]=1;
			}
			
			
		}	
		if (   (!isAnySelected) && (isServiceRequested) )
		{
			alert('Service & inventory requested. But no checkbox is selected');
			return false;
		}
		else if (!isAnySelected)
		{
			var response = confirm('No checkbox is selected, do you want to proceed');
			if (!response) return false;
		}
		
		var errMsg ='';
		
		for (k=1;k= 0 )
			{	
				if ( (serviceRequested[k] != inventoriesHavingSameService[k])  )
				{
					if (serviceRequested[k]>0) 
						errMsg = errMsg + "Inventory is not checked properly for service " + k +", Requested:" + serviceRequested[k] +", Assigned:" + inventoriesHavingSameService[k] + "\n";
					else if (serviceRequested[k]==0 && inventoriesHavingSameService[k]>0)
						errMsg = errMsg + "Inventory is not checked properly for service " + k +", Requested:" + serviceRequested[k] +", Assigned:" + inventoriesHavingSameService[k] + "\n";
				}
			}
		}
			
		if (errMsg.length>0)
		{
			alert(errMsg);
			return false;
		}
		return true;
	}
	
	//not 100% right, will fix later
	function checkDateFormat()
	{
		var pattern = new RegExp(0|1[0-9]/[0-3][0-9]/[0-9][0-9]);
		if(document.getElementById('timestampStarted').value.match(pattern))
		{
			var date_array = document.getElementById('timestampStarted').value.split('/');
			
			var month = date_array[0];
			var day = date_array[1];
			var year = date_array[2];

			// This instruction will create a date object
			source_date = new Date(year,month,day);
	
			if(month != source_date.getMonth())
			{
				alert('Month is not valid!');
				return false;
			}
	
			if(day != source_date.getDate())
			{
				alert('Day is not valid!');
				return false;
			}
			
			if(year != source_date.getYear())
			{
				alert('Year is not valid!');
				return false;
			}
		}
		else
		{
			alert('Date format is not valid!');
			return false;
		}
	
		return true;
	}

	//used by assignService.php
	function initializeServiceInstanceArr()
	{
		if (serviceInstancesArrAtLoad.length == 0)
			serviceInstancesArrAtLoad=document.getElementsByName("serviceInstances[]");
		length=serviceInstancesArrAtLoad.length;

		for(i=0;i0 )
			{
				var forwardAddresses = forwardAddress.value.split(',');
				var length=forwardAddresses.length;
				for(var i=0;i=1)
				{
					lengthModelId=modelId.options.length;
					modelId.options[lengthModelId-1]=null;
				}
      
        		for(var i=0;i=1)
				{
					lengthAddressId=addressId.options.length;
					addressId.options[lengthAddressId-1]=null;
				}
      
        		for(var i=0;i=1)
				{
					lengthServiceId=serviceId.options.length;
					serviceId.options[lengthServiceId-1]=null;
				}
      
        		for(var i=0;i passwordMaxLength.value)
			{alert('Password length should be <= '+passwordMaxLength.value );password.focus();return false}
			
						
			if (validate_required(password2,'Please re-enter site password !')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Site User Passwords must match");
				password2.focus();
				return false
			}
		}
	}
	
	function validateHostingDomainUserCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(domainId,'Domain name must be filled out!')==false)
			{domainId.focus();return false}
			
			
			if (validate_required(username,'Domain user name must be filled out!')==false)
			{username.focus();return false}
			
			if (validate_required(password,'Domain password must be filled out!')==false)
			{password.focus();return false}
						
			if ( password.value.length  < passwordMinLength.value )
			{ alert('Password length should be at least '+passwordMinLength.value); password.focus();return false }
			
			if (password.value.length  > passwordMaxLength.value)
			{alert('Password length should be <= '+passwordMaxLength.value );password.focus();return false}
			
			
			if (validate_required(password2,'Please re-enter site password !')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Domain User Passwords must match");
				password2.focus();
				return false
			}
		}
	}
	
	
	//outage
	function validateOutageCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(subject,'Subject must be filled out!')==false)
			{subject.focus();return false}
			
			//check community selection
			var communityNamesArr=document.getElementsByName("communityNames[]");
			lengthArr= communityNamesArr.length;			
			var isAnySelected = false;
			
			for (var i=0;i



Introduction to JQuery





JavaScript Frameworks





GWT: Google Web Toolkit





JavaScript DOM: Must knowledge to understand Ajax



  • Understanding Javascript DOM is the first step to understand Ajax.
  • DOM provides many methods to access and edit individual components of a web-page/document. The methods are called getters.
  •  < div id = 'test' > Hello < /div >
    getElementById method can reference to this div element. var testDiv = document.getElementById("test"); CSS #test{} refers to the same area of the document
  • getElementsByTagName: all the elements with the partcular tag name. Returns an array. var testTag = document.getElementsByTagName("p"); just like p{} in CSS applies to all

    tags.

  • testTag.length can be useful.
  • You can also cycle through the elements and take some actions
          for(var i = 0; i < testTag.length ; i++){
             //do something
          }
       
  • Another example: document.getElementById("test").getElementsByTagName("p"); [CSS #test p{} - will affect the same area in CSS]
  • DOM provides getAttribute () : can access the value of an attribute. < p id='test' title='justEtc Computer' > Hello <p> : var title= document.getElementById("test").getAttribute("title");
  • Web-page can be thought of a set of interconected nodes. getElementById, getElementsByTagName, getAttribute - all help in accessing the nodes.
  • Three basic types of nodes in web-pages: element, text, attribute. element - building block, text = attribute = content
  • Every node is contained under another node. So there will be parent and child relationships. parentNode, childNode - are corresponding methods for accessing parents and childs.
  • Example: var test = document.getElementById("test"); var testParent= test.parentNode; var testChild = test.childNodes;
  • childNodes - returns an array
  • var allEle = document.getElementsByTagName("*"); - a collection of all the elements of the web-page.
  • firstChild - first Child of an element, lastChild - lastChild of an element, previousSibling, nextSibling - having same parent of the current node (next element), nodeValue, nodeValue - content of a node,
  • DOM Setters
  • Using DOM, you can create elements dynamically and put it in the document. createElement() - method serves the purpose
  • var paragraph = document.createElement("p"); - element created - element node - but not inserted in the document yet
    
    var textNode = document.createTextNode("A new text node from DOM!"); - creates a text node
    
  • setAttribute() - method can be used to set the attributes of a node. example: paragraph.setAttribute("title", "introduction");
  • appendChild() - append one node under another node;
  •     var pNode = document.createElement("p");
        var textNode = document.createTextElement("How is it going?");
         pNode.setAttribute("title","Test Title");
         pNode.appendChild(textNode);     
         var testDiv = document.getElementById("testDiv");
         testDiv.appendChild(pNode);
    
  • removeChild() - helps to remove a child node from a parent node



Ajax: An Overview



  • Ajax: dynamically changes a portion of the current web-page without refreshing the total web-page. Resembles the way IFrame works. So far I know, google uses IFrame to display/refresh maps in web-pages
  • XMLHttpRequest is the object that serves the purpose of Ajax
  • The way it works: create an instance of the XMLHttpRequest object, send request to the back-end web-page that will do some processing and perhaps return some data, receive the response data, dynamically change the content of the target area, you may need to get a reference to the target area using DOM, after sending request - you have to wait for the response to come back
  • create an instance of the XMLHttpRequest object: It varies for the different browsers. IE provides ActiveX Control for the purpose. A sample code can be as follows:
  • 
      function getAjaxObject(){
        var ajaxObject = false;
        if (window.XMLHttpRequest){
             ajaxObject = new XMLHttpRequest();
        }else if (window.ActiveXObject) {
          try{
            ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
          }catch(e){
             try{
              ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(e){
               ajaxObject = false;
             }
    
          }
        }
        return ajaxObject; 
      }
    
    
  • XMLHttpRequest has three core components. onreadystatechange - event to notify response has come or identify server activity, open - method , send method
  • use of onreadystatechange
    if (ajaxObject){
       ajaxObject.onreadystatechange = takeAction; //takeAction - reference to a function
    }
    
  • Open method specifies the server side script to handle the request, data to send to the server, method of sending (GET, POST) : Required: type of request (first argument), location of the file in the server (2nd argument)
  • Open method: third argument: true = processing will be done asynchronously, false = synchronous processing - browser will stop processing until response comes [true is usually better]
  • send : send method initiates the request : also passes data to the server
  • For GET method the argument can be set to null, for POSt method the argument can be a query string such as "id=500&name=keith&age=18"
  • use setRequestHeader() - to provide metadata
  • Sample code:
     var ajaxObject = getAjaxObject();
     if (ajaxObject ){
        ajaxObject.onreadystatechange = takeAction; 
        ajaxObject.open("POST","file.jsp", true);
        ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxObject.send("id=500&name=keith&age=18");
     }
    
  • How to receive and process the response:
  • The readyState property indicates the current status of the request. 0 - Uninitialized, 1 - Loading, 2 - Loaded, 3 - interactive, 4 - complete
  • each time the value of readyState changes onreadystatechange - event is triggered. At value 4, we can collect the response and change the web-page dynamically
  • Sample:
     function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         //do something with the response
      }
     }
    
  • status is another property to consider - it indicates the status of sending request like 404 - not found, 200 = success, 304 = not modified
  • The prev function
     function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
         }
      }
     }
    
  • responseText is the response from the server
  •  function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
              alert(ajaxObject.responseText);
         }
      }
     }
    
  • responseXML can be used when the response was sent as xml and the response header is "text/xml"
  • All together
      function getAjaxObject(){
        var ajaxObject = false;
        if (window.XMLHttpRequest){
             ajaxObject = new XMLHttpRequest();
        }else if (window.ActiveXObject) {
          try{
            ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
          }catch(e){
             try{
              ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(e){
               ajaxObject = false;
             }
    
          }
        }
        return ajaxObject; 
      }
    
      function entryPoint(){
        var ajaxObject = getAjaxObject();
         if (ajaxObject ){
        ajaxObject.onreadystatechange = function(){
          takeAction(ajaxObject); 
        };
        ajaxObject.open("POST","file.jsp", true);
        ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxObject.send("id=500&name=keith&age=18");
     }
     }
     function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
              alert(ajaxObject.responseText);
              var testDiv = document.getElementById("test");
              testDiv.innerText = ajaxObject.responseText; 
         }
      }
     }
    
  • Processing Response Data
  • The usual practice: response data can be in one of three formats: XML, JSON, HTML. And may be plain text.
  • XML is the most common. example receive: var data = ajaxObject.responseXML; Here we can use the DOM functions to parse the XML data
  • Example:
    var data = ajaxObject.responseXML;
    data.getElementsByTagName("name")
    data.getElementsByTagName("name")[0]
    data.getElementsByTagName("name")[0].firstChild
    data.getElementsByTagName("name")[0].firstChild.nodeValue
    Similarly, you can use other DOM functions
    
  • To change the contents of the web-page dynamically, you can use the DOM methods like -- create, set, innerText, innerHtml (use carefully) methods. Check the JavaScript DOM article [846] in this web-site. adding and removing childs/elements may be required in some situations - DOM also supports that
  • You can also send data as JSON from the server side like: JSON format:
    {"person":{ "name":"Keith Tang", "school":"uofm" } }
  • Receiving and extracting information from JSON: [content type will be text]
     var data = eval('('+ ajaxObject.responseText +')');
     var name = data.person.name;
     var school = data.person.school; 
    
  • Response data as HTML
  • The response can come as HTML. This may be useful, if only one area of the web-page is affected and we want to put the HTML response in that area. Otherwise it may not be great. Also, we need to use innerHTML method that was introduced by IE and later adopted by others. Still, it's not a standard (W3C)
  • Example: The content type of response data should be text/html
           if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
              alert(ajaxObject.responseText);
              var testDiv = document.getElementById("test");
              testDiv.innerHTML = ajaxObject.responseText; 
         }
    
    



Firebird as an Alternative to Oracle/MS SQL Server/Interbase/Access



Note: Firebird can be a very good alternatives to Oracle/MSSql Server/Interbase. First of all, it is free. It can be good enough for upto medium level of enterprises. Supported database size is more than 11 terabytes. For a single table 20GB. It also implements ACID properties well enough. Implements two phase commit and in record level locking and hence can provide more concurrency and connection. It also implements MGA to provide recovery that also Oracle/MSSQL server imitated from interbase/firebird. A well designed database and a well designed network using Firebird will be strong enough to support a mid - size company. Also, if the database is designed well and used the clean normalization, and used clean indexing, the query will be faster enough. Linux platform is more suitable than windows platform for Firebird. In 32 bit environment, Firebird server version support 2 GB of ram and hence around 450 concurrent connection. This is due to memory addressing in 32 environment, required cache size and for similar reasons. In Linux 64 bit versions Firebird can provide better service and more concurrent connections. Firebird is not stable and reliable enough to be used with windows platform in 64 bit environment. Though, Firebird project, hopes to work on this. Firebird, has a dedicated community to support the product. They provide supports through a discussion forum. (May be .. with some other ways). Firebird team also hopes to continue the project to fullfill future demand. Being opensource project the database system seems will be strong enough and well designed and well featured to meet customer demand. For details please check: A detail discussion can be found here. http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_enterprise_firebird Note: Firebird can be a good option for a Midsize company in Bangladesh

Features of Firebird



What is firebird:

The software has two main components: the database server, which lives on the same host machine as the databases, and the

application interface, commonly referred to as “the client library”. The client runs in the client pc or in the middleware

for accessing through internet browsers.

The server's executable is less than 1.5 Mb and a full server installation, including all tools and documentation, takes

up less than 10 Mb.

Versions:

1.5 most stable and tested

firebird 2: Mid of year 2006

Vulcan: A parallel project used by SAS to move many of its business applications from Oracle to Firebird. Purpose: redesigning the threading architecture of the database engine

Is Firebird “Enterprise Capable”?

stability, scalability, availability, capacity, interoperability and autonomy.

Stability

Stable enough, supports strongly ACID properties

Scalable??

Good enough but not extremely scalable

Firebird's upscaling is merely a question of adapting the environment. The same engine comfortably handles anything from

being embedded in a stand-alone client application, through to a classical two-tier client/server LAN of around 750

potential users, to incorporation in a multi-tier solution for thousands of potential clients. Database growth is

effectively limited only by the disk storage available and can be split across multiple hard disks.

Through smart replication and good connection management in the access layers, the workload of a busy system can be

distributed across multiple servers. For example, a well-resourced central server can handle the interactive demands of

LAN, intranet or extranet (or all together) while a replicated server takes care of long-running jobs that need to isolate

a snapshot of data for lengthy periods.

Availability

Among its users, Firebird has a reputation for being bomb-proof.

It uses optimistic locking at record level, drastically reducing the wait-time overheads in comparison to others where

read-write transactions lock entire sets, even tables, pre-emptively. No tuning is ever required to facilitate handling

varying workloads through the day or week. A database does not have to be shut down for backups. It can be replicated or

shadowed for almost instantaneous cutover in the event of disk failure. It is robust and recovers immediately from power

failure, without loss of database integrity.

Supports online backup.

Firebird is a popular choice for enterprises needing continuity of service around the clock. Command-line tools are

distributed with the software for all administrative activities, allowing regular housekeeping to be automated as

scheduled or on-demand jobs. A Services API is also available to wrap admin tasks into a program or service application.

Firebird Databases as the Back-end to Enterprise Software Systems

Who Uses Firebird? Because Firebird is free, there are no licences to count, no beans to count. It is known, from reputable enterprise surveys, that Firebird is chugging away on hundreds of thousands of production sites around the world. The following is a selection of companies and organisations that are publicly known to be using Firebird: Broadview Software Ltd, Toronto, Canada, vendor of information and control systems and online services for broadcasters worldwide Morfik P/L, Hobart, Tas., developers and vendors of WebOS development suite for construction and maintenance of interactive websites, stores web objects in a Firebird meta-layer (system database) as well as Firebird user data. Communicare Systems Pty Ltd, Perth, WA, vendor of patient management and medical records software for hospitals, clinics, medical practices and mobile health units across Australia. “The Examiner” newspaper, Launceston, Tas., high availability(24/7) business, information, production and news systems. U.S. Navy, broad range of management and logistical systems Frontrange Solutions USA Inc., Colorado Springs, U.S.A, as the back-end of the highly scalable, award-winning integrated CRM, service management and business systems “Goldmine” software suite. British Rail, U.K., timetabling, bookings, accounting and information systems for national railway passenger network. Deutsche Presse-Agentur GmbH, HQ in Hamburg, Germany, largest press agency in Germany, provides a worldwide service to newspapers, magazines, TV and radio news networks. KIMData, Munich, Germany, business intelligence systems and data warehousing for German hospitals.

Comparison: FireBird, MySQL, PostGreSQL



PosTGRESQL Provides better query responsetime than firebird and MySql. Firebird stands somewhere in the middle. A little longer response time than PostGreSql.
http://benchw.sourceforge.net/benchw_results_open3.html

Several PostGreSQL versions are compared at:
http://benchw.sourceforge.net/benchw_results_postgres_history.html

Several MySQL versions are compared at:
http://benchw.sourceforge.net/benchw_results_mysql_indexes.html


A good comparison among these databases will be found at: http://www.geocities.com/mailsoftware42/db/

Mentionable comments

PostGreSQL Supports 400+GB DB. One source: As for each connection it forks new thread, it is bit slower than MySql: Another source: postgresql is faster than mysql. Seems the truth is: for single connection postgresql can be faster but for multiple connections mysql is faster. just an information, not sure yet.

New PostGre Features

http://www.postgresql.org/docs/whatsnew Some mentionable comments: Supports SMP and almost linearly improves performance witth multiprocessor system.

Supports roles, in/out parameters/two phase commit/table partitioning shared row locking(firebird record level locking), 64 bit shared memory hence supports two terabytes of ram

PostGreSQL capability 4.4) What is the maximum size for a row, a table, and a database? These are the limits:
Maximum size for a database? unlimited (32 TB databases exist)
Maximum size for a table? 32 TB
Maximum size for a row? 400 GB
Maximum size for a field? 1 GB
Maximum number of rows in a table? unlimited
Maximum number of columns in a table? 250-1600 depending on column types
Maximum number of indexes on a table? unlimited
One limitation is that indexes can not be created on columns longer than about 2,000 characters. Fortunately, such indexes are rarely needed. Uniqueness is best guaranteed by a function index of an MD5 hash of the long column, and full text indexing allows for searching of words within the column. Source: http://www.postgresql.org/docs/faqs.FAQ.html 4.20) What replication solutions are available? Though "replication" is a single term, there are several technologies for doing replication, with advantages and disadvantages for each.
Master/slave replication allows a single master to receive read/write queries, while slaves can only accept read/SELECT queries. The most popular freely available master-slave PostgreSQL replication solution is Slony-I.
Multi-master replication allows read/write queries to be sent to multiple replicated computers. This capability also has a severe impact on performance due to the need to synchronize changes between servers. PGCluster is the most popular such solution freely available for PostgreSQL.
There are also commercial and hardware-based replication solutions available supporting a variety of replication models.

Important Notes

Server Configuration A number of postgresql.conf settings affect performance. For more details, see Administration Guide/Server Run-time Environment/Run-time Configuration for a full listing, and for commentary see http://www.varlena.com/varlena/GeneralBits/Tidbits/annotated_conf_e.html and http://www.varlena.com/varlena/GeneralBits/Tidbits/perf.html.
Hardware Selection
The effect of hardware on performance is detailed in http://www.powerpostgresql.com/PerfList/ and http://momjian.us/main/writings/pgsql/hw_performance/index.html.

Wikipedia link for postgressql-http://en.wikipedia.org/wiki/PostgreSQL

EnterpriseDB kind of commercial but cheap based on postgressql


PostGreSQL Limitations and solutions



http://searchopensource.techtarget.com/originalContent/0,289142,sid39_gci1172668,00.html

PostGreSQL Windows Installer http://pgfoundry.org/projects/pginstaller/



Important Links for Mysql, PostGreSQL, Firebird, EnterpriseDB, Ingres



Firebird and postgresql: http://www.linuxjournal.com/node/7010
Important comment: easy to migrate from oracle to firebird than to postgre or mysql. From interbase to firebird will be better as they are similar.

http://forums.devshed.com/firebird-sql-development-61/mysql--vs--firebird-sql-62269.html : Firebird is far better choice than mysql
As for Performance, MySQL will outperform Firebird on almost all tests on local machine......
On a Network Server a properly designed Firebird Server will outperform MySQL on any Test and the network-Traffic generated by Mysql will be many times higher than Firebird So you decide the one you need according to your needs .....

This link also compares fb with potgre and favors fb as the author's background is borland

Why Postgress is better than firebird

Firebird is not as good as PostgresQL (Score:0) By Anonymous Reader on 2004.12.03 2:21 (#102703) And here is why:

1. Firebird has no temp table support.

2. Firebird uses several SQL modes i.e DSQL which only works client side and PSQL which only works in procs. All sql works in Postgres functions. Try creating a table or a user in a Firebird proc...ooops can't be done.

3. Firebird databases grow out of control and have to be backed up restored on a regular basis.

4. Firebird has a concept of a OAT (oldest active transaction counter) if this counter gets stuck all transactions get held up and your DB size goes through the roof and performance goes to the basement.

5. Firebird has virtually no built in functions and flakey UDFs must be used. Postgres on the other hand has every function you can think of.

6. Postgres has many rich procedural languages including perl,TCL,Java and C# in the works.

I could go on.... Version 8 of Postgres which will be released soon adds point in time recovery, Try except error handling in functions, table spaces and more.

I converted all my apps from Firebird 1.5 to Postgresql 7.4 and I would never use Firebird again on Unix or Windows

Why PostGress better than FireBird: This comparison may not be accurate though.



Postgres Vs Interbase/Firebird (Score:0) By Anonymous Reader on 2004.12.03 18:23 (#102740) http://www.vitavoom.com/postgresql.html Firebird has not true text type you must use the clumsy blobs and weird blob subtypes. Postgres is much closer for enterprise use than Firebird. almost all of this applies to Firebird as well as interbase. PostgreSQL vs Interbase PostgreSQL... * ... has no "dialects" or other weird features. * ... has no "backdoors" which can compromise your whole company's security and business (check here and here). * ... supports unlimited row sizes, unlimited datasebase sizes, tables up to 16TB (!!), unlimited number of rows, unlimited indexes for table and 1Gb per field. * ... has a boolean field. * ... can cancel a query asynchronously (Interbase 6.5 - the commercial version - seems to support it now). * ... has a flexible (not fixed) types system, and supports more types then Interbase. You can always add your own types at your wish, or change existent types behavior. PostgreSQL even has geometrical and IPv4 types support (!!). * ... supports inheritance. * .. supports flexible full text indexing through OpenFTS. * ... has a much more sofisticated locking mechanism (MVCC). * ... has arbitrary precision numeric fileds (numeric type). * ... is resistant to crashes and power failures (by using it's logging system, MVCC and chepoint)). Although it is technically possible that a database gets corrupt, we at Vita voom never saw it (except for corrupt media storage of course). * ... supports functions (whose can be used as stored procedures). These functions current can be written on SQL, pl/PgSQL (a language similar to Oracle's pl/SQL), TCL, Perl, and Python, C, C++ (or other compiled languages) but it's not limited to them. * ... can have functions to define default values for columns (providing ultimate default value flexibility). * ... supports much more arrays types then Interbase, they are more flexible and can support much more elements. * ... supports rules. * ... supports "fetch" SQL command to get only a limited number of rows at a time, making queries more responsive and resource economic. * ... has regular expressions support (for searches and operations). * ... has a 'EXPLAIN' command which will show will how it will perform a query, so that you optimize it. * ... has statistics about database usage which can be used to optimize queries and indices. * ... has sequences. * ... has more built-in functions then Interbase (or any other open source RDBMS). * ... supports indexes on functions. * ... has broader subselects support then Interbase. * ... has a more flexible BLOB fields support. * ... can limit the number of rows retrieved at at time (with the 'LIMIT' keyword). * ... is more standards-compliant then Interbase. * ... allo

Speed: Firebird vs. PostGreSql



Please read. According to this article postgresql faster than firebird. But I also got information/tests where firebird is faster than postgresql.

http://archives.postgresql.org/pgsql-advocacy/2003-06/msg00280.php

However, Speed may not be the only factor to select a database product. We can improve raw speed in many alternate ways, hardware solutions, ram, faster storage, faster CPU. To compare speed issue, efficiency issue, we need to take a look how the query optimizations are implemented in databases. How, the joins, inner joins, outer joins are implemented. How multiple joins are implemented. Also, indexing is a factor that also affects performance issue. We can try creating same database and using a queries that are simple to complex and run on both databases and see, how well they perform.

Postgresql supports SMP (multiple processor system) and provides better efficiency in multiprocessor systems. Firebird, is not still matured in SMP environment.

Firebird supports 32 bit environment, still not stable/reliable enough for 64 bit env. It supports max ram of 2 gb and hence 150 - 450 concurrent users. Postgresql supports 2 TB of ram in a single server. For both of them, we can implement multiple servers with master/slave relation for better performances.

Tools to create ER diagrams from a database dynamically



Microsoft Visio, and dbVisualizer provide features to create ER diagrams from existing database tables.

Why needed?
ER diagram is very useful to understand the total
database structure that helps a new programmer to work on the existing databases more efficiently.

Visio:
While creating Database diagrams, a menu item named database is displayed. Reverse Engineering option under Database menu helps to create ER diagram from 

existing database tables. Before that, target database drivers for visio need to be installed. If the database is in db2/mysql/postgresql, then  

db2/mysql/postgresql drivers for visio should be installed. From Database/options/drivers, the driver needs to be configured. Afterwards, Reverse Engineering 

option may be used to create the ER diagram. There is no suitable driver for postgresql databses for Visio. ODBC drivers may be used for the purpose (the ER 

diagram may not be accurate from ODBC driver for postgresql). 

dbVisualizer:
In dbVisualizer, when the TABLEs group/option is selected in the left pane in the right/middle pane there will be a references option. When the references 

tab is selected, an ER diagram is displayed using all tables. The ER diagram can be displayed as Hierarchical, circular, orthogonal, or organic. There are 

options for the purpose.

When a single table name is selected, the table and the associated tables are displyed in an ER diagram.

In the rightest column, selected tables option allows to create ER diagrams only for the selected tables. When 'selected tables' is clicked a list is 

displayed in a dialogbox. Tables can be selected from this list (use control key). Build graph  option creates and displays the ER diagram.



Normalization (1NF to 5th NF)



Please check this link.
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p7.php

DBMS System Online Course



Please check the resources at:
http://www.cs.sfu.ca/CC/354/zaiane/material/notes/contents.html

Just like an undergraduate course in Database Management Systems. Along with other topic, ER-Diagram and representation of ER-Diagrams into tables are provided. Some of the complex forms of ER diagrams are discussed.



Practical Database Design Resources





Normalization in Relational DBMS Systems



First Normal Form:


All table columns should have distinct meaning

In another word: All attributes of an entity/table must be unique

Solution: 

Grow the table row wise[in the direction of rows] not the column wise
Group the columns with same meaning into one
To handle multiple values for the same attribute of an entity create multiple rows [not multiple columns]

To keep track of paycheques, you may think the table should be as follows:

Name, provider company, date 1, pay cheque 1, date2 , pay cheque 2, date 3, paycheque 3

See date1, date2, and date 3 have the same meaning
Pay cheque 1, Pay cheque 2, and Pay cheque 3 have the same meaning
These are the repeating attributes

Solution:
create table with:

number name, company, date,   paycheque
100    1,    xyz,      12/13,  1000.00
100    1,    abc,      12/13,  1000.00
100    1,    xyz,      12/31,  1000.00

or 

create a child entity with Date and amount. And a master entity with number, Name and Company
Entity one: number, name, company
Entity two: number, date, amount


2nd Normal form:
----------------

Rule: 

All attributes can be identified from the primary key. Primary key is directly related to all other attributes.
All attributes are fully dependent on the primary key.

Line Item Table/Entity:
--------------------
number [line item] [pk]
order number[pk]
vendor name
vendor town
product code
product amount

Here, vendor name and vendor town may not be fully dependent on the whole primary key. They are dependent on the order number.
So we can decompose it into another table.

Order entity
Number [pk]
Vendor Name
Vendor Town

Lineitem entity

number [pk]
order_number [pk]
product code
product amount


3rd normal form
-----------------
Rule: Non key attributes are fully dependent on the primary key but not on any other key or attribute.
In Order entity table, vendor town is not fully dependent on number[pk], but it does depend on the vendor name. So we can decompose order entity table into two

Vendor Entity
Name [pk]
Town

Order Entity
Number
vendor-name



Boyce/Codd and Fourth Normal Form



Boyce/Codd Normal Form
----------------------
It is just an extension to the third normal form. Third normal form ensures that non key attributes does not depend on any non key attribute but fully depend on the key[primary] attributes.

Boyce codd normal form ensures that non key attributes are fully dependent on the total set of the primary key. Non-key attributes should not depend [only] on a subset of the key[primary] attributes.

Fourth Normal Form:
-------------------
It tries to decompose an entity/table into multiple entities/tables when there are multiple independent[not dependent on each other] multivalued attributes in an entity/table.

For example: Consider a table with emp_number, skill name, objective of the employee. Employees may have many skills and also many objectives. Hence, skill_name, and objective are multivalued and also they do not depend on each other. This table will cause many redundant data.Better is to use two tables like:

Emp_skill
Emp_num, Skill Name

Emp_objective
Emp_num, Objective



Logical Data Modeling: Logical Database Design Steps: RDBMS



Logical Data Modeling

  1. Identify major entities
  2. Determine relationships between entities
  3. Determine primary and alternate keys
  4. Determine foreign keys
  5. Determine key business rules
  6. Add remaining attributes
  7. Validate user views through normalization
  8. Determine domains
  9. Determine triggering operations
  10. Combine user views
  11. Integrate with existing data models
  12. Analyze for stability and growth
Translate Logical Model into the Real Database System
  1. Identify tables
  2. Identify columns
  3. Adapt data structure to product environment
  4. Design for business rules about entities
  5. Design for business rules about relationships
  6. Design for additional business rules about attributes
  7. Tune for scan efficiency
  8. Define clustering sequences
  9. Define hash keys
  10. Add indexes
  11. Add duplicate data
  12. Redefine columns
  13. Redefine tables
Design for Special Design Challenges
  1. Provide for access through views
  2. Establish security
  3. Cope with very large databases
  4. Access and accommodate change
  5. Anticipate relational technology evolution
Reference: C. C. Fleming and B. V. Halle



PHP Security: Coding that Maintains Security



Php Security

PHP can be included as a module to the web-server, or executed as a separate executable binary. In either case, it can access files, execute commands, open network connections in the server. Further, PHP can be used to write scripts with all the power of the shell users. Hence, anything running on that server may face security problems. Though, careful coding will reduce the risks to a great extent[php.net].

Common security risks in PHP[Abdul Basit, php.net]

Most common are :

  • 1-Invalidated Input Errors
  • 2-Access Control Flaws
  • 3-Session ID Protection
  • 4-Cross Site Scripting (XSS) Attacks
  • 5-SQL Injection Vulnerabilities
  • 6-Error Reporting
  • 7-Data Handling Errors
  • 8-PHP configuration settings

PHP Security when installed as a CGI Binary[php.net]

  • Do not place any interpreters into the cgi-bin directory
  • Even If PHP is installed as a standalone binary (and in cgi-bin directory), PHP can prevent attacks that may arise from such setting.
  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd -- using such URLs can be risky, the part after ? may be treated as command line arguments to the interpreter, and hence, in some cases pose risks
  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html -- this way can also be risky

PHP compile time options such as --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent such risks.



PHP and IBM DB2



IBM-DB2: Random stuffs.

This is a great book on IBM-DB2. If you are experienced with DBMS systems like SQL Server, Oracle, MySQL, the first thing you may want to look at the features that are supported by IBM-DB2. Then you can try to find out the differences among them. It really will make your learning much faster. Then just skim through page by page, when you are at the end of the book, you will find you are ok to work with IBM-DB2. http://publib-b.boulder.ibm.com/Redbooks.nsf/RedbookAbstracts/sg244249.html

PHP has concepts like PDO and PDO_ODBC, and generic odbc features that will allow you to connect to and work with DB-2 databases. Generic odbc is the general/procedural way to connect to. PDO and PDO_ODBC are object oriented ways. PDO works with native IBM drivers. PDO_ODBC uses odbc connections to the DB2. For PHP you need to install drivers to support DB2. I worked with PDO_ODBC to connect to DB-2 databases in IBM iSeries servers. You need to install odbc db2 drivers for iseries servers. Then in /etc/odbcinst.ini file you need to mention driver specifications and in /etc/odbc.ini, you need to mention the odbc dsn name, database name, and some other parameters to connect to the database. Though, you may also supply some parameters in the PDO_ODBC connect method.

For details on PHP and DB2, please check: http://www.redbooks.ibm.com/redbooks/pdfs/sg247218.pdf



A Sample PHP Class



A sample PHP class is provided below. How the class is used?

When the submit button from the interface (web-page) will be clicked the code in the form-action web-page will call the the create method (static) to create a Ticket data/row in the database table Ticket. The method call will look like Ticket::create(array with field=>value pair, as formed with form submitted data) and you will get an Ticket object created with the inserted row/data.

To update a Ticket, you can create the Ticket object (constructor will do it for you) as you will know the Ticket id at this time. Then use the appropriate set method to update the value in the database.

To search call the static search method with a list/array of field=>value pair.

$dbh (read-only) and $dbhWrite(read-write) are global variables that represent connections to the database.




//represents a customer submitted Ticket
class Ticket
{
	public $parentTicket;
	private $dbh_;

	//member variables, named after the column names of the databse table - Ticket
	private $id_;
	private $type;
	private $subject_;
	private $timestampCreated_;
	private $timestampUpdated_;
	private $status_;
	private $parentTicketId_;
	private $categoryId_;
	private $categoryName_;
	private $internalNotifylist_;
	private $externalNotifyList_;
	private $customerId_;
	private $customerName_;
	private $creatorId_;
	private $creatorName_;
	private $ownerId_;
	private $assignedTo_;

	//constructor, creates a Ticket object with the table row with id = $id
	public function  __construct($id)
	{
		global $dbh;
		$this->dbh_ = $dbh;
		$this->refreshValues($id);
	}


	public function refreshValues($id)
	{

		$query="Select Ticket.*, TicketCategory.name
  from Ticket left join TicketCategory on Ticket.categoryId 
= TicketCategory.id
				where Ticket.id=$id";

		if ($result=$this->dbh_->query($query))
			if($result->num_rows==1)
			{


				$row=$result->fetch_object();

				$this->id_ = $id;
				$this->type_=$row->type;
				$this->subject_ = $row->subject;
				$this->timestampCreated_ = $row->timestampCreated;
				$this->timestampUpdated_ = $row->timestampUpdated;
				$this->status_ = $row->status;
				$this->parentTicketId_ = $row->parentTicketId;

				if($this->parentTicketId_>0)
					$this->parentTicket=$row->parentTicketId; //new Ticket($this->parentTicketId_);
				else $this->parentTicketId=0;

				$this->categoryId_ = $row->categoryId;
				$this->categoryName_ = $row->name;
				$this->internalNotifyList_ = $row->internalNotifyList;
				$this->externalNotifyList_ =$row->externalNotifyList;
				$this->customerId_ = $row->customerId;
				$this->creatorId_ = $row->creatorId;
				$this->ownerId_ =$row->ownerId;
				$this->assignedTo_ =$row->assignedTo;

				return true;
			}
			else
				return false;
	}

	//methods to retrieve/set data/member variables

	//retrieve id
	public function getId()
	{
		if($this->id_>0) return $this->id_;
		else return false;
	}
	//set id
	public function setId($id)
	{
		if (is_numeric($id))
		{
			if ($this->setField('id',$id)) return true;
			else return false;
		}
		else return false;
	}

	public function getCustomerId()
	{
		if($this->id_>0) return $this->customerId_;
		else return false;
	}
	public function setCustomerId($customerId)
	{
		if (is_numeric($customerId))
		{
			if ($this->setField('customerId',$customerId))
				return true;
			else return false;
		}
		else return false;
	}

    //used by methods to set member variables
	private function setField($field, $value)
	{
		$dbhWrite=getDbhWrite();
		$query="update Ticket set 
$field='".$dbhWrite->escape_string($value)."' where 
id=$this->id_";

		$result = $dbhWrite->query($query);
		if ($result==true)
		{
			if($dbhWrite->affected_rows==1)
			{
				$this->setTimestampUpdated();
				$this->refreshValues($this->id_);
				return true;
			}
			else return false;
		}
		else return false;
	}

    //used to create an entry into the Ticket table (database).
    //After insertion this row is used to form a Table object and returned to the caller
	static public function create($fields)
	{
		$dbhWrite=getDbhWrite();
		$timestamp = time();
		$parentTicketId='null';
		$customerId='null';
		$ownerId='null';
		$assignedTo='null';
		$categoryId='null';
		$type='null';

		foreach($fields as $field => $value)
		{
			switch($field)
			{
				case "type":
					if(self::isPermittedType($value)) $type=$value;
					else return false;
					break;
				case "status":
					if(self::isPermittedStatus($value)) $status=$value;
					else return false;
					break;
				case "subject":
					if (is_string($value))
						$subject=$dbhWrite->escape_string($value);
					else
						return false;
					break;
				case "parentTicketId":
					if(is_numeric($value))
						$parentTicketId=$value;
					break;
				case "categoryId":
					if(is_numeric($value))
						$categoryId=$value;
					break;
				case "customerId":
					if(is_numeric($value)) $customerId=$value;
					else return false;
					break;
				case "creatorId":
					if(is_numeric($value))
						$creatorId=$value;
					else return false;
					break;
				case "ownerId":
					if(is_numeric($value))
						$ownerId=$value;
					break;
				case "assignedTo":
					if(is_numeric($value))
						$assignedTo=$value;
					break;
			}
		}


		$insertStr = "insert into Ticket 
(type,subject, timestampCreated, timestampUpdated, status, 
parentTicketId, categoryId, customerId, creatorId, ownerId, 
assignedTo) values ($type, '$subject', $timestamp, 
$timestamp, $status, $parentTicketId, $categoryId, 
$customerId, $creatorId,$ownerId,$assignedTo)";

		$result = $dbhWrite->query($insertStr);

		if ($result == true)
		{
			if ($dbhWrite->affected_rows==1)
			{
				$ticket=new Ticket($dbhWrite->insert_id);
				return $ticket;
			}
			else return false;
		}
		else return false;

	}



	//searches the entire ticket table based on supplied field=>value pairs
	static public function searchFields($fields,$orderBy='id')
	{
		global $dbh;

		$query="select * from Ticket where ";
		foreach($fields as $field => $value)
		{
			if($value[0]=="!") //checking for not equal condition
			{
				$value=substr($value,1);
				$query.="`".$dbh->escape_string($field)."`!='".$dbh->escape_string($value)."' and ";
			}
			else
				$query.="`".$dbh->escape_string($field)."`='".$dbh->escape_string($value)."' and ";
		}
		$query=substr($query,0,-5);
		$query.=" order by ".$dbh->escape_string($orderBy);
		$result = $dbh->query($query);

		if ($result)
		{

			if ($dbh->affected_rows>0)
			{
				$tickets = array();
				$tickets = Ticket::processResult($result);
				return $tickets;
			}
			else return false;
		}
		else return false;
	}


    //used by searchFields method. Converts a set of retrieved data rows into array of objects.
	static private function processResult($result)
	{
		if($result->num_rows >= 1)
		{

			$tickets=array();
			while($row=$result->fetch_object())
			{
				$tickets[] = new Ticket($row->id);
			}

			return $tickets;
		}
		else return false;
	}





}



MVC for PHP





PHP Content Management Systems



  • What is a Content Management System (CMS)? I think, I can consider the skeleton/framework that I am using for this web-site is a simple CMS. I developed the framework completely on my own from the scratch. Many times, I thought based on the code, I should release a open source CMS system for further development or create a CMS system for web-publishers and sale it. Though never happened, still it runs on my head sometimes, may be one day. This web-site includes CMS like features such as:
    • I have an administration area from where I can administer the articles and video trainings/tutorials
    • I have a user registration and permission set-up area where I can create new users and assign permissions. Also users can register.
    • I have a user subscription and emailing (news letter) system
    • I can create new categories and sub-categories both for articles and training videos under my administration area
    • The left menu is dynamically generated from the database, I can change the display order of the items.
    • At this moment, the web-pages are divided into separate sections such as, left, right, top, bottom, and body. Each one uses a separate file (is included in the main file). The article is taken from the database (though file based system may be search engine friendly, will go that route soon). I could create a section in the administration area to upload banner and content for the top section. I could create a section to provide contents for the left/right menu. Also, could provide options to insert user login, survey, quiz, live chat and related components to be inserted in the right or left menu.
    • From the administration window, I can create books based on the articles. There are options to create multiple chapters and select articles for each chapter. I can create both HTML and PDF books.
    • Administration window also allows traversing through the articles and editing them
    • You can also include video contents
    • More that I could do, I could control the subscription fee from the administration window, control whether the search engine will be there or not, where the search engine will be placed, provide different layout options, different themes, or select background from a collection of images or colors, change the font color and size
    • Could provide features to enable/disable user submitted articles, enable/disable/remove user comments
    • I have many other plans with this web-site and will add many other features that will be controlled under the administration window
  • Popular PHP CMSs/Frameworks:
    • CMS Made Simple
    • Drupal
    • e107
    • Joomla
    • PHP Fusion
  • How to start with Drupal



Comparison among some popular PHP CMSs





MySql Administration SQL Commands



Using MySQL, Administration Workshop Requirements You should have access to the MySQL command line client software. Various different PRIVILEGES on the MySQL Server Introduction In the other MySQL Virtual Workshops we have used commands that are pretty much applicable to anyone. This part of the MySQL series is aimed at giving a rudimentary understanding of managing a MySQL database server. As such the task covered here are not really about manipulating data or database structures, but the actual databases themselves. Creating a Database In order to create a database you need to have the PRIVILEGES- this may be because you are the root user or you (or you systems administrator) has created an admin user that has ALL PRIVILEGES over all databases. In these examples a user called 'admin' has been created precisely for this purpose. Creating a database is fairly straightforward. Logging In A reminder of how to start the MySQL Client Software, and as we are not concerned with manipulating just one database we don't have to specify a database as part of our startup command. $ mysql -u -p Enter password:Create database command Next we are ready to enter the very simple command to create a database which is: mysql> CREATE DATABASE ; Let's imagine that we are going to create a 'vworks' database (those wishing to create a database for use with the VWs should use this). We would enter the command: mysql> CREATE DATABASE vworks; We can now check for the presence of this database by typing: mysql> SHOW DATABASES; +-----------+ | Database | +-----------+ | mysql | | vworks | +-----------+ 2 rows in set (0.06 sec)The other database listed ('mysql') is the internal database which MySQL uses to manage users, permissions etc. NOTE: Deleting or DROPing a database is similar to the DROP TABLE command issued in Part 4. e.g. DROP DATABASE Granting Privileges on the new database Now that we have created a database, we need to decide who gets to use it. This is done by granting permissions for a user to use the database. This has a simplified syntax of: GRANT ON TO [IDENTIFIED BY ] [WITH GRANT OPTION]Where the items in square brackets are optional. The most common use is to give ALL PRIVILEGES on a database to a local user who has to use a password to access the database (in this case vworks). mysql> GRANT ALL PRIVILEGES -> ON vworks.* -> TO newuser@localhost -> IDENTIFIED BY 'newpassword'; If you are creating a database for use with the rest of the Virtual Workshops you should use this statement, substituting your username and password of choice. There are some other options we will look at. To restrict the user to manipulating data (rather than table or database structures) the statement would be altered to: mysql> GRANT SELECT,INSERT,UPDATE,DELETE -> ON vworks.* -> TO newuser@localhost -> IDENTIFIED BY 'newpassword'; So that the user can only change the data using SELECT,INSERT,UPDATE or DELETE statements. If you wished to give a non-local user permissions on the database (for use with remote clients) then you could designate an IP or host address from which the user can connect: mysql> GRANT ALL PRIVILEGES -> ON vworks.* -> TO newuser@192.168.0.2 -> IDENTIFIED BY 'newpassword'; Now a user on the machine '192.168.0.2' can connect to the database. To allow a user to connect from anywhere you would use a wildcard '%' mysql> GRANT ALL PRIVILEGES -> ON vworks.* -> TO newuser@'%' -> IDENTIFIED BY 'newpassword';You could even decide that a user doesn't need a password if connecting from a certain machine. mysql> GRANT ALL PRIVILEGES -> ON vworks.* -> TO newuser@192.168.0.2But I think it is sometimes good to provide a password anyway. Finally we'll look at the WITH GRANT OPTION condition. This allows the user to give others privileges to that database: mysql> GRANT ALL PRIVILEGES -> ON vworks.* -> TO newuser@localhost -> IDENTIFIED BY 'newpassword' -> WITH GRANT OPTION; This would allow the user 'newuser' to log into the database and give their friend privileges to SELECT,INSERT,UPDATE or DELETE from the database. mysql> GRANT SELECT,INSERT,UPDATE,DELETE -> ON vworks.* -> TO friend@localhost -> IDENTIFIED BY 'friendpass'; The WITH GRANT OPTION usually signifies ownership although it is worth noting that no user can GRANT more privileges that they themselves possess. Revoking privileges Revoking privileges is almost identical to granting them as you simply substitute RE VOKE.... FROM for GRANT....TO and omit any passwords or other options. For example to REVOKE the privileges assigned to a user called 'badvworks': mysql> REVOKE ALL PRIVILEGES -> ON vworks.* -> FROM badvworks@localhost; Or just to remove UPDATE, INSERT and DELETE privileges to that data cannot be changed. mysql> REVOKE INSERT,UPDATE,DELETE -> ON vworks.* -> FROM badvworks@localhost; Backing Up Data There are several methods we can use to backup data. We are going to look at a couple of utilities that come with MySQL: mysqlhotcopy and mysqldump. mysqlhotcopy mysqlhotcopy is a command line utility written in Perl that backs up (to a location you specify) the files which make up a database. You could do this manually, but mysqlhotcopy has the advantage of combining several different commands that lock the tables etc to prevent data corruption. The syntax (as ever) first. $ mysqlhotcopy -u -p /backup/location/Which SHOULD copy all the tables (*.frm, *.MYI, *.MYD) into the new directory - the script does require the DBI perl module though. To restore these backup files simply copy them back into your MySQL data directory. mysqldump This is my preferred method of backing up. This outputs the table structure and data in series of SQL commands stored in a text file. The simplified syntax is $ mysqldump -u -p [] > file.sqlSo for example to back up a 'vworks' database which may have been created by completing the workshops: $ mysqldump -u admin -p vworks > vworks.sql After entering the password a 'vworks.sql' file should be created. When you look at this file you can actually see that the data and structures are stored as a series of SQL statements. e.g.: -- MySQL dump 8.22 -- -- Host: localhost Database: vworks --------------------------------------------------------- -- Server version 3.23.52 -- -- Table structure for table 'artist' -- CREATE TABLE artist ( artistID int(3) NOT NULL auto _increment, name varchar(20) default NULL, PRIMARY KEY (artistID) ) TYPE=MyISAM; -- -- Dumping data for table 'artist' -- INSERT INTO artist VALUES (1,'Jamiroquai'); INSERT INTO artist VALUES (2,'Various'); INSERT INTO artist VALUES (3,'westlife'); INSERT INTO artist VALUES (4,'Various'); INSERT INTO artist VALUES (5,'Abba'); And so on for the other tables. We could also have chosen to output just one table from the database, for example the artist table: $ mysqldump -u admin -p vworks artist > artist.sqlWe could even dump all the databases out (providing we have the permissions). $ mysqldump -u admin -p --all-databases > alldb.sqlRestoring a Dump Restoring a dump depends on what you have actually dumped. For example to restore a database to a blank database (perhaps having transferred the sql file to another machine) it is fairly simple. $ mysql -u admin -p vworks < vworks.sql...or to add a non-existent table to a database... $ mysql -u admin -p vworks < artist.sqlHowever, what happens if we want to restore data to an existing database (perhaps a nightly backup) ? Well we would have to add other options: The equivalent of overwriting the existing tables would be telling the dump to automatically drop any tables that exist before restoring the stored tables. This is done with the ' --add-drop-table ' option added to our statement. $ mysqldump -u admin -p --add-drop-table vworks > vworks.sqlThen restore like normal: $ mysql -u admin -p vworks < vworks.sqlThe reverse might also be true. We may wish to create the database if it doesn't already exist. To do this we use the '--databases' option to specify the database we wish to back up (you can specify more than one). $ mysqldump -u admin -p --databases vworks > vworksDB.sqlThis will create additional SQL statements at the start of each database that CREATEs the dumped database (checking first to see if it does indeed exist) then USEing that database to import the table data into. -- Current Database: vworks -- CREATE DATABASE /*!32312 IF NOT EXISTS*/ vworks; USE vworks; Again we can resort like normal, but of course this time we can omit the database name. $ mysql -u admin -p < vworksDB.sqlOptimising a dump There are a couple of options that are sometimes worth including when backing up and restoring large databases. The first option is '--opt', this is used override the mysql server's normal method of reading the whole result set into memory giving a faster dump. Example: $ mysqldump -u admin -p --opt vworks > vworks.sqlThe second option is '-a' or '-all' (either will do). Which also optimises the dump by creating mysql specific CREATE statements that speeds up the restore: $ mysqldump -u admin -p --all vworks > vworks.sqlUsing mysqldump to copy databases. It is possible to combine a dump and a restore on one line by using a pipe '|' to pass the output of the dump directly to mysql basically bypassing the file. This may initially seem a bit redundant, but we can use this method to copy a database to another server or even create a duplicate copy. For example to copy the 'vworks' database to a mysql server called 'remote.server.com': $ mysqldump -u admin -p --databases vworks | \ > mysql -u backup -p MyPassword -h remote.server.com Note: the"\" at the end of the first line means you wish to contine the command on another line before executing it. You may, in certain circumstances, wish to make a copy of live data so that you can test new scripts and 'real world' data. To do this you would need to duplicate a local database. First create the duplicate database: mysql> CREATE DATABASE vworks2; Then once appropriate privileges have been assigned we can copy the tables from the first table into the second. $ mysqldump -u admin -p vworks | mysql -u backup -p MyPassword vworks2Notice in both these examples the second half of the line (after the pipe) passes the password as part of the connection statement. This is because asking for two separate passwords at the same time breaks most shells. That is why I have used a 'backup' user who can be granted permissions and have them revoked as necessary. Miscellaneous Leftovers This final bit includes a few brief tricks that weren't really appropriate to include elsewhere, but are still worth noting. Remote Client Connection If you have set the privileges to allow remote connections to a database, you can connect from a remote command line client by using the -h flag: $ mysql -u -p -h For example to connect to a fictional vworks.keithjbrown.co.uk server: $ mysql -u admin -p -h vworks.keithjbrown.co.ukNon-Interactive Commands Sometimes you may wish to just do a quick look up on a table without the hassle of logging into the client, running the query then logging back out again. You can instead just type one line using the ' -e ' flag. For example: $ mysql -u admin -p vworks -e 'SELECT cds.artist, cds.title FROM cds' Enter password: +------------+------------------------------+ | artist | title | +------------+------------------------------+ | Jamiroquai | A Funk Odyssey | | Various | Now 49 | | westlife | westlife | | Various | Eurovision Song contest 2001 | | Abba | Abbas Greatest Hits | +------------+------------------------------+

Securing MySQL Database



After installing mysql, we will need to remove test database and associated users and their permissions. We will need to use mysql database to remove associated users and permission.





-- DROP DATABASE test;



-- SELECT db.Host, db.Db, db.User, db.Select_priv -> FROM db WHERE (db.DB = "vworksDB");



--- SELECT db.User, db.Host, db.Db -> FROM db -> WHERE (db.Db LIKE 'test%');



--- DELETE FROM db

-> WHERE (db.Db LIKE 'test%');

---

mysql> DELETE FROM db

-> WHERE (db.Host = "%");

mysql> DELETE FROM db

-> WHERE (db.User = "");

--- SELECT user.Host, user.User

-> FROM user

-> WHERE ((user.Host = "%") OR (user.User = ""));

---

DELETE FROM user -> WHERE ((user.Host = "%") OR (user.User = "")); ---

FLUSH PRIVILEGES; ---

details: http://www.keithjbrown.co.uk/vworks/mysql/mysql_pA.php#secure

Joins in MySQL



Cross-Join: All row by all row, ex: SELECT FROM ,


The Equi-Join or Inner Join: Syntax:
SELECT
FROM ,
WHERE (Table1.column = Table2.column)



SELECT cds.artist, cds.title, genres.genre
-> FROM cds, genres
-> WHERE (cds.genreID = genres.genreID);



The Left Join: Syntax:


SELECT
FROM
LEFT JOIN
ON Table1.column = Table2.column


Without adding a WHERE clause the Left Join produces the same results as the equi-join example above.
mysql> SELECT cds.artist, cds.title, genres.genre
-> FROM cds
-> LEFT JOIN genres
-> ON cds.genreID = genres.genreID;


The USING Clause: You can use this if the columns you are carrying out the join on have the same name.
Syntax:

SELECT
FROM
LEFT JOIN
USING ()



UPDATE JOIN:

mysql> UPDATE cds, artists
-> SET
-> cds.title = 'The Funkship Odyssey',
-> artists.Artist = 'George Clinton'
-> WHERE (artists.artistID = cds.artistID)
-> AND (cds.cdID = '2');



UPDATE cds->LEFT JOIN artists
-> ON cds.artistID = artists.artistID
-> SET
-> cds.title = 'A Funk Odyssey',
-> artists.name = 'Jamiroquai'
-> WHERE (cds.cdID = '2');



DELETE Joins: mysql> DELETE cds
-> FROM cds, artists
-> WHERE (cds.artistID = artists.artistID)
-> AND (cds.artistID = '3');





MySQL Resources



Mysql Resources:

First you need the latest/stable version of MySQL. Right now 6.0 is the latest version. Mysql has two different releases like:
community server[free]
enterprise server[commercial]

Note: MAXDB is the current full package with many features that may not be fully tested.

Download MySQL:

You can download MySQL from

http://dev.mysql.com/downloads/mysql/5.0.html

Check the lower portion of the webpage.

Working with Mysql:

After installation you can interact with MySQL server through command line[Best to become guru]. But you may also want to use GUI IDE to interact with. GUI tools can be downloaded from:

http://dev.mysql.com/downloads/gui-tools/5.0.html

GUI are of two types: to administer MySQL server. Used for backup, restore, security

Development: For creating Database and interact with database using tables, Queries, Stored procedures, triggers


Application Development:

You can build appications that use MySQL databases at the backend. You can use languages like PHP, Perl, Java, .net to interact with MySQL databases. Usually, the package for these languages contain a driver to provide the functionalities. Otherwise, you can download drivers from:

http://dev.mysql.com/downloads/connector/

for many different programming languages like Java, PHP, Perl and similar.



MySQL Resources: MySQL Start



Mysql Resources:

First you need the latest/stable version of MySQL. Right now 6.0 is the latest version. Mysql has two different releases like:
community server[free]
enterprise server[commercial]

Note: MAXDB is the current full package with many features that may not be fully tested.

Download MySQL:

You can download MySQL from

http://dev.mysql.com/downloads/mysql/5.0.html

Check the lower portion of the webpage.

Working with Mysql:

After installation you can interact with MySQL server through command line[Best to become guru]. But you may also want to use GUI IDE to interact with. GUI tools can be downloaded from:

http://dev.mysql.com/downloads/gui-tools/5.0.html

GUI are of two types: to administer MySQL server. Used for backup, restore, security

Development: For creating Database and interact with database using tables, Queries, Stored procedures, triggers


Application Development:

You can build appications that use MySQL databases at the backend. You can use languages like PHP, Perl, Java, .net to interact with MySQL databases. Usually, the package for these languages contain a driver to provide the functionalities. Otherwise, you can download drivers from:

http://dev.mysql.com/downloads/connector/

for many different programming languages like Java, PHP, Perl and similar.



Stored Procedure in MySql



Starting from MySQL 5, you get Stored Procedure in Mysql

What is a stored procedure: A stored procedure is simply a procedure that is stored on the database server like MySQL. In programming languages, you write procedures to execute a function/logic. You can write similar procedure in SQL and store it in the database. From the front end application you can just call the procedure to get the functionality. Usually, you send series of sqls to the databases to execute a logic. A stored procedure is better as it needs one single call. But not every logic can/should be implemented as stored procedures.

Sample stored procedure

CREATE PROCEDURE sp_hello()
SELECT 'Hello World';

It just creates a procedure. To run the procedure, you have to type

call sp_hello;

You will see 'Hello World' as output.

Stored procedures can also take parameters and return values. Both needs to be mentioned as parameter. In the parameter list we can declare a variable as IN, OUT, or INOUT parameter. You can use SQLs[insert,select] inside procedure to perform database operations. Also, you can use to set/unset session variables.

Session variable example

SET @X=100;
CREATE PROCEDURE sp_in(p VARCHAR(10))
SET @x = P;

call sp_in(1000);

You see 1000 in screen

A more practical stored procedure with multiple statements mysql> DELIMITER | mysql> CREATE PROCEDURE sp_declare (P INT) -> BEGIN -> DECLARE x INT; -> DECLARE y INT DEFAULT 10; -> SET x = P*y; -> INSERT INTO sp1(id,txt) VALUES(x,HEX('DEF')); -> END| Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ; mysql> CALL sp_declare(4);

please, note the use of | and DELIMETER. They provide support so that you can use ; in your procedures.

Some stored procedure related SQL commands

SHOW PROCEDURE STATUS SHOW CREATE PROCEDURE Hello SELECT * FROM INFORMATION_SCHEMA.ROUTINES [Ansi standard] Thanks Sayed

MySQL Reference Manual





MySQL: Special Interests





Configuring IIS 6.0



Please check:

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0a199196-4ae9-41eb-b8c1-572251f9f550.mspx?mfr=true

It is a very good resource

Check the following link to know in 2003 server that runs IIS what services should be enabled/disabled

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/eb255518-2cc7-4972-8dd9-40bbaa7ca331.mspx?mfr=true

Common Administrative Tasks: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/f504d2a6-be2a-49fa-b3e9-931ab1671bf1.mspx?mfr=true

WebLogic and WebSpheres



I was just checking about weblogic and websphere. Some resources that I went through:

Note: Sometimes knowing information like where to get the information is important especially when you know if you read, you will understand, and if you understand, you will be able to implement.



Installing Apache Tomcat 6.0: Windows



  • Make sure you have installed J2SE 5 (both the jdk and the jre) or greater (for tomcat 6.0, j2se5 is required according to my experience)
  • Set the JAVA_HOME environment variable to the path of the JDK
  • Download Tomcat 6 from http://tomcat.apache.org/download-60.cgi
  • Click on the downloaded setup.exe file
  • Select Core+service+examples i.e. full install
  • When the installer asks for the JRE, provide the path for jre 5 (jre 6 did not work for me)
  • For user name and password I kept user name to be admin password to be blank [you can also set one]
  • Next, Next, Finish - tomcat will be installed and start running [if the option was selected]
  • Set the CATALINA_HOME environment variable to the installation path of the Tomcat 6.0 - it is important for deploying J2EE web applications under Tomcat


Web Hosting Companies



Best Hosting Companies

I was searching for a suitable webhosting for me. Until now features and cost wise I liked HostGator, VodaHost, HostMonster, BlueHost. Yahoo is another one I like but pricy. I am into hostgator and vodahost mainly. Though, vodahost has some bad reputation and their customer support may not be great. Just few other hosting companies are below. They are also very popular with huge customers. They may be better than Hostgator or Vodahost or HostMonster for you but for me I am sticking with HostGator[Do not have much experience with their customer support though]. It's really difficult to come up with the best.



Choosing the best video format for your web site





Complete path analysis to get a merchant account



Please Check: http://www.sitepoint.com/article/merchant-account-review
Detail Discussion to have a Merchant account
If pricing is a concern check it. http://www.sitepoint.com/article/money-where-mouse-is-gateways/4
For detail explanations, please check the following link: http://www.sitepoint.com/article/money-where-mouse-is-gateways

Online Payment Processing with Moneris



Resources

Video Tutorial on Payment Processing by JustEtc

  • Guide on How to implement: https://www3.moneris.com/connect/en/download/feb05/HOSTED/eSELECTplus_HPP_IG.pdf
  • Demo for Hosted Pay Page Implementation: https://www3.moneris.com/connect/en/process/tryit/index.html
  • Demo Store Administration: https://esqa.moneris.com/mpg/admin/hppv3_config/index.php
Topics Covered
  • Collect Order Information: Basic, Detail
  • Go to Moneris Paypage : Validate payment, Configure payment screen
  • Return from Moneris: Success: Show success message & Receipt, Failure: Show failure message
  • Administer Moneris Store: Customize pay page appearance, Response Field Configuration, Success & Failure page configuration



Search Engines To Submit your Online Stores



Search Engines
Robots (Search Engines)(Major)
Make sure and submit to these.

Aeiwi
Alexa
AltaVista
AOL Netfind
Anzwers
Canada.com
Direct Hit
EuroSeek
Excite
Find What
Google
HotBot
ICQ It
I Won
InfoMak
InfoSeek
Lycos
MSN Search
Northern Light
NBCi
Surf Gopher
Thunderstone
UKMax
WebCrawler
World Search Center
What-U-Seek


Indexes & Catalogs (Major)
Submit to these critical directories manually so nothing is left to chance.

Britannica
LookSmart
ComFind
Jayde
LookSmart
Lycos (directory)
Netscape Search
Open Directory Project
Pronet
Rex
Snap!
TurnPike
What's New Too
Yahoo
Yellow Pages


Robots (Smaller Search Engines)

A2Z Solutions
Diabolos
Fathead
Final Search
Funky Cat
Galaxy
GlobeTech
Matilda
MaxBan
National Directory
Neftem
NetSearch
Search It
The Cozy Cabin
Web Search 2K
WhatUseek
World Search Center


Indexes & Catalogs (General)


ABAT NZ

CanLinks
CyberDirectory
Dewa
Discover it
DirectFind
EarthFind
EgyptWeb
ELaud
FetchDog
Find It
FindLink
Frequent Finders
Global Page
http://www.gohip.com/
HandiLinks
Hits Galore
ICN iExplorer
Infohiway
InfoSpace
JumpCity
LifeStyle UK
LinkMaster
MasterSite
NerdWorld
NTT Directory
Omnisearch
PeekABoo
PlanetClick
PointGuide
QuestFinder
Scrub The Web
SearchBlazer
SearchHound
SearchKing
SearchMode
SelectSurf
SiteShack
SplatSearch
Starting Point
theNet1
WebIndex
WebScout
WebSleuth
WhatsNu
WebVenture Hotlist
Yep


Indexes & Catalogs (General Business Related)

411Locate

411Now
AE Business Exchange
BizCardz
BizWeb
Business Seek
Comfind
InfoMarket
LinkStar
OZOnline
ProNet
QuickPage
WebDirect
USA Online
 


Required Components for Internet Income



Do you want to earn through your website? Well you want to start your own home business. In this category, we will provide you detailed information to meet your needs. We will provide information how you can earn through your website. We will also explore the opportunities for online based home business and online business.

First you need to know what are the options that can make you money through your websites. If you search the Internet you will find thousands of options and opportunities. I personally believe all of them are not useful. Some of them are just scam. We will try to identify some good options.

Here we will discuss our opinions in several steps: Steps:

  1. Types of programs that will pay you
  2. Requirements and tools needed for such programs

Types of Programs. For details click on HOME Button.

  1. Pay Per Click
  2. Pay Per Surf
  3. Pay Per Sale
  4. Pay Per Lead
  5. Pay Per Email Read
  6. Pay Per Pop Up show
  7. Pay for Blind Clicks
  8. Earn by Joining Reseller Programs
  9. Being a Seller in a Program
Well, these are some basic categories. We will add when we are familiar with new options. You can join and test one program alone. Even, you can try multiple programs simultaneously. Please, check the policies for corresponding programs whether they comply together.

Tools and Requirements needed for online earning:

  1. A Well Designed Website
  2. Website Hosted with User Friendly URL
  3. Merchant Tools
  4. Marketting

A Well Designed Website
You yourself can build your website or take help of an expert to build your website. You can learn HTML, FrontPage, DreamWeaver, JavaScript, Phtoshop, Flash, PHP, MySQL to build a good website. In future links to several free tools to build website will be provided.

Website Hosted with User Friendly URL
You need a hosting space for your website. There are plenty of free webhosting services in the Internet. The good talk about them are they are free. However, they are not good for online business. Also they are not good for Pay Per Click programs as they might force you to keep their adds on your webpages. If you are interested with free webhosting please search google.com with the phrase "free webhosting" and try the links. You can also try the link http://www.free-webhosts.com/. If you want paid hosting service you can search google with the phrase "ranking web hosting". You can also try with similar phrases. You can also try www.TheHostingChart.com, www.top10webhosting.com, toptenreviews.com.

For online transactions you will need to setup merchant accounts with your hosting packages. You need secure SSL connection. If you work as a seller you will need to use shopping cart from your hosting/other companies. You can yourself program your shopping cart. Verisign is a company that will help you to preserve security in your online transactions.

When you join a program you will get payment from the company. The company will pay you in various ways. They might send you check. There are some convenient ways to accept money online from the owner of the programs. Such as:

  1. Paypal
  2. Egold
  3. StormPay
  4. IntGold
  5. EPassporte

Personally I am familir with paypal. I found it to be secure and trustable way of making online transactions. Other options are new to me. However, not all companies work paypal. Hence, in some cases you will not have any option to avoid the others. Read articles regarding the other options, consult with your friends and other webmasters to know about the services clearly.

Meta Tag Generator

Websites that offers free Meta tag Generator Utility



20 Tips to Improve ASP.net Application Performance



Please check: http://www.realsoftwaredevelopment.com/2007/08/20-tips-to-impr.html



ASP.Net Controls



HTML Server Controls
HtmlAnchor
HtmlButton
HtmlForm
HtmlGeneric
HtmlImage
HtmlInputButton
HtmlInputCheckBox
HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlSelect
HtmlTable
HtmlTableCell
HtmlTableRow
HtmlTextArea

Web Server Controls
AdRotator
Button
Calendar
CalendarDay
CheckBox
CheckBoxList
DataGrid
DataList
DropDownList
HyperLink
Image
ImageButton
Label
LinkButton
ListBox
ListItem
Literal
Panel
PlaceHolder
RadioButton
RadioButtonList
BulletedList
Repeater
Style
Table
TableCell
TableRow
TextBox
Xml


Validation Server Controls
CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator
ValidationSummary



ASP.Net Examples



ASP.NET HTML Controls

HTMLAnchor
HTMLButton
HTMLImage
HTMLImage 2
HTMLInputbutton
HTMLInputCheckbox
HTMLInputHidden
HTMLInputImage
HTMLInputRadiobutton
HTMLTable
HTMLTable 2
HTMLTextarea

ASP.NET Web Controls

AdRotator
Button
Button 2
Calendar
Calendar 2
Calendar 3
Checkbox
CheckboxList
DataList
DataList with styles
DataList with
DropdownList
Hyperlink
Image
ImageButton
Label
LinkButton
Listbox
Literal
Literal 2
Panel
Radiobutton
RadiobuttonList
Repeater
Repeater with
Repeater with
Table
Table 2
Textbox
Textbox 2
Textbox 3
XML

ASP.NET Validation Controls

CompareValidator
CompareValidator 2
CustomValidator
RangeValidator
RangeValidator 2
RegularExpressionValidator
RequiredFieldValidator
Validationsummary
Validationsummary 2

ASP.NET Events

Page_Load
Page.IsPostBack

ASP.NET Data Binding

ArrayList RadioButtonList
ArrayList DropDownList
Hashtable RadioButtonList 1
Hashtable RadiobuttonList 2
Hashtable DropDownList
SortedList RadioButtonList 1
SortedList RadiobuttonList 2
SortedList DropDownList
XML RadiobuttonList

ASP.NET Database

Database connection - Bind to a Repeater control
Database connection - Bind to a DataList control



How to optimize SQL Server Cursors



Optimize Cursors
  1. Avoid using SQL Server cursors whenever possible
  2. Always close SQL Server cursors when result sets are not needed
  3. Deallocate SQL Server cursors when the data structures comprising the cursors are not needed
  4. Reduce the number of records to process in the cursor
  5. Only use the required columns in the cursors
  6. Use READ ONLY cursors, whenever possible, instead of updatable cursors.
  7. Avoid using insensitive, static and keyset cursors, whenever possible.
  8. Use FAST_FORWARD cursors, whenever possible.
  9. Use FORWARD_ONLY cursors, if you need updatable cursors



What are cursors?



Cursors are server side database objects that are used by 
applications to apply operations on the database table data 
on a row-by-row basis. The operations may vary from one row 
to another row dynamically based on the requirements 
(business logic) and also multiple operations can be 
performed on the same row. Typical SQL commands apply the 
same updates/changes to all the selected rows at once where 
cursors apply updates/changes one by one row. 

Cursors must be declared in the database before they can be 
used/called from the applications [front end]. Afterwards, 
you can open cursors to fetch data using them, you can fetch
row by row and make multiple operations on the currently 
active row in the cursor. You should close the cursors and 
deallocate them after you are done with the cursors.


This is the Transact-SQL Extended Syntax:

DECLARE cursor_name CURSOR
[LOCAL | GLOBAL]
[FORWARD_ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR select_statement
[FOR UPDATE [OF column_name [,...n]]]

An example cursor:

DECLARE AuthorsCursor CURSOR FOR
SELECT authors.id, au_lname, au_fname
FROM authors
ORDER BY authors.id

Another Example

DECLARE @AuthorID char(11)
	
DECLARE Cursor1 CURSOR READ_ONLY
FOR
SELECT au_id
FROM authors

OPEN Cursor1

FETCH NEXT FROM Cursor1
INTO @AuthorID

WHILE @@FETCH_STATUS = 0
BEGIN

	PRINT @AuthorID

	FETCH NEXT FROM Cursor1
	INTO @AuthorID

END

CLOSE Cursor1
DEALLOCATE Cursor1


where

cursor_name: The name of the server side cursor

LOCAL: The cursor will be available only to the batch, stored procedure, or trigger in which the cursor was created 

GLOBAL: The cursor is global to the connection 

FORWARD_ONLY: The cursor can only fetch data sequentially 

STATIC: The cursor will use a temporary copy of the data instead of base tables 

KEYSET: Specifies keysets so that the membership and order of rows in the cursor are fixed when the cursor is opened 

DYNAMIC: The cursor reflects all data changes made to the base tables as you scroll around the cursor 

FAST_FORWARD: The cursor is FORWARD_ONLY and READ_ONLY  

READ ONLY: The cursor [data] cannot be updated

SCROLL_LOCKS: The fetched data will be locked 

OPTIMISTIC: The cursor does not lock rows as they are read into the cursor 

select_statement: The standard select statement, cannot contain COMPUTE, COMPUTE BY, FOR BROWSE, and INTO keywords

UPDATE [OF column_name [,...n]]: Specifies which columns can be updated




SQL Server Hints



SQL Server Hints
----------------
What are hints?
Simply to influence query execution plans to retrieve data 
faster.

syscacheobjects
----------------
SQL server after compiling a query creates the execution 
plan and keeps it on syscacheobjects object.
You can query the object to see the existing query plans as 
follows:

select * from sys.syscacheobjects
where cacheobjtype='compiled plan'


Hints
-----

When you specify hints in your queries the query execution 
plans are biased toward your hints rather than using default
 strategies.

Types of Hints
--------------
Join Hints: Affects the joins [join types]
Query Hints: Affects overall execution plan
Table: Affects to table access 


Join Hints
----------
Loops: Uses nesting for join. Each row of the inner table is
 checked for condition satisfaction with the corresponding 
outer row.
Hash: One table is treated as a hash table and the other is 
scanned one row at a time and the hash function is used to 
find equalities

Merge: Each table is sorted first. Then they are compared 
row by row [corresponding]

Remote: In this case, at least one table is remote. The join
 is done at the right table side.


Example:

select *
-----
----
---
option (merge join)


or

select * 
from x
inner merge join y on...


Query Hints:
------------
Specified at the end of the query with keyword 'Option'


select * from x
------------
------------
option (recompile, fast 80)
Hash Group or Order groups:  Aggregations (group by, compute, distinct) are done by hashing or ordering
Concat Union, Hash Union, Merge Union: All unions will be done with the specified union type
Loop Join, Hash Join, Merge Join: Joins will be done with the specified join types
FAST number_rows:
Force Order:
MaxDop:
Optimize For:
Recompile:
Keep Plan:
Expand Views:



Table Hints:
------------
Affects how the table will be locked or which index will be 
used for the query.
NoEXPAND
INDEX
fastfirstrow
nowait
rowlockpaglock
tablock
nolock
holdlock
ignore_triggers


Plan Guides
-----------
Sometimes queries are originated from a third part application and you have no control to change the query.
You can use plan guides to influence such queries. For example: Using plan guides you can specify the nature of the
 select, update, insert queries.
You can use built in stored procedures to create or drop 
plan guides.

sp_create_plan_guide
sp_control_plan_guide



Scalability: SQL Server 2005



Scalability: SQL Server 2005

After you have optimized your database design and the application design, you can improve the scalability of SQL Server in two ways
1.Scaling Up
2.Scaling Out

Scaling Up: Improve performance by
1. Adding more processors, memory, and storage capacity

2. Replacing existing hardware with faster hardware

Note: You also need the right version of SQL Server so that scaling up is supported.

How to scale up Processors:
SQL Server is mostly I/O bound not CPU bound, still better/faster CPU usually provides better performance [depends on the application need though].

Processor choices: 32 bit
64 bit x64
64 bit IA64
Hyperthread technology
Multiprocessor based server
Multicore based servers

It is always better to go for 64 bit than 32 bit as it will also support more memory. 64 bit x64 processors provide better performance than ia64 however if your work requires lots of floating point operations and the workload needs > 8 processors you can think about IA64 processors

Multiple processor systems provide better performance than the single processor systems. Windows implements SMP architecture of parallel computing and SQL Server 2005 also takes advantage of it.

Multiple processor systems usually performs better than the equivalent multicore uniprocessor systems.

Intel's hyperthreading technology may increase performance (10-20%) based on the applications (but not always)

Memory Subsystem:
As SQL server is I/O bound using more memory almost always increases performance. Though the amount of memory that we can add depends on the operating systems. 32 bit operating systems supports 4GB RAM max. For 32 bit windows 2 GB is reserved for operating system, in Windows Server 2003 we can specify 1 gb for operating system so getting 3gb for SQL Server.

32 bit SQL Servers can address 4 gb ram, the actual ram amount depends on the operating system used. if 32 bit windows then 2 to 3 gb max as mentioned before

When 64 bit windows and 64 bit sql server then physical memory limits 32TB.

I/O SubSystems:
You can improve disk I/O subsystem by using an appropriate RAID array or SAN (Storage Area Network) solution

Using Network Interface Card (NIC) teaming, you can also improve performance. NIC teaming allows to bond multiple physical NICs into one logical network device. Teaming provides load balance, fault tolerance, and high bandwidth.

Scaling Out will be discussed later.

Scaling Out involves using multiple SQL servers to provide increased scalability.



Scaling Out



Methods

  • SQL Server instances
  • Clustering
  • Database mirroring
  • Log shipping
  • Replication
  • Shared scalable databases
  • SQL Server instances In the same computer install multiple instance of SQL Server to take advantage of multiple processors. Each instance may use separate processor with separate lock manager, worker threads, tempdb system database.

  • Clustering Failover Clustering can provide robustness and protection against failure. Clustering can provide scaling using spare hardware through passive nodes

  • Database mirroring With database mirroring transaction logs are directly sent to the mirror. The mirror is up to date and can be used in case of failure of the principle server.

  • Log shipping It depends on the transaction log backups, file copying. The secondary database need not to be updated in real time. The secondary database is read only and hence, be in great use for reporting purposes.

  • Replication Merge Replication: Both way, both from and to publishers and subscribers
    Transactional Replication: Publisher to the subscriber

  • Shared scalable databases Scale out a read-only database only for reporting purposes.



    Dynamic Management Views



    Dynamic Management Views provide ways to analyze database performance and to find the cause behind bad-performing SQL server databases/instances. Bad performance can be due to: poor design, insufficient memory, poorly configured system, disk bottlenecks, poorly written queries and many others

    Previously Windows System Monitor(perfmon.exe) and SQL server profiler were used to find the cause of bad-performance. Now, Dynamic Management Views can help a lot better.

    Dynamic Management Views are categorized into 12 categories

    • Common language runtime:
    • Database: Provides details about database sizes, files used, and partition information.
    • Database mirroring related: About mirroring and mirroed databases
    • Execution related: Provides insight into query execution statistics.
    • Full text search: Provides information on full-text catalogs, indexes, full-text crawl memory buffer
    • Input/Output Related: Provides insights into I/O operations, I/O devices, and database file statistics.
    • Index related: Database file statistics
    • Query notification related: Insights into active query notifications subscriptions in the server
    • Replication related: Insights into the workings of replication in the database
    • Service Broker Related: Insights into the workings of Service Broker
    • Sql server operating system related: Insights into the internal operations of the SQL Server OS.
    • Transaction Related: Insights into the operations of active transactions


    Performance Data Warehouse: A historical archive of periodic snapshots of the DMV data of interest. How can it help? the problem may occur only at night 3:00 a.m. and when there are not many users. If you want to fix the issue in the morning Performance Data Warehouse will be of great help.



    SQL Server Database System Tuning



    Database tuning approach

    • Proactive approach
    • Reactive approach
    Best Approach: Use a mix of both.

    Be aware (collect information) of the followings that may have significant impact on the performance.
    Hardware: Server, Available memory, number of processors, disk subsystems.

    Network Infrastructure: Network Cards, Switches, and the rest of your LAN and WAN.

    Operating System: Make sure the OpSys is optimally configured for SQL Server.

    Database Engine: Know about the SQL Server Architecture and about your operational environments.

    Database: Tune database properly

    Client Connection: How clients connect to the server

    Monitoring and Tuning Hardware: Use Network Monitor Agent, Performance Logs and Alerts, System Monitor, and Task Manager.

    System monitor (perfmon.exe) is a great tool for the purpose Using perfmon.exe you can also find where the bottleneck is Processor Subsystem, Memory Subsystem, I/O Subsystem

    Monitoring and Tuning SQL Server: Tools:
    • DBCC Commands
    • Dynamic Management Views
    • SQL Server Profiler
    • SQL Server Management Studio
    • System Stored Procedures
    • SQL Trace
    System Monitor: when SQL server is installed many new parameters (performance objects and their counters) are added to System Monitor (perfmon.exe) that help to monitor SQL Server performance.

    SQL Server Profiler: This tool is used to capture traces like client activities, stored procedure calls, lock activities. SQL server profiler can help to determine if the client application is at fault.

    SQL Trace: create traces using using stored procedures.

    Tuning the tempdb system database

    • Capacity plan and pre-allocate adequate space
    • Separate the log file from the database file
    • Use multiple secondary files for the tempDB system database
    • Use a faster disk
    • Use an appropriate RAID solution.
    • Use local disk sybsystem for tempdb.
    Tuning Database Layout

    Use file and filegroup architecture properly.
    File: Use multiple data files for your databases.

    Filegroups: example: create two file groups and place them in different drives. Create tables in one file group and create non-clustered indexes in the other. table I/O and Index I/O are now divided.



    SQL Server: Index



    SQL Server: Index

    • Indexes make database access faster. Without index your queries will run but indexes can increase the performance dramatically.
    • You can define multiple indexes for a table and select the index that is required for current operations.
    • Only one clustered index is supported for a table
    • To get advantage of indexes you have to mention the index related constraints in your where clause like where last_name ='xyz'
    • If you have indexes on two or more columns, in where clause mention the first column name/constraint first [that was first in the index creation].
    • A clustered index contains table data sorted in the index where a non-clustered index contains reference to the table data or clustered index. Non-clustered indexes are both physically and logically independent of table data.
    Index Best Practices

    1. Select a column/(columns) for indexes that will provide good uniqueness and selectivity otherwise indexing may degrade the performance
    2. Create indexes that result in lower number of rows to be searched
    3. Create indexes that select a range of rows
    4. Try to create clustered index with as uniqueness as possible
    5. Keep indexes as narrow as possible (not many/unnecessary columns)
    6. Don't index very small table


    In SQL server, you can create indexes through your sql statements or using the development studio interface.



    SQL Server : Backups



    Why are backups needed?

    To protect accidental data loss. Still, if you use highly available and fault-tolerant systems like SAN, and RAID, you may need to backup your database regularly. These fault tolerant systems can not provide accidental data delete by users, accidental data corruption from software and hardware failure. If you have a disaster recovery site or a secondary datacenter to where all data are replicated and data changes are stored, then you may not need backup but otherwise regular backups are always useful.

    Data backup can restore data until the last backup. . Transaction Logs may help to restore data up to the point of failure. Restore data from the data backup, then if you have the transaction log up to the failure apply it to the data.

    SQL Server Recovery Models:

    • Simple Recovery Model. Transaction logs are not used
    • Full Recovery Model: Use both data and transaction log backups
    • Bulk-logged recovery model: Like full recovery model. But here bulk operations are minimally logged to the transaction log. So full recovery becomes faster.
    Types of Backups
    • Full database backup: Full database, all files and file groups are backed up
    • Partial Back up: It's not the differential backup. Here, all primary file groups and any other file groups that are read-write are backed up. But read-only file groups are not backed up by default.
    • File or file group backup: Usefull when full back ups take too long. Backup in parts.
    • Differential back up: Backup only the changes. Should be applied to a full backup.
    • Log backup: In log back ups, transaction logs are backed up regularly. It helps in bulk logged recovery model and full recovery model.
    • Copy only backups:
    • Full text catalog backups


    Knowing about backup devices, media sets, and backup history tables is also important.

    Mirrored Media Sets: Backup data to more than one media at the same time.

    Backup Strategy:

    Based on your company need and type of data, you should come up with a backup strategy.

    Some backup strategies

    Strategy - 1
    1. Take full database backup every saturday night
    2. Take a differential backup every wednesday night
    3. Perform, continual transaction log backups every 30 minutes
    Strategy - 2: If the database is too big, and user activities need continuous uptime and optimal performance
    1. Filegroup 1 backup every saturday night
    2. Filegroup 2 backup every sunday night
    3. File group 1 differential backup every Tuesday night
    4. File group 2 differential backup every wednesday night
    5. File group 1 differential backup every Thursday night
    6. File group 2 differential backup every Friday night
    7. Perform, continual transaction log backups every 30 minutes

    Backup System Databases

    It is also important to back up system databases like master, model, msdb, tempdb, distribution, resource.



    Differences between Java Bean and EJB



    please check http://members.tripod.com/gsraj/ejb/chapter/

    A good book on EJB



    Opening and reading files with Java JDK 1.0.x



       1. Open the file with the File class;
       2. Create a FileInputStream object using the File object;
       3. Convert the FileInputStream to a BufferedInputStream to greatly increase file reading speed;
       4. Convert the BufferedInputStream to a DataInputStream; the methods of DataInputStream give me a fair amount of flexibility in reading the data.
       5. Read the file until the end
    
    
    File f = new File("mydata.txt"); 
    FileInputStream fis = new FileInputStream(f); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    DataInputStream dis = new DataInputStream(bis);  
    String record = null; 
    
    try { 
    
       while ( (record=dis.readLine()) != null ) { 
          // 
          // put your logic here to work with "record" 
          // 
       } 
    
    } catch (IOException e) { 
       // 
       // put your error-handling code here 
       // 
    } 
    



    Java XML Example - XML File Parse and Use Attributes



    A good example: http://developerlife.com/tutorials/?p=25
    Another very good example: http://www.developerfusion.co.uk/show/2064/: I followed this code to extract attribute values from an xml file.



    MVC : Struts : Java : Industry Web Application



    Industries use frameworks for application development quite often. 
    
    For example: Java concepts like JSP, Servlet, Swing, Bean, JDBC can 
    
    be used directly to create web-applications but when such 
    
    applications become big, it becomes difficult to maintain and 
    
    develop them further. Hence, frameworks like struts are used to develop 
    
    large web-based Java applications. This makes maintenance and 
    
    further development easier. If you need to write a very simple web 
    
    application with a few pages, then you might consider using 
    
    JSP/Servlet directly otherwise Struts like frameworks are better 
    
    options.
    
    Struts-1 uses the concept Model View Architecture (MVC) and provides 
    
    the controller. In MVC model, Model represents business logic, View 
    represents user interfaces, and Controller represents/controls control 
    flow of the application. 
    
    
    Struts' control layer is based on standard technologies like 
    
    Java Servlets, JavaBeans, ResourceBundles, and XML, as well as 
    
    various Apache Commons  packages, like BeanUtils and Chain of 
    
    Responsibility. 
    
    For the Model,  struts-1 framework can interact with standard 
    data access technologies, like JDBC  and EJB,  as well as most 
    any third-party packages, like Hibernate,  iBATIS,  or Object Relational 
    Bridge.  For the View,  the framework works well with JavaServer Pages,  
    including JSTL and JSF,  as well as  Velocity Templates,  XSLT,  and 
    other presentation systems.
    
    
    The framework's Controller acts as a bridge between the application's Model and the web View. 
    When a request is received, the Controller invokes an Action  class. The Action class consults 
    with the Model to examine or update the application's state. The framework provides an ActionForm  
    class to help transfer data between Model and View.
    
    Struts-1 Configuration
    -----------------------
    web.xml is one of the configuration files. It is an XML-formatted file that works as a 
    deployment descriptor. 
    
    struts-config.xml is another resource file to initialize the applications resources. 
    These resources include  ActionForms  to collect input from users,  ActionMappings  
    to direct input to server-side  Actions,  and ActionForwards to select output pages.
    
    Sample struts-config.xml file.
    
    <?xml version="1.0" encoding="ISO-8859-1" ?>
        <!DOCTYPE struts-config PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
              "http://struts.apache.org/dtds/struts-config_1_3.dtd">
        <struts-config>
            <form-beans>
                <form-bean
                    name="logonForm"
                    type="app.LogonForm"/>
            </form-beans>
            <action-mappings>
                <action
                    path="/Welcome"
                    forward="/pages/Welcome.jsp"/>
                <action
                    path="/Logon"
                    forward="/pages/Logon.jsp"/>
                <action
                    path="/LogonSubmit"
                    type="app.LogonAction"
                    name="logonForm"
                    scope="request"
                    validate="true"
                    input="/pages/Logon.jsp">
                    <forward
                        name="success"
                        path="/pages/Welcome.jsp"/>
                    <forward
                        name="failure"
                        path="/pages/Logon.jsp"/>
                </action>
                <action
                    path="/Logoff"
                    type="app.LogoffAction">
                    <forward
                        name="success"
                        path="/pages/Logoff.jsp"/>
                </action>
            </action-mappings>
            <message-resources parameter="resources.application"/>
        </struts-config>
    
    Other resources like Validators can be initialized here.
    
    



    Linked List and Iterator in Java



    /*
     * LinkedList.java
     *
     * Created on January 10, 2008, 8:51 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
    
    package linkedlist;
    
    import java.util.List;
    import java.util.LinkedList;
    import java.util.Iterator;
    import java.util.ListIterator;
    import java.util.Collections;
    import java.util.Random;
    
    /**
     *
     * @author Sayed
     */
    public class LinkedListTest {
        
        /** Creates a new instance of LinkedList */
        public LinkedListTest() {
        }
        
        /**
         *Example operations using linked lists
         */
        
        public void linkedListOperation(){
            
            final int MAX = 10;
            int counter = 0;
    
            //create two linked lists
            List listA = new LinkedList();
            List listB = new LinkedList();
    
            //store data in the linked list A
            for (int i = 0; i < MAX; i++) {
                System.out.println("  - Storing Integer(" + i + ")");
                listA.add(new Integer(i));
            }
           
            //print data from the linked list using iterator 
            Iterator it = listA.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
    
            //print data from the linked list using listIterator. 
            counter = 0;
            ListIterator liIt = listA.listIterator();
            while (liIt.hasNext()) {
                System.out.println("Element [" + counter + "] = " + liIt.next());
                System.out.println("  - hasPrevious    = " + liIt.hasPrevious());
                System.out.println("  - hasNext        = " + liIt.hasNext());
                System.out.println("  - previousIndex  = " + liIt.previousIndex());
                System.out.println("  - nextIndex      = " + liIt.nextIndex());
                System.out.println();
                counter++;
            }
    
    
            //retrieve data from the linked list using index
            for (int j=0; j < listA.size(); j++) {
                System.out.println("[" + j + "] - " + listA.get(j));
            }
    
            //find the location of an element
            int locationIndex = listA.indexOf("5");
            System.out.println("Index location of the String \"5\" is: " + locationIndex);  
    
            //find the first and the last location of an element
            System.out.println("First occurance search for String \"5\".  Index =  " + listA.indexOf("5"));
            System.out.println("Last Index search for String \"5\".       Index =  " + listA.lastIndexOf("5"));
    
            //create a sublist from the list 
            List listSub = listA.subList(10, listA.size());
            System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + listSub);
    
            //sort the sub-list
            System.out.println("Original List   : " + listSub);
            Collections.sort(listSub);
            System.out.println("New Sorted List : " + listSub);
            System.out.println();
    
            //reverse the new sub-list
            System.out.println("Original List     : " + listSub);
            Collections.reverse(listSub);
            System.out.println("New Reversed List : " + listSub);
            System.out.println();
    
            //check to see if the lists are empty
            System.out.println("Is List A empty?   " + listA.isEmpty());
            System.out.println("Is List B empty?   " + listB.isEmpty());
            System.out.println("Is Sub-List empty? " + listSub.isEmpty());
            
            //compare two lists
            System.out.println("A=B? " + listA.equals(listB));        
            System.out.println();
    
            //Shuffle the elements around in some Random order for List A
            Collections.shuffle(listA, new Random());
    
            //convert a list into an array
            Object[] objArray = listA.toArray();
            for (int j=0; j < objArray.length; j++) {
                System.out.println("Array Element [" + j + "] = " + objArray[j]);
            }
    
            //clear listA
            System.out.println("List A   (before) : " + listA);        
            System.out.println();
            listA.clear();
            System.out.println("List A   (after)  : " + listA);        
            System.out.println();
            
        }
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            LinkedListTest listExample = new LinkedListTest();
            listExample.linkedListOperation();
        }
        
    }
    



    Set, TreeSet, Iterator in Java



    /*
     * TreeSetExample.java
     *
     *Illustrates mathematical set operations
     *
     * Created on January 10, 2008, 9:28 PM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
    
    package treesetexample;
    import java.util.Set;
    import java.util.TreeSet;
    import java.util.Iterator;
    
    /**
     *
     * @author Sayed
     */
    
    public class TreeSetExample {
        
        /** Creates a new instance of TreeSetExample */
        public TreeSetExample() {
        }
        
        //example set operations 
         public static void treeSetOperations() {
    
            final int MAXIMUM = 20;
    
            //create a TreeSet
            Set ss = new TreeSet();
    
            //store data in the set, set can contain only one type of data
            for (int i = 0; i < MAXIMUM; i++) {
                System.out.println("  - Storing Data(" + i + ")");
                ss.add(new Integer(i));
            }
    
            //display set data using an iterator
            Iterator it = ss.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
        }
    
            
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            TreeSetExample treeSet = new TreeSetExample();
            treeSet.treeSetOperations();
        }
        
    }
    



    Java Bean : Basic Idea



    What is Java bean?
    Just a component technology. You can create platform independent components using Java beans. 
    
    Key Bean Concepts:
    
    1. introspection: Through introspection beans expose their properties, methods, and events. Beans support 
    introspection in two ways:
       1.1: Design patterns: The Introspector class examines beans for design patterns to discover bean features
    
       1.2: Through a related bean information class that implements the BeanInfo interface. The class lists the 
    bean features that are to be exposed 
    
    2. Properties: Are the appearance and behavior characteristics of a bean that can be changed at 
    design time
    
    3. Beans use events to communicate with other beans
    
    4. Persistence enables beans to store and retrieve their state using serialization
    
    5. Beans provide methods that can be called from other beans, or scripting language
    
    
    Bean Property Types
    --------------------
    
    # Simple – with a single value 
    
    # Indexed – a range of values 
    
    # Bound – a change to the property results in a 
    notification being sent to some other bean
    
    # Constrained – a change to the property requries 
    validation by other bean
    
    
    Bean Properties can be
        *Writable – can be changed
              o Standard
              o Expert
              o Preferred 
        * Read Only – cannot be changed
        * Hidden – can be changed. not disclosed with the BeanInfo class 
    



    How to upload data from an excel file to database using servlets?



    Use third party API bundles like jexcelApi.
    http://jexcelapi.sourceforge.net/.

    ---
    create an XML file to define the structure of your excel file like how many columns, column names, corresponding database table/class column/variable name,

    Create a Java class that can retrieve information from that xml file. You can use XPATH and DOM for the purpose. check http://www.ibm.com/developerworks/library/x-javaxpathapi.html for ideas

    ---
    write an html form that use input type='file', the form action should point to the servlet that will collect data from the excel file and store it in the database. servlet will collect data from the input stream

    -----------
    in the servlet use the class that represents the xml file. to get information about the file that will help mapping the excel file data to the corresponding table column. You can also create a class representing the database table. From servlet extract data, create an object of table class type, and create a function that takes the object and inserts into the table.

    ---------------
    How servlet will process the excel file:

    jexcelAPI Workbook class represents the total workbook
    use getsheet method of workbook class to get the sheet number 0,1,2....

    use getCell method of worksheet to get a particular cell object in the excel file
    use getContents on the cell object to get data in string type.

    from the XML file having excel file structure, you can get number of columns in the file. So you can write a look that will read data row,column wise from the excel file

    ----
    code to process excel file [in servlet]

    Workbook workbook = Workbook.getWorkbook(new File("myfile.xls"));

    Sheet sheet = workbook.getSheet(0);

    Cell a1 = sheet.getCell(0,0);

    Cell b2 = sheet.getCell(1,1);

    Cell c2 = sheet.getCell(2,1);

    String stringa1 = a1.getContents();

    String stringb2 = b2.getContents();

    String stringc2 = c2.getContents();

    ----------------------

    check the following webpage, it provides file upload and extract data from input stream in servlet applications

    http://jexcelapi.sourceforge.net/resources/faq/



    Java Collections Framework



    Some URLs
    http://www.javaworld.com/javaworld/jw-11-1998/jw-11-collections.html?page=2
    http://www.informit.com/articles/article.aspx?p=781700
    http://java.sun.com/docs/books/tutorial/collections/index.html
    Vector Vs. ArrayList
    Vector vs. Hashtable
    ArrayList vs. LinkedList



    Unit Testing in Eclipse for Java



    Unit Testing in Eclipse for Java: just an overview

    Why Unit Test?

    Say, you have written some Java classes, before making use of them in real application functionalities, it's always better to check whether the classes (their functions/methods) are working properly. Unit tests simply test a single unit like a single class, or a single function at a time. It's almost always a good practice to design the software first, also design the classes and their methods along with interactions among classes, early in the project. After, classes and their methods are written, you should do some testing to make sure they are working properly.

    How to Unit test in Eclipse?

    1. You need to add junit.jar in your project build path. You can do that by selecting the project, then right click, then select properties, the java build path, then libraries tab, and then add jars/add external jars and select JUnit.jar.

    2. You can create a folder to keep your unit test codes say unittestcodes.

    3. The basic idea is, to test a class, you will need to create a test case class with methods like setUp, tearDown, and test methods for all the methods that you want to test (one for one). The setUp() method can be used to create the data for testing [you have to write the code though]. The other test methods will call the corresponding class methods using the data to check if the methods are working properly or not. Methods like assertTrue may come handy in the test methods.

    4. How to create these test classes and test methods?

    Right click the folder for testcode like unittestcodes, select new, select other, type Junit in the text box, select Junit test case...and then provide other parameters like the name of your test class, which class do you want to test, do you want to have setUp(), tearDown() methods or not?. In the next step, you have to select which methods of the class you want to test. Then the test class (skeleton) will be written for you.

    5. In the setUp() method, write code to build test data. From the other test methods call the related class methods to test them.

    6. How to run the experiment: right click the name of this test class from the left window, select run as, select Junit test case. Now analyze the output and fix the class methods if required. Try with different data, data from different ranges, boundary value data and you know what to test in your use cases.



    What is Spring Framework? What does it mean to J2EE developers



    What is Spring Framework? What does it mean to J2EE developers?

    Spring is a light-weight framework, very often referred as an alternative/competitor to EJB, for the development of enterprise-type applications. Spring provides many features such as declarative transaction management, access to remote logic using RMI or web services, mailing facilities and database abstraction.

    Features of Spring Framework

    1. Transaction Management: A generic abstraction layer for transaction management that removes low-level interactions
    2. JDBC Exception Handling: An exception hierarchy to simplify the error handling strategy
    3. Integration with Hibernate, JDO, and iBATIS
    4. AOP Framework: Aspect Oriented Programming Framework
    5. MVC Framework: Spring provides MVC web application framework built on core Spring functionality


    Spring Architecture

    1. Spring AOP: Provides declarative enterprise services such as declarative transaction management
    2. Spring ORM: Provides integration layers for object-relational mapping APIs, including JDO, Hibernate and iBatis for database access.
    3. Spring Web: Provides web application development stack that includes Spring MVC.
    4. Spring DAO: Provides standardization to data access using the technologies like JDBC, Hibernate or JDO.
    5. Spring Context: Provides support for using message sources, and resources. It is based on Java bean.
    6. Spring Web MVC: Provides MVC for web applications.
    7. Spring Core: Provides Dependency Injection features



      EJB 3: Stateless Bean



      
      No need to maintain the state of a bean between calls. 
      
      //CalculatorBean.java
      
      @Stateless
      public class CalculatorBean implements CalculatorRemote, CalculatorLocal
      {
         public int add(int x, int y)
         {
            return x + y;
         }
      
         public int subtract(int x, int y)
         {
            return x - y;
         }
      }
      
      
      //CalculatorRemote.java
      import javax.ejb.Remote;
      @Remote
      public interface CalculatorRemote extends Calculator
      {
      
      }
      
      
      //CalculatorLocal.java 
      import javax.ejb.Local;
      @Local
      public interface CalculatorLocal extends Calculator
      {
      }
      
      
      //Client.java
      
      import tutorial.stateless.bean.Calculator;
      import tutorial.stateless.bean.CalculatorRemote;
      import javax.naming.InitialContext;
      
      public class Client
      {
         public static void main(String[] args) throws Exception
         {
            InitialContext ctx = new InitialContext();
            Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote");
      
            System.out.println("1 + 1 = " + calculator.add(1, 1));
            System.out.println("1 - 1 = " + calculator.subtract(1, 1));
         }
      }
      
      



      EJB 2: How to build a stateless EJB



      EJB 2: How to build a stateless EJB

      1. Install an EJB Server
      2. Specify the EJB Remote Interface
      3. Specify the Home Interface
      4. Write the EJB bean Class
      5. Create the ejb-jar File
      6. Deploy the EJB bean
      7. Write the EJB Client
      8. Run the Client



      EJB 3: Statefull EJB



      
      States need to be maintained between calls. In EJB3 all beans are homeless [no home interface]
      
      //ShoppingCartBean.java
      
      import java.io.Serializable;
      import java.util.HashMap;
      import javax.ejb.Remove;
      import javax.ejb.Stateful;
      import javax.ejb.Remote;
      
      
      @Stateful
      @Remote(ShoppingCart.class)
      public class ShoppingCartBean implements ShoppingCart, Serializable
      {
         private HashMap cart = new HashMap();
      
         public void buy(String product, int quantity)
         {
            if (cart.containsKey(product))
            {
               int currq = cart.get(product);
               currq += quantity;
               cart.put(product, currq);
            }
            else
            {
               cart.put(product, quantity);
            }
         }
      
         public HashMap getCartContents()
         {
            return cart;
         }
      
         @Remove
         public void checkout()
         {
            System.out.println("To be implemented");
         }
      }
      
      
      //ShoppingCart.java
      //remote interface
      import java.util.HashMap;
      import javax.ejb.Remove;
      
      public interface ShoppingCart
      {
         void buy(String product, int quantity);
      
         HashMap getCartContents();
      
         @Remove void checkout();
      }
      
      
      //client
      //Client.java
      //client uses JNDI to look up for EJB services
      
      import java.util.HashMap;
      import javax.naming.InitialContext;
      import org.jboss.tutorial.stateful.bean.ShoppingCart;
      
      
      public class Client
      {
         public static void main(String[] args) throws Exception
         {
            InitialContext ctx = new InitialContext();
            ShoppingCart cart = (ShoppingCart) ctx.lookup("ShoppingCartBean/remote");
      
            System.out.println("Buying 1 memory stick");
            cart.buy("Memory stick", 1);
            System.out.println("Buying another memory stick");
            cart.buy("Memory stick", 1);
      
            System.out.println("Buying a laptop");
            cart.buy("Laptop", 1);
      
            System.out.println("Print cart:");
            HashMap fullCart = cart.getCartContents();
            for (String product : fullCart.keySet())
            {
               System.out.println(fullCart.get(product) + "     " + product);
            }
      
            System.out.println("Checkout");
            cart.checkout();
      
            System.out.println("Should throw an object not found exception by invoking on cart after @Remove method");
            try
            {
               cart.getCartContents();
            }
            catch (javax.ejb.EJBNoSuchObjectException e)
            {
               System.out.println("Successfully caught no such object exception.");
            }
      
      
         }
      }
      



      EJB 3: Entity Bean Basic



      Plain Java objects with persistence storage. They are not 
      remotable and must be accessed through the new 
      javax.persistence.EntityManager service. 
      
      An entity bean implementation is provided in the following 
      three files/classes
      
      Beans
      Order.java
      LineItem.java
      
      Entity Manager
      ShoppingCartBean.java
      
      //Order.java
      import javax.persistence.CascadeType;
      import javax.persistence.Entity;
      import javax.persistence.FetchType;
      import javax.persistence.GeneratedValue; import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.OneToMany;
      import javax.persistence.Table;
      import javax.persistence.Id;
      import javax.persistence.CascadeType;
      import javax.persistence.FetchType;
      import java.util.ArrayList;
      import java.util.Collection;
      
      @Entity
      @Table(name = "PURCHASE_ORDER")
      public class Order implements java.io.Serializable
      {
         private int id;
         private double total;
         private Collection lineItems;
      
         @Id @GeneratedValue(strategy=GenerationType.AUTO)
         public int getId()
         {
            return id;
         }
      
         public void setId(int id)
         {
            this.id = id;
         }
      
         public double getTotal()
         {
            return total;
         }
      
         public void setTotal(double total)
         {
            this.total = total;
         }
      
         public void addPurchase(String product, int quantity, double price)
         {
            if (lineItems == null) lineItems = new ArrayList();
            LineItem item = new LineItem();
            item.setOrder(this);
            item.setProduct(product);
            item.setQuantity(quantity);
            item.setSubtotal(quantity * price);
            lineItems.add(item);
            total += quantity * price;
         }
      
         @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="order")
         public Collection getLineItems()
         {
            return lineItems;
         }
      
         public void setLineItems(Collection lineItems)
         {
            this.lineItems = lineItems;
         }
      }
      
      
      
      
      
      //LineItem.java
      import javax.persistence.Entity;
      import javax.persistence.GeneratedValue; import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.JoinColumn;
      import javax.persistence.ManyToOne;
      import javax.persistence.Entity;
      
      @Entity
      public class LineItem implements java.io.Serializable
      {
         private int id;
         private double subtotal;
         private int quantity;
         private String product;
         private Order order;
      
      
         @Id @GeneratedValue(strategy=GenerationType.AUTO)
         public int getId()
         {
            return id;
         }
      
         public void setId(int id)
         {
            this.id = id;
         }
      
         public double getSubtotal()
         {
            return subtotal;
         }
      
         public void setSubtotal(double subtotal)
         {
            this.subtotal = subtotal;
         }
      
         public int getQuantity()
         {
            return quantity;
         }
      
         public void setQuantity(int quantity)
         {
            this.quantity = quantity;
         }
      
         public String getProduct()
         {
            return product;
         }
      
         public void setProduct(String product)
         {
            this.product = product;
         }
      
         @ManyToOne
         @JoinColumn(name = "order_id")
         public Order getOrder()
         {
            return order;
         }
      
         public void setOrder(Order order)
         {
            this.order = order;
         }
      }
      
      
      
      
      
      //ShoppingCartBean.java
      Interacts with Order as a plain Java object. The checkout()
       method stores orders with persistence storage by using the 
      required EntityManager service.
      
      
      import javax.ejb.Remote;
      import javax.ejb.Remove;
      import javax.ejb.Stateful;
      import javax.persistence.EntityManager;
      import javax.persistence.PersistenceContext;
      import javax.persistence.PersistenceContext;
      
      
      @Stateful
      @Remote(ShoppingCart.class)
      public class ShoppingCartBean implements ShoppingCart, java.io.Serializable
      {
         @PersistenceContext
         private EntityManager manager;
         private Order order;
      
         public void buy(String product, int quantity, double price)
         {
            if (order == null) order = new Order();
            order.addPurchase(product, quantity, price);
         }
      
         public Order getOrder()
         {
            return order;
         }
      
         @Remove
         public void checkout()
         {
            manager.persist(order);
         }
      }
       
      
      GNU Distribution Without Warranty License
      



      Comparison EJB 2 and EJB 3



      Comparison EJB 2 and EJB 3

      1. EJB 2.0 has deployment descriptors but EJB 3.0 has no deployment descriptor
      2. In EJB 2.0 you have to write Home and Remote Interfaces But in EJB3.0 you do not need to write Home interfaces
      3. In EJB 3.0, all entities are identified with '@'
      4. In EJB 3.0 methods like ejbPassivate, ejbActivate, ejbLoad, ejbStore, etc. are not required
      5. EJB 3.0 is totally newly designed including the entity manager
      6. EJB 3.0 entity beans are just POJO
      7. No EJB container required to run
      8. EJB 3.0 supports Java Persistence API for all of its data needs
      9. No XMLDeployment Descriptors but annotations
      10. EJB 3.0 entity beans/JPA becomes local
      11. Queries are very flexible. Multiple levels of joins are enabled
      12. EJB 3.0 pluggable, security enabled



      JDBC: Stored Procedure



      Sample stored procedure call using JDBC:
      Call stored procedure to change/set a value in the database

      //set birthday - supply professor name try { String professor= "dylan thomas"; CallableStatement proc = connection.prepareCall("{ call set_birth_date(?, ?) }"); proc.setString(1, professor); proc.setString(2, '1950-01-01'); cs.execute(); } catch (SQLException e) { // .... } Stored procedures can also return result/data to the caller: like //return birth day connection.setAutoCommit(false); CallableStatement proc = connection.prepareCall("{ ? = call birthday_when(?) }"); proc.registerOutParameter(1, Types.Timestamp); proc.setString(2, professorName); cs.execute(); Timestamp age = proc.getString(2); Stored procedures can also return complex data like resultsets. JDBC drivers from oracle, Sql Server, PostgreSQL support this.



      SCJA: Java Really Basic Stuffs - But you may need to know them for exams like SCJA



      SCJA: Syllabus

      http://www.sun.com/training/catalog/courses/CX-310-019.xml

      Floating point types: http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
      Enumerated types in Java: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
      is a finite set of symbolic literals
      is represented as first-class object
      are allowed in case statements
      the literals may be any valid Java identifier

      Java Interface
      an interface may NOT contain any concrete method implementations
      an interface is NOT a class of any style
      an interface is NOT a member of a class
      An interface defines a set of abstract methods that may have many implementations.

      Class Association, Class Composition, dependency:
      Compositions may also have navigation methods, but these methods must NOT pass references to the owned objects. This is usually achieved by passing back a copy of the object rather than the owned object itself.
      Composition implies that the owning object controls the life cycle of the owned object
      Dependency merely imply that one object uses another object during computations.

      disadvantages of proper information hiding?
      Access to object attributes incur a runtime penalty.However, the Sun hotspot JVM usually can eliminate the added overhead by "inlining" the methods where they are called.
      a mutator method is longer than an assignment operation
      it is time consuming to use methods to access object attributes rather than direct access.

      program to an interface
      References to objects should be declared as interfaces rather than concrete classes
      the reference variables to objects that need to be as generic as possible. This is the "program to an interface" principle.

      correct representation of an attribute in UML

      - attr : int uml

      0..1 indicates zero or one multiplicity, which is how you can represent an optional association.

      ? is NOT a valid multiplicity indicator.
      * is an abbreviation for 0..*.
      M is NOT a valid multiplicity indicator.
      ? is NOT a valid multiplicity indicator.
      0..* is exactly how to indicate zero or more.

      Statement types



      Java: Some basic important stuffs



      Data types to represent telephone numbers:

      a string of ten digits can represent all ten-digit telephone numbers.
      an object can hold data (integers or strings) of the elements of a telephone number
      an integer data type can represent all ten-digit numbers
      -- a boolean can only represent two values
      an enumerated type can only represent a fixed number of constant



      Abstract Class:

      An abstract class may have constructors, but it is illegal to invoke the new operator on an abstract class
      An abstract class is allowed to have method implementations
      There is no restriction about the placement of abstract classes in a class hierarchy
      It is legal for an abstract class to implement an interface and implement one or more interface methods



      Design a role player game:

      creating an abstract superclass for a generic player will simplify the design.
      This is because the maintenance of the common methods will be simplified.
      An abstract class is the perfect container, as a superclass, for the common methods



      Model

      A sports team with fixed number of players in which players may participate in other teams
      a many-to-many association from players to team Will work

      Java Bean convention for setter methods

      void setFirstName(String value)



      Data Hiding

      A well-encapsulated class must have all of its attributes marked private.
      A well-encapsulated class must hide all internal methods. This is because this is NOT part of the class's public interface.
      NOT all attributes require accessor or mutator methods.

      The principle of "programming to an interface"?

      Generalize the return type of a method. The return type of a method should be as abstract as possible, such that any object of that type could be returned. If a concrete class is used as the return type, then only an object of that type (or its subclasses) can be returned.

      A class hierarchy is a static part of the code structure. Polymorphism and program to an interface are principles that apply to the dynamic aspects of the code, such as the objects that are stored in variables and passed through methods.

      The parameter type of a method should be as abstract as possible, such that any object of that type could be passed in to the method. If a concrete class is used as the parameter type, then only an object of that type (or its subclasses) can be used as a parameter.

      The type of an instance variable should be as abstract as possible, such that any object of that type could be held by the owning object. If a concrete class is used as an instance variable type, then only an object of that type (or its subclasses) can be held in that variable.

      The relationship between classes and interfaces form only a static part of the code structure. Polymorphism and program to an interface are principles that apply to the dynamic aspects of the code



      JAVA: Some links: useful for exams like scjp/scja



      Assertions in Java: http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
      Enum in Java:http://www.java2s.com/Code/Java/Language-Basics/Enum.htm
      StringBuffer and StringBuilder Classes have similar methods where StringBuffer is synchronized: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
      Serialize and Deserialize: http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html
      java.util package is very important: http://java.sun.com/j2se/1.4.2/docs/api/java/util/package-summary.html



      SCJP: Java Operators



      Exams like SCJP test your understanding of Java operators and how to use them like:
      assignment operators: =, +=, -=
      arithmetic operators: +, -, *, /, %, ++, --
      relational operators: <, <=, >, >=, ==, !=
      logical operators: &, |, ^, !, &&, ||
      conditional operators: ? :
      Also operators to check the equality of two objects or two primitives

      In the following table operators and their precedences are shown. Upper rows operators have higher precedence. Same row operators have equal precedence. For equal precedence operators, All binary operators except the assignment operators work from left to right while assignment operators work from right to left.

      Operator Precedence
      OperatorsPrecedence
      postfixexpr++ expr--
      unary++expr --expr +expr -expr ~ !
      multiplicative* / %
      additive+ -
      shift<< >> >>>
      relational< > <= >= instanceof
      equality== !=
      bitwise AND&
      bitwise exclusive OR^
      bitwise inclusive OR|
      logical AND&&
      logical OR||
      ternary? :
      assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=
      The following quick reference summarizes the operators supported by the Java programming language.

      Simple Assignment Operator

      =	Simple assignment operator
      

      Arithmetic Operators

      + 	Additive operator (also used for String concatenation)
      - 	Subtraction operator
      *	Multiplication operator
      / 	Division operator
      %	Remainder operator
      

      Unary Operators

      + 	Unary plus operator; indicates positive value (numbers are positive without this, however)
      - 	Unary minus operator; negates an expression
      ++  	Increment operator; increments a value by 1
      --    	Decrement operator; decrements a value by 1
      !     	Logical compliment operator; inverts the value of a boolean
      

      Equality and Relational Operators

      ==	Equal to
      !=	Not equal to
      >	Greater than
      >=	Greater than or equal to
      <	Less than
      <=	Less than or equal to
      

      Conditional Operators

      && 	Conditional-AND
      || 	Conditional-OR
      ?:      Ternary (shorthand for if-then-else statement)
      

      Type Comparison Operator

      instanceof	Compares an object to a specified type 
      

      Bitwise and Bit Shift Operators

      ~	Unary bitwise complement
      <<	Signed left shift
      >>	Signed right shift
      >>>	Unsigned right shift
      &	Bitwise AND
      ^	Bitwise exclusive OR
      |	Bitwise inclusive OR
      



      Details about java operators



      SCJP: Classpath and Jar



      Java certification exams like SCJP test your knowledge about java classpath. Check here for an excellent resource on the topic .

      System classpath

      We can specify classpath in the command line or make use of a `system' class path. The IDEs have their own way of maintaining class paths. System class paths will be used by both the Java compiler and the JVM in the absence of specific instructions.

      Set Linux System Classpath:
      CLASSPATH=/myclasses/myclasses.jar;export CLASSPATH

      Windows:
      set CLASSPATH=c:\myclasses\myclasses.jar

      For permanent result, in Linux, put the commands in the file .bashrc in your home directory. On Windows 2000/NT, set it from `Control Panel', System, Environment Variables.

      You can also specify .jar files full of your required classes in your classpath.

      CLASSPATH=/usr/j2ee/j2ee.jar:.;export CLASSPATH

      where the `.' indicates `current directory'.

      From command line, if you want to add more paths to the classpath use:

      Linux:javac -classpath $CLASSPATH:dir1:dir2 ...

      Windows:javac -classpath %CLASSPATH%;dir1:dir2 ...

      if you have spaces in your path use double quote to concatenate words.

      Also check this resource



      SCJP: Topics and Resources : will be continued



      SCJP topics and related resources are provided. I have skimed through the resources at least one time.

      Garbage Collection

      Parameter Passing Command Line Parameter
      Access Modifiers, Package Declaration, Import
      Concurrency:java.lang.Thread and java.lang.Runnable Java Thread:wait/notify/notifyall-lock OOP Concept 1



      Java Collection Framework



      Array
      Benefits Constraints
      • Data access is fast.
      • Good for ordered data, which is not changed or searched frequently.
      • Inefficient if number of elements grow.
      • Inefficient if an element to be inserted in middle of collection.
      • Provides no special search mechanism.


      Linked List
      Benefits Constraints
      • Allows efficient inserts/delete at any location
      • Allows arbitrary growth of collection.
      • Applying order to the elements is easy.
      • Slower while accessing elements by index.
      • No special search mechanism is provided.



      Tree
      Benefits Constraints
      • Easy addition/deletion in middle.
      • Allows arbitrary growth.
      • A better and efficient search mechanism.
      • Ordering is peculiar and some comparison mechanism is required.
      • Searching is not efficient for unevenly distributed data.



      Hashtable
      Benefits Constraints
      • Efficient searching.
      • Good access mechanism.
      • Allows arbitrary growth of collection.
      • Not good for small data set because of overheads.
      • Overhead for storing keys for the values in collection.
      • Overhead of hashing scheme.



      SCJP: Language Fundamentals



      Class declaration and java source file.

      • Only "one" top-level public class is allowed per java source file.
      • The name of the java source file and the name of the top-level public class MUST be the same.
      • If no public class is there in a file, after compiling separate class files will be created for all classes in the file.
      • Package statement, import statements and class definition MUST appear in the order given.

      Keywords and Identifiers

      • Keywords are always in a lower case.
      • Some keywords: const, goto, strictfp, and volatile
      • Identifiers must start with either letter, $ or _ (underscore) and can have letter, $, _ or digits in it.
      • no keyword is allowed as identifiers
      abstract do import public transient
      boolean double instanceof return try
      break else int short void
      byte extends interface static volatile
      case final long super while
      catch finally native switch
      char float new synchronized
      class for package this
      continue if private throw
      default implements protected throws

      Default Values, Local Variables

      • Each primitive data type has a default value specified. Variable of primitive data type may be initialized
      • Only class member variables are automatically initialized. Method variables need explicit initialization
      • Local variables (also known as automatic variables) are declared in methods and in code blocks
      • Automatic variables are not automatically initialized
      • local variables should be explicitly initialized before first use. These are automatically destroyed when they go out of scope

      Arrays

      • Fixed-sized ordered collection of homogeneous data elements
        int[] ints; // array declaration
        ints = new ints[25]; // array construction at runtime.

      • Array declared, constructed and initialized at the same time.
        int[] ints = {1,2,3,4,5}; // array declaration,
      • An array of primitive data type created using the new keyword is automatically initialized. Each array element is initialized to its default value.
        For example,
        char[] arrayOfChars = new char[10];

      • Array of object references: An array of object references created using the new keyword is also initialized. Each array element is initialized to its default value, i.e. null.
        String[] names = new String[10];
      • length is a property of array (and not a method)
      • java.lang.Object is the superclass of an array

      Argument passing during method calls

      • Always a copy of argument value is passed to calling method
      • Arguments of primitive data types: first, a copy of the passing variable is made and then it is passed. The original copy remains unaffected
      • Object reference as an argument: A copy of object reference is passed for method calls. It still points to the same object. The original copy is affected.



      SCJP: Garbage Collection



      Garbage Collection

      • Java itself does memory management. You do not need to allocate memory at the time of object creation; also you do not need to free memory explicitly
      • Object is created either on the heap or on a stack
      • Memory heap: Objects created with new keyword are placed in heaps. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory becomes eligible for garbage collection
      • Stack: During method calls, objects are created for method arguments and method variables. These objects are created on stack. Such objects are eligible for garbage-collection when they go out of scope.
      • Garbage Collection is a low-priority thread in java
      • Garbage Collection cannot be forced explicitly. JVM may do garbage collection if it is running short of memory.
      • The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.
      • Garbage Collection is hardwired in Java runtime system. Java runtime system keeps the track of memory allocated. Therefore, it is able to determine if memory is still usable by any live thread. If not, then garbage collection thread will eventually release the memory back to the heap.
      • Garbage Collection usually adopts an algorithm, which gives a fair balance between responsiveness (how quickly garbage-collection thread yields?) and speed of memory recovery (important for memory-intensive operations). Responsiveness is especially important in real time systems.
      • An object is eligible for garbage collection when no object refers to it.
      • An object also becomes eligible when its reference is set to null. (Actually all references to the object should be null for it to be eligible.)
      • The objects referred by method variables or local variables are eligible for garbage collection when the method or their container block exits



      SCJP: Flow controls and exception



      Flow Control and Exceptions Flow control statements

      • Conditional: if, if-else and switch-case
      • Looping: for, while, do-while
      • Exception handling: try-catch-finally, throw
      • Ad hoc flow control: break, continue with or without labels

      switch statement

      switch(expression){
      case ConstantExpression: statement(s);
      case ConstantExpression: statement(s);
      .
      .
      .
      default: statement(s);
      }

      • expression: must be char, byte, short, or int, or a compile-time error occurs
      • long primitive can be used if type casted to int
      • Object reference cannot be used as expression
      • Every case expression must be unique
      • break statement may be used at the end of a case statement, to discontinue execution.
      • There can be at most only one default statement.
      • The order of case statements and default can be anything.
      break and continue
      • A break statement transfers the control out of an enclosing statement. break used within a loop breaks the execution of the current loop. In case of nested loops, the break statement passes the control to the immediate outer loop.
      • A continue statement breaks the current iteration and moves to next iteration.
      • break and continue with labels.
        • Labels specify the target (statement) for continue and break
        • continue with label does not jump to the labeled statement but instead jumps to the end of the labeled loop.
        • Same label identifiers can be reused multiple times as long as they are not nested.
        • Label names do not conflict with the same named identifier(variable, method or class name).

      Checked and Unchecked Exceptions

      Checked Exceptions
      • Checked Exceptions are checked by the compiler to see if these exceptions are properly caught or specified. If not, the code will fail to compile
      • Checked exception forces client program to deal with the scenario in which an exception may be thrown
      • Checked exceptions must be either declared or caught at compile time
      Unchecked Exceptions
      • Unchecked exceptions are RuntimeException and all of its subclasses.
      • Class java.lang.Error and its subclasses also are unchecked.
      • Unchecked Exceptions are not checked by the compiler.
      • Runtime exceptions do not need to be caught or declared.



      Code Conventions for the Java Programming Language



      Why Have Code Conventions?

      • 80% of software life cycle is spent on software maintenance.
      • Hardly the original author maintains a software
      • Code Conventions improve the readability of the software
      • If you require to ship your source code as a product, code conventions make your product well packaged

      Java Code Conventions

      • Avoid assigning several variables to the same value in a single statement
      • Avoid using an object to access a class (static) variable or method. Use a class name instead
      • Don't make any instance or class variable public without good reason. When the class is essentially a data structure, you can use public instance variables
      • Two blank lines: Between sections of a source file, between class and interface definitions
      • One blank line: Between methods, between the local variables in a method and its first statement, before a block or single-line, between logical sections inside a method
      • Blank spaces: Between a keyword and parenthesis, after commas in argument lists, after Casts
      • Each line should contain at most one statement
      • One declaration per line is recommended
      • Initialize local variables where they're declared
      • Put declarations only at the beginning of blocks
      • No space between a method name and the parenthesis
      • Methods are separated by a blank line
      • Four styles of implementation comments: block, single-line, trailing, and end-of-line
      • Documentation comments describe Java classes, interfaces, constructors, methods, and fields. Use /**...*/ for doc comments
      • Doc comments: One comment per class, interface, or member
      • Doc comments: Should appear just before the declaration
      • Avoid lines longer than 80 characters
      • Break longer lines: after a comma, before an operator, Prefer higher-level breaks to lower-level breaks, align new lines with the previous line, or indent the new line with 8 spaces
      • You can get a detailed code conventions at Java Code Conventions



      SCJP: Class Declarations



      class declarations

      • Start with modifiers such as public, private followed by class keyword
      • The class name, with the initial letter capitalized
      • The name of the class's parent (superclass), preceded by the keyword extends (if any). A class can only extend (subclass) one parent.
      • list of interfaces implemented by the class, preceded by the keyword implements (if any). A class can implement more than one interface
      • The class body, surrounded by braces, {}.
      • Class member variable declarations
        • Requires three components, in order:
        • Zero or more modifiers, such as public or private
        • The field's type
        • The field's name.

      Abstract Classes

      • A class declared with abstract keyword is an abstract class. It may or may not include abstract methods
      • Abstract classes cannot be instantiated
      • Abstract classes can be subclassed
      • Class containing abstract methods, must be declared to be abstract
      • Abstract methods are methods declared without implementation (braces)
      • The subclass of an abstract class must provide implementations of all the abstract methods otherwise the subclass itself needs to be declared as abstract.
      • An abstract class may have static and final fields and methods. Interfaces can not
      • If an abstract class contains only abstract method declarations with no implementations, it should better be declared as an interface
      • It's a good design to declare a common abstract class with common methods with implementations for several very related classes (will extend the abstract class)
      • An abstract class can implement an interface but are not bound to implement all interface methods

      Nested Classes

      • Classes declared under another class are called nested classes
      • Two types: Static Nested: declared with static keyword, Inner Nested: declared with no static keyword
      • inner classes have access to other members of the outer class including private members
      • Static nested classes do not have access to other members of the outer class
      • Static nested classes are accessed using the outer class name such as: OuterClass.StaticNestedClass
      • To use inner classes, the outer class must be instantiated first. Then, inner object can be created as follows: OuterClass.InnerClass innerObject = outerObject.new InnerClass();
      • Local inner classes: Declared within the body of a method
      • Anonymous inner classes: Declared within the body of a method without naming it
      • Inner classes may have similar access modifiers like other outer class members
      • Why use nested classes:
        • For logically grouping classes that are only used in one place
        • It increases encapsulation.
        • May lead to more readable and maintainable code



      SCJP: Interfaces



      Interface

      • An interface is a reference type, similar to a class
      • Interfaces can contain only constants, method signatures, and nested types
      • No method is implemented
      • Interfaces cannot be instantiated
      • They can only be implemented by classes or extended by other interfaces
      • Interfaces are not part of the class hierarchy
      • A class can implement multiple interfaces



      SCJP: Random Stuffs



      • An enum may NOT be declared in a method
      • An enum can be imported
      • If the JVM has a choice, it will select a method without varargs before selecting a method with varargs
      • When enums are equal, both .equals and == always return true
      • The headMap() method returns the portion of the map whose keys are less than the key sent to it
      • The asList() method of Arrays creates a fixed-size list that is backed by the array, so no additions are possible.
      • A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Used to initialize class variables
      • All enums implicitly extend java.lang.Enum.
      • A class can extend only one other class, an interface can extend any number of interfaces
      • An interface might also contain constant definitions.
      • An abstract class that implements an interface may not implement all interface methods



      Java : SCJP: Important Resources





      SCJP: Basic Java I/O



      • ByteStream is the basic I/O stream. Handles data as a stream of bytes. Does operation with byte unit and uses 8 bit. FileInputStream, FileOutputStream - can be used to copy files as byte by byte.
      • Character Streams: FileReader and FileWriter are character streams. They treat file data as 16 bit unicode charater streams.
      • InputStreamReader, OutputStreamWriter are also character streams. May be used in socket data reading.
      • Line-Oriented I/O: BufferedReader and PrintWriter
      • Buffered Streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams
      • You can set autoflush() of buffered streams or call manually flush() method.
      • The scanner API breaks input into individual tokens. The formatting API assembles data into nicely formatted, human-readable form.
      • Scanner:
        Scanner scanner = new Scanner(new BufferedReader(new FileReader("test.txt")));
        
        
        
                    while (s.hasNext()) {
                        System.out.println(s.next());
                    }
        
        
      • To create formatted output streams, instantiate PrintWriter not PrintStream
      • Check: System.out.format("The square root of %d is %f.%n", i, r);
      • System.out and System.err are PrintStream objects. PrintStream is really a byte stream but uses some mechanism to emulate character stream.
      • InputStreamReader cin = new InputStreamReader(System.in); System.in is a byte stream. InputStreamReader is used to emulate a character stream.
      • System.console provides character streams to handle console read/write operations. Provides readPassword method to read password from the console
      • Data Streams: Support I/O operations of primitive data types. DataInputStream and DataOutputStream.
      • Check:
        out = new DataOutputStream(new
                    BufferedOutputStream(new FileOutputStream(dataFile)));
        out.writeDouble(prices);
        out.writeInt(units);
        out.writeUTF(descs);
        
      • DataStreams detects an end-of-file condition by catching EOFException
      • Correct type to represent currency values: java.math.BigDecimal - an object type
      • Object Streams: ObjectInputStream and ObjectOutputStream. Use writeObject and readObject to write and read objects respectively.
      • A stream can contain only one copy of an object but many references to it when required.
      • File Objects: File I/O
      • Random access file:
        new RandomAccessFile("test.txt", "r");
        new RandomAccessFile("test.txt", "rw");
        
        RandomAccessFile methods:
        
            * int skipBytes(int) 
            * void seek(long)  
            * long getFilePointer() 
        
      • The new java.nio.* package provides supports to handle file i/o for high performance applications.



      SCJP: Java Concurrency





      Java: Collections Frameworks



      • Core collection interfaces: Collection (Set(SortedSet), List, Queue), Map(SortedMap)
      • A Map is not a true Collection.
      • public interface Collection extends Iterable {
            // Basic operations
            int size();
            boolean isEmpty();
            boolean contains(Object element);
            boolean add(E element);         //optional
            boolean remove(Object element); //optional
            Iterator iterator();
        
            // Bulk operations
            boolean containsAll(Collection c);
            boolean addAll(Collection c); //optional
            boolean removeAll(Collection c);        //optional
            boolean retainAll(Collection c);        //optional
            void clear();                              //optional
        
            // Array operations
            Object[] toArray();
             T[] toArray(T[] a);
        }
        
      • Traverse collections:
        for (Object o : collection)
            System.out.println(o);
        
      • You can also use Iterator to traverse through collections. like: for (Iterator it = c.iterator(); it.hasNext(); )
      • Use iterator over for construct to remove an item from the collection or to iterate parallelly two or more collections.
      • Collection to array: String[] a = c.toArray(new String[0]);
      • Each Queue method exists in two forms: (1) one throws an exception if the operation fails, and (2) the other returns a special value if the operation fails
      • Collections represent data items that form a natural group
      • All general-purpose collection implementations have a constructor that takes a Collection argument. This constructor (conversion constructor), initializes the new collection to contain all of the elements in the specified collection
      • List list = new ArrayList(c) - where c is a Collection
      • Remove all of the null elements from a Collection c: c.removeAll(Collections.singleton(null));
      • Set can not contain duplicate elements. Hence, converting any collection to a set can remove duplicate elements from the collection. Example: Collection noDups = new HashSet(c);
      • The Set interface contains only methods inherited from Collection
      • Set overrides equals method of the Object class. Two Set instances are equal if they contain the same elements.
      • Set implementations: HashSet, TreeSet, and LinkedHashSet. HashSet: uses hash table to store data, the best-performing implementation, not ordered. TreeSet: uses red-black tree as storage, ordered, substantially slower than HashSet. LinkedHashSet: uses hash table as storage with a linked list running through it, ordered according to the insertion order
      • HashSet fastest, LinkedHashSet average, TreeSet slowest among sets
      • s1.addAll(s2) - s1 union s2 : s1, s2 are sets
      • s1.retainAll(s2) - s1 intersection s2
      • s1.removeAll(s2) - s1 subtract s2
      • Java List Interface
        public interface List extends Collection {
            // Positional access
            E get(int index);
            E set(int index, E element);    //optional
            boolean add(E element);         //optional
            void add(int index, E element); //optional
            E remove(int index);            //optional
            boolean addAll(int index,
                Collection c); //optional
        
            // Search
            int indexOf(Object o);
            int lastIndexOf(Object o);
        
            // Iteration
            ListIterator listIterator();
            ListIterator listIterator(int index);
        
            // Range-view
            List subList(int from, int to);
        }
        
      • List: types of operations: Positional access, Search, Iteration , Range-view
      • List types: ArrayList, LinkedList, Vector (retrofitted to implement List)
      • Concatenate two lists: List list3 = new ArrayList(list1); list3.addAll(list2);
      • List has its own Iterator called ListIterator that can move in both directions
      • List algorithms: # sort , shuffle ,reverse ,rotate , swap ,replaceAll ,fill , copy ,binarySearch ,indexOfSubList ,lastIndexOfSubList
      • To generate sublist use subList(fromIndex,toIndex)
      • Queue methods add, remove, and element throw exception (illegalStateException, NoSuchElementException) in case of errors while offer, poll, peek return null or false in case of errors.
      • Null is not a recommended value for queue as they return null in case of errors. Queue doesn't support null values where LinkedList version of Queue supports.
      • Like Set Maps are of three kinds HashMap, TreeMap, LinkedHashMap and HashTable is retrofitted to Map.
      • Performance order: HashMap, HashMap, TreeMap, LinkedHashMap, TreeMap
      • Sorting collections: If you try to sort a list, the elements should implement Comparable otherwise Collections.sort(list) will throw a ClassCastException.
      • You can also create Comparator object for sorting and use Collections.sort(list, comparator). but the list elements should be comparable to one another using the comparator
      • SortedSet is a set whose values are sorted according to the natural order or the provided comparator object at creation.
      • it's okay to use range-views on sorted sets for long periods of time, unlike range-views on lists.
      • Two range-view methods of SortedSet:
        SortedSet volume1 = dictionary.headSet("n"); From first but does not include "n", until "n"
        SortedSet volume2 = dictionary.tailSet("n");: from "n" to the end of the set.
      • SortedMap has similar methods like SortedSet
      • From this point implementations of the interfaces (collection related) will be discussed
      • HashSet, ArrayList, and HashMap are the most used collections
      • TreeSet and TreeMap implementations came from SortedSet and SortedMap interfaces respectively
      • Queue implementations: LinkedList: FIFO, PriorityQueue: Ordered according to values
      • General-purpose implementations: None are synchronized (thread-safe). All have fail-fast iterators, are Serializable, and support a public clone method.
      • Thread-safe collections: the synchronization wrappers, allow any collection to be transformed into a synchronized collection
      • The java.util.concurrent package: Implements BlockingQueue interface, which extends Queue, and ConcurrentMap interface, which extends Map. Much higher concurrency than mere synchronized implementations



      SCJP: Rules



      • A class's superclasses don't have to implement Serializable in order to be serialized
      • if a superclass doesn't implement Serializable then it's constructor will run during deserialization
      • A transient variable's state is lost during serialization, but a volatile variable's state is not lost
      • Java:Volatile variable
      • Transient Variable
      • NumberFormat, Calendar, DateFormat are abstract classes. Use the getInstance method to get NumberFormat instances.
      • The + quantifier in a regular expression indicates 1 or more occurrences, * indicates 0 or more, [] just one character in the group, () indicates a whole group match.
      • The default separator in Scanner class is a blank NOT a comma
      • Multiple threads can be created using the same Runnable object, but a given thread can be started only once.
      • Thread.yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute.
      • Thread.join(): Waits for this thread to die.
      • Wait(), Notify(), NotifyAll() methods
      • Low coupling: classes know the least possible about each other, is preferable over tight coupling.
      • High cohesion: Each class has well focused responsibilities. Is preferable over low cohesion.
      • Polymorphism does NOT apply to static methods.
      • Instance variable cannot be referenced from static method



      Sun certifications: Topics





      SCEA:Security in Java: Potential threats to a system and how to address the threats:Java Enterprise Architect



      • Input Validation Failures: Input should be validated both at the client end and the server end (before any processing). Validating both from trusted and untrusted sources is important. Otherwise code injection attack may happen. Validation should include: data type (string, integer), format, length, range, null-value handling, verifying for character-set, locale, patterns, context, legal values and validity, and so on.
      • Output Sanitation: If you display the user entered values or if the generated output contains a significant use of the input values, in some cases, the user may be able to relate the output to the input. The user may provide malicious data to display say a pop up or an affiliate ad or to break the system.
      • Buffer Overflow: Some users may try to cause buffer overflow and hence, break the system. This may be part of a denial of service attack. Suppose you have set a not null table column to be of size 50 and did not validate the input, then data > 50 chars may break the system based on the operations and platforms. Or a user can just insert huge amount of data to eat up your server resources.
      • Data Injection Flaw: In this case, security intruders can try to pass sql queries as part of their data to get useful information or to break your system.
      • Cross-Site Scripting (XSS):
      • Improper Error Handling: In case of errors, such as, out of memory, null pointer exceptions, system call failure, database access failure, network timeout many applications display detailed internal error messages. Based on the error messages (weak points), hackers may be able to design an attack.
      • Insecure Data Transit or Storage: Data in storage or transit when represented as plain text are vulnerable to attack. Encryption algorithms may help in these situations.
      • Weak Session Identifiers: If you assign session identifiers before user authentication or display session identifier in plain text, hackers may spoof user identity and do harmful business transactions.
      • Weak Security Tokens:
      • Weak Password Exploits: Passwords, many times, can be guessed or watched or retrieved by using password-cracking tools to obtain data from password files. Strong authentication or multifactor authentication mechanisms using digital certificates, biometrics, or smart cards is strongly recommended.
      • Weak Encryption:
      • Session Theft:
      • Insecure Configuration Data:
      • Broken Authentication:
      • Broken Access Control:
      • Policy Failures:
      • Audit and Logging Failures:
      • Denial of Service (DoS) and Distributed DOS (DDoS):
      • Man-in-the-Middle (MITM):
      • Multiple Sign-On Issues:
      • Deployment Problems:
      • Coding Problems:



      SCJP: Short Notes





      Java Design Patterns: Architectural Frameworks





      Java: Common Architectures





      SCJP: More Rules



      • java -classpath gFolder/Game.jar civilization.java: In such command, -classpath will override (replace) CLASSPATH environment variable.
      • java -classpath gFolder/Game.jar civilization.java: if both gFolder and current directory contain Game.jar then the jar file under gFolder will be used.
      • If you want java compiler to recognize your jar file, either you have to mention the location of the jar file in javac command using -classpath switch or you have to add the jar file in the CLASSPATH environment variable. Mentionable - you need to add the file, adding upto the directory will not work.
      • Garbage collection: can Java program run out of memory? yes.
      • Can objects be garbage collected even if it has a valid reference? yes. when no live thread has access to the object.
      • Can Objects created within inner classes be eligible for garbage collection.? yes.
      • Do garbage collector deletes objects from the stack? No. As objects reside in heaps not in the stack.
      • If an object's finalize method runs to completion will it always be garbage collected? No. The finalize method may create some other references.
      • Arrays.equals(Object[] a1, Object[] a2) : Returns true if the two specified arrays of Objects are equal to one another
      • The results of Binary search on an unsorted array are undefined
      • <A extends Alpha> Alpha go(int i) is a valid method declaration with a generic return type. class Alpha{}



      SCJP Practice Exams



      Check these practice exams. Be careful that many java rules may have changed over the time. Check that which jdk version or the exam these practice exams support



      SCJP Essential Knowledge



      • int x=5; String y="3"; System.out.print(x + 1 + y); Output: 63
      • When there is no live reference to an object, the object becomes eligible for garbage collection.
      • The concrete interface method implementation must be public.
      • When a class implements Comparator, it must implement a compare method.
      • When a class implements Comparable, it must implement a compareTo method.
      • The Arrays.asList() method creates a fixed-size list
      • A method like void go(Set a) can be called with objects created as: TreeSet t = new TreeSet(); TreeSet t = new TreeSet();. Remember, TreeSet t = new TreeSet(); TreeSet t = new TreeSet(); will not work where Dog is a sub-class of Animal.
      • When two enums are equal, both .equals and == always return true.
      • TreeSet is ordered in their natural order or according to the Comparator provided at creation.
      • SortedMaps are abstract
      • Is-a relationships can use inheritance
      • Tightly encapsulated classes can have a has-a relationship
      • is-a or has-a relationships does not apply to methods
      • java command in details:
        Usage: java [-options] class [args...]
                   (to execute a class)
           or  java [-options] -jar jarfile [args...]
                   (to execute a jar file)
        
        where options include:
            -client	  to select the "client" VM
            -server	  to select the "server" VM
            -hotspot	  is a synonym for the "client" VM  [deprecated]
                          The default VM is client.
                          
            -cp 
            -classpath 
                          A ; separated list of directories, JAR archives,
                          and ZIP archives to search for class files.
            -D=
                          set a system property
            -verbose[:class|gc|jni]
                          enable verbose output
            -version      print product version and exit
            -version:
                          require the specified version to run
            -showversion  print product version and continue
            -jre-restrict-search | -jre-no-restrict-search
                          include/exclude user private JREs in the version search
            -? -help      print this help message
            -X            print help on non-standard options
            -ea[:...|:]
            -enableassertions[:...|:]
                          enable assertions
            -da[:...|:]
            -disableassertions[:...|:]
                          disable assertions
            -esa | -enablesystemassertions
                          enable system assertions
            -dsa | -disablesystemassertions
                          disable system assertions
            -agentlib:[=]
                          load native agent library , e.g. -agentlib:hprof
                            see also, -agentlib:jdwp=help and -agentlib:hprof=help
            -agentpath:[=]
                          load native agent library by full pathname
            -javaagent:[=]
                          load Java programming language agent, see java.lang.instrument
        



      SCWCD: Essential Knowledge : Web Development in Java



      • HttpServlet request servicing methods: Java Servlet Specification, Version 2.4 (pgs 23, 231)
        • doGet() to process HTTP GET requests
        • doPost() method to process HTTP POST requests
        • doGet() method will process HEAD requests in the absence of a doHead() method.
        • It is not required for servlets to override the service() method to handle basic requests. service() method delegates to other methods which are more practical to override
        • HttpServlet supports GET, PUT, POST, HEAD, DELETE, OPTIONS, and TRACE requests
      • HttpServlet request object methods: Java Servlet Specification, Version 2.4 (pgs 35)
        • • getParameter: request.getParameter("name");
        • • getParameterNames
        • • getParameterValues: request.getParameterValues("name")[0];
        • • getParameterMap
        • getParameterValues:returns an array of String objects containing all the parameter values associated with a parameter name. getParameterMap: returns a java.util.Map of the parameter of the request, which contains names as keys and parameter values as map values.



      Regular Expressions



      • java.util.regex provides APIs for pattern matching with regular expressions
      • java.util.regex API is most similar to that found in Perl
      • java.util.regex: Three important classes: Pattern, Matcher, and PatternSyntaxException
      • Pattern : no public constructors : must call one of the public static compile methods to get a Pattern object
      • Matcher: To get a Matcher object call matcher method on a Pattern object. No public constructor.
      • PatternSyntaxException: regular expression pattern syntax error. unchecked exception.
      • Notice: matcher.find(),matcher.group(), matcher.start(), matcher.end()
      • Regular expression metacharacter: a character with special meaning in a regular expression.
      • Java meta characters: ([{\^-$|]})?*+.
      • ! @ and # never carry a special meaning
      • enforce a metacharacter to be treated as an ordinary character: precede the metacharacter with a backslash, enclose it within \Q (which starts the quote) and \E (which ends it)
      • Character classes:
        Character Classes
        [abc] a, b, or c (simple class)
        [^abc] Any character except a, b, or c (negation)
        [a-zA-Z] a through z, or A through Z, inclusive (range)
        [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
        [a-z&&[def]] d, e, or f (intersection)
        [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
        [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z] (subtraction)
      • Simple Classes: [bcr]at, Negation: [^bcr]at, ranges:[a-c], union:[0-4[6-8]], Intersections:[0-9&&[345]], subtraction:[0-9&&[^345]]
      • Quantifiers:

        Quantifiers
        Meaning
        Greedy Reluctant Possessive
        X? X?? X?+ X, once or not at all
        X* X*? X*+ X, zero or more times
        X+ X+? X++ X, one or more times
        X{n} X{n}? X{n}+ X, exactly n times
        X{n,} X{n,}? X{n,}+ X, at least n times
        X{n,m} X{n,m}? X{n,m}+ X, at least n but not more than m times
      • Zero-length matches always start and end at the same index position
      • [abc]+ (a or b or c, one or more times) or (abc)+ (the group "abc", one or more times)
      • Greedy quantifiers: the matcher reads in, or eat, the entire input string prior to attempting the first match. If it fails, the matcher backs off the input string by one character and tries again, repeating the process until a match is found or there are no more characters left to back off from.
        Reluctant quantifiers: start at the beginning of the input string, then reluctantly eat one character at a time looking for a match.
        possessive quantifiers: always eat the entire input string, trying once (and only once) for a match.
      • Backreferences: To match any 2 digits, followed by the exact same two digits, you would use (\d\d)\1 as the regular expression: here \1 is the back reference to indicate to call the group(\d\d) one more time.

      • Boundary Matchers
        ^ The beginning of a line
        $ The end of a line
        \b A word boundary
        \B A non-word boundary
        \A The beginning of the input
        \G The end of the previous match
        \Z The end of the input but for the final terminator, if any
        \z The end of the input
      • pattern = Pattern.compile("[az]$", Pattern.MULTILINE | Pattern.UNIX_LINES);
      • The quote(String s) method of the Pattern class, returns a literal pattern String for the specified String. Metacharacters or escape sequences in the input sequence will be given no special meaning.
      • Matcher class methods: matches() requires the entire input sequence to be matched, while lookingAt does not
      • Matcher class methods


      Generics in Java



      • Generics can prevent many run time errors.
      • A generic class:
        public class Box<T> {
        
            private T t; // T stands for "Type"          
        
            public void add(T t) {
                this.t = t;
            }
        
            public T get() {
                return t;
            }
        }
        
        Object creation:
        Box<Integer> integerBox = new Box<Integer>();
      • Generic method syntax: public <U> void inspect(U u){}
      • Type Erasure:Check this code:
        public class MyClass<E> {
            public static void myMethod(Object item) {
                if (item instanceof E) {  //Compiler error
                    ...
                }
                E item2 = new E();   //Compiler error
                E[] iArray = new E[10]; //Compiler error
                E obj = (E)new Object(); //Unchecked cast 
        
        warning
            }
        }
        



      Basic Java But Essential Knowledge for exams like SCJA, or to the project managers new to Java technologies



      • By definition an enumerated type is a finite set of symbolic literals
      • In Java an enumerated type is represented as first-class object.
      • Enumerated type literals are allowed in case statements.
      • The literals of an enumerated type may be of any valid Java identifier
      • An interface may NOT contain any concrete method implementations
      • An interface is NOT a class of any style.
      • An interface defines a set of abstract methods that may have many implementations.
      • An interface is NOT a member of a class.
      • Both class associations and class compositions relationship may be of any multiplicity.
      • compositions may also have navigation methods, but these methods must NOT pass references to the owned objects. This is usually achieved by passing back a copy of the object rather than the owned object itself. Composition implies that the owning object controls the life cycle of the owned bject.
      • Dependency:one object uses another object during computations.
      • the portability of a Java application is NOT dependent
      • upon whether information hiding was used. the class cannot protect bad assignments. For example, setting a negative value for an account balance.
      • classes that do NOT support information hiding are NOT treated specially in Java
      • Disadvantages of information hiding: Access to object
      • attributes incur a runtime penalty.However, the Sun hotspot JVM usually can eliminate the added overhead by "inlining" the methods where they are called.
      • It is time consuming to use methods to access object attributes rather than direct access.
      • Information hiding does NOT restrict the reusability of a superclass.
      • Interfaces are only contracts (declarations of public methods) and a program needs classes for actual behavior.
      • NOT every class will have behavior that requires an explicit contract (interface).
      • It is the reference variables to objects that need to be as generic as possible. This is the essence of the "program to an interface" principle.
      • An interface cannot be instantiated using the new operator
      • The minus symbol in a uml class diagram signifies private visibility
      • the + symbol in a uml class diagram signifies public visibility
      • encapsulation: all of its attributes be private and it provides appropriate public accessor and mutator methods.
      • UML: attribute representation: - attr : int
      • UML
        • ? is NOT a valid multiplicity indicator.
        • 0..* indicates zero or more multiplicity.
        • 0..1 indicates zero or one multiplicity, which is how you can represent an optional association.
        • ?..1 is NOT a valid multiplicity indicator.
        • ? is NOT a valid multiplicity indicator.
        • * is an abbreviation for 0..*.
        • M is NOT a valid multiplicity indicator.
        • ? is NOT a valid multiplicity indicator.
        • 0..* is exactly how to indicate zero or more.
        • M is NOT a valid multiplicity indicator.
      • Enums and arrays make use of object references
      • A source file can have zero package statements or one package statement.
      • A source file automatically imports all classes of its package.
      • java -version com.example.MyProgram: The Java interpreter prints the version information and exits.
      • The Collections APIs contain interfaces for lists and sets.
      • The Collections APIs are in the java.util package.
      • the classes for TCP and UDP communication are contained in the java.net package.
      • cell phone side of an application requires the micro edition and the server side with EJB requires the enterprise edition
      • the J2SE platform has rich GUI capabilities, as well as IP communication capabilities allowing multiple, Internet-wide applications to exchange data.
      • TCP/IP sockets are the basis of RMI.
      • RMI may create new threads for each request.
      • JMS is used to communicate with messaging services asynchronously.
      • HTML does NOT provide interactive capabilities.
      • HTML does NOT provide a rich set of UI components.
      • HTML does provide navigation capabilities, such as hyperlinks.
      • HTML does provide rich text formatting capabilities, such as tables and cascading style sheets.
      • J2me include APIs for playing audio media.
      • J2ME provides limited user interface components.
      • J2ME applications usually execute on small devices with small screen resolution, which cannot support rich UI components.
      • an Applet executes within a security sandbox that, by default, prohibits access to the user's filesystem.
      • an Applet might fail to execute correctly (or at all) if the web browser does NOT have the appropriate JRE installed.
      • an Applet does NOT have access to the web browser's cookie information.
      • the default security sandbox does permit communication with the originating enterprise server.
      • Applets execute in a security sandbox that does NOT permit access to files on the client system.
      • Applets can be used to create animated games. However, Applets do NOT have access to gaming-specific APIs like J2ME applications do.
      • Applets cannot connect to arbitrary Internet servers.
      • Applets may connect to the server that delivered the Applet to access media files on that server.
      • Applets can access other Applets on the same web page.
      • Applets can access other Applets on the page through the AppletContext object supplied by the web browser.
      • Swing (Richest GUI components in j2SE) has a broader GUI component set than AWT.
      • MIDP is a J2ME (not J2SE) profile.
      • JSF is a J2EE web-based UI component framework with only a limited component set.
      • AWT has a more limited GUI component set than Swing
      • SWT is NOT a standard J2SE technology.
      • JSP is used to create dynamic HTML content. It does NOT handle business logic.
      • JMS is the technology that handles asynchronous requests and performs the business logic of these requests.
      • JDBC is a database communication technology and does NOT handle business logic.
      • JNDI is a naming and directory service interface. It does NOT handle business logic.
      • JNDI and JDBC support completely independent purposes in an application. JNDI is an interface to directory servers and JDBC is an interface to database servers.
      • servlets and SQL support completely independent purposes in an application. Servlets respond to HTTP requests and SQL is used to communicate with relational databases.
      • JavaMail uses SMTP (simple mail transfer protocol), which is used to send email from an application to users.
      • JavaScript and EJB support completely independent purposes in an application. JavaScript provides interactivity to web pages and Enterprise JavaBeans provide business logic.
      • JSP technology simplifies the creation of dynamic web pages.
      • JSP technology is a server-side technology.
      • JSP technology is NOT intended to be used to create business components.
      • JSP technology is ideal for web designers who are NOT familiar with Java programming.
      • JSP technology is NOT an integration technology.
      • JSP is NOT an EJB technology
      • servlets are NOT an EJB technology
      • MDBs do NOT record client conversational state
      • stateful session beans are used to record client conversational state
      • stateless session beans do NOT record client conversational state
      • entity beans are used to represent persistent data.
      • message-driven beans handle asynchronous events.
      • Session beans only handle synchronous events.
      • session beans represent business processes and
      • stateless session beans are client-independent. That is, they do NOT store conversational state.
      • session beans do NOT exist in the web container
      • stateless session beans are used to represent client-independent business processes.
      • J2EE provides a rich and flexible programming model, but it is NOT simple
      • J2EE infrastructure provides rich concurrency support in both the web and EJB tiers, which supports highly scalable application development.
      • clustering is NOT directly supported by the J2EE specification. However, most vendor implementations of J2EE do support clustering.
      • J2EE provides declarative transaction management.
      • declarative transaction management is a required feature of the EJB container
      • declarative user interface construction - is NOT part of the J2EE specification.



      Java Rules



      • Do not synchronize an instance variable or a code block without an object - it is illegal in Java
      • a synchronized context: wait(), notifyAll() - may be required to be called
      • Do not add a checked exception to an overridden method
      • A superclass does not have to be serializable, but its constructor will run when a serializable subclass instance is deserialized.
      • Loose coupling: you can change the implementation of a class without affecting the other classes. For example, if two classes say A and B - do not use each other at all (no instantiation of the other or no method calling ), they are not coupled. If A uses B but B does not use A, then they are loosely coupled. If both A and B use each other, then they are tightly coupled. Loose coupling expects that a class should keep its members private and that the other class should access them through getters and setters



      Java Web-sites ad Forums





      Maven 1.0: A pretty good article: Compare Ant and Maven





      Essential Knowledge on Web Component Development



      • doGet() processes HEAD requests in the absence of a doHead() method
      • Not the service() method but the methods that are called by the service method are better candidates for overriding
      • HttpServlet supports GET, POST, DELETE, OPTIONS, and TRACE requests
      • Retrieve a single value for a form parameter named "username": String u = request.getParameter("username");, String u = request.getParameterValues("username")[0];
      • java.util.Enumeration getHeaderNames() - retrieves the complete collection of request headers
      • set the content type of a servlet response:
        response.setContentType("text/html");
        response.setHeader("Content-Type", "text/html");
        response.addHeader("Content-Type", "text/html");
      • Servlet.destroy(): Servlets release resources: When called, the servlet container may not route other requests to that instance of the servlet: Servlet.destroy() may never be called
      • The destroy() method, called by the web container when the servlet (or the web application) is being shutdown. This is a very good place to put the code to close related socket connection
      • no guarantee on when the finalize() method will be called by the JVM
      • The init() method is called by the web container before any HTTP requests are processed by the servlet. This is a good place to open a socket connection
      • web.xml, JAR files, Class files, the deployment descriptor - are expected to be placed under WEB-INF directory
      • A welcome file: used when a user requests a directory
      • welcome files may be used at any directory level
      • the default servlet is used to handle requests for specific files that exist in the webapp
      • By default, the web container sends a 404 error back if the requested file does not exist
      • Define a mime-mapping: pdf application/pdf
      • WAR files are created using the jar command.
      • A web application may be packaged into a WAR file for deployment, but it is not required.
      • The files within the WEB-INF directory and the files within the META-INF directory of a WAR file must not be directly served as content by the container in response to a Web client's request.
      • A webapp can only have one web.xml file and all configuration must exist in that one file even if the Java class files exist in some other package
      • String boundObjectName = getServletContext().getInitParameter("com.example.BoundObj");:returns a String if an initializathttp://www.justetc.net/knowledge/editArticlesNext.php http://www.justetc.net/knowledge/editArticlesNext.phpion parameter of that name exists in web.xml
      • session.removeAttribute("app.util.DataSource");: removes a session attribute
      • Servlet context listeners are notified when the context is ready to process requests and when it is about to be shut down
      • HttpSession.setAttribute(String attributeName,Object value): method stores an object


      Servlet, JSP Specifications





      JSP: Reference Manuals





      EJB 3.0: Specifications : Simplified API



      • Focused on annotations - reduces the number of classes and interfaces, eliminates the need for a deployment descriptor
      • Encapsulation of environmental dependencies and JNDI access: annotations, dependency injection, simple lookup mechanism
      • Simpler enterprise bean types
      • session beans: business interface can be a plain Java interface
      • session beans: no need for a home interface
      • entity persistence: Java Persistence API.
      • A query language for Java persistence
      • session beans and message driven beans: an interceptor facility
      • implementation of callback interfaces is not a must
      • Java persistence API: provide object relational mapping, can replace Hibernate
      • A POJO (Plain Old Java Object) programming model
      • A lightweight ORM persistence framework
      • Dependency injection
      • Metadata annotations
      • Configuration by exception
      • Elimination of component interfaces
      • Elimination of home interfaces
      • Reduction of the use of checked exceptions



      A simple EJB 3.0 application: Explanation of EJB 3.0 technology: EJB => Spring Framework





      Java Design Patterns and Examples





      Your First EJB Application





      Java Fundamentals



      • An abstract class may have constructors
      • It is illegal to invoke the new operator on an abstract class
      • An abstract class is allowed to have method implementations
      • There is no restriction about the placement of abstract classes in a class hierarchy
      • It is legal for an abstract class to implement an interface and implement one or more interface methods
      • A well-encapsulated class must have all of its attributes marked private
      • A well-encapsulated class must hide all internal methods.
      • NOT all attributes require accessor or mutator methods



      Java File Operation Example



      Code that helped me to create http://add.justEtc.net - the Bangladesh section based on the the web-site http://winnipeg.justEtc.net

      package hello;
      
      import javax.swing.JOptionPane;
      import java.util.ArrayList;
      import java.util.Iterator;
      import java.io.*;
      
      /**
       * Created by IntelliJ IDEA.
       * User: Sayed Ahmed
       * Date: May 30, 2008
       * Time: 9:45:08 PM
       * To change this template use File | Settings | File Templates.
       */
      
      /**
      Class containing major methods - operation methods
      */
      class Process{
          private FileReader src = null; //source folder
          private FileWriter dest = null; //destination folder
          private ArrayList cityList = new ArrayList(); //arraylist to contain the names of all cities
      
          private String cityFileName; //reference to the file containing all city names
          private String folderToCopy; //path to the folder to be copied
          private String destination; // path  to the folder where the copy will be kept
      
          /**
           * Constructor
           */
          Process(){
      //JOptionPane.showInputDialog(null,"City File Name");
              cityFileName = "C:\\test_development\\java\\resources\\cityList.txt";  
      //JOptionPane.showInputDialog(null,"Folder to Copy");
              folderToCopy = "C:\\test_development\\java\\hello\\src\\resources\\source\\Winnipeg";  
      //JOptionPane.showInputDialog(null,"Destination Path"); 
              destination = "C:\\test_development\\java\\hello\\src\\resources\\destination";         
      
              //load city list from the file to an arraylist
              copyCityList(cityFileName);
      
              //to create a file with links to all the cities of Bangladesh
              createFile();
      
              //copy a folder (winnipeg) and rename it to all the city names of Bangladesh -- one by one
              Iterator it = cityList.iterator();
              while(it.hasNext()){
                  copyDirectory((String) it.next());
              }
      
          }
      
          /**
           * load city list into an ArrayList
           */
          private void copyCityList(String cityFileName){
              String city = "";
              try {
                  BufferedReader bfCity = new BufferedReader(new FileReader(cityFileName));
                  while(null != (city = bfCity.readLine())){
                      cityList.add(city);
                  }
              } catch (IOException e) {
                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
              } finally {
              }
          }
      
          /**
           * copy a folder , name the folder as the city name
           */
          private void copyDirectory(String city){
              try {
                  copyDirectory(new File(folderToCopy), new File(destination+"/"+city), city);
              }catch (IOException e){
                  e.printStackTrace();
              }
          }
          /**
           * Copies all files under srcDir to dstDir.
           * If dstDir does not exist, it will be created.
           * @param srcDir - folder to copy
           * @param dstDir - where to keep
           * @param city  - new folder name
           * @throws IOException
           */
          public void copyDirectory(File srcDir, File dstDir, String city) throws IOException {
              //if srcDirectory is a directory , create the directory
              if (srcDir.isDirectory()) {
                  if (!dstDir.exists()) {
                      dstDir.mkdir();
                  }
                  //if srcDir has child directories , create child directories - Recursively
                  String[] children = srcDir.list();
                  for (int i=0; i
      
      



      Hello World: Web Service Application: IntelliJ, Tomcat, Apache Axis/Glassfish



      This is an excellent document to start with. A sample server and a sample client are built in both Apache Axis and Glassfish



      Skeleton of the Ant File



      Ant can be used to compile and deploy Java applications. Struts and Spring applications also make use of Ant. Here, we have provided the structure of the build.xml file with examples that is used to carry out the functionalities. The redistribution of this file is in compatible with the copyright law of The Apache Foundation.

      
      
      <!--
           General purpose build script for web applications and web services,
           including enhanced support for deploying directly to a Tomcat 5
           based server.
      
           This build script assumes that the source code of your web application
           is organized into the following subdirectories underneath the source
           code directory from which you execute the build script:
      
              docs                 Static documentation files to be copied to
                                   the "docs" subdirectory of your distribution.
      
              src                  Java source code (and associated resource files)
                                   to be compiled to the "WEB-INF/classes"
                                   subdirectory of your web applicaiton.
      
              web                  Static HTML, JSP, and other content (such as
                                   image files), including the WEB-INF subdirectory
                                   and its configuration file contents.
      
           $Id: build.xml.txt 565211 2007-08-13 00:09:38Z markt $
      -->
      
      
      <!-- A "project" describes a set of targets that may be requested
           when Ant is executed.  The "default" attribute defines the
           target which is executed if no specific target is requested,
           and the "basedir" attribute defines the current working directory
           from which Ant executes the requested task.  This is normally
           set to the current working directory.
      -->
      
      <project name="My Project" default="compile" basedir=".">
      
      
      
      <!-- ===================== Property Definitions =========================== -->
      
      
      <!--
      
        Each of the following properties are used in the build script.
        Values for these properties are set by the first place they are
        defined, from the following list:
      
        * Definitions on the "ant" command line (ant -Dfoo=bar compile).
      
        * Definitions from a "build.properties" file in the top level
          source directory of this application.
      
        * Definitions from a "build.properties" file in the developer's
          home directory.
      
        * Default definitions in this build.xml file.
      
        You will note below that property values can be composed based on the
        contents of previously defined properties.  This is a powerful technique
        that helps you minimize the number of changes required when your development
        environment is modified.  Note that property composition is allowed within
        "build.properties" files as well as in the "build.xml" script.
      
      -->
      
        <property file="build.properties"/>
        <property file="${user.home}/build.properties"/>
      
      
      <!-- ==================== File and Directory Names ======================== -->
      
      
      <!--
      
        These properties generally define file and directory names (or paths) that
        affect where the build process stores its outputs.
      
        app.name             Base name of this application, used to
                             construct filenames and directories.
                             Defaults to "myapp".
      
        app.path             Context path to which this application should be
                             deployed (defaults to "/" plus the value of the
                             "app.name" property).
      
        app.version          Version number of this iteration of the application.
      
        build.home           The directory into which the "prepare" and
                             "compile" targets will generate their output.
                             Defaults to "build".
      
        catalina.home        The directory in which you have installed
                             a binary distribution of Tomcat 5.  This will
                             be used by the "deploy" target.
      
        dist.home            The name of the base directory in which
                             distribution files are created.
                             Defaults to "dist".
      
        manager.password     The login password of a user that is assigned the
                             "manager" role (so that he or she can execute
                             commands via the "/manager" web application)
      
        manager.url          The URL of the "/manager" web application on the
                             Tomcat installation to which we will deploy web
                             applications and web services.
      
        manager.username     The login username of a user that is assigned the
                             "manager" role (so that he or she can execute
                             commands via the "/manager" web application)
      
      -->
      
        <property name="app.name"      value="myapp"/>
        <property name="app.path"      value="/${app.name}"/>
        <property name="app.version"   value="0.1-dev"/>
        <property name="build.home"    value="${basedir}/build"/>
        <property name="catalina.home" value="../../../.."/> <!-- UPDATE THIS! -->
        <property name="dist.home"     value="${basedir}/dist"/>
        <property name="docs.home"     value="${basedir}/docs"/>
        <property name="manager.url"   value="http://localhost:8080/manager"/>
        <property name="src.home"      value="${basedir}/src"/>
        <property name="web.home"      value="${basedir}/web"/>
      
      
      <!-- ================== Custom Ant Task Definitions ======================= -->
      
      
      <!--
      
        These properties define custom tasks for the Ant build tool that interact
        with the "/manager" web application installed with Tomcat 5.  Before they
        can be successfully utilized, you must perform the following steps:
      
        - Copy the file "server/lib/catalina-ant.jar" from your Tomcat 5
          installation into the "lib" directory of your Ant installation.
      
        - Create a "build.properties" file in your application's top-level
          source directory (or your user login home directory) that defines
          appropriate values for the "manager.password", "manager.url", and
          "manager.username" properties described above.
      
        For more information about the Manager web application, and the functionality
        of these tasks, see <http://localhost:8080/tomcat-docs/manager-howto.html>.
      
      -->
      
        <taskdef name="deploy"   classname="org.apache.catalina.ant.DeployTask"/>
        <taskdef name="list"     classname="org.apache.catalina.ant.ListTask"/>
        <taskdef name="reload"   classname="org.apache.catalina.ant.ReloadTask"/>
        <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/>
      
      
      <!--  ==================== Compilation Control Options ==================== -->
      
      <!--
      
        These properties control option settings on the Javac compiler when it
        is invoked using the <javac> task.
      
        compile.debug        Should compilation include the debug option?
      
        compile.deprecation  Should compilation include the deprecation option?
      
        compile.optimize     Should compilation include the optimize option?
      
      -->
      
        <property name="compile.debug"       value="true"/>
        <property name="compile.deprecation" value="false"/>
        <property name="compile.optimize"    value="true"/>
      
      
      
      <!-- ==================== External Dependencies =========================== -->
      
      
      <!--
      
        Use property values to define the locations of external JAR files on which
        your application will depend.  In general, these values will be used for
        two purposes:
        * Inclusion on the classpath that is passed to the Javac compiler
        * Being copied into the "/WEB-INF/lib" directory during execution
          of the "deploy" target.
      
        Because we will automatically include all of the Java classes that Tomcat 5
        exposes to web applications, we will not need to explicitly list any of those
        dependencies.  You only need to worry about external dependencies for JAR
        files that you are going to include inside your "/WEB-INF/lib" directory.
      
      -->
      
      <!-- Dummy external dependency -->
      <!--
        <property name="foo.jar"
                 value="/path/to/foo.jar"/>
      -->
      
      
      <!-- ==================== Compilation Classpath =========================== -->
      
      <!--
      
        Rather than relying on the CLASSPATH environment variable, Ant includes
        features that makes it easy to dynamically construct the classpath you
        need for each compilation.  The example below constructs the compile
        classpath to include the servlet.jar file, as well as the other components
        that Tomcat makes available to web applications automatically, plus anything
        that you explicitly added.
      
      -->
      
        <path id="compile.classpath">
      
          <!-- Include all JAR files that will be included in /WEB-INF/lib -->
          <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
      <!--
          <pathelement location="${foo.jar}"/>
      -->
      
          <!-- Include all elements that Tomcat exposes to applications -->
          <pathelement location="${catalina.home}/common/classes"/>
          <fileset dir="${catalina.home}/common/endorsed">
            <include name="*.jar"/>
          </fileset>
          <fileset dir="${catalina.home}/common/lib">
            <include name="*.jar"/>
          </fileset>
          <pathelement location="${catalina.home}/shared/classes"/>
          <fileset dir="${catalina.home}/shared/lib">
            <include name="*.jar"/>
          </fileset>
      
        </path>
      
      
      
      <!-- ==================== All Target ====================================== -->
      
      <!--
      
        The "all" target is a shortcut for running the "clean" target followed
        by the "compile" target, to force a complete recompile.
      
      -->
      
        <target name="all" depends="clean,compile"
         description="Clean build and dist directories, then compile"/>
      
      
      
      <!-- ==================== Clean Target ==================================== -->
      
      <!--
      
        The "clean" target deletes any previous "build" and "dist" directory,
        so that you can be ensured the application can be built from scratch.
      
      -->
      
        <target name="clean"
         description="Delete old build and dist directories">
          <delete dir="${build.home}"/>
          <delete dir="${dist.home}"/>
        </target>
      
      
      
      <!-- ==================== Compile Target ================================== -->
      
      <!--
      
        The "compile" target transforms source files (from your "src" directory)
        into object files in the appropriate location in the build directory.
        This example assumes that you will be including your classes in an
        unpacked directory hierarchy under "/WEB-INF/classes".
      
      -->
      
        <target name="compile" depends="prepare"
         description="Compile Java sources">
      
          <!-- Compile Java classes as necessary -->
          <mkdir    dir="${build.home}/WEB-INF/classes"/>
          <javac srcdir="${src.home}"
                destdir="${build.home}/WEB-INF/classes"
                  debug="${compile.debug}"
            deprecation="${compile.deprecation}"
               optimize="${compile.optimize}">
              <classpath refid="compile.classpath"/>
          </javac>
      
          <!-- Copy application resources -->
          <copy  todir="${build.home}/WEB-INF/classes">
            <fileset dir="${src.home}" excludes="**/*.java"/>
          </copy>
      
        </target>
      
      
      
      <!-- ==================== Dist Target ===================================== -->
      
      
      <!--
      
        The "dist" target creates a binary distribution of your application
        in a directory structure ready to be archived in a tar.gz or zip file.
        Note that this target depends on two others:
      
        * "compile" so that the entire web application (including external
          dependencies) will have been assembled
      
        * "javadoc" so that the application Javadocs will have been created
      
      -->
      
        <target name="dist" depends="compile,javadoc"
         description="Create binary distribution">
      
          <!-- Copy documentation subdirectories -->
          <mkdir   dir="${dist.home}/docs"/>
          <copy    todir="${dist.home}/docs">
            <fileset dir="${docs.home}"/>
          </copy>
      
          <!-- Create application JAR file -->
          <jar jarfile="${dist.home}/${app.name}-${app.version}.war"
               basedir="${build.home}"/>
      
          <!-- Copy additional files to ${dist.home} as necessary -->
      
        </target>
      
      
      
      <!-- ==================== Install Target ================================== -->
      
      <!--
      
        The "install" target tells the specified Tomcat 5 installation to dynamically
        install this web application and make it available for execution.  It does
        *not* cause the existence of this web application to be remembered across
        Tomcat restarts; if you restart the server, you will need to re-install all
        this web application.
      
        If you have already installed this application, and simply want Tomcat to
        recognize that you have updated Java classes (or the web.xml file), use the
        "reload" target instead.
      
        NOTE:  This target will only succeed if it is run from the same server that
        Tomcat is running on.
      
        NOTE:  This is the logical opposite of the "remove" target.
      
      -->
      
        <target name="install" depends="compile"
         description="Install application to servlet container">
      
          <deploy url="${manager.url}"
             username="${manager.username}"
             password="${manager.password}"
                 path="${app.path}"
             localWar="file://${build.home}"/>
      
        </target>
      
      
      <!-- ==================== Javadoc Target ================================== -->
      
      <!--
      
        The "javadoc" target creates Javadoc API documentation for the Java
        classes included in your application.  Normally, this is only required
        when preparing a distribution release, but is available as a separate
        target in case the developer wants to create Javadocs independently.
      
      -->
      
        <target name="javadoc" depends="compile"
         description="Create Javadoc API documentation">
      
          <mkdir          dir="${dist.home}/docs/api"/>
          <javadoc sourcepath="${src.home}"
                      destdir="${dist.home}/docs/api"
                 packagenames="*">
            <classpath refid="compile.classpath"/>
          </javadoc>
      
        </target>
      
      
      
      <!-- ====================== List Target =================================== -->
      
      <!--
      
        The "list" target asks the specified Tomcat 5 installation to list the
        currently running web applications, either loaded at startup time or
        installed dynamically.  It is useful to determine whether or not the
        application you are currently developing has been installed.
      
      -->
      
        <target name="list"
         description="List installed applications on servlet container">
      
          <list    url="${manager.url}"
              username="${manager.username}"
              password="${manager.password}"/>
      
        </target>
      
      
      <!-- ==================== Prepare Target ================================== -->
      
      <!--
      
        The "prepare" target is used to create the "build" destination directory,
        and copy the static contents of your web application to it.  If you need
        to copy static files from external dependencies, you can customize the
        contents of this task.
      
        Normally, this task is executed indirectly when needed.
      
      -->
      
        <target name="prepare">
      
          <!-- Create build directories as needed -->
          <mkdir  dir="${build.home}"/>
          <mkdir  dir="${build.home}/WEB-INF"/>
          <mkdir  dir="${build.home}/WEB-INF/classes"/>
      
      
          <!-- Copy static content of this web application -->
          <copy todir="${build.home}">
            <fileset dir="${web.home}"/>
          </copy>
      
          <!-- Copy external dependencies as required -->
          <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
          <mkdir  dir="${build.home}/WEB-INF/lib"/>
      <!--
          <copy todir="${build.home}/WEB-INF/lib" file="${foo.jar}"/>
      -->
      
          <!-- Copy static files from external dependencies as needed -->
          <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
      
        </target>
      
      
      <!-- ==================== Reload Target =================================== -->
      
      <!--
      
        The "reload" signals the specified application Tomcat 5 to shut itself down
        and reload. This can be useful when the web application context is not
        reloadable and you have updated classes or property files in the
        /WEB-INF/classes directory or when you have added or updated jar files in the
        /WEB-INF/lib directory.
      
        NOTE: The /WEB-INF/web.xml web application configuration file is not reread
        on a reload. If you have made changes to your web.xml file you must stop
        then start the web application. 
      
      -->
      
        <target name="reload" depends="compile"
         description="Reload application on servlet container">
      
          <reload url="${manager.url}"
             username="${manager.username}"
             password="${manager.password}"
                 path="${app.path}"/>
      
        </target>
      
      
      <!-- ==================== Remove Target =================================== -->
      
      <!--
      
        The "remove" target tells the specified Tomcat 5 installation to dynamically
        remove this web application from service.
      
        NOTE:  This is the logical opposite of the "install" target.
      
      -->
      
        <target name="remove"
         description="Remove application on servlet container">
      
          <undeploy url="${manager.url}"
               username="${manager.username}"
               password="${manager.password}"
                   path="${app.path}"/>
      
        </target>
      
      
      </project>
      
      

      Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.



      Java Connector Overview and an Example



      • Java Connector Architecture (JCA) enables integration of the J2EE components to any Enterprise Information Systems (EIS). EIS can be heterogeneous where scalability is a must.
      • JDBC assumes DBMS/RDBMS in the back-end, JCA targets any kind of EIS.
      • One of the key parts of JCA is the Resource Adapter - usually a part of the application servers. Multiple resource adapters can be used to connect to different EISs of heterogeneous types.
      • When resource adapters are plugged into the Application Servers they provide necessary transaction, security, and connection pooling mechanisms
      • In the JCA, an application contract defines the API that provides the client view to access EISs. The API can be EIS/resource adapter specific or standard.
      • Common Client Interface (CCI) - a set of interfaces and classes that allows J2EE applications to interact with heterogeneous EISs.
      • Example of JCA
        • EJBs, Servlets can connect to EISs through CCI and then access the EISs as required
        • J2EE SDK provides a black box resource adapter that we will use in our example to connect to EISs. We will assume RDBMS as the EIS in the example
        • Example: The flow of the application: client->servlet->resource adapter->EIS Tier (RDBMS - stored procedure)
        • In a servlet example: first step: import javax.resource.cci.*;
        • javax.resource.cci.*; - for ResourceException class
        • import cci blackbox classes: import com.sun.connector.cciblackbox.*;
        • Also, import servlet and application specific classes
        • public class ExampleServletConnector extends HttpServlet{
             private Connection con;
             private ConnectionFactory cf;
             private String user;
          
            public void init() throws ServletException{
                try{
                      //establish JNDI interface
                      InitialContext ic = new InitialContext();
                     //look up user and password
                     user = (String) ic.lookup("java:comp/env/user");
                     String password = (String) ic.lookup("java:comp/env/password");
                    //reference to the connection factory 
          for the CCI black box resource adapter - 
          coded name CCIEIS
                    cf = (ConnectionFactory) ic.lookup("java:comp/env/CCIEIS");
                   //collect connection specification, connect to the database
                   ConnectionSpec conSpec = new ConnectionSpec (user,password);
                 con = cf.getConnection(conSpec);
                }catch(ResourceException rex){
                   rex.printStackTrace();
                }catch(NamingException nex){
                  nex.printStackTrace();
                }
            }
          
        • Now define the doGet method for processing. An example doGet method is as follows
        • public void doGet(HttpServletRequest req, HttpServletResponse res) 
          throws ServletException {
            PrintWriter output = null;
            res.setContentType("text/html");
            try{
               PrintWriter out = res.getWriter();
               //find the number of rows in the account table - 
          check getAccountAccountCount method in the next item
               int accCount = getAccountAccountCount();
               out.println("Account Count" + accCount);
            }catch(Exception ex){
             ex.printStackTrace();
            }
          }
          
        • getAccountAccountCount() method: to query the database and determine the number of rows in the account table
        • 
          public int getAccountCount(){
             int count = -1;
             try{
                 Interaction ix = con.createInteraction();
                 CciInteractionSpec iSpec = new CciInteractionSpec(); 
                 iSpec.setSchema(user); 
                 iSpec.setCatalog(null); 
                 //stored procedure name to calculate the number of rows
                 iSpec.setFunctionName("ACCOUNTCOUNT");
                 RecordFactory rf = cf.getRecordFactory();
                 IndexedRecord iRec = rf.createIndexedRecord("InputRecord");
                 Record oRec = ix.execute(iSpec, iRec);
                 Iterator it = ((IndexedRecord)oRec).iterator();
                 //process
                  while(it.hasNext()){
                    Object obj = it.next();
                    if (obj instanceof Integer){
                       count = ((Integer) obj).intValue();
                    }else if (obj instanceOf BigDecimal){
                     count = ((BigDecimal) obj).intValue();
                    }
                  }
             }catch(Exception ex){
             }
             return count;
          }
          
          



      EJB Overview: EJB in a nutshell



      • Objects provide encapsulation/re-usability at the class level.
      • A component can be comprised of multiple objects
      • Component = logical groups of classes = distributed objects = business objects
      • A component can be developed to address a specific enterprise applications.
      • Hence, components can provide significant encapsulation/re-usability in the partitioned enterprise problems.
      • Component model = components + their environments + contracts for interaction
      • EJB is a server side component model. Used to create application server side components
      • Most sophisticated application server = CTM = Transaction Processing Monitors + Object Request Brokers = J2EE Servers
      • EJB components: entity, session, message-driven
      • Entity beans = real world objects = business objects = data objects = customers = products = may be contained as records in the database = persistent
      • Multiple clients can access entity beans concurrently
      • Session beans = processes + tasks. Example: the act of reserving a ticket = to control work flow = to handle a series of tasks carried out by the entity beans = can also access/(help to access) data = do not represent data = transient = after the task is done - no need to maintain states = do not need to support concurrent access
      • Message-driven beans = stateless beans = no component interface = respond to client requests = clients place requests through JMS = support concurrent client access = can be used to perform tasks and manage interactions among beans = asynchronous = request and response two separate processes, RMI = synchronous



      Accessing EJBS from Servlet



      • EJBs can be used to create enterprise applications like banking systems. Clients will interact with such systems for operations like: withdraw cash, transfer cash, pay bills
      • When clients directly access EJBs it poses concerns such as: security risks, firewall blocking, EJB architecture becomes transparent to the clients
      • Servlets can act as the middleman between the EJBs and clients.
        • Change to EJB becomes easier - hidden from the user
        • Data in EJB better protected
        • Central control of EJBs
      • When servlets work as the proxy, smaller devices become capable to access EJBs through http protocol (light weight protocol - good for smaller devices )
      • Servlets can work as a front controller
      • Supports different types of clients
      • Better separation of responsibilities that is desirable - web: flow control logic, EJBs: business logic, EIS: Enterprise Information Systems
      • Remember: servlets can be bottlenecks here, better servlet design strategy is required - synchronization may help
      • For small applications - may be overkill
      How to use EJBs from servlets
      • Think about a banking system implemented in EJBs.
      • Entity beans = Customers, Accounts
      • Session beans = operations like withdraw cash
      • In this scenario, servlets can call the session beans and return the results to the clients
      • A sample servlet to access the EJBs: Here remote ejbs are assumed : EJB2 is assumed : just example is shown - the coding style may not be great ... just an example
      • // for remote references to objects such as EJBs
        import javax.rmi.PortableRemoteObject;
        //banking system ejb package
        import bankingSystemEjbClasses.*;
        import java.io.*;
        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.naming.*;
        
        public class ServletEjb extends HttpServlet{
           public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws IOException, ServletException{
          float credit = 10;
          float debit = 20;
          String custName = "";
          float initBalance = 0, endBalance = 0;
        
          try{
              //locate and instantiate the account manager bean
              Context context = new InitialContext();
              Object ref = context.lookup("AccountManager");
              AccountManagerHome accountManagerHome = (AccountManagerHome) 
        PortableRemoteObject.narrow 
        (ref, AccountManagerHome.class);
              AccountManager accountManager  = accountManagerHome.create(); 
        
        //create a savings account and manipulate it
        accountManager.createSavingsAccount(1,"John Smith")  
        initBalance = accountManager.getInitialBalance("1");
        
        //create customer
        accountManager.createCustomer(1,"John Smith")  
        custName = accountManager.getCustomerName();
        
        //generate output
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.println("<html>");
        out.println("<body>");
        out.println("Customer Name:" + custName);
        out.println("Initial Balance:" + initBalance);
        
        out.println("</body>");
        out.println("</html>");
        
        
          }catch(Exception ex){
        }
        
        }
        }
        
        
        



      Servlet Random Information



      • Web component information sharing: web context (ServletContext), request, session, and page
      • ServletContext - Scope: entire web-application (Servlets & JSPs)
      • page/PageContext : A single point of access for many of the attributes of a JSP page
      • For each access of the servlet a thread is created. In applications a thread can be accessed concurrently by many threads.
      • If the servlet accesses and edits some external resources, then data inconsistency, and data loss may occur
      • Synchronized access should help:
      • public class TestServlet extends HttpServlet implements SingleThreadModel will provide synchronization and concurrency
      • In JSP, you can include <%@ page isThreadSafe="false" %> - to provide thread safety
      • For SingleThreadModel: you still have to synchronize access to class variables and to any shared resources that are stored outside the servlet. example:
        
         synchronized(sharedResource) {
         }
        
        
      • For high-traffic servlets, you should use explicit synchronization blocks rather than implementing SingleThreadModel
      • Synchronization is only an issue if the servlet accesses external data resources -- returns data from another source: not for a servlet that just performs a task with no data access



      Java 2 Security Architecture



      • Security Services Provide
        • Data Integrity
        • Data Confidentiality
        • Access Control - Authentication and Authorization
      • Encryption helps to provide such security services
      • Core Java Security Architecture
        • -- Core Java 2 Security Architecture
        • -- Java Cryptography Architecture (JCA)
        • -- Java Cryptography Extension (JCE)
        • -- Java Secure Socket Extension (JSSE)
        • -- Java Authentication and Authorization Service
        • -- JCE and JSSE extends JCA
      • JCA - Platform Packages
        • java.security - core security classes and interfaces
        • java.security.cert - certificate management
        • java.security.interfaces - Interfaces used to manage DSA and RSA keys
        • java.security.spec - key specification, algorithm parameter specification
      • JCA - not useful for data encryption
      • JCE provides the data encryption
      • JCE packages: javax.crypto, javax.crypto.interfaces, javax.crypto.spec
      • JSSE includes a Java implementation of SSL and Transport Layer Security (TLS) - server authentication, message integrity, optional client authentication.
      • JSSE Packages: javax.net.ssl, javax.net, javax.security.cert
      • JAAS : limit access to resources based on user identity. JAAS implements PAM (Pluggable Authentication Module Framework) - user-based, group-based, role-based access control
      • JAAS packages: javax.security.auth, javax.security.auth.callback, javax.security.auth.login, javax.security.auth.spi
      • Core Security
        • java.security.Permission, PermissionCollection, Permissions - specify level of access to resources in J2EE applications
        • Permissions - sets of diverse permissions
        • Permission Example:
        • Permission has many subclasses like FilePermission, SerializablePermission, SocketPermission, NetPermission
        • FilePermission prm = new FilePermission("c:\\test.img","read,write");
        • Security Policy - list permissions in files System Policy - jre/lib/security/java.policy file User Policy - java.policy file under user's directory
        • Java 2 has a policy tool under [JAVA_HOME\bin\policytool]- GUI based - to create/edit policy files - type policytool in the command prompt
        • Java Security Manager - determines whether requests to the access valued resources should be allowed? - core java security classes also ask security manager
        • For access permission check
        • Access Controller controlls access to critical system resources. Security Manager calls Access Controller methods to delegate tasks
      • J2EE Application Security
        • J2EE Role Based Security
        • J2EE applications can contain both protected and unprotected resources. Access to the protected resources can be controlled using authorization mechanisms.
        • Authorization
          • Identification : recognize an entity - device or person
          • Authentication : process to identify
        • Role based security: create logical privileges known as roles - may be based on customer/user/job profile
        • Users are grouped together into the roles - same role users into the same role group
        • Creating roles for J2EE Applications: Create roles, associate them with an application, WAR file, JAR files
        • At the time of deployment, the deployer maps roles to the security identities
        • Principle: identity assigned to a user or group after authentication
        • A tool named deploytool can be used to add users and groups to a J2EE server.
        • You can get J2EE and deploytool at: http://java.sun.com/javaee/downloads/index.jsp
        • In deploytool menu->tools->server configuration->select users from left -> select reals from right ->
        • Provide ID/Password for the user. Assign a group to the user. - Rest will be common sense, play with the tool
        • You can also use realmtool to add users and groups example: realmtool -add 5006 5006admin admin,staff Syntax: -add user password groups add, import, userGroups
        • Under deployment tool, afterwards, you can apply permissions to the different applications. You can also view and modify the descriptor file from : menu->tools>view configuration.



      J2EE:Java EE Code Samples & Apps





      J2EE Architecture: J2EE Design Patterns: Related Concepts



      • Design Patterns
        • What are design patterns? Design patterns are specific/(context-based) solutions/approaches to address specific problems/situations. Some problems are general/open problems and very common problems in a particular type of applications. Design patterns can be created to solve such problems in a specific context and that can be re-used every time that type of situations arise. Design patterns help designers to easily communicate their ideas (in a common concept).
        • Benefits: Proven solution to a specific problem, saves time as you don't have to come up with an original solution each time you encounter a particular problem
        • Design patterns can be applied at different levels of abstractions such as, Analysis, Architectural, Behavioral, Creational, Design, and Structural
        • J2EE patterns are mostly for design and architecture purpose and for three architectural tiers: Presentation, Business, and Integration
      • J2EE Applications: Client Tier (Clients for J2EE Applications): Design Issues
        • J2EE supports many types of clients. Hence, you need to decide which types of clients you want to make use of. Also, based on the clients you need to decide how to solve a specific problem. Design patterns can be client-specific and problem-specific
        • J2EE clients: laptops, desktops, palmtops, and cell phones.
        • Connection Mechanisms (to J2EE Applications): an intranet, the Internet, a wireless network, a wired network, and a combination of wired and wireless networks
        • Clients can be thin, server dependent, browser based, rich, and stand-alone
        • Client design issues: Concerns: which types of clients to use, should more than one type of clients be supported?, network types to support, security considerations, platform considerations, and unreliability of networks
        • Clients should: Connect to the network on an ad-hoc basis, transmit minimum amount of data, should consider situations when firewalls may block particular protocols, mobile clients should consider that they have small display screens and limited resources
        • More design issues for J2EE clients: Logic for user interface presentation, validate user inputs, communicate with the server using a common protocol, maintain the conversational state
        • Browser clients - design issues: can not function independently of the server, easy to design and implement, widely available, well-familiar to the users, provide limited functionality, can perform user input validation, servers can also do the validation, uses HTTP protocol, needs to maintain conversational states using Cookies, URL rewriting, or server side session
        • Java clients - design issues:
        • Client types: applications, applets, MIDlets are the Java client options
        • Applications like usual desktop applications - can run offline, use JFC/Swing for user interface, provide richer user experience, more responsive than thin clients, use less bandwidth than browser clients, and can create fewer connections than browser clients
        • Applets run mostly under browsers, use JFC/Swing for user interface
        • MIDlets are mostly for small applications for cell phones, two-way pagers, and palmtops - use MIDP user interface APIs
        • Java clients (Applications, applets, MIDlets) can handle most user input validation and hence, reduce network overhead, can connect to J2EE applications, directly to the web tier (using HTTP though face some complexity of translation), EJBs, EISs,
        • Applets and applications can connect to EJBs directly,
        • Java clients can access EIS tier directly (not recommended as it would bypass J2EE server and transaction management)
        • Java clients have the facility to cache and manipulate large amounts of state in memory and manage session effectively
      • Web Tier
        • Servlets, and JSPs are web-tier component
        • Manage the interaction between web-clients and the application's business logic.
        • Output from this tier: mostly HTML and XML content
        • Business logic can be implemented entirely here, though, enterprise beans are recommended
        • Servlets should be used to: implement web-application logic, generate binary content, act as a web-tier controller
        • JSPs are better suited to generate static HTML text
        • JSP Purpose: produce structured textual content, generate XML messages, act as templates
        • In JSP, custom tags are more desirable than scriptlets. Why? scriplets - not reusable, mix logic with content, make JSP pages difficult to read and update, errors can be difficult to interpret, difficult to test (including unit testing)
        • Web-Tier Application Framework
          • Many web-tier application requirements are not met by the actual J2EE platform. A framework working on top of J2EE can meet these requirements such as, dispatching requests, invoking model methods, and compiling views.
          • Making use of existing ready-built and proven application framework is recommended than creating your own [it takes time and may be all your designs will not be the best]
          • Some frameworks: J2EE blueprints Web Application Framework, Apache Struts, JavaServer Faces
        • Model View Controller (MVC)
          • Well-suited for interactive applications such as web-applications.
          • Divides applications into three modules - model, view, controller
          • model: data representation and business logic, view: data presentation and user input, controller: controls information flow
          • Benefits: separation of design and implement, decreased code duplication, centralized control
          • Servlets are ideal as controllers
          • Controllers receive all incoming client requests and direct them to the appropriate business logic component, after processing the requests, the controller selects the right view to return to the client.
        • Model 1 and Model 2
          • Model 1: No controller, direct access to the JSP pages, decentralized application, simpler and hence suited for small and static applications
          • Model 2: Uses a controller, are favored as they are easy to maintain and extend, provide a single point for security and logging
      • EJB Tier
        • Hosts business logic of a J2EE application
        • Provides system level services to the business components
        • Developers can focus on business-logic problems
        • J2EE platform handles the system related problems (complex many times) such as, state maintenance, transaction management, and availability to local and remote clients
        • EJBs provide a good interface between presentation components in the web-tier and business data and systems in the EIS tier
        • EJBs - entity, session, message driven
        • EJBs can provide remote or local access by providing remote or local interfaces. EJBs are mostly designed for distributed environments and hence typically provide remote interfaces
        • When to use entity beans: for business objects when it represents persistent data and requires persistent storage, multiple client access, data access in portable manners, server managed transaction handling is preferable
        • Entity beans: Persistence can be managed by yourself or by the EJB container
        • When to use Stateful Session-beans: for client centric business logic, business objects are short-lived, and non-persistent. Works for the client to maintain conversational state
        • When to use Stateless session beans: Provide server side behavior, do not maintain states for a specific client, good for reusable service objects, to minimize resources and support a large number of clients, when the business object does not operate on instance variables.
      • EIS Tier
        • J2EE EIS technologies: J2EE Connectors to integrate J2EE applications with existing EISs using resource adapters - synchronous
        • Java Message Service: To be used with enterprise messaging systems - asynchronous
        • JDBC - integrates J2EE applications with relational database systems
        • asynchronous: high quality and reliable message-delivery service, provide higher volume of messaging, more work for the developers
        • synchronous - suitable to handle two or more EISs synchronously.



      Core J2EE Component Technologies



      Core J2EE Component Technologies

      • J2EE Application Components: Web Components, Business Components
      • Web-Component:
        • Software entity hosted by a web-container on a J2EE Server
        • Generate user interface for web-based applications
        • Two Types: Servlets, JSPs
        • Servlets: Process requests dynamically, format responses
        • JSPs: How to process requests, and format responses
      • Business Components: EJB Components or enterprise beans: Contain business logic of an enterprise application. Three types: Session Beans, Entity Beans, Message Beans

      J2EE Services

      • Distributed Communication Services:
        • Distributed Communication Services provide J2EE components distributed communications capability and EIS access
        • Web-container Service Components: JMS, JNDI, RMI-IIOP,CORBA and Java IDL
        • Roughly: RMI-IIOP, CORBA and Java IDL: Applet and Application Container to Web-Container Communications
        • JMS, JNDI: Between web-container and EJB container components. For application components not for users
        • JNDI: Naming and directory services.
        • CORBA: Objects to communicate regardless of their implementation language or the operating system
        • Java IDL API enables J2EE applications to utilize CORBA functionality
      • Other support technologies
        • JDBC, Java Transaction API, Java Transaction Service, J2EE Connectors, JavaMail
        • JDBC: Provides database access from Java.
        • Latest JDBC: Provides connection pooling and distributed transaction support for the J2EE platform
        • JDBC Drivers: Java, Partial Java, Java Native Interface (JNI)
        • J2EE connector architecture provides supports to connect to EISs
        • JavaMail API to handle mailing



      Distributed J2EE Applications



      • Single tier applications are easier to design. Single tier applications mix data, presentation, business logic altogether. It is easier design but workload distribution becomes difficult. Moreover, software maintenance becomes a big headache.
      • Multi-tier applications can address these challenges. Here, the application, hence, the workload is divided into multiple modules - tiers. The presentation, data, business logic can be separated from each other. This provides well organized software development. The workload can be divided among several developers more effectively. Also, software maintenance becomes easier.
      • Multitiered Applications Benefits:
        • Availability: Accessible at all times - more accessible. Move parts of your applications into separate machines
        • Extensibility: Ability to add more capabilities. Can add more capabilities without breaking the systems
        • Scalability: Support more users: Add extra computing resources to each layer,
        • Reliability: Maintain the accuracy and integrity of the data. Separating business logic from the rest of the applications, grouping operations into transactions
        • Maintainability: Ability to update software code
      • Design considerations for Distributed Applications/Systems
        • Event handling: Generation and notification of distributed events
        • Persistence: How distributed objects are stored and accessed
        • Concurrency: Acquiring and releasing locks in distributed environments
        • Security: Mechanisms to provide distributed authentications, authorization, encryption, and auditing
        • Transactions:
        • Language dependencies
        • Platform dependencies : Provide seamless operations irrespective of the underlying OSs or processors
      • Distributed object management issues:
        • Create and delete distributed objects
        • Reliable communications among distributed objects
        • Provide interfaces for object mapping
        • Activating distributed objects and binding them to names
        • Advertising and accessing objects and services
      • Design distributed systems:
        • Partition the problem into modular
        • Make the module small enough to be individually solvable
        • Findout the application and communication layers/requirements
      • Transaction Management



      Creating Java Development Environment with Struts for Your Home PC





      Step By Step Video Tutorial: Struts-based Java Web Application Development





      Struts 2 vs. Struts 1



      Please check the following resources:



      Key J2EE Components : Basic Concepts with Examples



      • Java EE 5 (J2EE 5) uses XML deployment descriptors for the configuration of the web-applications and web-components.
      • What Java EE provides? It provides the internal framework/structure/system level capability/system-level infrastructure to support large enterprise level applications with features like distributed database, distributed computing , security, and transaction management.
      • J2EE also provides specifications for Containers, Connectors, Interfaces, Communications among different components for enterprise applications
      • J2EE is J2SE based, it supports all of J2SE
      • J2EE in addition to Swing and AWT introduces JSF for user interface creations
      • Sun provides the J2EE specifications and a reference implementation. Anyone can re-implement the complete specification. Hence, if you develop applications based on the core J2EE, it should be compatible across different vendors who later re-implemented J2EE.
      • However, J2EE does not cover 100% of the requirements of all types of enterprise applications, hence vendors usually add values/extra features to their implementations.
      • J2EE provides multi-tier application development
      • Elements of J2EE
        • Clients: Fat Clients: A console application, and JFC, Swing, AWT based GUI applications. Thin clients: Browser based client applications
        • Servers: Connect client components to the business logic.
        • Server side components: Web-Components: JSPs, Servlets. Business components: EJBs.
        • J2EE containers provide the support/framework/infrastructure for these server side components. Web Container contains JSPs/Servlets. EJB Container contains EJBs
      • Some concepts in J2EE
        • Containers, JSF, JDBC, XML Support, Web-Services, Transaction Management, Security
        • Servlet: Mostly for Processing/calculations: From The clients, you can refer to a Servlet for example in HTML Form Actions. The Servlet runs in the server, does required processing and returns HTML web-page to the clients.
        • JSP: Mostly for user interfaces, can also include processing using Java codes
        • JSF: JSF is used to create rich user interfaces in conjunction with JSPs and Servlets.
        • JSF provides API based server side user interface creation
        • JDBC provides APIs to access relational databases. Enterprise applications very often will store information in databases. JDBC helps to access these information.
        • EJBs evolved on RMI's limitations to support enterprise applications. EJB components contain business logic.
        • EJBs are of three types: entity beans, session beans, message beans
      • J2EE 5 XML Support Technologies
        • JAXP: DOM based processing. SAX: Stream based processing
        • JAXB: Mapping between XML and Java classes
        • JAXR: XML Registries
        • JAXM for messaging
        • JAX-RPC: XML based RPC
        • JAXR, JAXM, and JAX-RPC: provide support for SOAP and web-services
      • Web-services: Here functions/operations are provided as web-based services. Others can call and make use of these services. Great for B2B communications and integrations.
      • Web-services: Related concepts: WSDL: Describes the services provided - Web Service Description Language. Service Registries such as ebXML, UDDI. JAXR API can access these registries. SOAP: The protocol for communications (web-services).
      • Transaction Management: Java EE including EJBs provides transaction management support.
      • J2EE also provides security supports such as role-based authorization, both declarative and programmatic securities.



      JSF: Lesson - 1: JSF Specifications



    8. Video Demonstration of a sample JSF application create: Read the article first
      • JSF Specifications
      • JSF is not standalone technology, you have to use it in conjunction with JSPs, Servlets, EJBs
      • How to use JSF with Servlets and EJBs: In Servlet or EJB, explicitly create instances of UI components and use the UI classes directly
      • JSF with JSPs: Use the JSF custom tag library with JSP
      • To use JSF, you need to understand JSF lifecycle: take a look at JSF Lifecycle: Restore view, Apply request values, Process validations, Update model values, Invoke application, Render response
      • How to install JSF: Current version of Sun's Application Server contains JSF and JSTL
      • For Tomcat 5.5:
        • Download JSF from http://java.sun.com/j2ee/javaserverfaces/download.html and JSTL from http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html.
        • Put these Six JSF JARs into your project WEB-INF/lib folder or tomcat lib folder: commons-beanutils.jar, commons-collections.jar, commons-digester.jar, commons-logging.jar, jsf-api.jar, and jsf-impl.jar
        • Download JSF Jars
        • Put these two JSTL JARs in the same way: jstl.jar and standard.jar
      • JSF provides different custom actions as will be provided below:
      • You can use these elements/controls/actions to collect user data, to display output, to validate user inputs, control the flow of the application dynamically/statically also, convert data from one type to another.
      • HTML Custom Actions
        Input: To create input elements
        h:inputHidden, h:inputSecret, h:inputText, h:inputTextarea

        Output:create output elements h:message, h:messages, h:outputFormat, h:outputLabel, h:outputLink, h:outputText
        Selection: Create selection elements like combo boxes h:selectBooleanCheckbox, h:selectManyCheckbox, h:selectManyListbox, h:selectManyMenu, h:selectOneListbox, h:selectOneMenu, h:selectOneRadio
        Commands: Create form submission buttons or links
        h:commandButton, h:commandLink
        Miscellaneous
        h:dataTable, h:form, h:graphicImage, h:panelGrid, h:panelGroup, h:column
      • JSF Core custom actions:

        Converters:Standard
        f:convertDateTime, f:convertNumber, f:converter
        Listeners:Listener for a component
        f:actionListener, f:valueChangeListener
        Miscellaneous
        f:attribute, f:loadBundle, f:param, f:verbatim
        Selection
        f:selectItem, f:selectItems
        Validators:Standard
        f:validateDoubleRange, f:validateLength , f:validateLongRange , f:validator
        View: Create JSF view or sub-view
        f:facet, f:subview, f:view
      • An example of JSF with JSP with Managed Bean Support
        • You need a configuration file like faces-config.xml , or you can use any other file but you have to supply the file name in the web.xml file.
        • To use a managed bean, you need to define a managed bean in the JSF configuration file with a name, class, and scope
        • Also you need to define navigation rules in the configuration file. A navigation-rule defines the start page, a condition, and which page to navigate to when the condition occurs
        • Create the managed bean class
        • In your JSP, you should refer to the JSF tag libs and JSTL tag libs by

          <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
          <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
        • Then in the JSP page you will be able to use the JSF tags and the managed beans directly
        • A sample example with code
        • Video Demonstration of the example JSF application create
        • Details about other JSF features like: using managed beans, controlling page navigation, accessing JSF context data in beans, converting data, validating user inputs, using message bundles to support internationalization will be disucssed in another article.



      JSF: Lesson - 2: JSF Managed Beans



      Codes for this article
      Video Demonstration for this article

      • Target: Intermediate level programmers and web-developers. Any programmer/web-developer can take a look.
      • Pre-requisite: HTML, JSP, Servlet, Tomcat, J2EE, MVC, and JSF Introduction. Check the corresponding sections of this web-site, to have an idea on the required technology knowledge
      • Pre-requisite: Download this sample JSF application
      • Beans used by JSF enabled applications are called managed beans as they are created and managed by JSF
      • JSF is based on the MVC architecture where beans provide the models
      • To be used with JSF, a bean must have a no argument constructor. The bean can expose its properties with get or set methods for reading or writing from outside
      • Beans can be used in two ways in JSF applications: The information required to create managed beans are provided in the configuration file (faces-config.xml), JSF uses value binding expressions or method binding expressions, to refer to the properties of the managed beans.
      • Configuring Managed Beans
        • Beans are configured in the faces-config.xml file. The file is usually provided under WEB-INF folder. Though from the web.xml file (using the javax.faces.CONFIG_FILES context parameter), you can refer to any other file where the configuration is provided.
        • META-INF/faces-config.xml file can also be used
        • Multiple configuration files can also be used. The file names should be mentioned in the web.xml file.
        • Initialize Bean Properties
        • Accessing Bean properties
          • Bind managed bean methods to expressions in JSP pages
          • <h:inputText value="#{bus.origination}" size="35"/> or <h:inputText value="#{bus["origination"]}" size="35"/> : set flight property as the control is a JSF input control
          • <h:outputText value="#{bus["origin"]}" size="35"/> or <h:outputText value="#{bus.origin}" size="35"/>: Retrieve value from the origin property.
          • Access list property values: #{bus.times["1"]}
          • Access Map property values: flight.airportNames.key, flight.airportNames[key]
          • Similarly, you can also bind managed bean methods to expressions in JSP pages.



      JSF: Lesson - 3: Controlling Page Navigation in JSF



      • Sample application for this article
      • Video Tutorial for this article
      • Pre-requisite: JSF Lesson 1 & 2
      • Navigation: Two Types:
        • Static: The destination page is fixed
        • Dynamic: The destination page varies with the conditions
        • Static
          • Static: You provide a fixed value for the "action" attribute for a JSF event control/action element
          • That fixed value is mapped to the fixed destination page in the configuration file such as the faces-config.xml
          • If you check our previous lesson, the searchForms.jsp contains . In this line, the text 'action="submit"' defines the static navigation.
          • The navigation rule in the following text maps submit action to searchResults.jsp page [static/fixed mappping] <navigation-rule>
            <from-view-id>/searchForm.jsp</from-view-id>
            <navigation-case>
            <from-outcome>submit</from-outcome>
            <to-view-id>/searchResults.jsp</to-view-id>
            <redirect/>
            </navigation-case>
            </navigation-rule>
        • Dynamic Navigation
          • In this case, the action takes a dynamic value. All possible values are mapped into [different] destination pages. Hence, when the action gets a different value, the destination page is also different [unless mapped to the same destination page]
          • To get dynamic nature, the action is mapped to a value/property or a method of a managed bean. The property must be of String type. Also, the method must return String and must not take any parameter.
          • At the time, the action is executed [the button is pressed], corresponding property value is retrieved or the method is called to get value. This value is then matched with the navigation cases in faces-config.xml.
          • The user is then redirected to the destination of the mathching navigation case.
          • Example: Binding action to a value/method expression in jsp: . Here, search is a method in the bus bean. Hence, at the button click, the search method is executed. For example, it may get values such as success, noTrips
          • Mapping in faces-config.xml: success, and noTrips are mapped in the following navigation cases.
          • <navigation-rule>
            <from-view-id>/searchForm.jsp</from-view-id>
            <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/searchResults.jsp</to-view-id>
            <redirect/>
            </navigation-case>
            <navigation-case>
            <from-outcome>noTrips</from-outcome>
            <to-view-id>/noTrips.jsp</to-view-id>
            <redirect/>
            </navigation-case>
            </navigation-rule>
      • Navigation Rules:
        • If you observe the navigation rules above, you will notice <from-view-id> elements. This is to mention, from where the action is generated.
        • <from-outcome>: is the action message based on which flow is maintained
        • <to-view-id> element provides the destination page
        • <from-view-id> is optional. If you omit <from-view-id>, then for all <from-outcome> message for the application, will be redirected to the related <to-view-id> destination page. If all page refers to the same privacy policy file, this rule can be useful
        • Example:
          <navigation-rule>
          <navigation-case>
          <from-outcome>privacy-policy</from-outcome>
          <to-view-id>/WEB-INF/privacy.jsp</to-view-id>
          </navigation-case>
          </navigation-rule>
        • You can also redirect for the same <from-outcome> message for a group of pages to the same destiation. Such as:
          <from-view-id>/order/*</from-view-id>
          <from-outcome>success</from-outcome>
          <to-view-id>/WEB-INF/invoice.jsp</to-view-id>
        • <from-action> element: Consider a case, in the same page, in two command buttons, the actions are mapped to save and search methods. Both save and search methods can return success as the element. But, if you want them (two successes from the two methods) to go to two different destination pages, then <from-action> element comes handy.
        • You can use <from-action> element in the following way:
        • <navigation-rule>
          <from-view-id>/searchForm.jsp</from-view-id>
          <navigation-case>
          <from-action>#{bus.search}</from-action>
          <from-outcome>success</from-outcome>
          <to-view-id>/searchResults.jsp</to-view-id>
          </navigation-case>
          <navigation-case>
          <from-action>#{bus.save}</from-action>
          <from-outcome>success</from-outcome>
          <to-view-id>/searchForm.jsp</to-view-id>
          </navigation-case>
          </navigation-rule>
      • Now check the sample example and the video.



      JSF: Lesson - 4: Accessing Context Data from Beans



      • In some cases, from the beans used in JSF applications, you will need to access the request parameters. For example, in the BusSearch.java, we accessed, the request parameters [Please check the previous JSF lesson].
      • How to access: FacesContext context = FacesContext.getCurrentInstance();
      • Some methods of FacesContext:
        • Map getApplicationMap()
        • String getInitParameter(java.lang.String name)
        • Map getInitParameterMap()
        • String getRemoteUser()
        • Map getRequestCookieMap()
        • Map getRequestHeaderMap()
        • Map getRequestHeaderValuesMap()
        • Map getRequestMap()
        • Map getRequestParameterMap()
        • Iterator getRequestParameterNames()
        • Map getRequestParameterValuesMap()
        • Map getSessionMap()
      • Sample code:
        FacesContext context = FacesContext.getCurrentInstance();
        Map requestParams = 
              context.getExternalContext().getRequestParameterMap();
            String tripNum = (String) requestParams.get("tripNum");
        



      JSF: Lesson - 5: Converting Data



      • Sample application for JSF Data Type Converter
      • Video Tutorial for JSF Data Type Converter
      • Pre-requisite: JSF Lesson 1, 2, 3, 4
      • JSF provides two different types of built-in data type converters such as: String and Date Conversion, Number and String Conversion.
      • Related tags: f:convertDateTime, f:convertNumber, f:converter
      • In our previous examples, we could accept departing and returning dates to be date/time types rather than string types [as expected]
      • How to achieve:
        <h:inputText id="departDate" value="#{bus.departDate}">
          <f:convertDateTime pattern="MM/dd/yy"/>
        </h:inputText>
        <h:message for="departDate"/>
        
      • For other types of conversions, you have to use custom converters.
      • To make use of the strategy, you have to write a class that will do the conversion work.
      • Your class should implement: javax.faces.convert.Converter interface that has two methods that you must implement. One method takes input as String and returns an Object. Another method, takes an Object as the input and returns String.
      • Methods
        Object getAsObject(javax.faces.context.FacesContext context,
           javax.faces.component.UIComponent component, java.lang.String value)
        String getAsString(javax.faces.context.FacesContext context,
           javax.faces.component.UIComponent component, java.lang.Object value)
        
      • getAsObject: Returns an object
      • getAsString: Returns String
      • As you have access to the JSF context, and the corresponding user interface component in these methods - you will be able to greatly customize your converter
      • How to use the custome converter:
        • Define a converter in the configuration file (faces-config.xml) as follows where TerminalConverter is your custom converter class:
          <converter>
          <converter-id>terminal.converter</converter-id>  
          <converter-class>
          net.justetc.jsf.TerminalConverter
          </converter-class>
          </converter>
          
        • From JSPs refer to a converter-id as defined in the configuration file. See example below:
        • 	<h:inputText value="#{bus.origin}">
          	  <f:converter converterId="terminal.converter"/>
          	</h:inputText>
          or
          
          	<h:inputText value="#{bus.origin}" converter="terminal.converter"/>
          
          
        • You can also, define/use the converter for all properties of a class such as Terminal as follows:
          <converter>  
          <converter-for-class>
          net.justetc.jsf.Terminal
          </converter-for-class>  
          <converter-class>net.justetc.jsf.TerminalConverter
          </converter-class>
          </converter>
          
          
          
        • In this last scenario, whenever JSF identifies a Terminal type data it converts the data using the TerminalConverter class.
             <h:inputText value="#{bus.origin}"/>
          
          In this example, as it encounters bus.origin to be of Terminal type, it will convert the origin to be a Terminal object though the user will just enter a String.



      JSF: Lesson - 6: Validating User Input in JSF



      • Target: Intermediate level web-developers.
      • Sample application for this article
      • Video Tutorial for this article
      • In web-application development, validating user inputs takes much efforts. JSF has made validations much easier than usual
      • JSF Built-in Validators:
        • validateDoubleRange: Checks that the value provided is a double value. You can also set a minimum and a maximum.
        • validateLongRange: Validates the input to be a long. It also has the optional minimum and maximum parameters.
        • validateLength: Validates the length of a string
        • Without the minimum and the maximum values these validators actually do nothing
      • You can also enforce a value as follows. If no value is provided, an error message is displayed
        <h:inputText id="origin" value="#{bus.origin}" size="35" required="true"/>
        
      • You can also create your own custom validator that should implement javax.faces.validator.Validator interface.
      • You have to implement the validate() method: validate(FacesContext arg0, UIComponent arg1, Object arg2) throws ValidatorException
      • In the error condition, you should throw ValidatorException from the validate method
      • Then you need to register the custom validator in the faces-config.xml file using a id as follows:
        <validator>
            <validator-id>currency.validator</validator-id>
            <validator-class>net.justetc.jsf.CurrencyValidator</validator-class>
          </validator>
        
      • From your JSP, you can refer to the validator as follows:
      • <h:inputText id="salary" value="#{employee.salary}">              
                      <f:validator validatorId="currency.validator"/>
                    </h:inputText>
        



      JSF: Lesson - 7: Using Message Bundles in JSF: Support Internationalization



      • Target: Intermediate level web-developers (Java-platform).
      • Sample application on Internationalization with JSF
      • Video Tutorial on Internationalization with JSF
      • To support Internationalization, in the web-pages, the text messages and the control texts make use of the keys for the values/messages. In the value fields, keys are mentioned/provided as the values. Later, based on the current locale/language, the keys are replaced with the appropriate texts for the current locale/language
      • In some property files, keys and their corresponding values are listed
      • For each language, one property file is provided
      • The file names usually end with .properties
      • Example: contents of the Property files:
        search.text.new=New Search
        orderBtn.text = Confirm Order
        
      • Wherever orderBtn.text is used for values, will be replaced with "Confirm Order"
      • If the file name is messages.properties, the file can be loaded into the JSP pages as follows:
        <f:loadBundle basename="net.justetc.jsf.messages" var="msgs"/>
        
      • Example use of the property file from JSP pages

        <h:outputText value="#{msgs.orderBtn.text}"/>

      • You are also required to list the default languages (that your application supports) in the faces-config.xml file



      Java: Struts: Lesson 5: Processing Requests with Action Objects



      Corresponding Video Tutorial
      Code Example for this article

      • What happens? When a form is submitted?
      • Flow:
        1. Refer to a x.do from form action
        2. Check struts-config.xml for action named 'x'
        3. Check the corresponding type (class) of the action, execute the execute method of that action type (really a class where execute is the class method)
        4. The method will usually return a string using mapping.findForward("string"),
        5. Then the string will be matched in struts-config.xml file in the global forwards section or as part of the actions.
        6. In forwards a string is mapped to a destination web-page/action
      • Steps to write a simple application [one programmer]:
        1. Create the first web-page with the form [html/jsp]
        2. Create an action for the action string of this form in struts-config.xml file [mention the type/class, and corresponding forwards and specify the destination]
        3. The destination of a forward can be another action, forwards can be part of the action or can be placed in the global forwards section,
        4. Write the class and the corresponding execute method
        5. In the execute method you may require to collect the user supplied values/inputs, process the data and return a string using mapping.findForward based() on your logic/requirements.
        6. Create the destination pages.



      Lesson 6: Handling Request Parameters with Form Beans



      Training Video for this article
      Code used for this article

      • In jsp pages, you can create forms with html form tag or html:form tag
      • Form Beans concept
        • You can use request.getParameter() to retrieve data from a form from the backend/server side. Or you can create a bean based on the form parameters/values. Then from the server side, you can retrieve values from these beans.
        • From server side, you can set output values to the request object directly or you can create a bean to carry output messages to the next step and set the output bean in the request/session object.
        • In the output jsp pages, you can use bean:write or jsp expression language to print those output/result bean values [provided that output values are set into a bean in the server side]
        • How to declare form beans: Just define a simple Java class that extends ActionForm and then declare it in the struts-config.xml file with form-beans tag
      • Steps in creating a struts application. This example will follow the same rules
        1. Modify the struts-config.xml file: declare the form beans, map incoimg .do to action classes, map all possible return strings from action calsses to destination pages
        2. Write the class for the bean that extends ActionForm. Write all the getter and setter methods, write reset method [useful for session scoped beans], write validate method for form input validation
        3. Create the result/output beans. You do not need to declare them in struts-config.xml file
        4. Define the action class to handle requests and return the right forward string that also need to be mapped in the config file
        5. Create the input pages that calles the actions
        6. Write output jsp pages