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