Monday, July 28, 2008

Send me an SMS


Hi,

Here is the link to send free SMS to any mobile in India. I use it too :-)

http://www.indyarocks.com/register_step1.php?invitor=MTYwNDMxNw==&emailencryp=Y2hhbmRyYTE3MDYuZGV2ZWxvcGVyQGJsb2dnZXIuY29t

-chandra shekhar


Please note: This message was sent to you by a user at Indyarocks.com. Click here in case you do not wish to receive any invite from this user. Click here if you do not wish to get any invitations from any Indyarocks user. If you have any queries please contact us at privacy@indyarocks.com

Tuesday, July 22, 2008

NoGray Time Picker

NoGray Time Picker

The first ever Time Picker that utilizes a very easy drag and drop interface. With its unique design, anyone can drag the minutes or hour hands independently to select a time.

Here is a quick list of features:

  • Easy to use and implement.
  • Independent hours and minutes hands.
  • Drag the clock hands to set the time.
  • Uses CSS spirits for faster loading time.
  • 12 or 24 hour output with and AM and PM (translatable) ticker.

Requirements:


The color picker requires an XHTML doctype, which means your <html> tag should look like

<!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">



Create It:

To create a time picker, you'll need to call the time picker class with three elements and a set of options.

  • Holding Element: the element that will hold the time picker parts.
  • Input Field: the input field that will take the time picker value. Can be null if no input field is required, just use the onChange event to populate any data.
  • Toggler: the element that will toggle the time picker on and off (if not visible). Can be null if no toggler is required, just use the openTimePicker and closeTimePicker functions to open and close the time picker.
  • Options


Example: HTML:

<input type="text" name="time2″ id="time2″ /> <a href="#" id="time2_toggler">Open time picker</a>
<div id="time2_picker" class="time_picker_div"></div>
later
Script:
var tp = new TimePicker('time2_picker', 'time2′, 'time2_toggler', {format24:true});
 

Configurations:

You can customized the look and feel of the color picker by changing the images or creating new images using the PhotoShop files included in the resource directory. Also, there are some configuration options you can set when initiating the time picker by passing an options object.

Options objects are a key: value object with the following syntax

{option: value,
option: {option: value,
                               option: value},
option: [value1, value2]}


Example:

var tp = new TimePicker('time_picker', null, null, {onChange:function()
{
          if (this.time.hour < 12) 
                               var ampm = this.options.lang.am;
          else var ampm = this.options.lang.pm;
               var hour = this.time.hour%12;
          if (hour < 10) hour = "0″+hour;
               var minute = this.time.minute;
          if (minute < 10) minute = "0″+minute;
                      $('time3_value').setHTML(hour+":"+minute+" "+ampm);        
 } });


 
Online Link:  http://www.nogray.com/time_picker.php 



--
--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

ClockPick - JQuery Time Picker

ClockPick

A jQuery timepicker plugin

To try different configuration options, set the options below, and then click again on field or clock.

Configuration

Basic

After including the jQuery script in your html <head> block, include the jquery.clockpick.js file like so:
<script src="path/to/jquery.clockpick.js"></script>

Include the clockpick css file:
<link rel="stylesheet" href="path/to/clockpick.css" type="text/css">

Then in your $(document).ready block, simply add the following bit of code:

$("#clockpick").clockpick();

This assumes you are binding the plugin to an element with the id "clockpick". You can certainly bind the plugin to any element that makes sense for your use.

Adding parameters

ClockPick takes two optional parameters:
options (hash) - an object containing settings keys and their values
callback (function) - a callback function to run after ClockPick is run

Example:

$("#clockpick").clockpick({
starthour : 6,
endhour : 15,
showminutes : false
}, mycallback
);

Click target different
than value field

If you want to have the action on a different element than the time field, you would configure as below (like the "click on clock" demo).

Assuming the field you wish to have filled with the time, has the name 'myfieldname':

$(".clockpick").clockpick({
valuefield : 'myfieldname'
});

Using bgIframe plugin

To account for the notorious IE6 select menu show-through issue, a popular jQuery plugin called bgIframe is frequently used. ClockPick offers support for this plugin by setting a configuration variable useBgiframe = true. By doing this, ClockPick calls the bgiFrame plugin at the right time so its divs are shown above any select menus that might be nearby.

First you will need to include the bgIframe plugin, somewhere afer your include of the jQuery library:
<script src="/path/to/bgiframeplugin.js" type="text/javascript"></script>

Then set the configuration variable when you call ClockPick:
$(".clockpick").clockpick({
useBgiframe : true
});

OnLine Link: http://www.oakcitygraphics.com/jquery/clockpick/trunk/ClockPick.cfm



--
--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

Sunday, July 20, 2008

Use GTalk in Sample HTML Page


Click Here

send/receive SMS messages via a compatible GSM modem or GSM phone

About SMSLib



Introduction


SMSLib is a Java library which allows you to send/receive SMS messages via a compatible GSM modem or GSM phone. SMSLib also supports some bulk sms operators (for outbound messaging only).
SMSLib is distributed under the terms of the Apache v2 license.

Features


SMSLib is currently on its 3rd version.
SMSLib v3 retains the old functionality:

  • Supports GSM phones and GSM modems connected via serial port interfaces or IP interfaces.
  • Works with PDU/TEXT protocols.
  • Supports Inbound & Outbound simple text messages.
  • Works with 7bit, 8bit and UCS2 (Unicode) message encodings.
  • Supports Inbound & Outbound big (multipart) messages.
  • Flash messaging.
  • Outbound messages with port information / addressing (16bit addressing only).
  • Outbound WAP PUSH SI messages.
  • Status (Delivery) Report messages.
  • Basic GSM information available: Modem, Manufacturer, S/W revision, Signal level, etc.

Furthermore, SMSLib v3 offers the following new functionality:

Multiple Gateways


SMSLib v3 has introduced the concept of the Gateway, which is an interface to a device or service that can send and/or receive SMS messages. A gateway could be a GSM modem or a supported bulk sms provider. SMSLib can handle multiple gateways at the same time.

Sending Priorities


SMSLib offers unlimited per-message priorities which can be used for sending messages. When possible, SMSLib priorities are mapped directly to the gateway(s) functionality, otherwise they get simulated.

Synchronous / Asynchronous Receiving


SMSLib gives you two options for receiving messages:

  • Either you take responsibility and periodically call the read() methods.
  • Or you wait for SMSLib to call you upon message receipt.


Synchronous / Asynchronous Sending


SMSLib gives you two options for sending messages:

  • Synchronously: when you call SMSLib to send a message, your thread blocks until the message gets sent or fails.
  • Asynchronously: when you call SMSLib to send a message, your thread does not block and SMSLib returns immediately. SMSLib queues your message(s) and sends them in the background. You may choose to get notified about the fate of your messages.


Callbacks


SMSLib gives you the option of defining callback methods which it will call when certain events occur:

  • Inbound voice calls: SMSLib can be set to call you upon reception of a voice call.Please note that the voice call will be automatically and unconditionally dropped and you will get notified about the number of the calling party.
  • Inbound messages: Each time a message is received, SMSLib can be set to call your specified method.
  • Outbound messages: When you asynchronously send messages, SMSLib can be set to call your specified method with the message sent (updated with status, etc).


Custom Sender ID


SMSLib supports custom Sender ID. This feature is not supported on GSM modems - you have to use one of the supported bulk sms operators.

download


program convert the numbers into words in C

Sample "C" Program to Convert Numbers into Words

#include
void pw(long,char[]);
char *one[]={" "," one"," two"," three"," four"," five"," six"," seven","
eight"," Nine"," ten"," eleven"," twelve"," thirteen"," fourteen","
fifteen"," sixteen"," seventeen"," eighteen"," nineteen"};
char *ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","
seventy"," eighty"," ninety"};


void main()
{
long n;
clrscr();
printf("Enter any 9 digit no: ");
scanf("%9ld",&n);
if(n<=0)
printf("Enter numbers greater than 0");
else
{
pw((n/10000000),"crore");
pw(((n/100000)%100),"lakh");
pw(((n/1000)%100),"thousand");
pw(((n/100)%10),"hundred");
pw((n%100)," ");
}
getch();
}


void pw(long n,char ch[])
{
(n>19)?printf("%s %s ",ten[n/10],one[n%10]):printf("%s ",one[n]);
if(n)printf("%s ",ch);
}

Tuesday, July 15, 2008

Scour.com invite from BollabathinChandrashkehar

Hey,

Did you hear about Scour? It is the next gen search engine with Google/Yahoo/MSN results and user comments all on one page. Best of all we get paid for using it by earning points with every search, comment and vote. The points are redeemable for Visa gift cards! It's like earning credit card or airline points just for searching! Hit the link below to join for free and we will both get points!

http://scour.com/invite/chandra4u/

I know you'll like it!

- BollabathinChandrashkehar

Friday, July 4, 2008

Never Say No - Managing Change in a Project

Never Say No - Managing Change in a Project
So, your project is up and running. You've defined Project Requirements and had them signed off in blood by the sponsor. All you need to do now is watch your New Model Army get on and deliver. Right? Ahhh no. Life is never that simple, and you can reasonably safely bet hard currency that the requirements will change during delivery. Managing those changes is a potential cause of massive disruption to your project and your relationship with the client if you don't do it well.
Never Say No To a Client
Change is Bad
It's often said that Salespeople never say No. And it's often true - whatever the customer asks for, they invariably say Yes, we can do that. And Project Managers generally hate that as it paints us into a corner where our projects are not under our control. Some PMs therefore retreat into a Yoda-like mantra:
• Saying Yes leads to Change
• Change leads to Lack of Control
• Lack of control leads to Suffering (which is a PM technical term for missing deadlines, budgets or quality objectives)
But as a client-facing PM, you soon learn that to say No is just unacceptable to most clients. It's seen as pure stonewalling; that you're not prepared to be cooperative, or (worse) that your team just isn't competent. Either can cause you serious problems in your sponsor relationship, maintaining which is one of your top priorities.
Change is Good
On the other hand, saying Yes to client requests tends to result in more work. In the other Yoda mantra:
• Saying Yes leads to Change
• Change leads to More Work
• More Work leads to Happiness (another PM technical term for Increased Project Revenue and Gross Profit, which you're often responsible for)
Balance - a Neat Trick
Balancing between stonewalling (pretending that nothing can be changed and rejecting all proposed changes) and accepting all proposed changes and causing major project control problems is a tough act. Trying to work it out mid-project is even tougher. Trying to work it out on the hoof is nigh on impossible. Here's the basic magic formula - if you take nothing else away from this article, take the following sentence. Put it in your wallet, stick it to your monitor, brand it on the back of your hand:
Your request makes sense, but it raises potential risks and issues that might cost time and money.
Use The Sentence even if the client request doesn't make sense. Some requests will, some won't, but The Sentence usually ends up with one of 2 results:
1. Client backs off
2. Client agrees to more time, more money or lower quality
In either case, it's a useful holding action that then lets you wheel out the Change Control Process that you thoughtfully included in your standard statement of work.
Change Control Process
This is a process to consistently handle the inevitable Change Requests that crop up mid-project, ensuring that the good ones get through, with associated adjustments to the cost/time/quality Holy Trinity, but the bad ones don't. You maintain control of your project, you're contractually covered, the client gets what they want, but pays for it if necessary.
What is a Change Request?
This one's easy: A Change Request is any request that changes the Project Requirements.
Do We Need a Change Control Process?
Again, easy. Yes. Every project must have a change process. Every change request must use it.
Time and time again, I've heard inexperienced clients, developers and sales people starting to say things like: This project is too small/rapid/ low-budget to have a change process. or This change is too small to go through change control. To which I invariably respond: Only if the project policy is to refuse all change requests - which is of course a change process, just a really simple one to operate - or find yourselves another PM.
Strict? Yes. But here's why: because Project Requirements are a contractual document, any change to Requirements is also a contractual document. If the appropriate project authorities (the Sponsor and you) haven't signed up to a Change to the Requirements, you will fail UAT, your project won't be accepted by the sponsor, and there's a good chance you won't be paid.
Here's an example: a stakeholder has a wizard wheeze. It's a pretty simple change to the requirements and won't take much effort to implement. Realising this, the stakeholder takes it straight to one of the developers, who codes it up and tests it in a couple of hours. Doesn't break anything else, doesn't noticeably impact timescales or budgets. But come UAT, the Sponsor notes that the delivered site doesn't match the requirements, and rightly asks Where did I agree to this? You cannot allow your project to get to that point, because the only honest answer is You didn't with the enevitable followups of When did you agree to it? and Who died and gave you authority over what I want. That's A Bad Place to be.
You don't need to follow the same process for small CRs as large ones, though. You can use a light weight process for small CRs, as long as the 2 processes are documented and agreed, including - vitally - the definition of a small CR.
Sample Change Control Process
Here's an example of a simple Change Control Process. It's not the only possible process you could use, but it is in line with most PMI- compliant methodologies, so would be generally accepted by most professionally run projects.

1. Someone submits a CR. You need to agree and document who is able to do this.
2. Assess the CR to see if it's worth investigating. Here, you need to work out how long it's going to take to analyse the impact of the CR, and compare that with the projected benefits. This is a quick preflight check to weed out the obvious non-starters. If it's going to take a week just to work out how much change is involved, and the benefit is tiny, or there's not a hope in hell of it being accepted (for example, it changes the objective of the project) then this gets thrown in the bucket of CRs that are a waste of time from the outset.
3. Document and Communicate. Essential for all outcomes of any process.
4. Analyse the impact. Answers the questions: If we implement the change, how is it going to hit the Holy Trinity? What's the Risk?
To do this, you will possibly need to replan a large chunk of the project - schedules, WBS, staffing, budgets and all. You may need time from developers for them to contribute - time they would otherwise spend delivering the project.
You must have allowed for this in your original budget and schedule, and have it explicitly written into your contract. Avoiding doing this unnecessarily is why you had the pre-assessment in step 2.
5. Document and Communicate
6. Approve the CR? This is where you take your assessment and put it in front of your sponsor. It's then the sponsor who decides whether the CR should go ahead, accepting the changes in Schedule, Cost, Quality and Risk. If the sponsor decides against the CR, you've been co-operative and (I hope) objective in putting it forward, and you're not the one saying No.
7. Document and Communicate
8. Document and Communicate
9. Implement Change

Which is where your developers think the real work starts.
Martin Burns has been doing this stuff since Netscape 1.0 days. Starting with the communication ends that online media support, he moved back through design, HTML and server-side code. Then he got into running the whole show. These days he's working for these people as a Project Manager, and still thinks (nearly 6 years on) it's a hell of a lot better than working for a dot-com. In his Copious Free Time™, he helps out running a Cloth Nappies online store.
Amongst his favourite things is ZopeDrupal, which he uses to run his personal site. He's starting to (re)gain a sneaking regard for ECMAscript since the arrival of unobtrusive scripting.
He's been a member of evolt.org since the very early days, a board member, a president, a writer and even contributed a modest amount of template code for the current site. Above all, he likes evolt.org to do things because it knowingly chooses to do so, rather than randomly stumbling into them. He's also one of the boys and girls who beervolts in the UK, although the arrival of small children in his life have knocked the frequency for 6.
Most likely to ask: Why would a client pay you to do that?
Least likely to ask: Why isn't that navigation frame in Flash?
REF: http://www.evolt.org/change-requests



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

Working With Design Patterns: State

Conditional logic is essential to building any application, yet too much can make an application incomprehensible. Many of the applications I build require that an object exist in many different states, with behavior differing from state to state. A straightforward implementation involves lots of if statements and complex conditionals, producing overly convoluted solutions in short order. As a remedy, I use the state design pattern to keep my code from getting out of hand.

Holdings in a library provide a good example. A holding is a copy of a book (see Listing 1). (In my implementation, the book is simply the ISBN classification information. Thus, each holding object references a copy number and a book object.) Holdings can be checked out, checked in, they can be moved from branch to branch, they can be held by a patron, they can be warehoused, and so on. Each of these events puts the holding into a state where different rules apply. For example, a book that's checked out obviously can't be warehoused.

Listing 1: The Book class.

// BookTest.java
import static org.junit.Assert.*;
import org.junit.*;

public class BookTest {
public static final Book CATCH22 = new Book("0-671-12805-1",
"Catch-22", "Heller, Joseph", "1961");

@Test
public void create() {
assertEquals("0-671-12805-1", CATCH22.getIsbn());
assertEquals("Catch-22", CATCH22.getTitle());
assertEquals("Heller, Joseph", CATCH22.getAuthor());
assertEquals("1961", CATCH22.getYear());
}
}

// Book.java
public class Book {
private final String isbn;
private final String title;
private final String author;
private final String year;

public Book(String isbn, String title, String author,
String year) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.year = year;
}

public String getIsbn() {
return isbn;
}

public String getTitle() {
return title;
}

public String getAuthor() {
return author;
}

public String getYear() {
return year;
}
}

Listing 2 shows a starter implementation for Holding. (Note that I'm not yet concerned with the relevancy of the patron ID.)

Listing 2: An initial Holding implementation.

import static org.junit.Assert.*;
import java.util.Date;
import org.junit.*;

public class HoldingTest {
private Holding holding;
private static final Date NOW = new Date();
private static final String PATRON_ID = "12345";

@Before
public void initialize() {
Book book = BookTest.CATCH22;
int copyNumber = 1;
holding = new Holding(book, copyNumber);
}

@Test
public void create() {
assertSame(BookTest.CATCH22, holding.getBook());
assertEquals(1, holding.getCopyNumber());
assertFalse(holding.isOnLoan());
}

@Test
public void checkout() {
holding.checkout(NOW, PATRON_ID);
assertTrue(holding.isOnLoan());
assertEquals(NOW, holding.getLoanDate());
}

@Test
public void checkin() {
Date later = new Date(NOW.getTime() + 1);
holding.checkout(NOW, PATRON_ID);
holding.checkin(later);
assertFalse(holding.isOnLoan());
}
}

// Holding.java
import java.util.Date;

public class Holding {
private final Book book;
private final int copyNumber;
private Date checkoutDate;

public Holding(Book book, int copyNumber) {
this.book = book;
this.copyNumber = copyNumber;
}

public Book getBook() {
return book;
}

public int getCopyNumber() {
return copyNumber;
}

public boolean isOnLoan() {
return checkoutDate != null;
}

public Date getLoanDate() {
return checkoutDate;
}

public void checkout(Date date, String patronId) {
checkoutDate = date;
}

public void checkin(Date date) {
checkoutDate = null;
}
}


The next story I
want to tackle is to allow patrons to place a hold on a book. If
checked in, the librarian places a held book behind the desk. Attempts
to check it out by a different patron are rejected. If checked out, the
system marks the book on hold for when it's returned. Holds are only
valid for three days; a daily update routine hits all holdings, giving
each an opportunity to clear any expired holds. The three-day timer
starts only once a book is returned, if it's checked out. A hold cannot
be placed on a book already on hold.

Based on these requirements, the code to manage patron holds (see
Listing 3) really isn't that bad, but I'm starting to wonder where it's
headed. I must ensure I have if statements in the right
place, for example, when doing an update: If I add code to check to see
whether any hold needs to be cleared, but neglect to guard against the
case where the holding isn't already on hold, my code throws a
NullPointerException. As I consider similar features, such as transfers
and placing books on reserve, I'm thinking that the code easily could
start getting unwieldy and confusing.

Tracking State



A holding can be in a number of states: checked out, checked in, on
hold or not, in transit between branches, and so on. For the existing
code, a holding can be in one of four possible states:

  • checked out, on hold

  • checked out, not on hold

  • checked in, on hold

  • checked out, not on hold



Defining the states allows me to draw a state diagram (see Figure
1). The state diagram captures each separate state as a separate box. A
holding can transition between states when specific events occur, such
as the holding being checked in. Events usually trigger actions as part
of transitioning to another state.





Click here for a larger image.


Figure 1: State transitions.

The state pattern says that I can take each of these states and
represent them as a separate class. The current state is tracked within
Holding as a reference to a state object. I define the possible events
as methods on all states. Each state handles the set of events however
appropriately by invoking an action on the Holding object. The event
handler also is responsible for updating the state reference on the
Holding object if a state transition is required.

Listing 3: Holding, revised.
// HoldingTest.java
import static org.junit.Assert.*;
import java.util.*;
import org.junit.*;

public class HoldingTest {
private Holding holding;
private static final Date NOW = new Date();
private static final Date LATER = new Date(NOW.getTime() + 1);
private static final String PATRON_ID1 = "12345";
private static final String PATRON_ID2 = "22345";

@Before
public void initialize() {
Book book = BookTest.CATCH22;
int copyNumber = 1;
holding = new Holding(book, copyNumber);
}

@Test
public void create() {
assertSame(BookTest.CATCH22, holding.getBook());
assertEquals(1, holding.getCopyNumber());
assertFalse(holding.isOnLoan());
}

@Test
public void checkout() {
holding.checkout(NOW, PATRON_ID1);
assertTrue(holding.isOnLoan());
assertEquals(NOW, holding.getLoanDate());
}

@Test
public void checkin() {
holding.checkout(NOW, PATRON_ID1);
holding.checkin(LATER);
assertFalse(holding.isOnLoan());
}

@Test
public void placeHoldOnCheckedInHolding() {
assertFalse(holding.isOnHold());
holding.placeHold(NOW, PATRON_ID1);
assertTrue(holding.isOnHold());
}

@Test
public void rejectsDuplicateHolds() {
holding.placeHold(NOW, PATRON_ID1);
try {
holding.placeHold(NOW, PATRON_ID2);
fail();
} catch (HoldException expected) {
assertTrue(holding.isOnHold());
}
}

@Test(expected = HoldException.class)
public void holdOnCheckedOutBookRetainedOnCheckin() {
holding.checkout(NOW, PATRON_ID2);
holding.placeHold(NOW, PATRON_ID1);
holding.checkin(LATER);
assertTrue(holding.isOnHold());
holding.checkout(NOW, PATRON_ID2);
}

@Test
public void releaseHold() {
holding.placeHold(NOW, PATRON_ID1);
holding.releaseAnyHold();
assertFalse(holding.isOnHold());
}

@Test
public void holdReleasedAfter3Days() {
holding.placeHold(NOW, PATRON_ID1);
holding.update(DateUtil.addDays(NOW, 1));
assertTrue(holding.isOnHold());
holding.update(DateUtil.addDays(NOW, 2));
assertTrue(holding.isOnHold());
holding.update(DateUtil.addDays(NOW, 3));
assertFalse(holding.isOnHold());
}

@Test
public void holdReleasedAfter3DaysAfterCheckin() {
holding.checkout(NOW, PATRON_ID1);
holding.placeHold(LATER, PATRON_ID1);
Date checkinDate = DateUtil.addDays(NOW, 3);
holding.update(checkinDate);
assertTrue(holding.isOnHold());
holding.checkin(checkinDate);
assertTrue(holding.isOnHold());
holding.update(DateUtil.addDays(checkinDate, 3));
assertFalse(holding.isOnHold());
}

@Test
public void releaseHoldHarmlessIfNoHolds() {
holding.releaseAnyHold();
assertFalse(holding.isOnHold());
}

@Test
public void checkoutReleasesHold() {
holding.placeHold(NOW, PATRON_ID1);
holding.checkout(LATER, PATRON_ID1);
assertFalse(holding.isOnHold());
}

@Test
public void rejectCheckoutForHoldByDifferentPatron() {
holding.placeHold(NOW, PATRON_ID1);
try {
holding.checkout(NOW, PATRON_ID2);
fail();
} catch (HoldException expected) {
}
}
}

// Holding.java
import java.util.*;

public class Holding {
private final Book book;
private final int copyNumber;
private Date checkoutDate;
private String holdPatron;
private Date holdDate;

public Holding(Book book, int copyNumber) {
this.book = book;
this.copyNumber = copyNumber;
}

public Book getBook() {
return book;
}

public int getCopyNumber() {
return copyNumber;
}

public boolean isOnLoan() {
return checkoutDate != null;
}

public Date getLoanDate() {
return checkoutDate;
}

public void checkout(Date date, String patronId) {
if (isOnHold() && patronId != holdPatron)
throw new HoldException();
releaseAnyHold();
checkoutDate = date;
}

public void checkin(Date date) {
checkoutDate = null;
}

public void placeHold(Date date, String patronId) {
if (isOnHold())
throw new HoldException();
this.holdPatron = patronId;
holdDate = new Date();
}

public boolean isOnHold() {
return holdPatron != null;
}

public void releaseAnyHold() {
holdPatron = null;
}

public void update(Date date) {
if (isOnHold() && !isOnLoan() &&
DateUtil.daysBetween(holdDate, date) >= 3)
releaseAnyHold();
}
}


I refactor my code
slowly, running tests continually. The first class I create is the
HoldingState class (see Listing 4), an abstract class intended to
provide null behavior for each of the possible events.

Listing 4: HoldingState.
// HoldingState
import java.util.*;

abstract class HoldingState {
protected final Holding holding;
HoldingState(Holding holding) {
this.holding = holding;
}
void checkout(Date date, String patronId) {
}
void checkin(Date date) {
}
void placeHold(Date date, String patronId) {
}
void update(Date date) {
}
}

I then create state derivatives, one for each of the three states.

After I create the derivatives, I begin to move code over from the

Holding class. For each event (checkout, checkin, placeHold, update),

the job of the Holding object is simply to delegate the event to the

current HoldingState object. For example, the checkout method in

Holding ends up reading:


public void checkout(Date date, String patronId) {
state.checkout(date, patronId);
}

Because these are simple delegations, I could consider using the

Java proxy mechanism. Right now, I'm not concerned about a rapidly

growing public interface on Holding, so I'll defer that enhancement.


States that need to do something with the checkout event

call an action method and/or transition to another state. Other states

may choose to ignore that event. One interesting result of implementing

the state pattern, though, is that it may help point out a potential

problem in the system by making ignored events apparent. For example,

my CheckedOut state object provides no behavior for the checkout event. That unhandled event triggers me to think that I must determine what should happen if someone does try to check out a book twice.


The benefit from moving all the code into the state objects is that

the conditionals begin to disappear. When in the CheckedInHeld state, I

no longer have to check whether or not a book is held before I proceed:


class CheckedInHeld extends HoldingState {
// ...
@Override
public void checkout(Date date, String patronId) {
if (patronId != holding.holdPatron)
throw new HoldException();
holding.doCheckout(date, patronId);
holding.state = new CheckedOut(holding);
}
// ...
}

Previously, the code in checkout in Holding had to ask

whether or not the book was already held. Because this code is

executing when the Holding references the CheckedInHeld state, that

question no longer needs to be asked.


The state classes are shown in Listing 5. Each of the state classes is small, simple, and easily could be tested directly.


Listing 5: State derivatives.


// CheckedOut.java
import java.util.*;

class CheckedOut extends HoldingState {
CheckedOut(Holding holding) {
super(holding);
}

@Override
public void checkin(Date date) {
holding.doCheckin(date);
holding.state = new CheckedIn(holding);
}

@Override
public void placeHold(Date date, String patronId) {
holding.doHold(date, patronId);
holding.state = new CheckedOutHeld(holding);
}
}

// CheckedIn.java
import java.util.*;

class CheckedIn extends HoldingState {
CheckedIn(Holding holding) {
super(holding);
}

@Override
public void checkout(Date date, String patronId) {
holding.doCheckout(date, patronId);
holding.state = new CheckedOut(holding);
}

@Override
public void placeHold(Date date, String patronId) {
holding.doHold(date, patronId);
holding.state = new CheckedInHeld(holding);
}
}

// CheckedInHeld.java
import java.util.*;

public class CheckedInHeld extends CheckedIn {
CheckedInHeld(Holding holding) {
super(holding);
}

@Override
public void checkout(Date date, String patronId) {
if (patronId != holding.holdPatron)
throw new HoldException();
holding.doCheckout(date, patronId);
holding.state = new CheckedOut(holding);
}

@Override
public void placeHold(Date date, String patronId) {
throw new HoldException();
}

@Override
public void update(Date date) {
holding.doReleaseOldHold(date);
}
}

// CheckedOutHeld.java
import java.util.*;

public class CheckedOutHeld extends HoldingState {
CheckedOutHeld(Holding holding) {
super(holding);
}

@Override
public void checkin(Date date) {
holding.doCheckin(date);
holding.state = new CheckedInHeld(holding);
}

@Override
public void placeHold(Date date, String patronId) {
throw new HoldException();
}
}


The Holding class that remains (see Listing 6) is now devoid of most conditional logic! I can now test it, too, with excruciating ease.

The state pattern is one of the few design patterns that requires tight coupling between its classes: The Holding class is dependent upon the initial state, and each of the states is in turn dependent upon Holding. Although there are some clever ways to break this, it's probably not necessary, because the classes represent a self-enclosed subsystem that can remain isolated from the rest of the system. For the implementation of the state classes, I took advantage of Java's package-level access, directly having the states access Holding variables as needed, but not exposing these fields to external clients of Holding. It's one of the rare cases where I won't insist that a field remain private.

Listing 6: Holding, using the state design pattern.

import java.util.*; public class Holding { private final Book book; private final int copyNumber; Date checkoutDate; String holdPatron; Date holdDate; HoldingState state = new CheckedIn(this); Date checkinDate; public Holding(Book book, int copyNumber) { this.book = book; this.copyNumber = copyNumber; } public Book getBook() { return book; } public int getCopyNumber() { return copyNumber; } public boolean isOnLoan() { return checkoutDate != null; } public Date getLoanDate() { return checkoutDate; } public void checkout(Date date, String patronId) { state.checkout(date, patronId); } public void checkin(Date date) { state.checkin(date); } public void placeHold(Date date, String patronId) { state.placeHold(date, patronId); } public void update(Date date) { state.update(date); } public boolean isOnHold() { return holdPatron != null; } public void releaseAnyHold() { holdPatron = null; } // callback actions void doHold(Date date, String patronId) { holdPatron = patronId; holdDate = date; } void doCheckout(Date date, String patronId) { checkoutDate = date; releaseAnyHold(); } public void doCheckin(Date date) { checkoutDate = null; } public void doReleaseOldHold(Date updatedAt) { if (DateUtil.daysBetween(holdDate, updatedAt) >= 3) releaseAnyHold(); } }

Adding new functionality into the state diagram usually is simple and straightforward. The separate state classes help keep conditional logic to a minimum by avoiding confusion about the conditions under which something can occur. Often, modifications will necessitate changes to transitions between states, requiring updates to multiple state derivatives. Drawing a state diagram can be a good idea, but there's another possible solution to help manage the transitions.

State diagrams can be represented as simple tables. If I were to refactor to a more disciplined implementation of the state pattern, I could dramatically simplify my work. The table would define event methods and callback action method names; these would be used to automatically generate code for the state derivatives. This automation can be critical in a highly dynamic state system. The Object Mentor web site contains a download for just such a Java code generator, SMC (State Machine Compiler). There also are state pattern variants that can simplify state system changes in a more dynamic subsystem.



Click here for a larger image.

Figure 2: The State pattern.

REF: http://www.developer.com/design/article.php/10925_3753906_1



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

How do I configure CVS connection settings?

How do I configure CVS connection settings?

  • You can specify connection settings in the Checkout wizard. Settings are persistently stored.

For example, to check out NetBeans sources, choose Versioning > Checkout (or Versioning > CVS > Checkout) from the main menu and use :pserver:anoncvs@cvs.netbeans.org:/cvs with empty password for anonymous checkout. Alternatively use your own NetBeans.org login and password instead of anoncvs.

  • Otherwise, the IDE uses automatic configuration detection (probing common cvs setup files). Open the Favorites window, and right-click to add and open an existing repository directory. If the cvs session fails, the IDE shows the connection configuration dialog so you can change the settings (e.g. configure a proxy).

Applies to: NetBeans 6.x, 5.x



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

Hibernate setting for live environment

Here is the hibernate configuration setting for live environment.

we can use the below for production systems.

If any one has question regarding this please post a comment.

<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.c3p0.acquire_increment">3</property>
<property name="hibernate.c3p0.idle_test_period">
54000
</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">3</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.preferredTestQuery">
select 1;
</property>

<property name="current_session_context_class">thread</property>
<!– Cache Settings
<property name="cache.use_second_level_cache">false</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

<property name="hibernate.cache.use_query_cache">false</property>–>
<!– End Cache Settings –>
<!– Disable the second-level cache
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>–>
<!– Echo all executed SQL to stdout –>
<property name="show_sql">false</property>



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

Web Statistics -AWStats

AWStats is short for Advanced Web Statistics. AWStats is powerful log analyzer which creates advanced web, ftp, mail
and streaming server statistics reports based on the rich data contained in server logs. Data is graphically presented in
easy to read web pages.
Designed with flexibility in mind, AWStats can be run through a web browser CGI (common gateway interface) or directly
from the operating system command line. Through the use of intermediary data base files, AWStats is able to quickly
process large log files, as often desired. With support for both standard and custom log format definitions, AWStats can
analyze log files from Apache (NCSA combined/XLF/ELF or common/CLF log format), Microsoft's IIS (W3C log format),
WebStar and most web, proxy, wap and streaming media servers as well as ftp and mail server logs.

AWStats' reports include a wide range of information on your web site usage:
* Number of Visits, and number of Unique visitors.
* Visit duration and latest visits.
* Authenticated Users, and latest authenticated visits.
* Usage by Months, Days of week and Hours of the day (pages, hits, KB).
* Domains/countries (and regions, cities and ISP with Maxmind proprietary geo databases) of visitor's hosts (pages, hits, KB,
269 domains/countries detected).
* Hosts list, latest visits and unresolved IP addresses list.
* Most viewed, Entry and Exit pages.
* Most commonly requested File types.
* Web Compression statistics (for Apache servers using mod_gzip or mod_deflate modules).
* Visitor's Browsers (pages, hits, KB for each browser, each version, 123 browsers detected: Web, Wap, Streaming Media
browsers…, around 482 with the "phone browsers" database).
* Visitor's Operating Systems (pages, hits, KB for each OS, 45 OS detected).
* Robots visits, including search engine crawlers (381 robots detected).
* Search engines, Keywords and Phrases used to find your site (The 122 most famous search engines are detected like
Yahoo, Google, Altavista, etc…)
* HTTP Errors (Page Not Found with latest referrer, …).
* User defined reports based on url, url parameters, referrer (referer) fields extend AWStats' capabilities to provide even
greater technical and marketing information.
* Number of times your site is added to Bookmarks / Favorites.
* Screen size (to capture this, some HTML tags must be added to a site's home page).
* Ratio of integrated Browser Support for: Java, Flash, Real G2 player, Quicktime reader, PDF reader, WMA reader (as
above, requires insertion of HTML tags in site's home page).
* Cluster distribution for load balanced servers.
In addition, AWStats provides the following:
* Wide range of log formats. AWStats can analyze: Apache NCSA combined (XLF/ELF) or common (CLF) log files,
Microsoft IIS log files (W3C), WebStar native log files and other web, proxy, wap, streaming media, ftp and mail server log
files. See AWStats F.A.Q. for examples.
* Reports can be run from the operating system command line and from a web browser as a CGI (common gateway
interface). In CGI mode, dynamic filter capabilities are available for many charts.
* Statistics update can be run from a web browser as well as scheduled for automatic processing.
* Unlimited log file size
What is AWStats / Features Overview 2/87 13/04/2008
* Load balancing system split log files.
* Support 'nearly sorted' log files, even for entry and exit pages.
* Reverse DNS lookup before or during analysis; supports DNS cache files.
* Country detection from IP location (geoip) or domain name.
* Plugins for US/Canadian Regions, Cities and major countries regions, ISP and/or Organizations reports (require non free
third product geoipregion, geoipcity, geoipisp and/or geoiporg database).
* WhoIS lookup links.
* Vast array of configurable options/filters and plugins supported.
* Modular design supports inclusion of addition features via plugins.
* Multi−named web sites supported (virtual servers, great for web−hosting providers).
* Cross Site Scripting Attacks protection.
* Reports available in many international languages. See AWStats F.A.Q. for full list. Users can provide files for additional
languages not yet available.
* No need for esoteric perl libraries. AWStats works with all basic perl interpreters.
* Dynamic reports through a CGI interface.
* Static reports in one or framed HTML or XHTML pages; experimental PDF export through 3rd party "htmldoc" software.
* Customize look and color scheme to match your site design; with or without CSS (cascading style sheets).
* Help and HTML tooltips available in reports.
* Easy to use − all configuration directives are confined to one file for each site.
* Analysis database can be stored in XML format for easier use by external applications, like XSLT processing (one xslt
transform example provided).
* A Webmin module is supplied.
* Absolutely free (even for web hosting providers); source code is included (GNU General Public License).
* Works on all platforms with Perl support.
* AWStats has a XML Portable Application Description.
Requirements:
AWStats usage has the following requirements:
* You must have access to the server logs for the reporting you want to perform (web/ftp/mail).
* You must be able to run perl scripts (.pl files) from command line and/or as a CGI. If not, you can solve this by
downloading latest Perl version at ActivePerl (Win32) or Perl.com (Unix/Linux/Other).

reference : http://awstats.sourceforge.net/



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

JavaFX as Rich Internet Application Platform

JavaFX as Rich Internet Application Platform

JavaOne wrapped up on Friday. We hosted individuals from across the globe, and from every industry: consumer electronics and gaming, to enterprise IT, space exploration, factory automation, the automotive industry, academia - like the network itself, Java delivers something for nearly everyone, everywhere.

This year's biggest announcements centered around Java's role in the future of rich internet applications (or RIA's). What's a rich internet application? It depends on your perspective - from mine, it's any network connected application that persists in front of a user, typically outside a browser, that can operate when disconnected from the network.

On the one hand, I'd claim Java's always been a RIA platform - before the world really wanted one. Early Java applets delivered interactivity, but at the expense of development complexity and, in the early days, performance - when a browser, and more recently Javascript, would suffice.

But browser based applications are hitting complexity and performance limits, and content owners are striving for higher levels of engagement (via high definition video, or advanced interactivity). Developers are demanding something new - the browser's a wonderfully accessible programming model, but it's a weak deployment model for rich/disconnected applications.

An unspoken driver of RIA is also business model evolution - many companies behind rich applications are seeking independence from browsers and search engines, whose default settings and corporate parents present a competitive threat. There's a growing appetite for locally installed applications that build rich, direct and permanent engagement with consumers. No one wants to pay a toll to meet their own customers.

With that in mind, as we looked to reinvent the Java platform, we heard a consistent set of requirements. And not just from coders, but from sports francishes seeking to directly engage their fans, media companies wanting to bypass browser defaults, to artists and businesses and device manufacturers - everyone's looking to uniquely engage consumers via the network. These audiences have nearly identitical requirements for a RIA platform - they want technology that:

  • Reaches every internet consumer - on desktops, mobile, and new devices, too.
  • Delivers high performance - and the ability to engage creative professsionals in the design process.
  • Leverages existing skills and enterprise infrastructure.
  • Is totally free, and open source.
  • Provides content owners with control and ownership of their own data.

At JavaOne last week, we addressed every one of those issues - here's how:

First, RIA developers want to reach every consumer on earth, and on every device.

Why? Because the market is in front of consumers - no matter what screen they may be using. Desktop, mobile phone, personal navigation, digital book - you name it. The market’s in front of all the screens in your life, not just a PC.

That said, on PC’s alone, Java’s popularity has grown in the last few years, as measured by runtime downloads - we routinely download 40 to 50 million new Java runtimes a month, and update more than a billion every year. The adoption of the Java platform exceeds the adoption of Microsoft’s Windows itself - Sun’s Java runtime environment (JRE) is preloaded on nearly every Windows machine (from HP, Dell, Lenovo, etc.), but also runs on Apple’s Macintosh, Ubuntu, Fedora, SuSe, Solaris and OpenSolaris desktops. In addition, a JRE is present on billions - yes, billions - of wireless and mobile devices, from automobile dashboards and navigation devices, to Amazon’s Kindle (did you know Amazon’s Kindle is a Java platform?).

Which is to say, the Java platform reaches more people than any other software technology the world has ever seen.

Second, RIA developers want performance, functionality AND simplicity.

Why? Because content owners and application developers want to engage consumers - and want to engage artists and creative professionals in the workflow.

Java’s history with simplicity isn’t perfect - which is why our teams have rewritten the applet model, and focused so intently on making the new consumer Java runtime environment (download a beta version here) exceptionally fast to load within a web page, exceptionally performant for complex interactivity, and trivially accessible to consumers. We’ve also simplified Java with a scripting language, JavaFX script, that enables creative professionals to engage with coders to create immersive experiences, while embracing the creative tool chain (from interaction design to pixel manipulation) used by the worlds designers and digital artists.

And I’m really pleased we’ve solved the desktop installation problem, by making JavaFX applets separable from a web page with a simple drag and drop (click the image above to watch this demonstrated). Developers can now bypass the browser to trivially install apps on desktops - once the applet’s dropped on the desktop, content owners have a direct relationship with their consumers.

You might have also seen that we’re adding full high quality audio and video codecs to Java on every platform on which it runs - resolving another gap for RIA developers, support for time-based media (click here for a demo of high performance video).

Third, enterprises want to reuse their existing Java skills and assets in moving to RIA.

Nearly every enterprise employs programmers with Java skills - it’s still the number one internet language taught across the world, and found pervasively in global business infrastructure. As businesses move to engage their customers via RIA platforms, reusing existing skills, and connecting RIA’s to existing systems, gives the Java community a unique ability to build from what exists - rather than attempt to replace it.

This familiarity also allows businesses and developer teams to focus on engaging with consumers - rather than irritating IT with new infrastructure requirements (JavaFX developers simply link to existing enterprise infrastructure, vs. requiring new systems for RIA apps).

Fourth, RIA developers want free and open platforms.

Why free? Because developers don’t want to encumber their applications with royalty bearing dependencies, or use technologies that predefine where consumers might appear. You don’t build developer communities around closed source, you build user communities - and this is an instance where developer selection and adoption will define the broadest RIA marketplace. JavaFX will, like all of Sun’s software platforms, be made freely available as open source, and it’ll be released via the GPL (v2) license.

And lest you think free and open software is the province of those with goatees and tattoos… we’re seeing a rising tide of developing nations mandating free and open software in government and academic procurement. Why? To protect choice, and build indigenous opportunity - there’s no reason to build dependencies upon proprietary software if you can avoid it.

Lastly, lets face it, the real value in Web 2.0 is the data - not the app. And that data is YOURS.

If you’ve been watching the social media space as carefully as we have, you understand the value of instrumentation and intentionality in building a business on the web. Knowing what users are doing with your product, whether it’s a fantasy cricket league or a consumer banking application, enables more innovative business models, the delivery of higher value services, placement of more valuable ads - data allows for better decisions, and better value creation (and bluntly put, higher CPA).

But most rich internet applications are built, then deployed - into a fog. Developers who leave the confines of the browser either lose access to information about what their users are doing, or have to rely upon a technology provider that’s inserting itself into their data stream. And some of those technology providers compete with content developers.

With a project code named Project Insight, we’ll be instrumenting the Java platform to enable developers to harvest the data stream generated by their RIA content. JavaFX developers can focus on their business models - rather than enhancing someone else’s.

_______________________

With all that said, what’s the success of JavaFX worth to Sun?

By definition, it’s worth more to Sun than the adoption of someone else’s platform (known as “positive option value”) - and the proprietary infrastructure used to serve it (don’t forget, RIA’s have rich internet back-ends (RIBs?). And in the RIA world, all the options are going to be priced at free, anyways - this isn’t a contest to be won on price.

From where I sit, the platform likely to win will be the one that sets developers free - to pursue markets, opportunities and customer experiences as they define them, not as vendors define them. Now, setting developers free - that’s where we can excel. It’s in the DNA of everything we do.

For developers, learn more at JavaFX.com. And be sure to check out NetBeans - like Java itself, it’s starting to rock the free world…

See also

http://blogs.sun.com/jonathan/entry/rocking_the_free_world?cid=925029






--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

W3C’s Validations for Link Checker, CSS Validator



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

Online Sitemap Generator for SEO

What is "XML sitemap"?

By placing a formatted xml file with site map on your webserver, you enable Search Engine crawlers (like Google) to find out what pages are present and which have recently changed, and to crawl your site accordingly.

What is "Change frequency"?

This value indicates how frequently the content at a particular URL is likely to change.

What is "Last Modified"?

The time the URL was last modified. This information allows crawlers to avoid recrawling documents that haven't changed.
You can let the generator set this field from your server's response headers or to specify your own date and time.

What is "Priority"?

The priority of a particular URL relative to other pages on the same site. The value for this tag is a number between 0.0 and 1.0, where 0.0 identifies the lowest priority page(s) on your site and 1.0 identifies the highest priority page(s) on your site.
The default priority of a page is 0.5.



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

getHibernateLazyInitializer bug in hibernate on linux systems

Thread implementations are different (JVM on some linux kernels uses child process and shared memory to implement multithreading, it can depend on JVM settings and implementation) and can produce many anomalies if code is not thread safe. The right way is to make application code thread safe, workarounds can help to hide a problem, but not to solve it.

I ran into this same issue on JDK 1.5/Linux/client mode, while never seeing it under Windows

—–

I saw the error on Linux, and can verify that the problem has (so far) gone away when I added -server to the JVM



--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.

Working with JSTL TAGS - java

STL Examples
(last updated: Dec 15, 2006)

Select font size:
8pt 9pt 10pt 11pt 12pt 14pt 16pt

Download the

JSTLexamples.war

archive. This archive contains the following files:

index.jsp                   Script with a variety of examples
bean/MyBean.java User-defined bean example
mytaglib/MyFunctions.java JSTL tag library classes
Functions.tld JSTL tag library definition

Install and run in Eclipse

Prior to starting eclipse, you need to make available two new library JAR files which are included in the apache-tomcat distribution but not available for all applications. Locate the directory:

apache-tomcat-6.0.14/webapps/jsp-examples/WEB-INF/lib/

and within it, the files:

jstl.jar  standard.jar

Simply copy these two files into:

apache-tomcat-6.0.14/common/lib/

Then start up eclipse. Follow the steps in JSP Forms import the WAR file JSTLexamples.war and run the project on Tomcat.

The JSP Standard Tag Library (JSTL)

The JSTL library provides a means, through variables, expressions and tags, to avoid the interleaving of Java and tag-style code. Using this language, we can, for the most part, eliminate explicit Java code in JSP pages in favor of augmenting the XML-like tag structure. See

You should refer to this online documentation:

and/or download it yourself:

The standard tags are those described in the table below. We have omitted the sql tags since we don't plan to use SQL done directly in JSP. Using one of tag groups is effected by the addition of one of the following respective tag statements below.

c:   <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
fn: <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
fmt: <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
xml: <%@taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

The uri is simply an identifier of the tag set. The prefix is determinable by the user, but the prefixes seen here are standard.

TLD tags and functions
c: core fmt: formatting fn: functions x: xml
c:catch
c:choose
c:forEach
c:forTokens
c:if
c:import
c:otherwise
c:out
c:param
c:redirect
c:remove
c:set
c:url
c:when
fmt:bundle
fmt:formatDate
fmt:formatNumber
fmt:message
fmt:param
fmt:parseDate
fmt:parseNumber
fmt:requestEncoding
fmt:setBundle
fmt:setLocale
fmt:setTimeZone
fmt:timeZone
fn:contains()
fn:containsIgnoreCase()
fn:endsWith()
fn:escapeXml()
fn:indexOf()
fn:join()
fn:length()
fn:replace()
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()
x:choose
x:forEach
x:if
x:otherwise
x:out
x:param
x:parse
x:set
x:transform
x:when

These and other tag systems are used in JSP in one of two forms:

<tag-prefix:type attribute1="VALUE1" ...

or, as functions to create expressions:

tag-prefix:function(arg1,arg2,...)

As in XML, tags can be complete, using a single tag ending with "/>", or in pairs, containing a content terminated by a matching ending tag </tag-prefix:tag-type>. Some example of the common usages of the "c" tags are these:

<c:out value="..." escapeXml="true"/>
<c:set var="x" value="..." />
<c:if test="..." > ... </c:if>
<c:forEach var="x" items="..." > ... </c:forEach>

Expression Language (EL)

The syntax for what replaces the "…" above is specified by a Java-like language, unimaginately called Expression Language (EL). EL is part of JSP; its expressions are all surrounded by the syntax ${ }. but typically can only be used most effectively in conjunction with JSTL tags. EL is closely related to Java but has some extensions and conceptual simplifications. In particular, EL is more like other web script languages being loosely typed along with other semantic simplifications. EL expressions permit variables and most of the usual arithmetic and boolean operators. Here are some points:

  • The == operator for strings functions like the Java .equals operator.
  • an EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string.
  • EL has a unary operator empty: empty(x) acts like the expression x==null but also means "x equals the empty string".
  • the operators or, and are synonyms for ||, &&, respectively.

Query parameters

The value of the parameter "xx" is expressed by the EL expression param.xx. When used directly in HTML,

${param.xx}

is equivalent to the JSP expression:

<%= (request.getParameter("xx") != null) ? (request.getParameter("xx") : "" %>

Session variables are EL variables

A session variable x automatically becomes available as an EL variable, e.g. if we have:

<%
session.setAttribute( "x", "hello" );
// or
pageContext.setAttribute( "x", "hello" );
%>
...
x = ${x} <!-- prints: x = hello -- >

JSP beans in JSTL

The EL language provides a simplified syntax for accessing bean's get/set accessor functions. For example, the bean we use in the examples below is this:

<jsp:useBean id="mb" class="bean.MyBean" />

from the class:


bean/MyBean.java


package bean;

public class MyBean {
private String count;
public String getCount() { return count; }
public void setCount(String count) { this.count = count; }
public MyBean() {
System.out.println("MyBean intialized");
count = "0″;
}
}

EL treats the expression ${mb.count} as the value of mb.getCount(). A typical JSTL tag statement is something like

<c:set var="i" value="${mb.count}" />

The c:set tag is also used to call the set member function as follows:

<c:set target="${mb}" property="count" value="5" />

is equivalent to mb.setCount("5″). Caution: If you use both set and get property, they must be consistent. For example, suppose you have these member functions:

String getSomeProperty() { ... }
void setSomeProperty(int n) { ... }

Then EL will consider this a mismatch and most likely reject the setter member function if you tried to use:

<c:set target="${mb}" property="someProperty" value="5" />

We can also remove a bean from the session using the JSTL c:remove tag:

<c:remove var="mb" />

Data structures: arrays, arrays, maps, sets

Arrays and maps permit access to their collection via indices: arrays via integer indices and maps via key indices. EL regards both of these accesses as syntactically similar using the [ ] operator. For example:

<%
Map<String,String> theMap = new HashMap<String,String>();
theMap.put("John", "5"); theMap.put("Jim", "7");
String theArray[] = { "aaa", "bbb", "ccc" };

session.setAttribute( "theMap", theMap );
session.setAttribute( "theArray", theArray );
%>

${theMap["Jim"]} <!� same as theMap.get("Jim"), outputs 7 �>
${theArray[1]} <!� outputs bbb �>

The EL expressions for maps, sets and lists can all print directly. Arrays, as in Java, don't print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose:

${fn:join(theArray,",")}

Iterating over data structures

In order to iterate over an array, list, map, or set, the c:forEach tag pair serves our interests. Iteration with c:forEach treats arrays, lists and sets identically. For example, this code will iteratively print the elements:

<!-- L represents either an array, list or set -->
<c:forEach var="x" items="${L}" >
${x}
</c:forEach>

When using a map, the iteration generates Map.Entry pairs. Using the getKey and getValue functions the structure of the JSTL code to iteratively print the key/value pairs looks like this:

<!-- M is a map -->
<c:forEach var="x" items="${M}" >
${x.key}: ${x.value}
</c:forEach>

Choice tags c:if, c:choose/c:when

The c:if tag generates a choice situation with a syntax like:

<c:if test="${EL_BOOLEAN_EXPRESSION}" > ... </c:if>

The EL_BOOLEAN_EXPRESSION uses the usual boolean operators with simplifications and additions as mentioned above. If-else structures are based on the c:choose/c:when/c:otherwise tags:

<c:choose>
<c:when test="${EL_EXPR1}"> ... </c:when>
<c:when test="${EL_EXPR2}"> ... </c:when>
...
<c:otherwise> ... </c:otherwise>
</c:choose>

User-generated tag functions

If one wants to avoid explicit JSP sections of code then the Java classes and functions must be able to be accessed through the tag system. Beans provide a limited way of doing so through combinations of "get/set" member functions, but this is not intended for utility functions to manipulate objects. The fn tags provide some of these utility functions, but one can imagine that soon there would be need for your own specific utility functions. Towards this end, JSP provides a means to add your own tag libraries using a combination of Java classes and Tag Library Definition (TLD) files. Both XML-like tags and EL function tags can be added, but it's much easier to create user-defined EL function tags. The utility functions used must be static functions. For example, suppose we want to use the function defined in this class in an EL expression.


mytaglib/MyFunctions.java


package mytaglib;
import java.util.*;
public class MyFunctions {
public static boolean contains(Set<String> set, String target) {
return set.contains(target);
}
}

The glue which connects this functions to JSP is the XML file MyTags.tld held stored in the /WEB-INF/ project directory.


MyTags.tld


<?xml version="1.0″ encoding="UTF-8″?>
<taglib version="2.0″ …>
<tlib-version>1.1</tlib-version>
<uri>/WEB-INF/MyTags</uri>
<function>
<name>contains</name>
<function-class>mytaglib.MyFunctions</function-class>
<function-signature>
boolean contains(java.util.Set,java.lang.String)
</function-signature>
</function>
</taglib>

This file defines a uri by which it is accessed and a set of function prototypes in XML format. Each function has a tag name, the class it belongs to and the actual function prototype within this class. The necessary specification within the JSP file is something like this:

<%@taglib prefix="mtg" uri="/WEB-INF/MyTags"%>

The prefix chosen specifies how the function will be referenced within the EL syntax ― it can be anything you want, so long as it doesn't conflict with another tag set. In this case the function will be prefaced by mtg: as in this example:

<c:if test="${mtg:contains(someSet,someValue)}" > ... </c:if>

Example script


index.jsp


<%@ page language="java" contentType="text/html;
charset=US-ASCII" pageEncoding="US-ASCII"%>

<%@page import="java.util.*"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@taglib prefix="mtg" uri="/WEB-INF/MyTags"%>

<jsp:useBean id="mb" scope="session" class="bean.MyBean" />

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
<style>
h4 { color: red; margin-bottom:0px; text-decoration: underline; }
</style>
</head>
<body>
<%
String x = "testing";
String[] a = { "xx", "yy", "zz" };

Map<String, String> m = new LinkedHashMap<String, String>();
m.put("aa", "1″);
m.put("bb", "2″);
m.put("cc", "3″);

List<String> l = new ArrayList<String>();
l.add("nn");
l.add("mm");
l.add("oo");
Set<String> s = new LinkedHashSet<String>();
s.add("aa");
s.add("bb");
s.add("cc");
session.setAttribute("x", x);
session.setAttribute("a", a);
session.setAttribute("m", m);
session.setAttribute("l", l);
session.setAttribute("s", s);
%>
<h4>access values of query parameter p</h4>
<c:if test="${param.p == null}">param.p not defined<br /></c:if>
first value: ${param.p}<br />
all values: ${fn:join(paramValues.p,",")}

<h4>print objects</h4>
x: ${x}<br />
m: ${m}<br />
s: ${s}<br />
l: ${l}<br />

<h4>print array using join</h4>
a: ${fn:join(a,",")}
<br />

<h4>access individuals of array or map via [ ]</h4>
a[1]: ${a[1]}
<br />
m["bb"]: ${m["bb"]}
<br />

<h4>access individuals in c:forEach loop</h4>
a: <c:forEach var="i" items="${a}">${i} </c:forEach><br />
s: <c:forEach var="i" items="${s}">${i} </c:forEach><br />
l: <c:forEach var="i" items="${l}">${i} </c:forEach><br />
m: <c:forEach var="i" items="${m}">${i.key}=>${i.value} </c:forEach><br />

<h4>using c:set and escapeXml</h4>
<c:set var="k" value="<b>bold</b>" />
k: ${k}<br />
escaped(k): ${fn:escapeXml(k)}<br />
c:out escaped: <c:out value="${k}" escapeXml="true" />

<h4>using a bean's get and set properties indirectly</h4>
mb.count: ${mb.count}:
<c:set target="${mb}" property="count" value="${mb.count + 1}" />
<c:choose>
<c:when test="${mb.count > 6}">
became bigger than 6, re-initialize mb
<c:remove var="mb" />
</c:when>
<c:when test="${mb.count > 3}">became bigger than 3</c:when>
<c:otherwise>no more than 3</c:otherwise>
</c:choose>

<h4>User defined tag functions</h4>
s: ${s}<br />
<c:set var="t" value="cc" />
s.contains(${t}): ${mtg:contains(s,t)}<br />
<c:set var="t" value="dd" />
s.contains(${t}): ${mtg:contains(s,t)}

</body>
</html>


--
Thanks & Regards,
B.Chandra Shekhar.
Software Engineer,
Jiva Infotech Pvt Ltd.