Sunday, December 28, 2008

Basic Unix Commands

What is Shell..?

The shell is perhaps the most important program on the Unix system, from the end-user's standpoint.
The shell is your interface with the Unix system, the middleman between you and the kernel.

CONCEPT: The shell is a type of program called an interpreter. An interpreter operates in a simple loop: It accepts a command, interprets the command, executes the command, and then waits for another command. The shell displays a "prompt," to notify you that it is ready to accept your
command.

The shell is a program that the Unix kernel runs for you. A program is referred to as a process while the kernel is running it. The kernel can run the same shell program (or any other program) simultaneously for many users on a Unix system, and each running copy of the program is a separate process.

The basic form of a Unix command is: commandname [-options] [arguments]

ls -l /tmp

-l = Long list of options


ls -lR /lib/l*

-R causes ls to operate recursively, moving down directory trees

ls -m /etc/i*g

-m causes output to be streamed into a single line.

-l Shows you huge amounts of information (permissions, owners, size, and when last modified.)

-r Reverses the order of how the files are displayed.

-t Shows you the files in modification time.

Special Characters in Unix: `,~,!,$,%,^, & *, |, \,/, {,},[,],",',;

your file names cannot start with any of the spl characters above.


Getting Help in Unix:

man

whatis gives you a brief description of the command (wont specify the options)

File Permissions:

ls -l /etc/passwd
-rw-r--r-- 1 root sys 41002 Apr 17 12:05 /etc/passwd

first - (is a - if its a normal file, d, if its a directory and s if its a special file ex: device file)

next 3: rw- : permissons of the owner

next 3: r-- : Permissions of the group

next 3: r-- : permissions of others


To set file permissions, you may use to the "rwx" notation to specify the type of permissions, and the
"ugo" notation to specify those the permissions apply to.

To define the kind of change you want to make to the permissions, use the plus sign (+) to add a permission, the minus sign (-) to remove a permission, and the equal sign (=) to set a permission directly.

chmod g=rw- ~/.shrc (here you specify / set all permissions)
to change the file permissions on the file .shrc, in your home directory. Specifically, you are
specifying group read access and write access, with no execute access.

u : owner
g : group
o : others
a : all

chmod a-x socktest.pl (revoke execute permissions for all on a file)
$ ls -l socktest.pl
-rw-r--r-- 1 nick users 1874 Jan 19 10:23 socktest.pl

chmod 755
You might have encountered things like chmod 755 somefile and of course you will be wondering what this is. The thing is, that you can change the entire permission pattern of a file in one go using one number like the one in this example. Every mode has a corresponding code number, and as we shall see there is a very simple way to figure out what number corresponds to any mode.

Triplet for u: rwx => 4 + 2 + 1 = 7
Triplet for g: r-x => 4 + 0 + 1 = 5
Tripler for o: r-x => 4 + 0 + 1 = 5
Which makes : 755

So, 755 is a terse way to say 'I don't mind if other people read or run this file, but only I should be able to modify it' and 777 means 'everyone has full access to this file'

pwd : Print Working Directory

file is a standard Unix program for determining the type of data contained in a computer file.

The Unix file command allows you to determine whether an unknown file is in text format, suitable for direct viewing

file /bin/sh


The cat command
The cat command concatenates files and sends them to the screen. You can specify one or more files as arguments. Cat makes no attempt to format the text in any way, and long output may scroll off the screen before you can read it.

Output scrolls off of the screen

The tilde character (~) is Unix shorthand for your home directory


The more command
The more command displays a text file, one screenful at a time. You can scroll forward a line at a time by pressing the return key, or a screenful at a time by pressing the spacebar. You can quit at any time by pressing the q key.

head -15 /etc/rc
to see the first fifteen lines of the /etc/rc file.


tail /etc/rc
to see the last ten lines of the file /etc/rc. Because we did not specify the number of lines as an
option, the tail command defaulted to ten lines.

cp ~/.profile ~/pcopy
makes a copy of your .profile file, and stores it in a file called "pcopy" in your home directory.

mv ~/pcopy ~/qcopy
takes the pcopy file you created in the cp exercise, and renames it "qcopy".

The rm command is used for removing files and directories. The syntax of the rm command is rm
filename. You may include many filenames on the command line.

rm ~/.shrccopy

The Unix mkdir command is used to make directories. The basic syntax is mkdir directory-name.
If you do not specify the place where you want the directory created (by giving a path as part of the
directory name), the shell assumes that you want the new directory placed within the current working
directory.

mkdir ~/foo

The Unix rmdir command removes a directory from the filesystem tree. The rmdir command does not work unless the directory to be removed is completely empty.


The rm command, used with the -r option can also be used to remove directories. The rm -r command will first remove the contents of the directory, and then remove the directory itself.

Redirecting Input and Output


< = Input redirection
> Output redirection to file
>> output redirection to file (append)
2> error redirection


ex: more < /etc/passwd

Use standard input redirection to send the contents of the file /etc/passwd to the morecommand

Using the "less-than" sign with a file name like this:
< file1 in a shell command instructs the shell to read input from a file called "file1" instead of from the keyboard.

To see the first ten lines of the /etc/passwd file, the command:
head /etc/passwd
will work just the same as the command:
head < /etc/passwd


ls /tmp > ~/ls.out

ls /etc >> myls


sort < /etc/passwd > foo 2> err


Pipe:


CONCEPT: Unix allows you to connect processes, by letting the standard output of one process feed into the standard input of another process. That mechanism is called a pipe. Connecting simple processes in a pipeline allows you to perform complex tasks without writing complex programs.

ls -l /etc | more

How could you use head and tail in a pipeline to display lines 25 through 75 of a file?
ANSWER: The command
cat file | head -75 | tail -50


The grep utility recognizes a variety of patterns, and the pattern specification syntax was taken from
the vi editor. Here are some of the characters you can use to build grep expressions:
> The caret (^) matches the beginning of a line.
> The dollar sign ($) matches the end of a line.
> The period (.) matches any single character.
> The asterisk (*) matches zero or more occurrences of the previous character.
> The expression [a-b] matches any characters that are lexically between a and b.


grep 'jon' /etc/passwd
grep '^jon' /etc/passwd

ls -l /tmp | grep 'root'

PS:
Unix provides a utility called ps (process status) for viewing the status of all the unfinished jobs that
have been submitted to the kernel. The ps command has a number of options to control which
processes are displayed, and how the output is formatted.


ps -ef
to see a complete listing of all the processes currently scheduled. The -e option causes ps to include
all processes (including ones that do not belong to you), and the -f option causes ps to give a long
listing. The long listing includes the process owner, the process ID, the ID of the parent process,
processor utilization, the time of submission, the process's terminal, the total time for the process,
and the command that started the process.


To kill a process, you must first find its process ID number using the ps command. Some processes
refuse to die easily, and you can use the "-9" option to force termination of the job.
EXAMPLE: To force termination of a job whose process ID is 111, enter the command
kill -9 111

Executing a job in background


sort < foo > bar &


The commands related to job control will apply to
the current job, unless directed to do otherwise. You may refer to jobs by job ID by using the percent
sign. Thus, job 1 is referred to as %1, job 2 is %2, and so forth.

To place a foreground job to background, use bg command

Monday, October 13, 2008

Reflection in Java

Creating a object using reflection in Java:

Class parserClass=Class.forName(parser);
Object newParser=parserClass.newInstance();
Class classParams[]=new Class[1]; //To set type of parameter
Object arglist[]=new Object[1]; //To set the actual value

classParams[0] = String.class;
arglist[0] = tradeType;
String methodName="setLoadType";

Method meth = parserClass.getMethod(methodName, classParams);

meth.invoke(newParser, arglist); //Set setTradeType=tradeType

return (DefaultFileParser)newParser;


StringArrayConvertor in Java

public Object convert(Class type,
Object value)
Deprecated.
Convert the specified input object into an output object of the specified type.
If the value is already of type String[] then it is simply returned unaltered.
If the value is of type int[], then a String[] is returned where each element in the string array is the result of calling Integer.toString on the corresponding element of the int array. This was added as a result of bugzilla request #18297 though there is not complete agreement that this feature should have been added.
In all other cases, this method calls toString on the input object, then assumes the result is a comma-separated list of values. The values are split apart into the individual items and returned as the elements of an array. See class AbstractArrayConverter for the exact input formats supported.
Converting Strng Array to String in Java
public static String arrayToString(String[] a, String separator) {
StringBuffer result = new StringBuffer();
if (a.length lt 0) {
result.append(a[0]);
for (int i=1; i lt a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}

Saturday, September 27, 2008

What is a Bank and How it works

Source : HowStuffWorks

The funny thing about how a bank works is that it functions because of our trust. We give a bank our money to keep it safe for us, and then the bank turns around and gives it to someone else in order to make money for itself. Banks can legally extend considerably more credit than they have cash. Still, most of us have total trust in the bank's ability to protect our money and give it to us when we ask for it.

Banks are critical to our economy. The primary function of banks is to put their account holders' money to use by lending it out to others who can then use it to buy homes, businesses, send kids to college...

When you deposit your money in the bank, your money goes into a big pool of money along with everyone else's, and your account is credited with the amount of your deposit. When you write checks or make withdrawals, that amount is deducted from your account balance. Interest you earn on your balance is also added to your account.

Banks create money in the economy by making loans. The amount of money that banks can lend is directly affected by the reserve requirement set by the Federal Reserve. The reserve requirement is currently 3 percent to 10 percent of a bank's total deposits

When a bank gets a deposit of $100, assuming a reserve requirement of 10 percent, the bank can then lend out $90. That $90 goes back into the economy, purchasing goods or services, and usually ends up deposited in another bank. That bank can then lend out $81 of that $90 deposit, and that $81 goes into the economy to purchase goods or services and ultimately is deposited into another bank that proceeds to lend out a percentage of it.

In this way, money grows and flows throughout the community in a much greater amount than physically exists. That $100 makes a much larger ripple in the economy than you may realize!

What are Mortgage Backed Securities:

Mortgage-backed securities resemble bonds, instruments issued by governments and corporations that promise to pay a fixed amount of interest for a defined period of time. Mortgage-backed securities are created when a company such as Bear Stearns buys a bunch of mortgages from a primary lender—that is, from the company you actually got your mortgage from—and then uses your monthly payments, and those of thousands of others, as the revenue stream to pay investors who have bought chunks of the offering. They allow lenders to sell the mortgages they make, thus replenishing their coffers and allowing them to lend again. For their part, buyers of mortgage-backed securities take security in the knowledge that the value of the bond doesn't just rest on the creditworthiness of one borrower, but on the collective creditworthiness of a group of borrowers.

Saturday, September 20, 2008

Java Mail API examples

Mail w/o attachments
public class SendJavaMail
{
public static void main(String[] args)
{
try
{
// Create a properties file containing the host address of
// your SMTP server
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "smtp.myispserver.net");
// Create a session with the Java Mail API
Session mailSession =
Session.getDefaultInstance(mailProps);
// Create a transport object for sending mail
Transport transport = mailSession.getTransport("smtp");
// Create a new mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the From and the Recipient
message.setFrom(new InternetAddress(
"senorcoffeebean@wutka.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("mark@wutka.com"));
// Set the subject
message.setSubject("Hello from Java Mail!");
// Set the message text
message.setText("Hello!\n"+
"It is I, Senor Coffee Bean! I bring you greetings \n"+
"from the Java Mail API!. \n"+
" Senor Coffee Bean, Esp.\n");
// Save all the changes you have made to the message
message.saveChanges();
// Send the message
transport.send(message);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}
public class SendJavaMail
{
public static void main(String[] args)
{
try
{
// Create a properties file containing the host address of
// your SMTP server
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "smtp.myispserver.net");
// Create a session with the Java Mail API
Session mailSession =
Session.getDefaultInstance(mailProps);
// Create a transport object for sending mail
Transport transport = mailSession.getTransport("smtp");
// Create a new mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the From and the Recipient
message.setFrom(new InternetAddress(
"senorcoffeebean@wutka.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("mark@wutka.com"));
// Set the subject
message.setSubject("Hello from Java Mail!");
// Set the message text
message.setText("Hello!\n"+
"It is I, Senor Coffee Bean! I bring you greetings \n"+
"from the Java Mail API!. \n"+
" Senor Coffee Bean, Esp.\n");
// Save all the changes you have made to the message
message.saveChanges();
// Send the message
transport.send(message);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}


Mail w/ attachments and text:
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/** Uses the Java Mail API to send a message via SMTP. */
public class SendAttachment
{
public static void main(String[] args)
{
try
{
// Create a properties file containing the host address of
// your SMTP server
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", "smtp.myispserver.net");
// Create a session with the Java Mail API
Session mailSession =
Session.getDefaultInstance(mailProps);
// Create a transport object for sending mail
Transport transport = mailSession.getTransport("smtp");
// Create a new mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the From and the Recipient
message.setFrom(new InternetAddress(
"senorcoffeebean@wutka.com"));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress("mark@wutka.com"));
// Set the subject
message.setSubject("Hello from Java Mail!");
// Create the multipart object for doing attachments
MimeMultipart multi = new MimeMultipart();
// Create the message part for the main message text
BodyPart textBodyPart = new MimeBodyPart();
// Set the message text
textBodyPart.setText("Hello!\n"+
"It is I, Senor Coffee Bean! I bring you an attachment \n"+
"from the Java Mail API!. \n"+
" Senor Coffee Bean, Esp.\n");
// Add the body part to the multipart object
multi.addBodyPart(textBodyPart);
// Create an input stream to read the attachment data
FileInputStream in = new FileInputStream("SendAttachment.java");


// Create the body part for the attachment
BodyPart fileBodyPart = new MimeBodyPart(in);
// Give the attachment a filename (the name that appears when someone
// reads the message--it doesn't have to be the same as the file
// you're reading).
fileBodyPart.setFileName("SendAttachment.java");
// Add the attachment to the multipart object
multi.addBodyPart(fileBodyPart);
// The multipart object is the content for the email message
message.setContent(multi);
// Save all the changes you have made to the message
message.saveChanges();
// Send the message
transport.send(message);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}

Tuesday, September 9, 2008

Thoughtfully static

Static = One instance / jvm. So make sure you initialize your static variables in the factory in a particular order.
When you create a factory class, and make the objects as static and final, it is absolutely necessary that you initialize dependencies prior to the actual class.
Ex: my tfpService depends on the tfpDao so make sure you initialize the tfp dao fist and then the actual service. Else you get null ptr when you refernce tfpDao in tfpService.
private static final TFPDao tfpDao=new TFPDaoImpl();
private static final TFPParser tfpParser=new TFPParserImpl();
private static final TFPService tfpService=new TFPServiceImpl();

Monday, August 11, 2008

Wasted Words Throw Away Power

“You don’t have to interfere in something that may not be any of your business. Just send a good thought and say, ‘Hello’ or ‘Can I help you?’” Reason: These words of encouragement or help ‘vibrate with positive force.’ Unkind words can devastate people or cause them to be disheartened or offended, cautions Browne


“Wasted words are a misuse of vital force. This throws away power. Energy is a sacred commodity and should be preserved. When we squander our energy we don’t have enough when we need it… The only way to preserve our energy is to watch our words.”


So many of our personal relationships are destroyed because of the way we speak to each other, rues the author. “Prepare your speech,” she advises. “We often speak with no preparation that results in thoughtless words.”


Rude, abrupt, mean, harsh, nasty, or crude remarks have harmful effects, explains Browne. “When combined with the speaker’s tone of voice, they create discordant vibrations. These thoughtless words live long after they are spoken and affect everyone within hearing distance.” She mentions as examples what we ubiquitously find: such as bosses who are rude or abrupt to employees in the morning and thus set the tone of the office for the whole day; and how ‘an upbeat, happy greeting can get the staff in a positive frame of mind resulting in a productive workday.’ More powerful than spoken words are the written ones. “If you say something and regret it, you can withdraw it with an apology. It is easy to forget exactly what someone said.” Not so with the written word. It is ‘indelibly imprinted.

Writing our thoughts down is a way to structure our thinking, the author guides.

“When we write a letter, we usually take more time to compose our thoughts than we do when we make a phone call. That is why people feel letters are special.”


On the positive side, she highlights how the written word can be creative and inspiring. “It can teach, guide, instruct, entertain, and shift our consciousness. It has a huge effect on getting the things that we want.” However, good writing takes focus, patience, and persistence, counsels Browne.


In sum, her message is simple and straight: “Be careful what you think. Be equally careful what you say. Be even more careful what you write.”

Recommended for a careful read.

Killer Instinct

Another Fabulous article by Madhav Mohan (http://MadhavMohan.com) on the Killer instinct.

On the sun-drenched veldt in Africa, a deadly drama of life and death is enacted daily. The lioness is on the hunt! She’s spotted her prey and is going for the kill! Ears flattened, body downwind, every muscle taut, all senses focused on the hapless wildebeest. Nothing registers in her consciousness except the prey. And then, a blur of frenzied movement followed by death cries: the wildebeest is meat for the pride.

Snapping up orders


On a lazy Saturday afternoon, the door chime signalling a visitor snapped Shabnam out of her reverie. As the store manager of a large retail furniture and furnishing outlet she is responsible for the store’s performance. She leads a team of 20 people and knows that every walk-in could be a huge sale. She homes in on the visitor and locks on! After 30 minutes, a sale worth Rs 4 lakh materialises. Shabnam has treated her prospect to coffee, established a strong rapport, answered every question and provided just the right solution.

In market after market, the drama is similar! The salesman spots the prospect and closes in for the sale. Total focus and single-pointed attention to clinch it! All faculties are tuned to the customer and his objections; every question is an opportunity to move a step closer to the consummation. And finally, the order is at hand!

Watching Shabnam in action, I’m struck by her resemblance to the lioness on the veldt! The same concentration and dedication and the same total commitment to the job at hand. Both have something in common: the killer instinct. A complete and irrevocable commitment to finish the job on hand, to close the circuit and achieve the result, under all conditions! No prey or prospect can ever slip away!


A must for every CEO



Every CEO must, of course, possess that killer instinct. More importantly, as a leader and organisation builder, he must look for people with this instinct in every functional area. That’s when the organisation is guaranteed to grow and prosper. Far too often, competence is blunted by the absence of the killer instinct and so opportunities simply evaporate. It’s somewhat like the hockey centre forward who dribbles past three defenders and the goal keeper only to shoot the ball wide off the mark! Many companies snatch defeat from the jaws of victory by entrusting important projects to people without the killer instinct.


Spot the trait


It’s difficult to spot the killer instinct, though. One key indicator is consistency. If a person has a record of consistent achievement in any field (academics, sport, previous assignments) it is quite likely that the achievement has been fuelled by the killer instinct. A second indicator is initiative: can the person think through and act quickly? And finally, if stamina and perseverance are present, the killer instinct could also lurk in the background.

The recruitment process must probe deeply into the background and psyche of the candidate. Career development and training programmes must build the capability to deliver results at all times. In today’s hyper competitive environment, there’s a premium on the killer instinct. Organisations that don’t institutionalise it are in danger of being devoured by those that do!

Friday, July 18, 2008

EJB Deployment Issue

I ran into this weird ejb deployment issue lately. It was a working EJB, then I had to add new remote methods to it. So I added them to the remote interface and to the actual java implementation class. Then when I deployed it locally, it some how doesnt seem to recognize my new methods, and when I access it, it simply throws NoSuchMethodFound error. After struggling for 1.5 days , (as though I dont have enough troubles..) figured out that I have an old client jar with the same .class file,(class I am trying to modify) and the server is picking up the classes from the lib folder evern before deploying my .class files in ejb-jar.

So server always tries to read files in the following order:
1) .class files from the lib folder
2) then any of classes in ur war files webroot/web-inf/classes folder

Also in EJB2.0, you dont need to create stubs and skeletons when you make changes and deploy your ear file,

Also when you provide a service jar to any of your remote service callers, all you porvide in the jar is

1) .class files with Home and Remote interfaces.
2) And no no stubs required. :)

You can generate this jar, by selecting the java classes in your eclipse rt click--> export as jar. I would recommned automate it in ur build file so you dont have to do it everytime. :)

-Coding Rocks.. !!!

Monday, July 14, 2008

SQL where Group by order by having

Writing Complex SQL and ordering.. squence in which the key words must be arranged to prevent SQL Command not properly ended error.


SELECT <> FROM
WHERE
GROUP BY
HAVING
ORDER BY


EXAMPLE:

SELECT P_OID,BASE_CR_FAC_ID,COUNT(*) FROM
V_A_FAC_P_ITEM
WHERE PROPOSAL_ITEM_APPR_STATUS_CODE = 'discarded'
GROUP BY BASE_C_FAC_ID,P_OID
HAVING COUNT(*) >1
ORDER BY P_OID desc


Further Reading: http://www.java2s.com/Code/SQL/Select-Clause/UsingmathfunctioninHAVING.htm
- SQL ROCKS..!!!

Wednesday, June 25, 2008

Spring JDBC - SQL with params

ex: String sql="select distinct PRIMARY_OWNER from "+xyzSchema+"v_rptg rptg"+
" where rptg.fac_id=:facId and " +
" (:cDate >= cit_eff_asof_dt and :cDate < cit_eff_until_dt) "
+ " and (:cDate >= en_eff_asof_dt and :cDate < en_eff_until_dt) ";

So now you'll hve to bind the highlighted variables in the query.

Object[] params = { facId,cDate, cDate, cDate, cDate};

To your query, pass in sql and the parameters bound (ex: for i/p parameter like :cDate in your query, params should contain a cDate in the same order as it expects in the query)

long clietnOid=queryForLong(sql,params);

Monday, June 23, 2008

Tokens in Struts

Purpose: To prevent a page from being re-submitted when user hits refresh or hits submit multiple times or user clicks on back / forward on your browser and hits submit again

Solution: Tokens in Struts 2.0

Token Methods:

The methods we care about are:

saveToken(HttpServletRequest req)
isTokenValid(HttpServletRequest req)
resetToken(HttpServletRequest req)

Once of the basic concept for implementing tokens:

1) Always provide a setupForInsertOrUpdate dispatch method or indvidual Action. You could also break it up into setupForInsert and setupForUpdate if you so desire. Regardless, make sure you always go through this Action method before you go to your form.
2) In your setup method make sure to call "saveToken(request)." This puts a unique key into Session scope and will cause this token to be placed on your resulting JSP.
In your Action's update/insert dispatch method or your Action's execute method, make sure to first check if "isTokenValid(request)." This compares the token in Session with the one submitted through the Request. If they match, the token is valid and it's ok to procede with the update/insert. If they do not match, the user is likely simply resubmitting a stale page so we return from our action immediately. We need to remember before we leave our update/insert method that we call "resetToken(request)" so that we place a new token into Session scope, otherwise the old token will remain and it will match the one on the form and will allow duplicate submisssions.


Example:

public ActionForward setUpForInsertOrUpdate(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.debug("setUpForInsertOrUpdate");
saveToken(request);
EmployeeForm employeeForm = (EmployeeForm)form;
if (isUpdate(request, employeeForm)) {
Integer id = Integer.valueOf(employeeForm.getEmployeeId());
Employee employee = empService.getEmployee(id);
BeanUtils.copyProperties(employeeForm, employee);
}
prep(request);
return mapping.findForward(Constants.SUCCESS);
}



public ActionForward insertOrUpdate(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.debug("insertOrUpdate");
EmployeeForm employeeForm = (EmployeeForm)form;
if ( !isTokenValid(request) ) {
return mapping.findForward(Constants.INVALID_TOKEN);
}
if (validationSuccessful(request, employeeForm)) {
Employee employee = new Employee();
BeanUtils.copyProperties(employee, employeeForm);
if (isUpdate(request, employeeForm)) {
logger.debug("update");
empService.updateEmployee(employee);
} else {
logger.debug("insert" );
empService.insertEmployee(employee);
}
populateEmployees(request);
resetToken(request);
return mapping.findForward(Constants.SUCCESS);
} else {
prep(request);
return mapping.findForward(Constants.FAILURE);
}
}


-Smile ...tokens are making your life easy :D

Friday, June 20, 2008

Running db scripts from command prompt

During development, we usually put all the sql scripts on a separate .sql file and run them at once, when you move your code on to other servers for testing purposes.

Here is how you run the scripts from the command prompt.


1) Open a command prompt at the folder where you have your sql scripts
2) execute sqlplus userid/pwd@srgtdev
3) above command will connect you to the oracle and give u a sql>
4) run the following
5) start filename.sql


woo huu all sqls in the batch file will be run successfully and you are good to go. here is an sample batch sql file

set echo on
spool 7_tpa_srgdbo_datascripts.sql.log

--set escape on

delete xyz where template_id in (-7);
INSERT INTO XYZ (TEMPLATE_ID, TEMPLATE_NAME, UPDATE_DATE, STATUS, TYPE, ASSESSMENT_TYPE_ID) VALUES (-7, 'FBI - Test7', SYSDATE, 'InActive', 'FBI', 1);

delete from XYZ_template where template_id = 999;

INSERT INTO XYZ_TEMPLATE (TEMPLATE_ID, TEMPLATE_NAME, UPDATE_DATE, STATUS, TYPE, ASSESSMENT_TYPE_ID, HANDLER_CLASS, HANDLER_JSP, HANDLER_PDF, HANDLER_TEMPLATE_TYPE) VALUES (999, 'Notch Template', SYSDATE, 'InActive', 'NOTCH', 1, 'com.xyz.say.service.Sample', '', '', '');

/* delete temporary data */
delete xyz_template where template_id in (-7);

----------- notching data script starts

delete from xyz_notching_template_qestn where template_id = 20001;

delete from xyz_assessment_type_value where assessment_value_id > 20000 and assessment_value_id < 20034;

delete from xyz_template where template_id = 20001;

delete from xyz_ASSESSMENT_TYPE where ASSESSMENT_TYPE_ID > 20000 and ASSESSMENT_TYPE_ID < 20016;



COMMIT;



spool off
set echo off


-Happy Coding Sonu

Thursday, June 19, 2008

Reading from Properties file into Spring Application Context.xml

Problem: How to read a value from your properties file into your spring's applicationContext.xml..?

Here is how you do it. spring's angle brackets are replaced with []

[bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"]
[property name="location" value="classpath:application.properties"/]
[/bean]

[!-- A sample bean that needs some settings. --]
[bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"]
[property name="driverClassName" value="${jdbc.driver}"/]
[property name="url" value="${jdbc.url}"/]
[property name="username" value="${jdbc.username}"/]
[property name="password" value="${jdbc.password}"/]
[/bean]


Ex: If your properties file is :

jdbc.driver=org.h2.Driver
jdbc.url=jdbc:h2:mem:example
jdbc.username=sa
jdbc.password=asdfa

you can these values directly into ur application ctxt.

More info read:

Wednesday, June 18, 2008

SimpleDateFormat Example in Java

public class DateFormattingTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String myDate="Fri Dec 07 17:58:41 EST 2007";
SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");
try{

Date d1=sdf.parse(myDate);

String s1=sdf2.format(d1);

System.out.println("Date d1 is :"+d1);
System.out.println("Formatted String is :"+s1);

}catch(Exception e){
System.out.println("Date Parsing Exception");

}

}

}


Usage: When you have a String, and if you want to convert it into a java.util.Date,
SimpleDateFormat's instance should indicate the format of your input string for java to parse and convert it into a Date:

Ex: String myDate="Fri Dec 07 17:58:41 EST 2007";

SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");sdf should tell java the format of your input string for it to be able to parse it to a date like:

//Input is a String
//sdf indicates the format of date in i/p String
//Output is a Date


Date d1=sdf.parse(myDate);

Scenario 2: When you have a Date and if you want to convert it into a String,

your SimpleDateFormat object should indicate the format you wish to convert your string into and use format in this case.

ex: SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");

//Input is Date
//sdf indicates the format of the String you wish to see it as output
//Output is formatted String


String s1=sdf2.format(d1);

Sunday, June 15, 2008

TCP / IP

Transmission Control Protocol / Internet Protocol

TCP/IP is a connectionless protocol. Information is transfered in packets. Each of these packets is sent through the network individually. There are provisions to open connections to systems. However at some level, information is put into packets, and those packets are treated by the network as completely separate. For example, suppose you want to transfer a 15000 octet file. Most networks can't handle a 15000 octet packet. So the protocols will break this up into something like 30 500-octet packets. Each of these packets will be sent to the other end. At that point, they will be put back together into the 15000-octet file. However while those packets are in transit, the network doesn't know that there is any connection between them. It is perfectly possible that packet 14 will actually arrive before packet 13. It is also possible that somewhere in the network, an error will occur, and a packet won't get through at all. In that case, that packet has to be sent again. In fact, there are two separate protocols involved in doing this. TCP (the transmission control protocol) is responsible for breaking up the message into packets, reassembling them at the other end, resending anything that gets lost, and putting things back in the right order. IP (the internet protocol) is responsible for routing individual packets. It may seem like TCP is doing all the work. And in small networks that is true. However in the Internet, simply getting a packet to its destination can be a complex job. A connection may require the packet to go through several networks at Rutgers, a serial line to the John von Neuman Supercomputer Center, a couple of Ethernets there, a series of 56Kbaud phone lines to another NSFnet site, and more Ethernets on another campus. Keeping track of the routes to all of the destinations and handling incompatibilities among different transport media turns out to be a complex job. Note that the interface between TCP and IP is fairly simple. TCP simply hands IP a packet with a destination. IP doesn't know how this packet relates to any packet before it or after it.

Friday, June 13, 2008

Increase virtual memory in eclipse

Increasing JVM's virtual memory to avoid core dumps or Out of Memory Error.

1) rt click on ur eclipse.exe or on the shortcut on ur desktop
2) goto shortcut tab and in target specify the jvm vmargs parameter as Xms and Xmx properties.

C:\Suneetha\Dwnld\eclipse\eclipse.exe -product com.genuitec.myeclipse.product.ide -vmargs -Duser.language=en -Xms256M -Xmx512M -XX:PermSize=128M -XX:MaxPermSize=256M


--Sunny

Monday, June 9, 2008

3 C's for Success

Confidence : Confidence in getting things done

Control : Controlled execution of your ideas

Courage : Courage To think big

-Suni

Friday, June 6, 2008

Spring Quick Ref Guide

What is Spring ?

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

Spring is a lightweight, inversion of control AOP based container framework.

What are features of Spring ?

Lightweight:

spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.

Inversion of control (IOC):

Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

Aspect oriented (AOP):

Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

Container:

Spring contains and manages the life cycle and configuration of application objects.

MVC Framework:

Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.

Transaction Management:

Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.

JDBC Exception Handling:

The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

What is a BeanFactory?

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

What is XMLBeanFactory?

BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.

BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.

MyBean myBean = (MyBean) factory.getBean("myBean");

Explain Bean lifecycle in Spring framework?

1. The spring container finds the bean’s definition from the XML file and instantiates the bean.

2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.

3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.

6. If an init-method is specified for the bean, it will be called.

7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.


What are the important beans lifecycle methods?


There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.


What is Auto wiring?

You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.

What is a Target?

A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.

What is a Proxy?

A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

What are the different points where weaving can be applied?

Compile Time

Classload Time

Runtime

Thursday, June 5, 2008

Hrithik Photos Test

Regular Expressions in Java

Regular Expressions in Java:

A regular expression works by matching a String against a template or pattern (a Pattern object in Java), and in its simplest form, returning a boolean to say "yes, the string does look like the pattern" or "no, that doesn't match".

As of release 1.4 of Java, though, there's a standard package
java.util.regex
that's shipped with the JRE, and that's what we'll look at in this module.
"^\\S+@\\S+$"

is a regular expression to see if the string entered is an e-mail

Ex:

Pattern email = Pattern.compile("^\\S+cat\\S+$");

Matcher match=email.matcher("vandicated");
if(match.matches()){
System.out.println("Matches vindicated pattern");
}else{
System.out.println("No Match found");
}


If you want to match at the start of a String, start your pattern with a ^ character; if you want to match at the end, conclude your pattern with a $ character. Should you specify both a ^ and a $, then you're looking to match the complete String to your regular expression.

The ^ and $ elements are known as "anchors" as they tie the start and/or the end of the String down; this group as a whole is also known as "assertions" because they don't match any specific characters in the incoming string, they just assert that while the match is running a certain condition must occur at the given point in the match.


If you write

[abcdef]


in your regular expression, then you're matching any one character from the list given (a b c d e or f). You can expand this capability further by using a minus sign to specify a character range, thus

[a-z]
any lower case letter
[0-9a-fA-F]
any hexadecimal character


and if you want to match any character except one from a list, you can start the character list with an ^ character, for example:

[^a-z]
any character except a lower case letter
[^%0-9]
any character except a digit or a % character

but that would get messy really fast, so there are some common groupings available in Java's regular expressions:

\s
any white space character
\d
any digit
\w
any word character (letter, digit, underscore)


If you want any character except one of these, use a capital letter:

\S
any character that is not a white space
\D
any character that is not a digit
\W
any character that is not a word character


Sequences such as \s will be familiar to you if you use Perl's regular expressions, but there are other character groups too; these use a POSIX standard definition of the character groups, but it's extended and the format isn't taken from Perl, nor PHP, nor Tcl nor SQL!

\p{Space}
Alternative to \s for "any white space"
\p{Blank}
Space or tab character
\p{Alpha}
Any letter (upper or lower case)
\p{Graph}
Any visible character
\p{InGreek}
Any Greek letter
\p{Sc}
A currency symbol


You can negate these groups using \P rather than \p thus

\P{Graph}
Any character that is not visible


One final grouping, the ultimate group if you like, is the "." (full stop or period) character, which matches virtually any character.


COUNTS


The fourth main group (after anchors, literal characters, and character groups) are the counts; you use these in regular expressions if you want to give a quantity to a literal character or group, and you add the count character into you pattern directly after the element to which it applies. There are three very common counts:

+
one or more
*
zero or more
?
zero or one

Source: http://www.wellho.net/solutions/java-regular-expressions-in-java.html

Fun exploring new things. :)

Wednesday, May 21, 2008

Is There Any Reason To Get An MBA

Expert views on MBA:

Found this interesting article on Forbes.com

Arthur Blank

Education is a lifetime process. This is just one step along the way.

Tim Blixseth

That is one approach to success, but most people I know with a substantial net worth do not have one.


Otis Booth

Yes, many. Teaches the conventions by which businesses are conducted

Mark Cuban

Only if someone else is paying for it and you are going to a school where you can have a lot of fun.

Gerald Ford

Probably.

Danny Gilbert

What's an "MBA"?


Kenneth Hendricks

I don't know of any reason. I believe you can be successful without an MBA (i.e. Ted Turner and Bill Gates).


Wayne Huizenga

Yes, education is the most important thing to obtain the edge.

George Kaiser

Not for entrepreneurial business

Michael Ilitch

I don't have one myself, but I think it's a good idea today for people to get them. There's plenty to learn both in school and out. Always be open to learning.

William Moncrief

No.

Phillip Ruffin

It can't hurt but it's not essential.

Jorge Perez

Never got one, so I would not know. Nevertheless, the better the educational credentials, the greater the chance of getting a better start and the foundation to allow you to succeed.

James Sorensen

Yes, it would be nice to have the information it provides, but that is only the beginning. The real degree is earned after the formal degree.


Nice thoughts... and questions to ask yourself :)

-Nita

Tuesday, May 6, 2008

Spring Batch Update Code

Code snippet to execute batch operations using spring

Collection vBatchUtilitySlotModelCollection = batchSlotUtilityBusinessService.getCollection();
if(vBatchUtilitySlotModelCollection != null && vBatchUtilitySlotModelCollection.size()>0)
{
BatchSqlUpdate batchUpdater = new BatchSqlUpdate(getDataSource(),"UPDATE slot SET location_seq_num = ?, facility_seq_num = ? WHERE seq_num = ?");
batchUpdater.declareParameter(new SqlParameter(Types.BIGINT));
batchUpdater.declareParameter(new SqlParameter(Types.BIGINT));
batchUpdater.declareParameter(new SqlParameter(Types.BIGINT));
batchUpdater.compile();

for (Iterator iter = vBatchUtilitySlotModelCollection.iterator(); iter.hasNext(); ) {
VBatchUtilitySlotModel vBatchUtilitySlotModel = (VBatchUtilitySlotModel)iter.next();
batchUpdater.update(new Object[] {vBatchUtilitySlotModel.getLocationSeqNum(), vBatchUtilitySlotModel.getFacilitySeqNum(), vBatchUtilitySlotModel.getSeqNum()});
}
batchUpdater.flush();
}

It worked like a flash..!!!!

-Happy Coding
--Sunny

Friday, May 2, 2008

Singleton across JVM's

When you make an Object singleton, we all know its just unique per jvm or per class loader.

So what if you want to make an object unique in a clustered environment. One way of doing it is using JNDI object binding. Here is some sample code try to run on ur server.

private void jndiObjTest(){

try{
System.out.println("Teting jndi object cache");

NotchClient nc=new NotchClient("Sunny","T");

Hashtable ht = new Hashtable();
ht.put(Context.PROVIDER_URL, "http://localhost:7001");
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.REFERRAL,"throw");
InitialContext ctx = new InitialContext(ht);
ctx.bind("sam_name",nc);

System.out.println("Reading Object from JNDI lookup");
Object o=ctx.lookup("sam_name");

NotchClient n=(NotchClient)o;
System.out.println("Value of obj retrieved from jndi"+n.getName());

}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
Note: Please deploy the above code to ur local server to test, standalone java app wont work.

--Sunny

Monday, April 28, 2008

Recursion in Java

public void handleParent(int parentOid){

List clientBVOList=this.getClients(parentOid);
for(int i=0;i Lessthan clientBVOList.size();i++){
NcClient nc=(NcClient)clientBVOList.get(i);
if(nc.getNotchParentFl().equalsIgnoreCase("T")){

handleParent(parentOid-1);
resetFacs(nc);
}else{
resetFacs(nc);
}

}

}


private void resetFacs(NcClient nc) {
// TODO Auto-generated method stub

System.out.println("Resetting facilities for Client:"+nc.getName());

}


private List getClients(int parentOid) {
// TODO Auto-generated method stub
List ncList=new ArrayList();
if(parentOid==3){
System.out.println("Get clients for Parent 3");
NcClient nc=new NcClient("client1","F");
NcClient nc2=new NcClient("Client2","T");
NcClient nc3=new NcClient("Client3","F");
ncList.add(nc);
ncList.add(nc2);
ncList.add(nc3);
return ncList;
}
if(parentOid==2){
System.out.println("Get clients for Parent 2");
NcClient nc=new NcClient("client2.1","F");
NcClient nc2=new NcClient("Client2.2","T");
ncList.add(nc);
ncList.add(nc2);
return ncList;
}

if(parentOid==1){
System.out.println("Get clients for Parent 1");
NcClient nc =new NcClient("Client2.2.1","F");
NcClient nc2=new NcClient("Client2.2.2","F");
ncList.add(nc);
ncList.add(nc2);
return ncList;
}

return null;
}

NC Client:

public class NClient {

String nParentFl;
String name;

public NClient(String name,String parentFl){
this.name=name;
this.nParentFl=parentFl;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNParentFl() {
return nParentFl;
}
public void setNParentFl(String nParentFl) {
this.nParentFl = nParentFl;
}

}

Result:

Get clients for Parent 3
Resetting facilities for Client:client1
Get clients for Parent 2
Resetting facilities for Client:client2.1
Get clients for Parent 1
Resetting facilities for Client:Client2.2.1
Resetting facilities for Client:Client2.2.2
Resetting facilities for Client:Client2.2
Resetting facilities for Client:Client2
Resetting facilities for Client:Client3

Friday, April 25, 2008

So Small Lyrics

Carrie Underwood So Small Lyrics

While working lost in a busy day.. this song came from ipod like a refreshing spring shower ...quickly looked up lyrics on the internet..and pasting here. Another reason why I love my ipod so much.. :)).. sometimes it brings me out of my lostness.

Yeah, Yeah
What you got if you ain't got love
the kind that you just want to give away
its okay to open up
go ahead and let the light shine through
I know it's hard on a rainy day
you want to shut the world out and just be left alone
but don't run out on your faith

'cause sometimes that mountain you've been climbing
is just a grain of sand
and what you've been up there searching for forever
is in your hands
when you figure out love is all that matters after all
it sure makes everything else seem so small

it's so easy to get lost inside
a problem that seems so big at the time
it's like a river thats so wide
it swallows you whole
while you siting 'round thinking 'bout what you can't change
and worrying about all the wrong things
time's flying by
moving so fast
you better make it count 'cause you cant get it back

sometimes that mountain you've been climbing
is just a grain of sand
and what you've been up there searching for forever
is in your hands
oh when you figure out love is all that matters after all
it sure makes everything else seem so small

sometimes that mountain you've been climbing
is just a grain of sand
and what you've been up there searching for forever
is in your hands
oh when you figure out love is all that matters after all
it sure makes everything else...
oh it sure makes everything else seem so small
Yeah, Yeah

-- Playin the song agin. :D

Thursday, April 24, 2008

JConsole

Using JConsole

The JConsole graphical user interface is a monitoring tool that complies to the Java Management Extensions (JMX) specification. JConsole uses the extensive instrumentation of the Java Virtual Machine (Java VM) to provide information about the performance and resource consumption of applications running on the Java platform.

In the Java Platform, Standard Edition (Java SE platform) 6, JConsole has been updated to present the look and feel of the Windows and GNOME desktops (other platforms will present the standard Java graphical look and feel). The screen captures presented in this document were taken from an instance of the interface running on Windows XP.

1) You can use JConsole to monitor both local applications, namely those running on the same system as JConsole, as well as remote applications, namely those running on other systems
2) For monitoring production systems, use remote monitoring
3) Configure your jvm to run with JMX
3) Starting JConsole:
1) Have java Home in ur class path or open ur cmd prompt at C:\bea92\jrockit90_150_06\bin
2) type jconsole [processId] ex: jconsole 7280
4) Start remote JVM
type jconsole hostName:portNum




Using JConsole

Performance issues and Tools to use

Insufficient Memory

The Java Virtual Machine (JVM)* has the following types of memory: heap, non-heap, and native.

3 Types:
1) Heap Memory Error
2) Non Heap Memory Error
3) Native Memory Error

Memory Leaks

The JVM is responsible for automatic memory management, which reclaims the unused memory for the application. However, if an application keeps a reference to an object that it no longers needs, the object cannot be garbage collected and will occupy space in the heap until the object is removed. Such unintentional object retention is referred to as a memory leak. If the application leaks large amounts of memory, it will eventually run out of memory, and an OutOfMemoryError will be thrown. In addition, garbage collection may take place more frequently as the application attempts to free up space, thus causing the application to slow down.

Finalizers

Another possible cause of an OutOfMemoryError is the excessive use of finalizers. The java.lang.Object class has a protected method called finalize. A class can override this finalize method to dispose of system resources or to perform cleanup before an object of that class is reclaimed by garbage collection. The finalize method that can be invoked for an object is called a finalizer of that object. There is no guarantee when a finalizer will be run or that it will be run at all. An object that has a finalizer will not be garbage collected until its finalizer is run. Thus, objects that are pending for finalization will retain memory even though the objects are no longer referenced by the application, and this could lead to a problem similar to a memory leak.


Deadlocks

A deadlock occurs when two or more threads are each waiting for another to release a lock. The Java programming language uses monitors to synchronize threads. Each object is associated with a monitor, which can also be referred as an object monitor. If a thread invokes a synchronized method on an object, that object is locked. Another thread invoking a synchronized method on the same object will block until the lock is released. Besides the built-in synchronization support, the java.util.concurrent.locks package that was introduced in J2SE 5.0 provides a framework for locking and waiting for conditions. Deadlocks can involve object monitors as well as java.util.concurrent locks.

Typically, a deadlock causes the application or part of the application to become unresponsive. For example, if a thread responsible for the graphical user interface (GUI) update is deadlocked, the GUI application freezes and does not respond to any user action.


Looping Threads

Looping threads can also cause an application to hang. When one or more threads are executing in an infinite loop, that loop may consume all available CPU cycles and cause the rest of the application to be unresponsive.


High Lock Contention

Synchronization is heavily used in multithreaded applications to ensure mutually exclusive access to a shared resource or to coordinate and complete tasks among multiple threads. For example, an application uses an object monitor to synchronize updates on a data structure. When two threads attempt to update the data structure at the same time, only one thread is able to acquire the object monitor and proceed to update the data structure. Meanwhile, the other thread blocks as it waits to enter the synchronized block until the first thread finishes its update and releases the object monitor. Contended synchronization impacts application performance and scalability.

Problem: Insufficient memory
Symptom: OutOfMemoryError
Tool: Java Heap Analysis Tool (jhat)

Problem: Memory leaks Growing use of memory
Symptom: Frequent garbage collection Java Monitoring and Management Console (jconsole)
Tool: JVM Statistical Monitoring Tool (jstat)

Symptom: A class with a high growth rate. A class with an unexpected number of instances Memory Map (jmap)
An object is being referenced unintentionally jconsole or jmap with jhat
Tool: See jmap -histo option
See jmap -dump option

Problem: Finalizers
Symptom: Objects are pending for finalization jconsole
Tool: jmap -dump with jhat

Problem: Deadlocks Threads block on object monitor or
Symptom: java.util.concurrent locks jconsole
Tool: Stack Trace (jstack)

Problem: Looping threads
Symptom: Thread CPU time is continuously increasing
Tool: jconsole with JTop

Problem: High lock contention
Symptom: Thread with high contention statistics
Tool: jconsole

Had a great time exploring performance monitors.

-Knowledge is power.

Friday, April 18, 2008

Internationalization in Struts

Def: Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text.

How do we achieve this in Struts.. very simple. Struts comes with built in support for interanationalization.

by default you have applicationResources.properties file, which supports the default locale english. Now for every additional language you wish to support, create a new applicationResources_{Locale u r adding}.properties.

example: For Hindi create a file called,

ApplicationResources_hi.properties file and put all ur messages in a key, value format.

Ex: in ApplicationResources.properties (default for english) you define messages like
page.title=Thank you for visiting!

now for Hindi.. you'll have a file like
ApplicationResources_hi.properties
page.title=Dhanyawaad!


And define both files in ur struts-config.xml file, in message resources section

{message-resources
parameter="com.sunny.app.ApplicationResources" /}

{message-resources
parameter="com.sunny.app.ApplicationResources_hi" /}


Calling From JSP:

{h2}{bean:message key="page.title"/}{/h2}

Thats it depending on ur locale.. apt file will be invoked and apt msg in ur language is shown on screen.

Testing: To change locale of ur browser.. goto

tools-->internet options-->languages --> add-->

choose hindi add and move it to the top.

Now when you run your application, message is displayed in Hindi...:D


This is too cool and exciting..!!!

Friday, April 11, 2008

ConcurrentModificationException

Problem Def: java.util.ConcurrentModificationException, occurs when you iterate thur and modify the same List of values.

Solution: Tried using a for loop, List.iterator, Collections.synchronizedList() all in vain. With for loop, I often ran into array index out of bound. Using iterator got ConcurrentModification error. So the solution is copy your values into another list and modify new list while iterating the old one.

Wait a minute.. googling longer found a better answer.. you should use iterator.remove() yay..!!! effective way of all:D


Lesson learnt: Patience pays off


Happy reading
Sunny
-------------

Thursday, April 10, 2008

Garbage Collector

Dont gimme that look... :) I am talking about JVM's (Java Virtual Machine's) Garbage collector.

Automatic Garbage Collection is one of the most convenient features in Java, which promises to prevent memory leaks unlike in C or C++, where programmer has to manuallly allocate and de-allocate memory using malloc,calloc/de-alloc functions.

Lets learn the inner workings of GC. Excerpts of an article from Sun:

GC def: is a benevolent sentinel present in every JVM. Its role is to identify and free chunks of memory left unused by the currently running application. Its job should shed some light on the origin of the name "garbage collector." Despite the depreciating name, the GC is like Dilbert's garbage man who is very smart, even smarter than you sometimes.

During its lifecycle, an application creates a certain number of objects, that is to say a certain amount of data that consumes memory and lasts according to its role in the application. As a matter of fact, an application spawns a large amount of short-lived objects during its life span. So you can understand that defining and controlling the lifecycle of every single object generated by an application demands a tremendous amount of work from developers.

A simple example should give you a better idea of the incredible number of objects that are born and then killed. When you open a plain text file in a text editor, in our case Jext, 342,997 objects are created and destroyed.

A memory leak is caused by objects, called undeads or zombies, left unused but still marked alive in memory. The more undeads wandering about, the more memory the application will need. The program eventually runs of out fresh memory and crashes. Good memory management is one of the most difficult issues in low-level languages like C or C++. Some high-level languages, like Java or Python, rely on a GC that cuts down the programmer's workload. So a developer supported by a GC only needs to do object creation.

Although extremely convenient, a GC is not a miracle tool and every so often does wicked things



Parts of a JVM Heap:

The GC in the HotSpot JVM is also called the "generational garbage collector." As its name suggests, this GC can make a difference to several generations of objects. Within the virtual machine, objects are born, live, and die in a memory area known as the heap.

The heap itself is divided into two parts, each one corresponding to a given generation: the young space and the tenured space. The first hosts recent objects, also called children, while the second one holds objects with a long life span, also called ancestors. Next to the heap, the virtual machine contains another particular memory area, called the perm, in which the binary code of each class loaded by the currently executing program is archived. Although the perm is important to applications dynamically generating a lot of bytecode, like a J2EE server, it's unlikely you'll ever need to tweak it.


Both the tenured space and the young space contain a virtual space, a zone of memory available to the JVM but free of any data. That means that those spaces might grow and shrink with time

Whenever a new object is allocated to the heap, the JVM puts it in the eden.The GC uses the one that remains free as a temporary storage bucket. When the young space gets overcrowded, a minor collection is done. A very simple copy algorithm is used that involves the free survivor space. During a minor collection, the GC runs through every object in both the eden and the occupied survivor space to determine which ones are still alive, in other words which still have external references to themselves. Each one of them will then be copied into the empty survivor space.


In the tenured space the laws are different. Whenever more memory is needed, a major collection is done with the help of the Mark-Sweep-Compact algorithm. Though it's not complex, it's greedier than the copy algorithm. The GC will run through all the objects in the heap, mark the candidates for memory reclaiming, and run through the heap again to compact remaining objects and avoid memory fragmentation. At the end of this cycle, all living objects exist side-by-side in the tenured space. The major collections responsible for most Java applications slow down from time to time. Unlike a minor collection, running a major collection stops the execution of the whole application. So a good optimization trick is to reduce the burden of the Mark-Sweep-Compact algorithm.


Parameters of JVM Heap:
-Xms{size} specifies the minimal size of the heap. This option is used to avoid frequent resizing of the heap when your application needs a lot of memory.
-Xmx{size} specifies the maximum size of the heap. This option is used mainly by server-side applications that sometimes need several gigs of memory. So the heap is allowed to grow and shrink between the two values defines by the –Xms and –Xmx flags.
-XX:NewRatio={number} specifies the size ratio between the tenured space and the young space. For instance, -XX:NewRatio=2 would yield a 64MB tenured space and a 32MB young space, together a 96MB heap.
-XX:SurvivorRatio={number} specifies the size ratio between the eden and one survivor space. With a ratio of 2 and a young space of 64MB, the eden will need 32MB of memory whereas each survivor space will use 16MB.

Tuesday, April 8, 2008

Traditional IRA and Roth IRA

What is IRA?

An IRA is an INDIVIDUAL RETIREMENT ACCOUNT. An IRA is a personal savings plan that provides income tax advantages to individuals saving money for retirement purposes.

How does it work...?

You invest money in an IRA, up to the amounts allowable under the tax law. These investments are termed "contributions." In many instances an income tax deduction is available for the tax year for which the funds are contributed. The contributions, as well as the earnings and gains from these contributions, accumulate tax-free until you withdraw the money from the account. You therefore enjoy the ability to generate additional earnings, unreduced by taxes on these earnings, each year the funds remain within the IRA.

The withdrawals of the funds from the IRA are termed "distributions." Distributions are subject to income taxation, generally in the year in which you receive them. (Remember that in most cases you received an income tax deduction when you contributed the money to the IRA.) As with most things involving the government, the rules for distributions are more complicated than they need to be.

Since the original purpose of the IRA is to assist you in providing for your own retirement, there is a disincentive for withdrawing your IRA funds prior to an assumed retirement age of 59 1/2. This disincentive takes the form of a tax "penalty" in the amount of 10 % of the distributions received by you prior to age 59 1/2, unless certain exceptions apply. Given the complexity of this issue alone, professional advice should be obtained whenever significant amounts of distributions are needed prior to age 59 1/2. The fact is that many times the penalty can be avoided with proper planning. Obviously these distributions, whether before age 59 1/2 or later, are subject to income taxation upon receipt. Once you are age 59 1/2 this penalty, termed a "Premature Distribution" penalty, is no longer applicable.

On the flip side of the government not wanting you to withdraw your money at too young an age, it also has rules to prevent you from not withdrawing the money soon enough. (This is done in order that the government can tax it.) You usually need to begin taking money from your IRA no later than April 1 of the calendar year following the date you attained age 70 1/2. The rules established by the government regarding these Required Minimum Distributions, their timing, the amounts, the recalculations, and the effect various beneficiary designations have on them, are among the most complex of the Internal Revenue Code. The penalty is 50 % of the shortfall between what you should have withdrawn and the amounts you actually withdrew by the proper date. This punitive penalty is matched only by the civil fraud penalty in severity. The necessary calculations are therefore not something that most individuals should attempt on their own.

My observations:

IRA: is pretax. So it will reduce ur tax bracket by so much amount you are investing

IRA: If you withdraw after 59.5 yrs, you will hv to pay tax on both principle + interest you made

IRA: If you withdraw before hand, you have to pay 10% penality fee + taxes you owe (You can avoid the penality fee, if you take out for ur first home or higher education). at else, when you distribute (IRA tech term for withdrawl :D) the amount will add up to the total income you made.. and it might again increase your tax bracket for the year.


Roth IRA : is after tax: So you will have to pay taxes first and then invest.

Roth IRA : If you withdraw after 59.5 yrs, you will just hv to pay tax on the interest you made

Roth IRA : You can withdaw at anytime before 59.9 w/o 10 % penality and just pay taxes on the interest you owe.

Essentials of financial knowledge

Tuesday, April 1, 2008

Making frineds with Log4j

I was using log4j since a while now and I was living in a perfect world until one day it did an about face and stopped printing msgs on to my console, leaving me alone in the dark ;) ;)

My other best pal, google search, helped me get out of my grief. :D So.. I have log4j.jar in my eclipse build path. I also have my console appender defined in log4j and I am calling it from root with debug level. Everything looks so perfectly right..! So wots worng..!!???

Weblogic didnt throw me an error message either.. to frustrate me, it just keeps quite and not show any of my debug msgs I put in my code..

after struggling for 2 days..its just that I have it missing in my weblogic class path. Picture attached below. :D. So from now on pls make sure you have it
ur weblogic class path also.

Friday, March 28, 2008

New Day .. New Spirit

Tylenol is the best medicine to a bad head ache, so I had one last nite and it put me to sound sleep...Woke up to a fresh feeling this morning and having my sprits high, once again I felt passionate enough to tackle ACCESS problems at hand.

I am kind of person.. who loves to get things going.. and I really cant get stuck at one point and be there for long.. it stresses me out.

Coming into office this morning, I am thiniking.. isnt it what I like the most abt my job..IT is a challenging career, learning new technologies and have something different to work on in life.. I really cant do the same thing for more than a month okay may be 2 mo's.. I belive variety is the spice of life. So I shudnt complain but get along and accept challenges. So first thing I did is to write all my issues on a paper and come up with a plan to take one thing at a time. To my delight, it all worked out well and by 3.PM I have an answer to my issues...well not all of them.. but I am happy with my progress....focused enough that I forgot to have my lunch.

So lesson learnt: dont sweat small stuff and have a plan to deal with ur things. Life is not always fair. :D. And yes sometimes resting enough helps.

-Sunny

Thursday, March 27, 2008

So Totally Tired

Do I have to work on Access Database..? Yes
Do I want to..? NO

I am killing myself trying work on someting which I totally hate.
Like eveytime I had to write some new logic..the voice in my head says you dont have to..its not gonna add up to your skill set.

I dont have an option but meet my dead line.. (GRRRR).. Honestly its really depressing for a java pro(yeah tats me ;)) to work on something really boring as access db.

I dont know.. I always seem to get the patch up works in the proj..Not because I am free.. I hv tonns of coding to do in my other module.. still ppl are confident that I'll be able to do both. God gimme a break..

I am so totally tired today.. stretching myself to meet a requirement and the deadline..So I am screaming (inside) Is it weekend yet..? Pls say a prayer for me that I'll start liking what I am doing atleast until its rolled out on Apr. 4

btw totally un-realated, my hubby booked a bus trip for 2 to Washington DC, for sometime in late May. U know how much did it cost him..??? 50 cents.. yes 50 cents..!!!! hes such a good deal hunter..and we found it irresistible....so we are going..just for the heck of it :D Hope we'll hv fun.

PS: AFter reading the title of my post don't say SO..? like Cheney said to a reporter.. ;)

-Sunny

Thursday, March 20, 2008

Accessing Java code in JSP

Y'day I suddenly forgot (amnesia..??? naaa..:D).. and I was totally balnk abt some of the basic things we do every day.. like accessing java code in JSP.. so to persist.. I write it here in my blog. ;) I think I got so much carried away with the merger of Bear and the current market conditions.. so back to coding action.

but before we move on some smiles to persist from daily cartoons:Obama 1

{%
String showResetMsg = (String)request.getAttribute(Constants.SHOW_RESET_ACTION_MESSAGE_STD);
DetailsForm detailsForm = (DetailsForm)session.getAttribute("detailsForm");

String resetMsgInForm =detailsForm .getShowResetActionMsg();
if(null!=showResetMsg && showResetMsg.equals(Constants.YES))
{
detailsForm .setShowResetActionMsg("yes");
}
else
{
detailsForm .setShowResetActionMsg("no");
}
%}

Java Script Function executed on page load:

Lets say.. you are executing an action and if there is an exception, which you want to handle gracefully and show an alert message to the user. You can do so using a simple Java Script function. Which gets called always on page load. This fn, basically checks for the form variable and if its not null or empty always shows the alert msg.

{script='JavaScript'}

showErrMsgOnPgLoad(); //method is always called on page load. Carefully set and clear the form variable document.forms[0].errMsg.value

function showErrMsgOnPgLoad(){

var errmsg=document.forms[0].errMsg.value;
if(errmsg!=null && errmsg!=''){
alert(errmsg);
document.forms[0].errMsg.value='';
}

Tuesday, March 18, 2008

Fall of Bear -- JP Morgan's Jaw Dropping Deal

On Sunday, Mar 16th JP Morgan acquired Bear Sterns, to save it from the brink of Bankruptcy. It was the deal so quick, it stunned Wall Street.


All the credit goes to our CEO, Jamie Dimon who emerged as the most powerful financier of our times.

Here is the exerpts of the artile in New York Times

High in a Park Avenue skyscraper (Building opp. to where I work..proud to be morganite.. :D), within a maze of soft rugs and wood-paneled walls, James Dimon sits just footsteps from the mahogany roll-top desk of J.Pierpont Morgan, the feared lord of the House of Morgan and the most powerful financier of his time.

Mr. Dimon’s race to cut a deal for Bear began around 6 p.m. last Thursday, when Alan D. Schwartz, Bear’s chief executive, called with startling news: Bear had been driven to the brink of bankruptcy by what amounted to a bank run.

Mr. Dimon quickly dispatched his investment banking co-heads, Steven D. Black and William Winters, to assemble a team for a possible takeover. By Friday, JPMorgan was plotting how to assess Bear, particularly the risky mortgage-related assets that had led to crippling losses.

“Jamie was driving the process. It was an extraordinary thing to watch,” said a senior executive involved in the deal.

By 8 a.m. Saturday, about 40 bankers were huddled in the boardroom of the eighth-floor executive suite at JPMorgan’s headquarters, which served as a makeshift war room. Under the command of Mr. Black and Mr. Winters, the group divided into teams, each charged with assessing an aspect of Bear, and began heading across the street to Bear’s headquarters to scour the books. More than 200 bankers ultimately joined in this task.

By Saturday evening, the JPMorgan bankers believed they were so close to a deal that they began drawing up a presentation to investors. The expected price per share was in the double digits, roughly half Bear Stearns’s closing price of $30 on Friday.

But the bankers could not agree on how to value Bear’s holdings of complex mortgage securities. Back on the eighth floor at JPMorgan, Mr. Dimon and his lieutenants paced from room to room, trying to keep up with the latest information.

With so much uncertainty hanging over Bear’s portfolio, the JPMorgan bankers decided to ask federal officials to explore ways to limit the bank’s risk. Among the options was having the Fed guarantee billions of dollars’ worth of Bear securities — an unprecedented step for the central bank.

On Sunday morning, JPMorgan threatened to walk away from the deal because executives felt they would be taking on too much risk. Mr. Dimon and his team wanted to give federal officials time to explore other options, according to a person close to the deal. “You have to have a margin for error so if you are wrong, you are not jeopardizing the company,” Mr. Dimon said.

A Bush administration official said the government was not concerned about the fate of a single bank but about the stability of the financial markets. Indeed, this official said, Bear Stearns was “anything but too big to fail.” But its failure would have had huge repercussions for the stability of the broader markets, and that was why the Fed acted with administration support.

Soon the bankers and policy makers were racing to strike a deal before markets in Asia opened for trading on Monday, fearing markets might plunge if Bear failed to find a buyer. But by 3 p.m., there was still no agreement, but they were heading toward a federal guarantee.

With hope that a deal would be reached, JPMorgan executives began briefing credit ratings companies and Mr. Dimon talked to his board. Just after 7 p.m., with less than an hour to go before Asian markets opened, the two sides reached an agreement.

Mr. Dimon was quick to dispense credit to his top bankers, as well as to Mr. Paulson and Mr. Geithner. “Same with the team at Bear Stearns,” he added. “God knows what pressure they had to be under.”

“This is the first time someone has stepped up and offered to solve a problem, even if it will cost Bear Stearns dearly. And making a few bucks on the leadership is in the Morgan tradition as well.”

Mr. Dimon, for his part, said on Monday that he was looking forward to getting some rest.

“There are two types of not getting sleep,” he said. “There is not getting sleep because there is a lot of work. The other is because you can’t sleep. I had a little of both.”

NY Times Article

Wall Street Journal


"Proud to be a Morganite"

Thursday, March 13, 2008

Spring AOP Simplified

Spring AOP (Aspect Oriented Programming) Simplified:

Here is my exploration os spring aop. An interceptor which logs the method name
and the time taken for each method being invoked in the path of executing a request.

Back to Basics:

What is AOP:
AOP is a philosophy that is related to style of programming.
It addresses issues that can be solved in other approaches, but in a more elegant way.
To understand the spirit of AOP, you must understand the following issues

1) Things like logging, When you enter and exit methods and time take to execute are common across
the application (Caution: logging to debug ur app is different). It need not necessarily interfere with ur code.

2) Transaction management

3) Entitlements etc

Here is an example of how to implement AOP in spring

Lets try to see when user performs any action, see if session is active and throw
and error if its not.


public class SessionInterceptor implements MethodInterceptor {

public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("Suneetha in Sarc session Interceptor");
logger.info("calling... >>" + methodInvocation.getThis() + ">> "+ methodInvocation.getMethod().getName());
System.out.println("calling... >>" + methodInvocation.getThis() + ">> "+ methodInvocation.getMethod().getName());
HttpSession session = request.getSession(false);
if (session != null) {

System.out.println("Session is healthy");

}else{
System.out.println("Session expired");
throw new SessionTimeoutException("session expired");

}

//Make sure you always have these lines of code

try {
Object retVal = methodInvocation.proceed();
return retVal;
} catch (Exception e) {
logger.error(Constants.EVENT_TYPE_DIAGNOSIS + " "
+ Constants.BUSINESS_PROCESS_NAME + " "
+ this.getClass().getName() + " ", e);
throw e;
}
}
}


So now the wiring:

In your application context.xml you shud define the above bean and
also wire the aspect to it.

As always define the bean:

bean id="sessionInterceptor" class="com.jpmchase.srgtarc.interceptor.SessionInterceptor"
property name="sarcUserService"
ref bean="sarcUserService"/
/property
/bean


Now define the Aspect bean

bean name="logAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
property name="beanNames"
value /actions/smarc*,/actions/sMArc*,/actions/saMArc* /value
/property
property name="interceptorNames"
list
value sessionInterceptor /value
/list
/property
/bean

So the above aspect will be executed for all kinds of actions starting with

smarc or sMArc or saMArc etc



Other Killer AOP examples:


AOP thoroughly explained

spring wiki doc. Simple but profound

yes Knowledge is Power

Monday, March 10, 2008

Wearable Motherboard or "Smart Shirt"

Here is my 100th post.. and I am proud to be writing about the Inidan Scientist Sundaresan Jayaraman. Inventor of the Smart Shirt. Here is the highlights of his interview.. in 2006.. though I am a little late.. I am glad I discovered it atleast now. :D. Thanks to Science Channel, program on it called "2057" enlightened me. ;)

The basic product is what we call the wearable motherboard popularly known as the smart shirt. It started back in the Spring of 1996, and the U.S. Department of Defense, they put out what is called a broad agency announcement saying that they wanted a system for use by soldiers in battle that would do two things. One, be able to tell when a soldier has been hurt, and simultaneously to be able to say how badly he was wounded. So, I submitted a white paper conceptualizing the design of the system itself, and then sent the white paper to DARPA, the U.S. Navy, and they approved the white paper and they gave me the funding to start the research, which we did in October of '96, myself and two of my research associates.

One, we achieved the goal that the Department of Defense set out in terms of having a system to help soldiers in battle, so that when they put the shirt on it will identify where the soldier has been shot, simultaneously give vital signs, such as heart rate, body temperature, respiration rate, electrocardiogram, and the person could also talk into the shirt. So, in other words, the shirt had the capability of doing all these things, and most importantly, in the design of the technology, we focused on not just a functionality offered, but also the form, okay? So that, at the end of the design process, when the product is developed, we wanted a piece of technology that would not only serve its functional purpose, but it would be easy to use, okay? read more here

-Thanks for Reading.

Friday, March 7, 2008

Why are Indian Railways so profitable..?

Ever wondered how Indian railways turned so profitable..? is the magic of Lalu.. or is it a myth..? Whats the root ... they predicted bankruptcy for IR in just 2001..? how did it turnaround..? curious to know why..???....here is what I found. Fascinating analysis of an IIM-A grad.

here

-Happy Reading.

Friday, February 29, 2008

Adorable AJAX

We are freshly brewing AJAX into our Java appliction. AJAX is widely used across the web lately. All major google apps like gmail,google maps, google suggest are based on AJAX. In short it makes the server calls seamless to the web user.

Summary of AJAX: