CIBIL- was incorporated in 2000.The relationship between CIBIL and the Banks is that of close interdependence. Banks provide Cibil the information of its customers who have taken credit and there payments behavior and track record. CIBIL on the basis of information collated from all Banks, helps its member Banks to make faster credit decisions when they acquire new customers as they will be able to check his previous credit history.
The CIBIL Credit Score System:
It will be on a scale ranging from 100 to 999. Cibil collates data from its member Banks and creates a track of all loans, Credit taken by an individual and impart him a score based on his behavior of repayments of Emi’ s and Credit card from member Banks. Lower the CIBIL credit score lower the chances of getting money on credit. Say if your credit score is close to 100, then this implies, outright refusal of credit, requirement of additional security / guarantee, higher down payment, shorter duration and higher interest rates. If you have a very high CIBIL credit score, say 800, this implies, lower interest rates, waiver of processing fees and faster disbursement of funds.
So then, how can I improve my CIBIL Credit Score?
• Pay all your EMIs on Loans in time. And when you have more than one loan running it gets difficult to repay them or keep a track. So, it’s very important to make regular & timely re-payments of your loan to maintain your credit level.
• Never fail to pay the Minimum Payment required by your Credit Card. What is advisable is making full payments on your credit card every time. Credit Card is categorized as revolving credit and it helps in building a good credit history if payments are regular.
• Always make a budget for yourself & ensure your monthly income permits you to take a loan.
• Do not apply for loans or credit cards if not required. As this would mean more credit exposure. This could affect your credit score. Instead of applying for another loan, try checking for a top-up loan option on your existing loan. This will make your debt burden easier to manage.
• Use some of your savings to repay some of your debt. Always plough back extra income to reduce your debts. This will increase your credit score level.
• A cheque bounce on your credit card or on a loan also affects your credit rating.
• Avoid going in for settlements, although you make payments only for your purchases in a settlement it does bring down your score level. And never get into a write off case. This means not paying for your dues at all.
Now that you are aware of the CIBIL scoring system, please work on maintaining your score. Ensure that you are always in control of your finances. However, even if your credit score is low don’t be disheartened. The credit system always gives scope for improvement. You can start improving your credit score by simply paying of your debt and not opting for more until your score improves.
Thursday, December 4, 2008
Credit information Bureau (India) Limited (CIBIL)
Posted by Prem Kumar Jha at 6:09:00 PM 3 comments
Labels: CIBIL
Sunday, November 30, 2008
Lessons of Mumbai Terror Attack
As per the news being circulated the Mumbai Terror Attack problem is over with a few dozens dead and over 350 injured. We must congratulate our NSG, Marine Commandos, Army personnel who all had to operate in the danger zone around the Action areas for over 65 hours with a few of them losing their lives in action. We salute all of them who took part in the operation and flushed out the terrorists dead or alive. We also salute those of the finest IPS Officers of ATS and Police men who lost their lives in the starting phase of the battle between the law and order keeping forces and the Terrorists.
What are the lessons of the event?
That, the country was one, is one and will remain one against all such external or internal attacks, disturbances and disorders being created by vested interest groups outside the country and also inside it.
That, Maratha warriors like Bal Thakrey and his Shiv Sainiks and Raj Thakrey and his MNS Sainiks were seen nowhere in action of saving their very own Marathi Manush Mumbai. A shameful act on part of these Maratha warriors. Mumbaikars and the Marathis must have now more faith in the United India with brotherhood between the people of different linguistic, cultural and religious background and not in so called sainiks and their leaders.
That , major part of Police administration in Mumbai, except for ATS, seemed to be paralysed and fainted. This was the same force which flashed their bravery in killing Raj, a Bihari boy from a short distance a month ago.
That, neither CM Deshmukh nor his loud mouth Home Minister RR Patil who was shouting at the top of his voice about a month ago that guns will be met with guns (against the same Bihari boy Raj ) was not visible this time with his boys and the guns when the terrorist guns were spitting fire. There were many other brave Marathas like Praful Patel who matched his frequency with Raj Thakrey and challenged just a month ago whoever challenged the Marathas and their ego which in his opinion was not the rights or property of Northies, Hindi speaking population and last but not the least Biharis and Jharkhandis. All this Maratha talk was a shameful act then and now. Otherwise they should have been in the forefront of the Save Mumbai campaign from Terrorists. Is it possible that the Terrorists fixed the exact dates for action after making sure that Mumbai in particular had become weak due to the recent MNS action against the Biharis and Northies in Mumbai and Maharashtra? This may be a major probable cause.
This also has a lesson for us and our rulers in Delhi as to why we have a non-political PM and a weak Home Minister who seemed to be totally unaware of his job, that is, the situation prevailing in the country. They are certainly not pro-active. They are reactive. Therefore, we, over 100 crore people are not safe in these hands. It is not to say that BJP or their NDA will do anything better.
What we, the citizens of this country need to do is to reject all such defective people whose total perspective is to look at the Unity and existence of this country through the eyes of BSE and NSE indices, or divide the populace for votes on linguistic , caste and communal lines and are not interested in a sensible governance and development of a United and strong India.
Posted by Prem Kumar Jha at 9:26:00 PM 0 comments
Labels: Mumbai Terror attack
One of the best interview
Interviewer : Why are you interested to work in our Company?
Interviewee: Yeah, the reason is pretty simple. I must work in one of
idiotic company, only then I can run my life. It is necessary that I have to work for the stupid who appoints me. Other than that I don’t have any special respect/opinion on your company.
Interviewer: Can you tell me why must I appoint you?
Interviewee: If not I, some fool must be appointed, so why not me.
Interviewer: What are your peculiar talents?
First, I will see how to make fun. I will check what all can be stolen
from the office. By saying this appointment, I will borrow money from several fools. I will try to get a better job than this. Other than this, I don’t have any idea of working hard and sincere and develop your company.
Interviewer: What is your strength?
Interviewee: Once I get a job which pays me even one rupee more than this, immediately I will quit this job. I will not compromise this for anything.
Interviewer: Your weakness?
Interviewee: He,he, Money and Liquors…
Interviewer: What are your achievements in the previous company?
Interviewee: Nothing as such. If anything as that why I come to your
company? I would have exaggerated and earned more salary there itself.
Interviewer: What was your great challenge? How did you overcome that?
Interviewee: By Gods grace only. So far, no boss or manager found me
useless till my third salary.
Interviewer: Why did you quit your last job?
Interviewee: for the same reason for which you conduct this interview.
Interviewer: What do you expect?
Interviewee: Good Salary, 0% work and a few idiots to make fun.
Posted by Prem Kumar Jha at 9:13:00 PM 0 comments
Labels: Masala
Let's change -- In view of terror attack in Mumbai
dear all,
we all have seen what happened in mumbai and also what happened in past(from 93 mumbai blast to attack on parliament, to train blast of mumbai, bomb blasts of bangalore, delhi, assam, ahemedabed). the terrorists are taking us for granted they think we indian only know to get victimized.
we see the news, discuss about it find out whether our relative and all are safe or not and then forget or rather ignore it thinking at least I'm not affected directly.but, i think it's time we started thinking that this is my country's problem, my problem. today many country's have asked their people not to travel India ( you must have seen the news). what's it? it is not our loss? it is loss of our country's reputation, economy, image.
we as a citizen of this great country need to take some responsibility to correct it.no need to go out with the weapon and do something stupid. we need to create an environment around where we think beyond the small barriers like, state, religion, region, caste and gender. we need to create a cohesive culture where people empathize others problems as if it was theirs.
and we have to ensure that our workplace, our home and our society where we have our influence we try to change and keep trying till it becomes united.
United we stand and divided we fall.
And if as a country we are united and thinking for others then no body in this world will even dream of attacking on INDIA.
and we know that at least now we need to get united. let's become one for the bigger cause- that's our beloved India. we may think that i alone can't change much. but, if everyone thinks the same, then we will always have the repetition of what happened now and we will have only ourselves to blame. so let's change for a better future and let's change because we do not want to give our next generation this India(where nobody is sure whether he will be alive tomorrow or not).
Let's change
Posted by Prem Kumar Jha at 8:57:00 PM 0 comments
Labels: Mumbai Terror attack
Thursday, July 10, 2008
DB2 Manual Installation on Linux
Install
* Login as root.
* Create groups:
o groupadd -g 999 db2iadm1
o groupadd -g 998 db2fadm1
o groupadd -g 997 dasadm1
* Create users for each group:
o useradd -u 1004 -g db2iadm1 -m -d /home/db2inst1 db2inst1
o useradd -u 1003 -g db2fadm1 -m -d /home/db2fenc1 db2fenc1
o useradd -u 1002 -g dasadm1 -m -d /home/dasusr1 dasusr1
* Set password for each users created:
o passwd db2inst1
o passwd db2fenc1
o passwd dasusr1
* cd to installation file directory:
o Example: /tmp/db2/exp/disk1
* Run installation script:
o ./db2_install.sh
Post Install
* Login as root.
* Install license (example):
o /opt/ibm/db2/V9.1/adm/db2licm –a /tmp/db2/exp/disk1/db2/license/db2exp_uw.lic
Create the DB2 Administration Server (DAS)
* Login as root.
* Create DAS with dasusr1
o /opt/ibm/db2/V9.1/instance/dascrt -u dasusr1
* Login as dasuser1
o Start the DAS: db2admin start
* Optional: to enable autostarting of the DAS upon reboot
o /opt/ibm/db2/V9.1/instance/dascrt/dasauto –on
Create DB2 instance
* Login as root.
* Create instance with users db2fenc1 and db2inst1:
o /opt/ibm/db2/V9.1/instance/db2icrt -a server -u db2fenc1 db2inst1
* Optional: enable autostarting of the db2inst1 instance
o /opt/ibm/db2/V9.1/instance/db2iauto –on db2inst1
Update environment variables
* Example:
* Login as db2inst1
* edit .bash_profile
o vi /home/db2inst1/.bash_profile
o insert the following line at the end of the file – “. /home/db2inst1/sqllib/db2profile”
* Do the same for dasusr1, using its corresponding directory.
Database service
* Login as root:
* Add new service entry:
o vi etc/services
o insert this line “DB2_TMINST 50000/tcp” at the end of the file
Verification
* Login as db2inst1
* List installed DB2 products and features: db2ls
* Display the default instance: db2 get instance
o Result: The current database manager instance is: db2inst1
* Start the database instance: db2start
o Result: SQL1063N DB2START processing was successful.
* Stop the database instance: db2stop
o Result: SQL1064N DB2STOP processing was successful.
Posted by Prem Kumar Jha at 11:44:00 PM 0 comments
Labels: DB2
Sunday, July 6, 2008
Why to stay alone atleast once in bachelor life
After a long time I feel, I need to write why I love to stay alone. Many friends asked me why r you staying alone?, are you not bored to be alone. One of my collegues ask me again few days back the same question. So, to answer everyone seprately, I thought it's good if nxt time any body will ask I will pass my blog's link.
I think everyone should live alone atleast for few months and see.
Its certainly a different experience. Though there wont be any company when we need it and things like that, the freedom it offers is amazing.
Living with someone or a group is good in its own way. But there is always somebody else to consider. Even when you are not hungry enuf, you got to do stuff for the other person, you just cant sit and see that the other person’s working and all that. When you are alone, The house is all yours. You can eat when you want, you can take bath when you want, its all you..You are the sole custodian for the Remote control and what not.
You can just lie around and do nothing, or get creative and do stuff without any inhibitions. There is no one to comment, judge or criticize. It is truly your Home, where you don’t have to answer anyone. Ofcourse in our mind, our parents are gonna criticize how we are keeping the house and what not, but you can atleast try to ignore it, when its in your head.
Through out our School, College life either we live with our Parents or Hostel or with your roommates, so there is always rules to follow. I mean, somebody else’s rules. When we start earning and stuff, we can have our own rules based on our values. Its fun having roommates when your frequency aligns. Otherwise it’s a royal pain, everybody knows that. I have had my share of my roommates during college time. Sometimes it was fun, sometimes it wasn’t.
I had to stay alone for a year, few years back. There was no company. I had never even slept alone in a room before that. I am so tuned into all these ghost and stuff, sleeping alone was an impossible task for me. So I was kinda scared about staying alone. So initially, I used to sleep with Bedroom light on and slowly I learned to sleep with just a night lamp. Daytiem, it was never a problem for me. Dark scares me..Sometimes, I missed company. But I really started enjoying it. It was fun. Weekends, sleep late, wakeup around noon, eat take outs and cook sometimes if I feel like it, read lots and lots of books, no need to worry whether I am disturbing somebody with my crazy habits, I totally enjoyed it.
I am not talking against staying with Roommates and all.. I know lot of people enjoy that. I am just saying it’s a good experience to have, to stay alone for sometime and see..
After Marriage, its not possible. You cant stay alone and spend your parent’s money either. So all we have is that small period, where we earn and can be financially independent and unmarried. Ofcourse, staying alone in old age is not that good. There are lots of disadvantages in living alone, when you are old. So, that’s ruled out, I mean if we have the choice.
One main disadvantage in staying alone though, People tend to become loners..
There are other many good factors which forced me to stay alone. So, stay tune for other good new factors ......
prem
Posted by Prem Kumar Jha at 10:06:00 AM 0 comments
Labels: Stay Alone
Monday, April 14, 2008
ONE BEDROOM FLAT
ONE BEDROOM FLAT...
WRITTEN BY AN INDIAN SOFTWARE ENGINEER......
As the dream of most parents I had acquired a degree in
Software Engineering and joined a company based in USA, the
land of braves and opportunity. When I arrived in the USA, it
was as if a dream had come true.
Here at last I was in the place where I want to be. I decided I
would be staying in this country for about Five years in which
time I would have earned enough money to settle down in India.
My father was a government employee and after his retirement,
the only asset he could acquire was a decent one bedroom flat.
I wanted to do some thing more than him. I started feeling
homesick and lonely as the time passed. I used to call home and
speak to my parents every week using cheap international phone
cards. Two years passed, two years of Burgers at McDonald's and
pizzas and discos and 2 years watching the foreign exchange
rate getting happy whenever the Rupee value went down.
Finally I decided to get married. Told my parents that I have
only 10 days of holidays and everything must be done within
these 10 days. I got my ticket booked in the cheapest flight.
Was jubilant and was actually enjoying hopping for gifts for
all my friends back home. If I miss anyone then there will be
talks. After reaching home I spent home one week going through
all the photographs of girls and as the time was getting
shorter I was forced to select one candidate.
In-laws told me, to my surprise, that I would have to get
married in 2-3 days, as I will not get anymore holidays. After
the marriage, it was time to return to USA, after giving some
money to my parents and telling the neighbors to look after
them, we returned to USA.
My wife enjoyed this country for about two months and then she
started feeling lonely. The frequency of calling India
increased to twice in a week sometimes 3 times a week. Our
savings started diminishing.
After two more years we started to
have kids. Two lovely kids, a boy and a girl, were gifted to us
by the almighty. Every time I spoke to my parents, they asked
me to come to India so that they can see their grand-children.
Every year I decide to go to India… But part work part
monetary conditions prevented it. Years went by and visiting
India was a distant dream. Then suddenly one day I got a
message that my parents were seriously sick. I tried but I
couldn't get any holidays and thus could not go to India ... The
next message I got was my parents had passed away and as there
was no one to do the last rights the society members had done
whatever they could. I was depressed. My parents had passed
away without seeing their grand children.
After couple more years passed away, much to my children's
dislike and my wife's joy we returned to India to settle down.
I started to look for a suitable property, but to my dismay my
savings were short and the property prices had gone up during
all these years. I had to return to the USA...
My wife refused to come back with me and my children refused to
stay in India... My 2 children and I returned to USA after
promising my wife I would be back for good after two years.
Time passed by, my daughter decided to get married to an
American and my son was happy living in USA... I decided that
had enough and wound-up every thing and returned to India... I
had just enough money to buy a decent 02 bedroom flat in a
well-developed locality.
Now I am 60 years old and the only time I go out of the flat is
for the routine visit to the nearby temple. My faithful wife
has also left me and gone to the holy abode.
Sometimes
I wondered was it worth all this?
My father, even after staying in India,
Had a house to his name and I too have
the same nothing more.
I lost my parents and children for just ONE EXTRA BEDROOM.
Looking out from the window I see a lot of children dancing.
This damned cable TV has spoiled our new generation and these
children are losing their values and culture because of it. I
get occasional cards from my children asking I am alright. Well
at least they remember me.
Now perhaps after I die it will be the neighbors again who will
be performing my last rights, God Bless them.
But the question
still
remains 'was all this worth it?'
I am still searching for an answer.................!!!
START THINKING
IS IT JUST FOR ONE EXTRA BEDROOM???
LIFE IS BEYOND THIS …..DON'T JUST LEAVE YOUR LIFE ……..
START LIVING IT …….
LIVE IT AS YOU WANT IT TO BE …….
Posted by Prem Kumar Jha at 3:54:00 PM 0 comments
Labels: Article
Friday, April 4, 2008
What does volatile do?
What does volatile do?
This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:
1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
5. The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
Posted by Prem Kumar Jha at 11:43:00 PM 0 comments
Labels: JAVA
Saturday, March 22, 2008
why Swing is not thread safe and AWT is
Simple answer is - "that's the design choice the Swing team made". It is a well-known fact that writing thread safe API/library is more difficult and inefficient.
So to simplify the implementation of Swing library they chose it to be not thread safe. The argument being that most of the GUI related work happens in the callbacks from the GUI which happen on the single GUI thread anyways. Granted - for long running tasks the user will have to do more work if he/she wants to do multithreaded activity. Not making Swing thread safe allowed them to implement the Swing which covered a lot more ground (new controls, layouts, keyboard actions, layered pane etc) in a short amount of time.
It is not that bad though - Swing does provide a mechanism to deal with the issues of threading -
javax.swing.SwingUtilities.invokeLater(Runnable ...);
javax.swing.SwingUtilities.invokeAndWait(Runnable ...);
javax.swing.JProgressBar class
javax.swing.ProgressMonitor
javax.swing.ProgressMonitorInputStream
SwingWorker
For more explaination of why they made that decision please see the following URLs:
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html
The AWT is based on the OS's WIndowing System's peer objects which are inherently thread safe. That is why AWT is thread safe.
One can argue though that they should have provided factory methods (similar to collections framework) or subclasses to get thread safe versions of the Swing classes - for example, TSJTextField or TSJTree where the "TS" stands for 'thread safe'
Posted by Prem Kumar Jha at 9:51:00 PM 0 comments
Labels: JAVA
Friday, March 21, 2008
Synchronized Multithreading with Swing
For some people, hearing the word "thread" brings to mind spiders, or else other creeping things which can be seen on dark nights when one is coding alone in the office. However, this should not be the case, for in a Java program threads are your friend, and perhaps unbeknownst to you, they have been aiding your adventures from the first time you used the Swing library.
Before we slide down into a possible tangle of multiple threads, remember that one should not begin creating threads without a good purpose, for they are complex and need to be completely thought through before being used. When you are creating threaded code, keep it as simple as possible, for any complexity you introduce will surely lead you into some sticky situations like a moth who gets trapped forever in a deadlocked situation.
You may be surprised to find out that Swing already uses multiple threads. "How is this possible?" you might ask. "I have never implemented a Runnable interface nor extended Thread in my years of using Swing." Swing utilizes something called the event dispatch thread which operates behind the scenes. This thread is responsible for handling system events, such as when a user clicks the mouse button or when a Swing timer goes off. Fortunately, event handling code automatically executes in the event dispatch thread, so all of your callbacks are already taking place on this thread. When the user clicks on one of your controls, the event is handled by the event dispatch thread and your code that responds to this event is executed on this separate thread.
Try running this example which shows the name of the thread in the label on the left. Source Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThreadDemo extends JFrame {
JLabel label;
public ThreadDemo() {
super("Thread Demo");
setSize(300,50);
this.getContentPane().setLayout(new GridLayout(1,2));
label = new JLabel();
label.setText(Thread.currentThread().getName());
this.getContentPane().add(label);
JButton button = new JButton();
button.setText("Get Thread");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(Thread.currentThread().getName());
}
};
button.addActionListener(listener);
this.getContentPane().add(button);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]) {
new ThreadDemo();
}
}
The first time the call Thread.currentThread().getName() is invoked, it is in the thread named "main", because the label is created within the main thread. However, within the ActionListener which is invoked when you press the on screen button the thread name is "AWT-EventQueue-0". The actionPerformed call is invoked when you click the mouse button, which is handled in the event dispatch thread. You can use this technique of checking the thread name to ensure any code you are writing is actually being run in the event dispatch thread.
One of the fortunate things about the fact that events are handled automatically on the event dispatch thread is that Swing is not thread safe and you must modify any realized GUI components from within the event dispatch thread. Thus, the difficult and dangerous task of keeping Swing thread-safe is happening by default for your event handling code, and is already taking place within this context. You could imagine if a separate thread began modifying a combo box at the same moment a user chose that combo box and started scrolling through it. The technical term for such a confluence of events is "uh oh". In the worst case, not only will data integrity be compromised, but the entire application will lock up, and the hours of work the user has spent using your application will vanish into a cloud of smoke coming out of his or her ears.
Historically there has been one mighty exception to the rule that you must modify any GUI components from within the event dispatch thread; that was at startup. It had been considered safe to create the GUI in the application's main thread provided no GUI components were visible. This is the way most programs are written, and is likely to be safe, but now as you can see the official way to ensure complete safety is to now also create the GUI itself within the event dispatch thread. This will ensure you have no lockup at startup.
There are two methods for invoking code inside the event dispatch thread when you are not already in that thread: invokeLater and invokeAndWait. The invokeLater is utilized by passing in a Runnable interface object with a run method which executes at a later time on the event dispatch thread. The invokeAndWait operates in the same way, but does not return until the event dispatch thread has finished executing the code. When you create these Runnable objects and pass them to the invoke methods, they are executed on the event dispatch thread.
Below is the code to replace the main method coded above with the creation of the GUI taking place on the event dispatch thread. An anonymous class is created with the Runnable interface which calls the new ThreadDemo(); to create the GUI. As you can tell if you run the modified code, the creation of the label now takes place on the event dispatch thread. Source Code
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ThreadDemo();
}
});
}
Using other threads
If you have ever used an application and wondered "What the heck is taking so long here?" you have encountered a reason to use multiple threads. The user is in charge of your application, and as soon as you wander off with the event dispatch thread with an extremely slow piece of code, your user has lost control. The application will appear to hang, since no other mouse or keyboard events can be handled as long as the event dispatch thread is busy.
For this sample application we will compute the value of P using perhaps the slowest algorithm possible. Since P is an irrational number, a complete implementation could take forever to complete. In case the user is not willing to wait forever, we will utilize multiple threads: one thread to compute the value of P, and the other default event dispatch thread to keep the user informed of what we think P is at the moment. For this example we store the approximated value of pi in a double.
As an aside, the way we are computing P here is by throwing random darts that hit a square with a quarter of a circle inscribed in it. The ratio of darts which fall within the circle to the total number of darts thrown gives a way to approximate P. The square is 1 unit across, and the circle has a radius of 1 unit. The complete circle has an area of P * radius * radius so the quarter circle has an area of P / 4. Thus P is approximately equal to 4 * the number of circle quadrant hits divided by the number of throws.
P is roughly equal to the 4 * number of green dots / (number of green dots + red dots).
Since this is random, there is no guarantee we will converge on P- all of the darts may well fall into the circle quadrant and it will appear P is very close to 4.0. In reality the most significant digits of PI will be calculated fairly quickly and it will take a very long time to find additional significant digits. This is useful, however, as an example utilizing concurrent threading with Swing. Source Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatePi extends JFrame {
JLabel label;
volatile double pi = 0;
synchronized void setPi(double value) {
pi = value;
}
synchronized double getPi() {
return pi;
}
class ThrowDarts implements Runnable {
public void run() {
long counter = 0;
long hits = 0;
double x = 0;
double y = 0;
while (counter < Long.MAX_VALUE)
{
counter++;
x = Math.random();
y = Math.random();
if (Math.sqrt(x*x + y*y) < 1.0f)
{
hits++;
}
setPi(4 * (double) hits / (double) counter);
if (counter%1000 == 0)
{
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
label.setText("" + getPi());
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public CalculatePi() {
super("Throwing Darts");
setSize(300,50);
label = new JLabel();
label.setText(Thread.currentThread().getName());
this.getContentPane().add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
ThrowDarts dartThrower = new ThrowDarts();
Thread t = new Thread(dartThrower);
t.start();
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CalculatePi();
}
});
}
}
Notice that the variable pi is declared to be volatile. This tells the compiler not to place the value of pi into any registers so that it can be accessed from any thread. To guarantee that any accesses to the value of pi are atomic, that is taking place in a single operation, both set and get methods exist with the keyword synchronized to make sure that these operations complete fully before any other thread executes. The code that runs within these synchronized methods will be mutually exclusive; both of these methods can not be executed at once by different threads. Depending on the Java Virtual Machine implementation potentially half of the bytes of pi could be accessed when the other thread changes the value.
At regular intervals, whenever the counter is a multiple of 1000, an anonymous class implementing Runnable is created that updates the label. It is passed to invokeAndWait which will wait for the event dispatch thread to return before processing further. In this way, the update to the label that shows pi takes place on the event dispatch thread.
The invokeAndWait will wait for the event dispatch thread to return before computing more, thus preventing us from adding too many Runnable objects on the event dispatch thread. Do not create too many Runnable objects on the event dispatch thread or the thread can get bogged down. An alternative technique would be to utilize a timer to periodically update the label.
In the main method of the program, the interface is created on the event dispatch thread with its own anonymous instantiation of the Runnable interface.
Parting ideas
There are some methods which are thread safe within the Swing component hierarchy. They will be marked in the documentation as "This method is thread safe".
In summary, there is no need to create separate threads for the general Swing application, although you are advised to instantiate your GUI on the event dispatch thread. All of your event handling code will take place on the event dispatch thread by default. If you are doing something advanced that does require multiple threads, be sure to make it thread safe and manipulate Swing components from within the event dispatch thread. Java Virtual Machine implementations of threading are not consistent so code that works in your test environment may fail elsewhere unless you are careful. Unless the documentation explicitly states that methods are thread safe, you should assume that they are not.
Posted by Prem Kumar Jha at 7:03:00 PM 2 comments
Labels: Swing
Tuesday, March 18, 2008
Successful Trading
Successful Trading = (Knowledge + Experience + Discipline) * Luck.
Posted by Prem Kumar Jha at 2:09:00 PM 0 comments
Labels: Trading
Sunday, March 16, 2008
Factory v/s Facade Design Pattern.
The Factory Pattern :
--------------------------------------------------------------------------------
The factory completely abstracts the creation and initialization of the product from the client
This indirection enables the client to focus on its discrete role in the application without concerning itself with the details of how the product is created. Thus, as the product implementation changes over time, the client remains unchanged.
Client--------------------->Factory----------------->Product
The Facade Pattern
--------------------------------------------------------------------------------
Encapsulate the subsystem using a High-Level Interface/provides a
simplified and uniform interface to a large subsytem of classes.
The Client communicates with the 'Facade' which has methods to interact
with subsystems.The Client very rarely accesses objects in the subsystems.
Subsystems objects usually retain no knowledge of the client.
Subsystem objects do not normally maintain any reference to Faýade.
Client------------------->Facade------->Subsystems
My Question is this:
Arent both these pattern quite similar becos both designs access an Interface
which inturn invokes the required object of the subsystems?
Can anyone explain the major difference?
1. the Factory Pattern, is very useful for the creation of
the objects which it then hands to you and you deal with
the objects directly.
The Facade pattern, tries to simplify things for you, as
it keeps the objects away from you. This simplifies your
life if you are dealing with several complex objects.
2.Faýade
The Faýade pattern simplifies access to a related set of objects by providing one object that all objects outside the set use to communicate
with the set. This also promotes a weak coupling between the subsystem and its clients. This weak coupling allows you to vary the
components of the subsystem without affecting the clients.
Factory
Centralize the assembly of resources necessary to create an object. This prevents the need to change all classes from changing when a
Product changes and makes any change needed occur only in the Factory.
Posted by Prem Kumar Jha at 11:01:00 PM 3 comments
Labels: Design Pattern
Structural Patterns - Facade Pattern
Overview
This article provides a brief introduction to Facade Design Patterns. Facade Design pattern provides an easy to use interface to an otherwise complicated collection of interfaces or subsystems. It makes things easier by hiding the details of the implementation.
When designing good programs, programmers usually attempt to avoid excess coupling between module/classes. Using this pattern helps to simplify much of the interfacing that makes large amounts of coupling complex to use and difficult to understand.
In a nutshell, this is accomplished by creating a small collection of classes that have a single class (Facade) that is used to access them.
The facade pattern is an object-oriented design pattern. A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can accomplish all of the following.
It can make a software library easier to use and understand since the facade has convenient methods for common tasks.
It makes code that uses the library more readable for the same reason.
It can reduce dependencies of outside code on the inner workings of a library since most code uses the facade. This allows for more flexibility in developing the system.
It can wrap a poorly designed collection of APIs with a single well-designed API.
The following Non-software and software examples demonstrate this pattern.
Non-Software examples
In most of the Pizza centers, orders will be given through phone calls with the customer interacting with the Customer service representative. In this case, consumers do not have access to the Billing system, Kitchen and delivery department. The customer service representative acts as an interface and interacts with each of the departments involved in the transaction and ensures that Pizzas are delivered to the consumer.
We can relate this non-software example against the facade design pattern in the following way:
Customer Service representative corresponds to the facade.
Individual departments involved in the transaction correspond to Sub-systems.
Another example we can consider is Emergency services. In the event of fire we just inform an Emergency Service operator. The emergency operator interacts with police, ambulance and fire services and dispatches them. Here the client is shielded from individual emergency services.
Software examples
Web Service Facade Solution Architecture provides an example for Facade design pattern. In this architectural solution, instead of rewriting legacy applications or customizing those with middleware to connect to other applications one by one, this solution helps create a "facade" for the legacy application. Other applications are easily "plugged into" this facade. By modeling a legacy application into its basic functions of create, read, update, and delete and then exposing these functions as Web methods, the Web service facade solution allows other applications to access legacy data by making use of common Web services through standardized protocols. In this way, Facade decouples layers so that they do not depend on each other which can make it easier to develop, to use and to promote code re-use.
Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.
This is how facade pattern is used. It hides the complexities of the system and provides an interface to the client from where the client can access the system. In Java, the interface JDBC can be called a facade. We as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver.
Definition
Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems.
Where to use & benefits
Want to reduce complexities of a system.
Decouple subsystems , reduce its dependency, and improve portability.
Make an entry point to your subsystems.
Minimize the communication and dependency between subsystems.
Security and performance consideration.
Shield clients from subsystem components.
Simplify generosity to specification.
Related patterns include
Abstract Factory, which is often used to create an interface for a subsystem in an independent way, and can be used as an alternative way to a facade.
Singleton, which is often used with a facade.
Mediator, which is similar to facade, but a facade doesn't define new functionality to the subsystem.
Example
JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.
Security of a system may be designed with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information; special guests may be allowed to access more information; administrators and executives may be allowed to access the most important information. These subsystems may be generalized by one interface. The identified users may be directed to the related subsystems.
interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}
class GeneralInfo implements General {
public void accessGeneral() {
//...
}
//...
}
class SpecialInfo implements Special{
public void accessSpecial() {
//...
}
public void accessGeneral() {}
//...
}
class PrivateInfo implements Private, Special {
public void accessPrivate() {
// ...
}
public void accessSpecial() {
//...
}
public void accessGeneral() {
// ...
}
//...
}
class Connection {
//...
if (user is unauthorized) throw new Exception();
if (user is general) return new GeneralInfo();
if (user is special) return new SpecialInfo();
if (user is executive) return new PrivateInfo();
//...
}
The above code example illustrates that the whole system is not exposed to the clients. It depends on the user classification.
Posted by Prem Kumar Jha at 10:31:00 PM 0 comments
Labels: Design Pattern
Sunday, March 9, 2008
Ways to survive a Stock Market Correction!
Global markets all have corrected lately. Irrespective of which market you are investing in, you would have been affected by the recent volatility. You could be an investor in America, India, China, Korea or anywhere else in the world- your situation would be pretty much the same. Many of you who are new investors might have entered panic mode, where you are unable to relax and have lots of stress and depression. I understand how it must be for somebody who just started investing in either stocks or mutual funds two months ago to see a notional loss of 30% or more now.
I remember the first time several years ago when I witnessed a stock market correction, my portfolio was down by over 50% and I too had entered panic mode. But thankfully after reading books on investing and listening to more experienced investors, I decided not to panic and hold my quality stocks. I am a much happier person today thanks to that decision.
Here are some simple ways to survive a stock market correction as an investor:
1. Stop Listening To Analysts
Most analysts in the media instead of providing you with a solution will just confuse you. Somebody will say everything is doomed while others will say things are great in the long term. Forget listening to analysts- most of them won’t be of any help. The reason people listen to analysts is because they are looking for peace and hope. Trust me you will get none of that by listening to somebody else. Peace and hope are all within you.
2. Stop Staring At Your Portfolio Every Thirty Minutes
Another mistake people make is that they get up every morning and wait for the markets to open. Once markets open they start staring at their stock prices. A fall makes you feel worse and small rise makes you feel a little better. This won’t help either. Instead keep track of the fundamentals of your company every time the results are out. If your company is profitable and growing - be happy. If it isn’t, find out if you need to exit. The stock price will catch up in the near future if business is growing. Do you stare at your money kept in a bank FD everyday? Most probably not. Use the same principle when you invest in stocks or mutual funds.
3. Be Patient
Many of you might not have a lot of cash to buy cheap now; however please be patient with whatever you have bought. Even the youngest billionaire on Earth today is 23 years old. It took him 23 years to be a billionaire and he didn’t do it in few days or weeks. The youngest billionaire probably in history is 23-year-old Mark Zuckerberg - the founder of the social networking site-Facebook.
4. Speak To Actual Investors With Experience
Instead of interacting with analysts or your broker, speak with people who are actual investors and who have been in the market for longer periods of time than you. They will tell you how they have survived various stock market corrections and what has made them richer. Read and learn more about people who have actually created wealth and sustained it over a long period of time.
5. Stop Following Crazy Tips
Please for heaven’s sake stop following ‘hot’ tips which promise to make you a millionaire in a matter of months. Maybe the ‘hot’ tip is only meant for billionaires who would end up as millionaires in case they do follow the tip. If it seems to good to be true, it is probably just a scam, which hopes to take money away from retail investors and put them in the hands of greedy manipulators. Similarly stop following rumours about how fundamentally strong companies are going to be shut down and go bankrupt in the next few months. Use your own head and trust yourself.
6. Understand Market Cycles
Every asset class has a cycle. Stock markets, mutual funds, real estate all move in cycles. Please realize that nothing can keep going up forever in a single direction. There will be phases when prices will come down and again move up. If you go back into history you will see several instances when stock prices came down, however over a period of time quality companies always reward investors. Understand market cycles, and don’t become a slave to them.
7. Follow The Guru
Today the richest man on earth, Warren Buffett, is an investor who has created wealth because he has stayed away from what everybody else is doing and has simply invested in quality companies for the long term. He invested in Gillette, for the simple reason that he believed that men won’t stop shaving. It makes sense to follow, as I call him, “The Guru” and think long term and remember people who create wealth do things that others don’t.
I’m sure if you follow the simple techniques above you will be a much happier and a calmer investor. Investing is about controlling your emotions and being disciplined about what you do.
Posted by Prem Kumar Jha at 6:37:00 PM 0 comments
Labels: Trading
Saturday, March 8, 2008
Java Message Service
The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914.
General idea of messaging
Messaging is a form of loosely coupled distributed communication, where in this context the term 'communication' can be understood as an exchange of messages between software components. Message-oriented technologies attempt to relax tightly coupled communication (such as TCP network sockets, CORBA or RMI) by the introduction of an intermediary component, which in this case would be a queue. The latter approach allow software components to communicate 'indirectly' with each other. Benefits of this include message senders not needing to have precise knowledge of their receivers, since communication is performed using the queue.
Elements
The following are JMS elements: [1]
JMS provider
An implementation of the JMS interface for a Message Oriented Middleware (MOM). Providers are implemented as either a Java JMS implementation or an adapter to a non-Java MOM.
JMS client
An application or process that produces and/or receives messages.
JMS producer
A JMS client that creates and sends messages.
JMS consumer
A JMS client that receives messages.
JMS message
An object that contains the data being transferred between JMS clients.
JMS queue
A staging area that contains messages that have been sent and are waiting to be read. As the name queue suggests, the messages are delivered in the order sent. A message is removed from the queue once it has been read.
JMS topic
A distribution mechanism for publishing messages that are delivered to multiple subscribers.
Models
The JMS API supports two models:
point-to-point or queuing model
publish and subscribe model
In the point-to-point or queuing model, a producer posts messages to a particular queue and a consumer reads messages from the queue. Here, the producer knows the destination of the message and posts the message directly to the consumer's queue. It is characterized by following:
Only one consumer will get the message
The producer does not have to be running at the time the consumer consumes the message, nor does the consumer need to be running at the time the message is sent
Every message successfully processed is acknowledged by the consumer
The publish/subscribe model supports publishing messages to a particular message topic. Subscribers may register interest in receiving messages on a particular message topic. In this model, neither the publisher nor the subscriber know about each other. A good metaphor for it is anonymous bulletin board. The following are characteristics of this model:
Multiple consumers can get the message
There is a timing dependency between publishers and subscribers. The publisher has to create a subscription in order for clients to be able to subscribe. The subscriber has to remain continuously active to receive messages, unless it has established a durable subscription. In that case, messages published while the subscriber is not connected will be redistributed whenever it reconnects.
Using Java, JMS provides a way of separating the application from the transport layer of providing data. The same Java classes can be used to communicate with different JMS providers by using the JNDI information for the desired provider. The classes first use a connection factory to connect to the queue or topic, and then use populate and send or publish the messages. On the receiving side, the clients then receive or subscribe to the messages.
Application programming interface
The JMS API is provided in the Java package javax.jms.
ConnectionFactory interface
An administered object that a client uses to create a connection to the JMS provider. JMS clients access the connection factory through portable interfaces so the code does not need to be changed if the underlying implementation changes. Administrators configure the connection factory in the Java Naming and Directory Interface (JNDI) namespace so that JMS clients can look them up. Depending on the type of message, users will use either a queue connection factory or topic connection factory.
Connection interface
Once a connection factory is obtained, a connection to a JMS provider can be created. A connection represents a communication link between the application and the messaging server. Depending on the connection type, connections allow users to create sessions for sending and receiving messages from a queue or topic.
Destination interface
An administered object that encapsulates the identity of a message destination, which is where messages are delivered and consumed. It is either a queue or a topic. The JMS administrator creates these objects, and users discover them using JNDI. Like the connection factory, the administrator can create two types of destinations: queues for Point-to-Point and topics for Publish/Subscribe.
MessageConsumer interface
An object created by a session. It receives messages sent to a destination. The consumer can receive messages synchronously (blocking) or asynchronously (non-blocking) for both queue and topic-type messaging.
MessageProducer interface
An object created by a session that sends messages to a destination. The user can create a sender to a specific destination or create a generic sender that specifies the destination at the time the message is sent.
Message interface
An object that is sent between consumers and producers; that is, from one application to another. A message has three main parts:
A message header (required): Contains operational settings to identify and route messages
A set of message properties (optional): Contains additional properties to support compatibility with other providers or users. It can be used to create custom fields or filters (selectors).
A message body (optional): Allows users to create five types of messages (text message, map message, bytes message, stream message, and object message).
The message interface is extremely flexible and provides numerous ways to customize the contents of a message.
Session interface
Represents a single-threaded context for sending and receiving messages. A session is single-threaded so that messages are serialized, meaning that messages are received one-by-one in the order sent. The benefit of a session is that it supports transactions. If the user selects transaction support, the session context holds a group of messages until the transaction is committed, then delivers the messages. Before committing the transaction, the user can cancel the messages using a rollback operation. A session allows users to create message producers to send messages, and message consumers to receive messages. [2]
Posted by Prem Kumar Jha at 7:26:00 PM 0 comments
Labels: JMS
Friday, February 29, 2008
How to measure quality of software product
Objectives
Provide status on a new Software Product Quality
Measurement standard and its connection to CMMI
Provide ideas on how to get started with Software Product
Quality Measurement today
Outline
Background and Overview
Concepts and Models
Software Product Quality Measurement
Summary
Achieving Quality Software
Requires planning and intentional design
More than achieving the desired functionality
Must explicitly attend to both functional and non-functional
requirements
Need to verify all requirements are being met throughout
the life cycle
CMMI Definition for Quality Requirements
The phrase “quality and process-performance
objectives” covers objectives and requirements for
product quality, service quality, and process
performance. Process performance objectives include
product quality.
Requirements Development
This process area describes three types of requirements:
• customer requirements (quality in use)
• product requirements (external quality attributes)
• product-component requirements (internal quality
attributes)
Taken together, these requirements address the needs of
relevant stakeholders, including those pertinent to various
product life-cycle phases (e.g., acceptance testing criteria)
and product attributes (e.g., safety, reliability,
maintainability).
Requirements also address constraints caused by the
selection of design solutions (e.g., integration of
commercial off-the-shelf products).
Requirements Development Goals
SG 1 Develop Customer Requirements
Stakeholder needs, expectations, constraints,
and interfaces are collected and translated into
customer requirements.
SG 2 Develop Product Requirements
Customer requirements are refined and
elaborated to develop product and productcomponent
requirements.
SG 3 Analyze and Validate Requirements
The requirements are analyzed and validated,
and a definition of required functionality is
developed.
Process Management and Performance
The organization’s process needs and objectives
cover aspects that include the following:
• characteristics of the processes
• process performance objectives, such as time to
market and product quality
• process effectiveness
A quantitatively managed process is institutionalized
by doing the following:
• controlling the process using statistical and other
quantitative techniques such that product quality,
service quality, and process performance attributes
Key Points in Relationship of CMMI
and ISO 9126/25000
CMMI takes a total life cycle view and is inclusive in its
approach to requirements development.
Requirements development explicitly seeks to have
the developer consider quality requirements.
Project and Process Management processes explicitly
consider product quality as process performance
objectives.
Neither the standard nor CMMI endorses a unidimensional
view of quality.
Product Quality Requirements are transformed into
designs and implemented via the Technical Solution
and Product Integration process areas.
The implementation of Product Quality Requirements
are monitored and confirmed via the Project
Management, Verification, and Validation process
areas.
CMMI acknowledges the need for interaction and
perhaps iteration among the related process areas to
satisfactorily identify, specify, and address Product
Quality Requirements.
are measurable and controlled throughout the
project (internal and external quality measures and
criteria)
Relating Requirements, Evaluation,
and Measurement
Reference: http://www.sei.cmu.edu/sema/presentations/esepg.pdf
Posted by Prem Kumar Jha at 4:06:00 PM 0 comments
Labels: Software Quality Product
Observer and Observable
Here's the problem: You're designing a program that will render data describing a three-dimensional scene in two dimensions. The program must be modular and must permit multiple, simultaneous views of the same scene. Each view must be able to display the scene from a different vantage point, under different lighting conditions. More importantly, if any portion of the underlying scene changes, the views must update themselves.
None of these requirements presents an insurmountable programming challenge. If the code that handles each requirement had to be written de novo, however, it would add significant work to the overall effort. Fortunately, support for these tasks is already provided by the Java class library in the form of interface Observer and class Observable. The functionalities of these two were inspired, in part, by the requirements of the Model/View/Controller architecture.
The Model/View/Controller architecture
The Model/View/Controller architecture was introduced as part of the Smalltalk-80 version of the Smalltalk programming language (a popular object-oriented programming language invented by Alan Kay). The Model/View/Controller architecture was designed to reduce the programming effort required to build systems that made use of multiple, synchronized presentations of the same data. Its central characteristics are that the model, the controllers, and the views are treated as separate entities, and that changes made to the model should be reflected automatically in each of the views.
In addition to the program example described in the opening paragraph above, the Model/View/Controller architecture may be used for projects such as the following:
• A graph package that contains simultaneous bar-chart, line-chart, and pie-chart views of the same data
• A CAD system, in which portions of the design can be viewed at different magnifications, in different windows, and at different scales
Figure 1 illustrates the Model/View/Controller architecture in its most general form. There is one model. Multiple controllers manipulate the model; multiple views display the data in the model, and change as the state of the model changes.
Figure 1: The Model/View/Controller architecture
The Model/View/Controller architecture has several benefits:
• There is a clearly defined separation between components of a program -- problems in each domain can be solved independently.
• There is a well defined API -- anything that uses the API properly can replace either the model, the view, or the controller.
• The binding between the model and the view is dynamic -- it occurs at run time, rather than at compile time.
By incorporating the Model/View/Controller architecture into a design, pieces of a program can be designed separately (and designed to do their job well) and then bound together at run time. If a component is later deemed to be unsuitable, it can be replaced without affecting the other pieces. Contrast that scenario with the monolithic approach typical of many quick-and-dirty Java programs. Often a frame contains all of the state, handles all events, does all of the calculations, and displays the result. Thus, in all but the simplest of such systems, making changes after the fact is not trivial
Defining the parts
The model is the object that represents the data in the program. It manages the data and conducts all transformations on that data. The model has no specific knowledge of either its controllers or its views -- it contains no internal references to either. Rather, the system itself takes on the responsibility of maintaining links between the model and its views and notifying the views when the model changes.
The view is the object that manages the visual display of the data represented by the model. It produces the visual representation of the model object and displays the data to the user. It interacts with the model via a reference to the model object itself.
The controller is the object that provides the means for user interaction with the data represented by the model. It provides the means by which changes are made, either to the information in the model or to the appearance of the view. It interacts with the model via a reference to the model object itself.
At this point a concrete example might be helpful. Consider as an example the system described in the introduction.
Figure 2: Three-dimensional visualization system
The central piece of the system is the model of the three-dimensional scene. The model is a mathematical description of the vertices and the faces that make up the scene. The data describing each vertex or face can be modified (perhaps as the result of user input or a scene distortion or morphing algorithm). However, there is no notion of point of view, method of display (wireframe or solid), perspective, or light source. The model is a pure representation of the elements that make up the scene.
The portion of the program that transforms the data in the model into a graphical display is the view. The view embodies the actual display of the scene. It is the graphical representation of the scene from a particular point of view, under particular lighting conditions.
The controller knows what can be done to the model, and implements the user interface that allows that action to be initiated. In this example, a data entry control panel might allow the user to add, modify, or delete vertices and faces.
Observer and Observable
The Java programming language provides support for the Model/View/Controller architecture with two classes:
• Observer -- any object that wishes to be notified when the state of another object changes
• Observable -- any object whose state may be of interest, and in whom another object may register an interest
These two classes can be used to implement much more than just the Model/View/Controller architecture. They are suitable for any system wherein objects need to be automatically notified of changes that occur in other objects.
Typically, the model is a subtype of Observable and the view is a subtype of observer. These two classes handle the automatic notification function of the Model/View/Controller architecture. They provide the mechanism by which the views can be automatically notified of changes in the model. Object references to the model in both the controller and the view allow access to data in the model
Observer and Observable functions
The following are code listings for observer and observable functions:
Observer
public void update(Observable obs, Object obj)
Called when a change has occurred in the state of the observable.
Observable
public void addObserver(Observer obs)
Adds an observer to the internal list of observers.
public void deleteObserver(Observer obs)
Deletes an observer from the internal list of observers.
public void deleteObservers()
Deletes all observers from the internal list of observers.
public int countObservers()
Returns the number of observers in the internal list of observers.
protected void setChanged()
Sets the internal flag that indicates this observable has changed
state.
protected void clearChanged()
Clears the internal flag that indicates this observable has
changed state.
public boolean hasChanged()
Returns the boolean value true if this observable has changed
state.
public void notifyObservers()
Checks the internal flag to see if the observable has changed
state and notifies all observers.
public void notifyObservers(Object obj)
Checks the internal flag to see if the observable has changed
state and notifies all observers. Passes the object specified in the
parameter list to the notify() method of the observer.
How to use interface Observer and class Observable
The following section describes in detail how to create a new observable class and a new observer class, and how to tie the two together.
Extend an observable
A new class of observable objects is created by extending class Observable. Because class Observable already implements all of the methods necessary to provide the observer/observable behavior, the derived class need only provide some mechanism for adjusting and accessing the internal state of the observable object.
In the class ObservableValue listing below, the internal state of the model is captured by the integer n. This value is accessed (and, more importantly, modified) only through public accessors. If the value is changed, the observable object invokes its own setChanged() method to indicate that the state of the model has changed. It then invokes its own notifyObservers() method in order to update all of the registered observers
import java.util.Observable;
public class ObservableValue extends Observable
{
private int n = 0;
public ObservableValue(int n)
{
this.n = n;
}
public void setValue(int n)
{
this.n = n;
setChanged();
notifyObservers();
}
public int getValue()
{
return n;
}
}
Implement an observer
A new class of objects that observe the changes in state of another object is created by implementing the Observer interface. The Observer interface requires that an update() method be provided in the new class. The update() method is called whenever the observable changes state and announces this fact by calling its notifyObservers() method. The observer should then interrogate the observable object to determine its new state, and, in the case of the Model/View/Controller architecture, adjust its view appropriately
In the following class TextObserver listing, the notify() method first checks to ensure that the observable that has announced an update is the observable that this observer is observing. If it is, it then reads the observable's state, and prints the new value.
import java.util.Observer;
import java.util.Observable;
public class TextObserver implements Observer
{
private ObservableValue ov = null;
public TextObserver(ObservableValue ov)
{
this.ov = ov;
}
public void update(Observable obs, Object obj)
{
if (obs == ov)
{
System.out.println(ov.getValue());
}
}
}
Tie the two together
A program notifies an observable object that an observer wishes to be notified about changes in its state by calling the observable object's addObserver() method. The addObserver() method adds the observer to the internal list of observers that should be notified if the state of the observable changes.
The example below, showing class Main, demonstrates how to use the addObserver() method to add an instance of the TextObserver class (see the TextObserver listing above) to the observable list maintained by the ObservableValue class (see the ObservableValue listing above).
public class Main
{
public Main()
{
ObservableValue ov = new ObservableValue(0);
TextObserver to = new TextObserver(ov);
ov.addObserver(to);
}
public static void main(String [] args)
{
Main m = new Main();
}
}
How it all works together
The following sequence of events describes how the interaction between an observable and an observer typically occurs within a program.
1. First the user manipulates a user interface component representing a controller. The controller makes a change to the model via a public accessor method -- which is setValue() in the example above.
2. The public accessor method modifies the private data, adjusts the internal state of the model, and calls its setChanged() method to indicate that its state has changed. It then calls notifyObservers() to notify the observers that it has changed. The call to notifyObservers() could also be performed elsewhere, such as in an update loop running in another thread.
3. The update() methods on each of the observers are called, indicating that a change in state has occurred. The observers access the model's data via the model's public accessor methods and update their respective views.
A demonstration
The example in Figure 3 demonstrates how observables and observers typically work together in the Model/View/Controller architecture.
Figure 3: A better example
Like the model in the class ObservableValue listing shown previously, the model in this example is very simple. Its internal state consists of a single integer value. The state is manipulated exclusively via accessor methods like those in class ObservableValue. The code for the model is
import java.util.Observable;
public class ObservableValue extends Observable
{
private int nValue = 0;
private int nLow = 0;
private int nHigh = 0;
public ObservableValue(int nValue, int nLow, int nHigh)
{
this.nValue = nValue;
this.nLow = nLow;
this.nHigh = nHigh;
}
public void setValue(int nValue)
{
this.nValue = nValue;
setChanged();
notifyObservers();
}
public int getValue()
{
return nValue;
}
public int getLowerBound()
{
return nLow;
}
public int getHigherBound()
{
return nHigh;
}
}
Initially, a simple text view/controller class was written. The class combines the features of both a view (it textually displays the value of the current state of the model) and a controller (it allows the user to enter a new value for the state of the model). The code is
import java.awt.*;
import java.util.Observer;
import java.util.Observable;
public class TextObserver extends Frame implements Observer
{
private ObservableValue ov = null;
private TextField tf = null;
private Label l = null;
private int nLow = 0;
private int nHigh = 0;
public TextObserver(ObservableValue ov)
{
super("Text Observer Tool");
this.ov = ov;
setLayout(new GridLayout(0, 1));
nLow = ov.getLowerBound();
nHigh = ov.getHigherBound();
tf = new TextField(String.valueOf(ov.getValue()));
add(tf);
l = new Label();
add(l);
pack();
show();
}
public boolean action(Event evt, Object obj)
{
if (evt.target == tf)
{
int n = 0;
boolean boolValid = false;
try
{
n = Integer.parseInt(tf.getText());
boolValid = true;
}
catch (NumberFormatException nfe)
{
boolValid = false;
}
if (n < nLow || n > nHigh)
{
boolValid = false;
}
if (boolValid)
{
ov.setValue(n);
l.setText("");
}
else
{
l.setText("invalid value -- please try again...");
}
return true;
}
return false;
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.WINDOW_DESTROY)
{
ov.deleteObserver(this);
dispose();
return true;
}
return super.handleEvent(evt);
}
public void update(Observable obs, Object obj)
{
if (obs == ov)
{
tf.setText(String.valueOf(ov.getValue()));
}
}
}
Instances of this view can be created by pressing the upper button in Figure 3.
By designing the system using the Model/View/Controller architecture (rather than embedding the code for the model, the view, and the text controller in one monolithic class), the system is easily redesigned to handle another view and another controller. In this case, a slider view/controller class was written. The position of the slider represents the value of the current state of the model and can be adjusted by the user to set a new value for the state of the model. The code is
import java.awt.*;
import java.util.Observer;
import java.util.Observable;
public class ScrollObserver extends Frame implements Observer
{
private ObservableValue ov = null;
private Scrollbar sb = null;
public ScrollObserver(ObservableValue ov)
{
super("Scroll Observer Tool");
this.ov = ov;
setLayout(new GridLayout(0, 1));
sb = new Scrollbar(Scrollbar.HORIZONTAL,
ov.getValue(), 10,
ov.getLowerBound(),
ov.getHigherBound());
add(sb);
pack();
show();
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.WINDOW_DESTROY)
{
ov.deleteObserver(this);
dispose();
return true;
}
else if (evt.id == Event.SCROLL_LINE_UP)
{
ov.setValue(sb.getValue());
return true;
}
else if (evt.id == Event.SCROLL_LINE_DOWN)
{
ov.setValue(sb.getValue());
return true;
}
else if (evt.id == Event.SCROLL_PAGE_UP)
{
ov.setValue(sb.getValue());
return true;
}
else if (evt.id == Event.SCROLL_PAGE_DOWN)
{
ov.setValue(sb.getValue());
return true;
}
else if (evt.id == Event.SCROLL_ABSOLUTE)
{
ov.setValue(sb.getValue());
return true;
}
return super.handleEvent(evt);
}
public void update(Observable obs, Object obj)
{
if (obs == ov)
{
sb.setValue(ov.getValue());
}
}
}
Instances of this view object can be created by pressing the bottom button in Figure 3.
Conclusion
Coming up next month is an introductory "how-to" on graphics that should prepare the way for future columns on advanced topics such as animation and custom components. As always, I am interested in hearing from you. Send me mail if you have a suggestion for a future column or a question you would like addressed.
Posted by Prem Kumar Jha at 1:55:00 PM 0 comments
Labels: JAVA
Saturday, February 9, 2008
XML DOM
The DOM (Document Object Model) defines a standard way for accessing and manipulating documents.
The XML DOM
The XML DOM (XML Document Object Model) defines a standard way for accessing and manipulating XML documents.
The DOM views XML documents as a tree-structure. All elements can be accessed through the DOM tree. Their content (text and attributes) can be modified or deleted, and new elements can be created. The elements, their text, and their attributes are all known as nodes.
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents like XML and HTML:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The DOM is separated into 3 different parts / levels:
Core DOM - standard model for any structured document
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The DOM defines the objects and properties of all document elements, and the methods (interface) to access them.
What is the HTML DOM?
The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.
What is the XML DOM?
The XML DOM is:
A standard object model for XML
A standard programming interface for XML
Platform- and language-independent
A W3C standard
The XML DOM defines the objects and properties of all XML elements, and the methods (interface) to access them.
In other words:
The XML DOM is a standard for how to get, change, add, or delete XML elements.
DOM Nodes
According to the DOM, everything in an XML document is a node.
The DOM says:
The entire document is a document node
Every XML element is an element node
The text in the XML elements are text nodes
Every attribute is an attribute node
Comments are comment nodes
Posted by Prem Kumar Jha at 10:34:00 PM 0 comments
Labels: XML
Tuesday, February 5, 2008
Mahabaleshwar Trip
Now, Time to write something about my last trip which we went on 2nd Feb 2008, with veraz team. I didn't found all the team members of this trip in a single photographs, so adding max no of team member in a single photographs.
Let me start the journey from the beginning itself.
Posted by Prem Kumar Jha at 12:33:00 PM 0 comments
Labels: Trip
Thursday, January 31, 2008
Breaking News:Reliance Power Limited IPO Allotment today.
Reliance Power Limited IPO Allotment today.
15 Shares for the application of Rs 96750 or Rs 25875 (maximum) in the retail category.
No shares will be alloted to those who applied less then Rs 96750 or Rs 25875 (maximum) in the retail category.
Reliance Power received 49 lakh applications.
Around 4 lakh applications has been disqualified, due to several reasons.
Refund process will start from 1 feb.
Listing will take place around 5 feb
Posted by Prem Kumar Jha at 2:46:00 PM 0 comments
Labels: Trading
Wednesday, January 30, 2008
When to use HashMap
Assume we do have a application scope HashMap. The key is the userId and the value would be some user information object.
This HashMap is a application level shared variable. Also this is a web application.
Users can access the hashMap delete the entries and add the entries.
But it is guranteed that no two users would address the same location(key) of the hashMap. reason is those two users has two keys and they are not the same.
At the same time if we make this object a HashTable then when one user modifies it other users has to wait (Syncronization handled implicitly). Which might lead to purformance issues.
Do u think it is good to use a HashMap in this scenario?
Posted by Prem Kumar Jha at 10:03:00 PM 0 comments
Labels: JAVA
Tips for Trading Strategy
It's almost difficult to trade these days as there is no indication that how the market will behave in next moment, but there is a good chance to make money, How? Welll, it's something like if you want to gain any thing in this volatile market you need to take risk, or I can say a heavy risk.
Who can trade these days?
Not everybody can trade in this market. This type of market is only suitable for intraday trader or derivative. But, I won't recommend any derivative product for a long time(more then 3 days), so I can say market is for intraday trader only, until unless market get some stability.
Now what strategy intraday trader has to follow:
Well, again there is no hard and fast rule which I can fix for interaday trader.But, you can plan strategy :
1. If you are buying any share I assume you look something on that share now wen to sell:
A) Place order for sell around 1% profit from the buying position (.1% will go as a brokerage and 0.9% will be your profit). Now, suppose target didn't reached withnin an hour and if it is now below your buying level then wait for some time till it will again come up and now modify the order at less price (0.6%) for 50% shares. If it executed and gone more then 1% follow stop loss by taking 0.2%.
Stay tuned for new Tips.............. :)
Posted by Prem Kumar Jha at 3:33:00 PM 2 comments
Labels: Trading
Tuesday, January 29, 2008
रीड आईटी fully
WHEN THE BOY WAS RETURNING AFTER HIS MARRIAGE…HE FOUND HIS WIFE HOLDING
A SMALL PACKET;;;;;;;
THE BOY ASKED……..WHATS THERE IN THAT PACKET..
WIFE REPLIED…..DARLING THIS IS THE SECRET OF MY LIFE...PLS NEVER OPEN IT
OR ASK ME ABOUT IT FURTHER….OTHERWISE OUR MARRIAGE WILL BE IN
TROUBLE……………………………………………………………………..
THE COUPLE SPENT THEIR DAYS HAPPILY……BUT THE BOY WAS VERY KEEN TO KNOW
WHAT WAS THERE IN THAT SMALL PACKET……
AFTER SOME DAYS THE BOY AGAIN TOLD……DARLING AFTER MARRYING YOU , I GOT THE
WOMAN OF MY DREAM…BUT TELL ME WHAT THAT PACKET IS…….IT WLL NEVER AFFECT OUR
RELATIONSHIP…..AS I LOVE U MORE THAN MY LIFE………………..BUT WIFE ONLY TOLD THAT
I ALSO LOVE U MORE THAN MY LIFE….THATS WHY TELLING U NOT TO ASK ABOUT
THAT……….
AFTER SOME DAYS WIFE WENT TO HER OWN HOUSE AND FORGOT TO TAKE HER
PACKET………THEN THE BOY COULDN'T CONTROL HIMSELF….AND OPENED THAT
PACKET……………………………!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
HE WAS SHOCKED TO OPEN THAT……..THERE WAS 30 RUPEES……AND 2 WHEAT GRAINS….IN
THAT PACKET……THE BOY COULDN'T UNDERSTAND WHAT IT WAS…AND HOW IT COULD
AFFECT THEIR MARRIAGE LIFE………
THEN WHEN HIS WIFE RETURNED …..HE BURST INTO LAUGHTER…..AND TOLD …DARLING
WHAT IS THIS……AND HOW IT COULD HAVE AFFECTED OUR RELATIONSHIP……..WHATEVER
MAY BE……U HAVE TO TELL ME ABOUT THE SECRET…….
THE THE WIFE REPLIED………………………………………………
THAT'S NOT GOOD……………….ANY WAY…….IF U HAVE ALREADY FINALISED TO KNOW THE
SECRET …..HERE IT……………………………..
BEFORE MARRIAGE ..EACH TIME I HAD SEX WITH ANY GUY…I PUT A WHEAT GRAIN IN
THAT PACKET TO REALISE THAT I HAVE DONE A MISTAKE…….…………………………………
THE BOY SAW THOSE TWO WHEAT GRAINS….AND AFTER WAITING FOR TWO MINUTES
TOLD…..……….. ITS OK……EVERYBODY MAKES MISTAKE …….
I STILL LOVE U BECAUSE U TOLD ME THE TRUTH…….. BUT WHAT IS THAT 30
RUPEES……………………………… THE WIFE REPLIED…..THE BOY FAINTED……………………
-
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
THE WIFE SAID……I HAVE SOLD 6 KG WHEAT AT A RATE RS 5 PER
KG……………..!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Posted by Prem Kumar Jha at 1:31:00 PM 0 comments
Labels: Masala
The Return of Rajnikanth
Rajanikanth makes onions cry.
Rajanikanth can delete the Recycling Bin..
Bill Gates lives in constant fear that Rajanikanth' PC will crash..
Ghosts are actually caused by Rajanikanth killing people faster than Death can process them.
Rajanikanth can build a snowman..... out of rain.
Rajanikanth can strangle you with a cordless phone.
Rajanikanth can drown a fish.
Rajanikanth can play the violin....... ...with a piano.
When Rajanikanth enters a room, he doesn't turn the lights on,......... .... he turns the dark off.
Rajanikanth once had a heart attack...... ......... his heart lost.
When Rajanikanth looks in a mirror the mirror shatters, because not even glass is stupid enough to get in between Rajanikanth and Rajanikanth.
Brett Favre can throw a football over 50 yards. Rajanikanth can throw Brett Favre even further.
The last digit of pi is Rajanikanth. He is the end of all things.
Rajanikanth does not know where you live, but he knows where you will die.
Bullets dodge Rajanikanth.
A Handicap parking sign does not signify that this spot is for handicapped people. It is actually in fact a warning, that the spot belongs to Rajanikanth and that you will be handicapped if you park there.
Rajanikanth' calendar goes straight from March 31st to April 2nd, no one fools Rajanikanth.
If you spell Rajanikanth wrong on Google it doesn't say, 'Did you mean Rajanikanth?' It simply replies, 'Run while you still have the chance.'
Rajanikanth can do a wheelie on a unicycle.
Once a cobra bit Rajanikanth' leg. After five days of excruciating pain, the cobra died.
When Rajanikanth gives you the finger, he's telling you how many seconds you have left to live.
Rajanikanth can kill two stones with one bird.
Rajanikanth was once on Celebrity Wheel of Fortune and was the first to spin. The next 29 minutes of the show consisted of everyone standing around awkwardly, waiting for the wheel to stop.
Leading hand sanitizers claim they can kill 99.9 percent of germs. Rajanikanth can kill 100 percent of whatever he wants.
There is no such thing as global warming. Rajanikanth was cold, so he turned the sun up.
Rajanikanth can set ants on fire with a magnifying glass. At night.
Rajanikanth has a deep and abiding respect for human life… unless it gets in his way.
It takes Rajanikanth 20 minutes to watch 60 Minutes.
Rajanikanth once shot down a German fighter plane with his finger, by yelling, 'Bang!'
In an average living room there are 1,242 objects Rajanikanth could use to kill you, including the room itself.
Behind every successful man, there is a woman. Behind every dead man, there is Rajanikanth.
Rajanikanth destroyed the periodic table, because Rajanikanth only recognizes the element of surprise.
Rajanikanth got his drivers license at the age of 16 Seconds.
With the rising cost of gasoline, Rajanikanth is beginning to worry about his drinking habit.
The square root of Rajanikanth is pain. Do not try to square Rajanikanth, the result is death.
When you say 'no one's perfect', Rajanikanth takes this as a personal insult.
Posted by Prem Kumar Jha at 1:24:00 PM 0 comments
Labels: Masala
History
One day a group of boys
Decided to have a race
They chose to climb a great big tree
And set off at a pace
The rest of their friends gathered
To see the boys at play
They talked about it to themselves
"Will they make it?" "No way!"
They called up to the children
"You'll never make it up that tree"
But the boys just kept on climbing
And said "just watch and you will see"
But the others, how they shouted
And thought the boys tried to ignore
They began to drop out one by one
Another, another and then more
But one boy kept on climbing
And made it to the top of the tree
He never lost faith but believed in himself
And said "this won't defeat me"
The others were quite amazed
At the squirrel at the top of the tree
"How on earth did he do it?" they said
"Well", said one, "he's completely deaf, you see"
So the motto of this poem is
You can reach the top of the tree
Just don't listen to what others say
Just believe in yourself and you'll see......... .
Posted by Prem Kumar Jha at 1:21:00 PM 0 comments
Labels: Masala