Thursday, June 04, 2009

New Features in Java 1.5

  1. Generics: Collection<Student> students;
  2. Enhanced looping: for (Student currentStudent : students)
  3. Autoboxing and unboxing: Integer x = 4 // boxing; Integet y = 5 //boxing; System.out.println(x+y); //unboxing
  4. Enums: instead of static final constants e.g. enum colors {WHITE, GREEN, BLUE}
  5. Variable number of arguments:

·         Use sparingly and try not to overload variable argument methods as it becomes difficult to figure out which method will get invoked. They are invoked when no other method signature matches the call.

·         Zero or more arguments can be passed for variable arguments

·         Variable arguments can only be used as the final set of argument in a method

e.g.

…..func1(String one, String… args) // correct

…..func1(String… args, String one) // not correct

 

Old:

public class Test2

{

        public static void main(String[] args)

        {

                System.out.println(contact(",",new String[]{"one", "two", "three"}));

        }

 

        private static String contact(String seperator, String[] tokens)

        {

                StringBuilder s = new StringBuilder();

                for (String currentValue : tokens)

                {

                        s.append(currentValue);

                        s.append(seperator);

                }

                return s.toString();

        }

}

New:

public class Test3

{

        public static void main(String[] args)

        {

                System.out.println(contact(",","one", "two", "three"));

        }

 

        private static String contact(String seperator, String... tokens)

        {

                StringBuilder s = new StringBuilder();

                for (String currentValue : tokens)

                {

                        s.append(currentValue);

                        s.append(seperator);

                }

                return s.toString();

        }

}

 

Wednesday, June 03, 2009

Number types in Java


Boxing: If you use a primitive type where a Object is expected, then the compiler will auto-box it into a wrapper class. Similarly if a wrapper object is used where a primitive is expected, the compiler will auto-unbox it.

Integer x = 10; // 10 boxed into wrapper class instance x
Integer y = 20; // 20 boxed into wrapper class instance y
System.out.println(x+y); // x and y unboxed to primitives so that they can be added by passing them to the + operator

Advantages of using a Object-wrapper-of-a-primitive over using a primitive
1. Argument to methods that expect a Object such as the collection interfaces
2. To use constants defined in these wrapper classes such as min_value and max_value
3. To convert primitives to wrapper classes using methods exposed in wrapper classes

Methods exposed by sub-classes of Number
xxxValue() e.g. byteValue() returns the wrapped primitive value
static Byte | Short | Integer | Long | Float | Double valueOf (byte, short, int, long, float, double) -> primitive to wrapped type
static Byte | Short | Integer | Long | Float | Double valueOf (String) -> String to Wrapped type
int compareTo(Byte | Short | Integer | Long | Float | Double) - to compare Number instances
boolean equals(Object)
static String toString(int i), String toString() to convert primitive to String

Tuesday, June 02, 2009

Source of previous post on Business Objects

A business object

A business object is a software representation of a real life entity. The entity could be a person, process, event or place. Examples of business objects are employees, products, invoices and payments. Business objects contain business data and model business behavior/process.

 

Business objects are different from data object which only hold data and do not have any behavior.

 

There are 2 ways or 2 strategies to achieve business objects:

EJB Strategy: Uses Entity Beans to model business data (with or without Container Managed Persistence) and Session beans to model Business process.

Pojo Strategy: Use simple Pojo (Plain Old Java Objects) along with light weight persistence mechanism such as hibernate/JDO (Java Data Object) or JDBC.

Hibrid: Uses POJOs behind the scenes using EJBs. Implement session façade in session beans and use POJOs to persist data.

 

Design patterns - Session Facade

Design patterns - Session Facade (source)

Business processes involve complex manipulation of business processes. Business classes participate in several business processes. If the responsibility of orchestrating (making the calls on business objects [may be session and entity beans] necessary to achieve a business process) the business process is placed with the clients of business objects, then clients become difficult to write and business objects themselves become tightly coupled. 

The session facade defines a higher level component that abstracts the complex interactions between lower level business components. Session facade in implemented in a session enterprise bean. It provides a single interface for clients to achieve a full business process or a part of it. It also decouples lower lever business components from one another.

Facade in french means face. Hence the facade component exposes a single face for a business process.

Giving access to each small interface on the lower level business components increases network traffic and latency. 


Example: Approval of large purchase orders may be a complex business process involving several business objects. In this case a OPCAdminFacade (Order Processing Center) facade ay be introduced that exposes APIs to achieve order processing. In this case the UI code will interface with only the OPCAdminFacade and not with each of the business objects.

public interface OPCAdminFacade extends EJBObject {

public OrdersTO getOrdersByStatus(String status)
throws RemoteException, OPCAdminFacadeException;

public Map getChartInfo(String request,
Date start,
Date end,
String requestedCategory)
throws RemoteException, OPCAdminFacadeException;
}

OPCAdminFacade would be implemented in OPCAdminFacadeEJB.


The getOrdersByStatus would interface with ProcessManagerLocal and ManagerLocal to get a list of PurchaseOrderLocal entity beans. It then creates a List of transfer objects (OrderDetailsTO [transfer object]) and returns them to the client.

Web Services Notes (Source)

Web Services Notes (Source)

For 2 business applications to communicate with each other (distributed computing env.) they need. 
1. A means for find and register a service
2. A transport mechanism to access a service
3. A way to define what the input and out parameters are

RMI existed before web services. There was not a well established protocol or overlapping protocols (UDDI and ebXML) in RMI to achieve each of the above. The advantage with web services is significantly higher levels of abstraction. They are language transparent (web services written in c and java can interface with each other), Container transparent (Services hosted on heterogenous environment/servers can interface with each other) and implementation abstraction (one service fewer assumptions about the implementation of the other service thus coupling between the 2 services is reduced). 



Service provider hosts several services some of which are web services.
Service repository hosts meta information about services and are lookup by service clients
3 in diagram above indicates the address at which the service is available, the signature of the service and others
4 & 5 is client binding to the web service and their consumption of service exposed in the web service

Web services are better than RPC 
1. Web services uses XML for data interchange so there is no developer written code to marshell or unmarshell data
2. XML data is interchanged using HTTP or SMTP which are well defined standards
3. The underlying service is specified using WSDL (hosted by service provider)
4. Web services can be searched for using UDDI


WSDL (Web Services Description Language)
- (pronoinced wisdel) (a form of IDL - Interface definition language) 
- Specifies a interface in XML and defines the XML schema and thus provides the vocabulary for defining interfaces like <types> and <message>. 
- Semantics of services like synchronous request/reply synchronous reply only and asynchronous communicate
- end point and transport  of the service using <service> element i.e. who provides the service
- encoding using <binding> i.e. how to access the service



Thursday, May 28, 2009

java.util.Calendar and java.util.Date

java.util.Date – Is a point in time (maintains millisecond accuracy)

java.util.Calendar –helps manipulate and compare java.util.Date

 

To convert Date to Calendar

 

        Calendar cal1 = Calendar.getInstance();

        Date currentTime = new Date(); // run on May, 28th 2009

        cal1.setTime(currentTime);

        assertEquals(2009, cal1.get(Calendar.YEAR)); // returns true

        assertEquals(Calendar.MAY, cal1.get(Calendar.MONTH)); // returns true

        assertEquals(28, cal1.get(Calendar.DATE)); // returns true

 

To convert Calendar to Date

 

        Date date2 = cal1.getTime();

 

To find dates relative to each other – example to find the date tomorrow and yesterday

 

        Calendar cal1 = Calendar.getInstance();

        Date currentTime = new Date();// run on May, 28th 2009

        cal1.setTime(currentTime);

        cal1.roll(Calendar.DATE, 1); // one day after the date represented by cal1 i.e. 29th

        assertEquals(2009, cal1.get(Calendar.YEAR)); // returns true

        assertEquals(Calendar.MAY, cal1.get(Calendar.MONTH)); // returns true

        assertEquals(29, cal1.get(Calendar.DATE)); // returns true

 

        cal1.roll(Calendar.DATE, -1); // one day before the date represented by cal1 i.e. 28th

        assertEquals(2009, cal1.get(Calendar.YEAR)); // returns true

        assertEquals(Calendar.MAY, cal1.get(Calendar.MONTH)); // returns true

        assertEquals(28, cal1.get(Calendar.DATE)); // returns true

 

Monday, May 25, 2009

JDBC Notes (Source)

JDBC Notes (Source)




Types of JDBC drivers:
Type 1: Drivers that implement JDBC APIs to map to another API such as ODBC. Dependent of native library (limited portability). e.g. JDBC-ODBC bridge
Type 2:Partly written in java and partly in native code (limited portability). Use native client library specific to the data source. E.g. JDBC driver that wraps around the oracle client lib.
Type 3:Fully implemented in Java. Interfaces with middleware server using db independent protocol. Middleware server then interfaces with the actual data source.
Type 4:Fully implemented in Java. Implemented network protocol for a data source. Directly communicates with data source.
Basics steps in using JDBC
  1. Establish a connects
    1. Load the driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");// Driver document details class name to use
      • Creates a instance of the driver clas
      • Registers the instance with DriverManager
      • Once created the driver instance can make a connection to DBMS.
            B.  Make a connection
                     i.  Using DriverManager
        • Works with Driver interface to manage the set of drivers available to a jdbc client (code that makes jdbc calls)
        • JDBC client provides the URL (of the data source to connect to) and requests a connection with the DriverManager
        • DriverManager finds out a driver that recognizes the URL and uses the driver to connect to the data source
        • URL Pattern
<<protocol>>:<<sub-protocol>>:<<sub_name/db_name>>[property_list]
e.g.jdbc:derby:babudb
where 
<<protocol>> Usially jdbc
<<sub-protocol>> Specified in driver documentation
<<sub_name/db_name>> Usually data base name
<<property_list>> attributes supported by driver specified in driver documentation
        • Making a connection
public static Connection DriverManager.getConnection(String URL, Properties info);
public static Connection DriverManager.getConnection(String URL, String user, String password);
e.g.
Connection conn = DriverManager.getConnection("jdbc:derby:COFFEES");
Connection conn = DriverManager.getConnection("jdbc:derby:COFFEES", "babu", "babupassword"); // Connect to COFFEES database using babu/babupassword as cred.
          • If one of the drivers registered with DriverManager recognizes JDBC URL, then the driver establishes connection with the specified DBMS
          • DriverManager.getConnection() returns a open connection
          • The DriverManager manages all details of establishing the connection
          • Only driver authers need to know about Driver interface
                    ii.  Using DataSource
        • Increases application portability by using a logical name for data sources instead of referencing driver specific information in the JDBC client/application
        • Some examples:
// DataSource as a JNDI resource
InitialContext ic = new InitialContext()
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();

// DataSource implementation provided by vendor
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP");
ds.setPassword("APP");
Connection con = ds.getConnection();

The start of nuclear weapons

May 7th, 1945 - German Surrender
July 16th, 1945 - First U.S. Nuclear test
July 26th, 1945 - U.S., Britain (a day before Churchill's end of term )and China give ultimatum(Not intended to be acceptable by Japan)
August 6th, 1945 - Hiroshima bombing (Bomb name: Little boy, Uranium based)
August 9th, 1945 - Nagasaki bombing (Bomb name: Fat Man, Plutonium based)
August 29th, 1949 - First U.S.S.R Nuclear test

Friday, May 22, 2009

Overriding methods can only throw exception that are thrown by the overridden method

import java.io.IOException;

 

interface TestInterface

{

        void test();

}

 

public class Second implements TestInterface

{

        public void test() throws IOException

        {

                System.out.println("Second.test() invoked");

        }

 

        public static void main(String[] args) throws IOException

        {

                TestInterface j = new Second();

                j.test();

        }

}

 

C:\users\Babu\temp\java>javac Second.java

Second.java:10: test() in Second cannot implement test() in TestInterface; overridden method does not throw java.io.IOException

        public void test() throws IOException

                    ^

1 error

An implementation of a method need not throw all exceptions thrown by the interface

import java.io.IOException;

 

interface TestInterface

{

        void test() throws IOException;

}

 

public class Second implements TestInterface

{

        public void test() // DOES NOT THROW IOEXCEPTION

        {

                System.out.println("Second.test() invoked");

        }

 

        public static void main(String[] args) throws IOException

        {

                TestInterface j = new Second();

                j.test();

        }

}

 

C:\users\Babu\temp\java>javac Second.java

 

C:\users\Babu\temp\java>java Second

Second.test() invoked

All methods of a interface are public

import java.io.IOException;

 

interface TestInterface

{

        void test() throws IOException;

}

 

public class Second implements TestInterface

{

        void test() throws IOException

        {

                System.out.println("Second.test() invoked");

        }

 

        public static void main(String[] args) throws IOException

        {

                Second j = new Second();

                j.test();

        }

}

 

C:\users\Babu\temp\java>javac Second.java

Second.java:10: test() in Second cannot implement test() in TestInterface; attempting to assign weaker access privileges; was public

        void test() throws IOException

             ^

1 error

Tuesday, May 05, 2009

log4j log levels

Eric says:

 

Trace – I use for start and end of methods.

Debug – I use for low level debugging, info about the processing of single records.

Info – I use as a sparse group type comment, like ‘101 records processed.’

Warn – I use when something I don’t like happened, but the user may not care.

Error – I use when something un-expected happened and I’m stopping the processing.

Fatal –

                I don’t really use fatal I suppose I should – but how is it different then Error

Tuesday, April 14, 2009

Can never be too Sure - Eric Kamradt

My college in office made this statement today. Makes sense.

Tuesday, February 24, 2009

No. of people in prison per 100,000 citizens

http://en.wikipedia.org/wiki/File:Prisoner_population_rate_UN_HDR_2007_2008.PNG

Friday, February 20, 2009

How to write a generic API

Joel made an interesting point today. His approach to writing generic APIs. When there is only one use case for an API. Write the API specific to that use case. When you discover the second use case then generalize the API.

Wednesday, February 18, 2009

String concatenation in Java with +

In Java if you System.out.println(“String 1” + “String2”) then there are no issues. The compiler will optimize it and there is no performance penalty. But if you do a String one = “String1”; String two = “String2”; System.out.println(one + two), then the compiler does not optimize this and there IS a performance issue. In these cases use String.format(“%s %s”, one, two).

 

For static Strings + concatenation is fine, for dynamic Strings, use String.format().

Sunday, February 15, 2009

Craftsmanship and Ethics

Source
How to become a professional programmer
1. Short iterations - 1 to 2 weeks is fine. 4 weeks is too long. You have deployable software. Not deployed software. It is a business decision to decide is the deployable software should be deployed.
2. Best way to establish requirements is to implement your best guess and compare it against what the customer needs. Give the small changes to the customer and ask him if that is what they want. Don't ask the customer to sign off on the requirements document.
3. Separate what is likely to change from what is likely NOT to change and put them in different parts. E.g. Do not put business rules in GUI code. GUI and business rules change for different reasons. GUI changes for merit reason. Business rules change for policy rules. No validation in javascript. There is a way to get user experience and at the same time separating what changes from what does not.
4. Always better to DO than NOT DO (wait for req., Module b from group b). If you are wainting, help the other group achieve it.
5. NEVER be blocked. Decouple dependencies by creating stubs, mocks & stimulators. Your code can run without their code.
6. Architectures that impede software development. Doon't try to solve every problem tthat is. Do you create more difficulties than you solve. Have several simple architectures for the enterprise. Architects must write code. They must live the mess they create.
7. How do you address mess? Face that you have a mess and solve it increamentally solve it. Bit by Bit, day by day. Simple rule. Check in the code that is a little better than you checked it out.
8. No grand re-design. Mgmt. does not want it. It is expensive. Where are the reqs. for the new re-deisgn system? In the old system. The old system is changing. New system has to catch up. So one little bit at a time.
9. Practise progressive widening. Small/thin feature from GUI to DB. Then widen it one thin feature at a time.
10. Progressive deepening. Get something working in one layer and stretch it across other layers. GUI programmer waited for middle layer. GUI wrote simple dirty middle layer. Then write SOA, DAO etc...
11. Make it work, right, fast
12. Slowed down by bad code. Why did Jim write it? Bad code is not something that slows down somebody months from now, but us, right now. Don't write and you will not read. We did not have time to write it well. You are going to be significantly slowed down by this code but you did not take the time to avoid being significantly slowed down. You look at your 2 hours ago code and surprised at what it does. DO NOT WRITE BAD CODE. Bad code saves a few thousand $s. But bad code will increase repeating maintenance cost. Our product is code not the behaviour. It does not matter if the product behaves as expected. If code is bad, product is bad. Bad code stays with the team. If regression rate is high, there is a chance that code is fast. The only way to go fast is to slow down and write the code well.
13. Write clean code: Every line of code is the way you expect it to be. No surprises. As you read it its obvious. how big should a function be? Small, good function and variable names. Clean code begins with 1 line of good code.
14. TDD - test driven development. Do not write a unit of production code without writing test code. Stop writing unit test code the moment the test code fails. Compilation failure is unit test failure. Write production code. Stop writing production code until unit test passes. Write more unit test code. Keep swinging between unit test and production code every 30 seconds.
15. What makes s/w flexible. Tests. Test runnable in a simple fashion.
16. Don't use QA to find bugs. QA will find. But programmer's should aim at QA not finding bugs.
17. Increase code coverage. It should be as close to 100%. 90% is pretty good.
18. Avoid debugging. Look at the code. You had it working a minute ago. Do it rarely.
19. Automate them. Manual tests - less. Manual test should be explorative.
20. Done means - all tests passes.
21. Test through the right interface. Tesing through GUI, when GUI changes, tests fails. Do not test business rules through the GUI. Test business rules through a different test. Test only GUI code through the GUI test scripts.
22. Training. Make sure new people work with old people.
23. Write code because you care. Free ware tools are good quality. I will be as well as I can.

Friday, February 13, 2009

Construction cost in chennai

 

Source

 

Before you buy a plot

• Check whether the details of approved plan have been displayed at the site.

• Check whether the promoter/power of attorney has the right to transfer the undivided share of land.

• Check whether the completion certificate has been obtained after the completion of the building.

Source

Thursday, February 12, 2009

How deserving of success are you after you failure? - Me

 

Nice advice

  • Hard work: All hard work bring a profit, but mere talk leads only to poverty.
  • Laziness: A sleeping lobster is carried away by the water current.
  • Earnings: Never depend on a single source of income. [ At least make your Investments get you second earning ]
  • Spending: If you buy things you don't need, you'll soon sell things you need.
  • Savings: Don't save what is left after spending; Spend what is left after saving.
  • Borrowings:  The borrower becomes the lender's slave.
  • Accounting: It's no use carrying an umbrella, if your shoes are leaking.
  • Auditing: Beware of little expenses; A small leak can sink a large ship.
  • Risk-taking: Never test the depth of the river with both feet. [ Have an alternate plan ready ]
  • Investment:  Don't put all your eggs in one basket.

Have heard that the author is Warren Buffet. But not sure. 

 

Wednesday, February 11, 2009

Brand New Day - Nice poem this

"Brand New Day"

At the end of the day you are worn out, you are
worn out, and too tired to sleep
But then you do dream of wonderful things
That you might do, right on through to the next
day
And then you wake up
The sun's on your face
You're stretchin' while you're sayin'
It's a Brand New Day!

It's a brand new day and the sky is clear
So let's come together, everybody cheer
Come out people from everywhere
Let's see your faces, the day we'll share
Come on and celebrate a Brand New Day
Everyday!

Call out to the workers and the children in the
schools
It's a day of celebration so put down your tools
and
Celebrate a Brand New Day Everyday!

Come see the mountains and come see the
shores
Mother nature is calling so come climb aboard
and
Celebrate a Brand New Day Everyday! Let's go

At the end of the day there is no doubt you are
worn out
Ooh but then you do dream of wonderful things

Wonderful things you might do

And then you wake up
The sun's on your face
You're stretchin' while you're sayin'
It's a Brand New Day!

Celebrate a Brand New Day, Everyday!
Celebrate a Brand New Day, Everyday!

Author - not me :-)

Potassium permanganate a disinfecting agent

Nice knowing that.

Friday, January 23, 2009

"Be pleasant until ten o'clock in the morning and the rest of the day will take care of itself." - - Elbert Hubbard

 

Confusion are not just within me...good to know that :-)

“Among other things, you’ll find that you’re not the first person who was ever confused and frightened and even sickened by human behavior. You’re by no means alone on that score, you’ll be excited and stimulated to know. Many, many men have been just as troubled morally and spiritually as you are right now. Happily, some of them kept records of their troubles. You’ll learn from them - if you want to. Just as someday, if you have something to offer, someone will learn something from you. It’s a beautiful reciprocal arrangement. And it isn’t education. It’s history. It’s poetry.”

- 
J.D. Salinger, The Catcher in the Rye, Chapter 24

Friedrich Nietzsche: "It is hard enough to remember my opinions, without also remembering my reasons for them!"

 

Wednesday, January 21, 2009

Monday, January 19, 2009

Free to work

Being honest about what we can do frees us to work - Kent Beck

StringBuffer vs. StringBuilder?

 

Never ever String concatenate

Use String.format()

APIs in Java Interfaces

No access specifiers in method signatures specified in Interfaces. Implementation qualifiers like “final” not to be included in arguments. Details follow.

A close shave

“What might have been” causes you to be sad because you are comparing yourself with how good things would have been had you been successful.

Your comparisons can determine your happiness

The bronze medalist is happiest because he compares himself with those who did not get any medal.

 

The silver medalist is not as happy because he compares himself with the gold medalist. Happiness is a function of who you compare yourself with.

Secret of happiness is mild contentment not extra-ordinary happiness

People who are have extra-ordinary happiness also experience extra-ordinary sadness. Details

 

Friday, January 16, 2009

Vanity - Excessive pride in one's abilities

Another nice word that.

Strange are Madoff's ways

The $50 Billion Ponzi scheme fraudster was investigated thrice by the SEC and they could find nothing wrong with him. Strange world this.

U.S. not the country with most cars person....surprise!!!


Interesting facts these:

 

There are more cars per person in Iceland (which is now is a financial doom) than in U.S. Details.

 

Wednesday, January 14, 2009

Listing all check-ins on a specific day

The following SVN command lists all check-ins on a specific day(s).

 

> svn log --revision {20090113}:{20090114}

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

r4900 | bsubburu | 2009-01-13 16:54:12 -0700 (Tue, 13 Jan 2009) | 1 line

 

XYZA-2823. Implemented blah blah blah

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

r4902 | jweight | 2009-01-13 17:28:38 -0700 (Tue, 13 Jan 2009) | 1 line

 

XYZA -2823. Increased blah blah blah

Friday, January 09, 2009

Nice talk on India, Pakistan conflict

http://fora.tv/2008/11/20/Neil_Joeck_The_US_And_Pakistan_Next_Steps

Thursday, January 08, 2009

Treatment (yesterday and today) of Mr Ramalinga Raju - a glaring example of how assuming we are

I have always felt that we Indians are very assuming. If somebody is successful in creating of perception of being good the first few times then he is good for the rest of his life and vise-versa (If we get a perception of somebody being bad the first few times then he is bad for the rest of his life).

 

Till yesterday Mr Raju, for the Indian media and Indians in general, was a super here of India Inc. Because we bought into his image promotion. We bought into his false-hood (or public relations as it is called to give it legitimacy).

 

Something like the size of a Maytas acquisition needed to wake us all up and smell foul. Now we start the journey to the other side. Mr Raju the evil of corporate India. Yesterday, a news item in NDTV that said they could not find where Mr Raju was. There were news reporters at the Satyam headquarters, Mr. Raju’s residence all saying “Ohh….He is not here”, “He is not here too”. They just stopped short of vocally uttering the word “abscond”. But the word was wide written everywhere in the news item.

 

Till yesterday Mr. Raju was, actually, a liar. To us, He was a super hero of corporate India. Today Mr. Raju is, actually, less a liar than yesterday. To us, He is a super villain of corporate India. When will we start rational views and stop having extreme ones.  

 

I am no big fan of Mr Raju. In fact I do not know much about him. But my point is our (the Indian society) treatment of him brings out the flaw in our attitude.

Wednesday, January 07, 2009

A british territory in Indian ocean?

Pretty surprise to see a territory of UK in here.

Why use @Override annotation

If a method is annotated with @Override but does not correctly override a method (in one of the super-classes or interface), then the compiler will report an error. So this is a means to use the compiler to enforce your idea that the methods overrides some other method.

 

E.g. of a startElement() method exposed in ContentHandler.

 

    /**

     * ……

     */    

    @Override

    public void startElement(

            final String uri,

            final String localName,

            final String qName,

            final Attributes atts

    ) throws SAXException

    {……

 

Tuesday, January 06, 2009

BidiMap

This Map can be looked up by both the key and the value WITH the same performance. The catch is that the values should also be unique. Which is expected as the values become the keys in reverse lookup.

 

A simple example:

 

import org.apache.commons.collections.BidiMap;

import org.apache.commons.collections.bidimap.TreeBidiMap;

 

public class BidiMapDemo {

    public static void main(String[] args)

    {

        BidiMap map = new TreeBidiMap();

        map.put("US", "USA");

        map.put("IN", "India");

        map.put("UK", "United Kingdom");

       

        System.out.println(

            String.format(

                "Lookup by Key. key: %s Name: %s",

                "US",

                map.get("US") // returns "USA"

            )

        );

 

        System.out.println(

            String.format(

                "Lookup by value. Name: %s Key: %s",

                "India",

                map.getKey("India") // returns "IN"

            )

        );

       

    }

}

 

Output:

 

Lookup by Key. key: US Name: USA

Lookup by value. Name: India Key: IN

Monday, January 05, 2009

Indian deep space network

Until recently, I was of the idea that the space facility at Byalalu was custom buily only for the Chandrayan project. But only now did I come to know that the 2 antennas at this facility is part of the deep space network. Pretty Impressive.

Sunday, January 04, 2009

java and sax xml programming basics

How to read an xml document using SAX
Notes:

Sax exposes a org.xml.sax.XMLReader interface which must be implemented by all XML parsers. xerces implemented this interface in the org.apache.xerces.parsers.SAXParser class.

The first step is to create an instance of XMLReader. So

package test;

import org.xml.sax.XMLReader;

public class SaxRead1
{

public static void main(String[] args)
{
XMLReader reader = null;
}
}


Next to create an instance of SAXParser and assign it to XMLReader reference. So

package test;

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.XMLReader;

public class SaxRead1
{
public static void main(String[] args)
{
XMLReader reader = new SAXParser();
}
}


SAX call backs: