Thursday, June 26, 2008

Oracle TopLink or EclipseLink ?

" Oracle TopLink will be Oracle's distribution of EclipseLink included with support with all editions of our Application Server as well as for standalone usage for customers who want commercial support and maintenance."



I just read this interesting thread on the OTN TopLink Forum. Oracle TopLink &will henceforth become EclipseLink.

I have been having this question every since I read about the EclipseLink Project. However, I got the answer today after reading the thread on the forum.

The interesting part about this is that the EclipseLink project now has contributions from people with different backgrounds. The product will be developed by people from different compaines & affiliations.

I am sure this "open sourcing" of TopLink ( EclipseLink ) will take it to new levels.

I wish the best for the TopLink team & the community !

Tuesday, June 24, 2008

Apache Tiles : Error : TilesContainer not initialized

We have been trying to get a simple web application that uses Apache Tiles Framework 2.0.5 to work in JDeveloper 10.1.3 .3.0.

However, we kept hitting a generic error :-

javax.servlet.jsp.JspException: TilesContainer not initialized
at org.apache.tiles.jsp.taglib.ContainerTagSupport.doStartTag
(ContainerTagSupport.java:72)
at org.apache.tiles.jsp.taglib.RenderTagSupport.doStartTag
(RenderTagSupport.java:138)
at _pets._jspService(_pets.java:48)
[/pets.jsp]
at com.orionserver[Oracle Containers for J2EE 10g (10.1.3.1.1) ].http.OrionHttpJspPage.service(OrionHttpJspPage.java:59)
at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:462)
at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:598)
at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:522)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
My friend Sriram & myself struggled to resolve this error & we were just able to resolve it.

I believe the error occurs because of these three reasons :-

1. Incorrect / Missing DTD reference in the tiles-defs.xml
2. Incorrect / Missing XML Elements in the tiles-defs.xml
3. Missing retrotranslator-runtime-n.n.n.jar in WEB-INF/lib
I am sure there are many other reasons for the error - I have just presented a quick checklist of the problems that we encountered.

The third option is still a mystery to us. I mean, why do we need to use the RetroTranslator Library when we are using JDK 1.5 ?

We are still trying to figure that one out. I'll post an update if we unravel this last mystery.

Monday, June 23, 2008

Apache Directory Server : Default Settings

" We strive to increase LDAP awareness, comfort and adoption to bring forth what we call the Modern LDAP Renaissance. "



I just downloaded and installed the Apache Directory Server. It took less than 5 minutes to install the server & start it.

The Apache Directory Server is one of the best LDAP Servers that I have used, during prototyping stages. It's very easy to install & very fast in operation.

However, I did observe in a couple of customer engagements that I had to look a bit through the documentation to get a list of the default configuration. I just want to list the default configuration that I use frequently here, to save a bit of time :-

Defalut Host : localhost
Default Port : 10389
Admin user : uid=admin, ou=system
Admin pass : secret
Base DN : ou=system
Initial context Factory : com.sun.jndi.ldap.LdapCtxFactory


Overall, the Apache Directory Project is simply too good !

WebLogic Server 10 : Deployment : OutOfMemory Error

I created a connection to WebLogic Server 10 in my JDeveloper 10.1.3. Now, I am using this connection to deploy a simple Web Application that contains a single JSP.

However, I keep hitting this bug frequently :-

[BasicOperation.deriveAppName():140] : appname established as: webapp1
weblogic.deploy.api.tools.deployer.DeployerException: Java heap space
at weblogic.deploy.api.tools.deployer.Jsr88Operation.postExecute(Jsr88Operation.java:563)
at weblogic.deploy.api.tools.deployer.DeployOperation.execute(DeployOperation.java:48)
at weblogic.deploy.api.tools.deployer.Deployer.perform(Deployer.java:139)
at weblogic.deploy.api.tools.deployer.Deployer.runBody(Deployer.java:88)
at weblogic.utils.compiler.Tool.run(Tool.java:158)
at weblogic.utils.compiler.Tool.run(Tool.java:115)
at weblogic.Deployer.run(Deployer.java:70)
at weblogic.Deployer.main(Deployer.java:54)
Caused by: java.lang.OutOfMemoryError: Java heap space
[ServerConnectionImpl.close():334] : Closing DM connection
[ServerConnectionImpl.close():354] : Unregistered all listeners
[ServerConnectionImpl.closeJMX():374] : Closed JMX connection
[ServerConnectionImpl.closeJMX():386] : Closed Runtime JMX connection
[ServerConnectionImpl.closeJMX():398] : Closed Edit JMX connection
**** weblogic.deploy returned with non-zero exit status: 1
**** weblogic.deploy returned with non-zero exit status: 1
Elapsed time for deployment: 46 seconds
#### Deployment incomplete. #### Jun 20, 2008 5:53:41 PM


The error clearly tells that the Java process used for the deployment is out of memory & is unable to deploy the application.

I have to increase the heap size of the java process that is used to deploy the application in JDeveloper.

I looked at the deployment profile for my application & noticed this command for WebLogic 9.x :-

${java} ${jvm.max.heap.size}
-classpath ${weblogic.jar} weblogic.Deployer
-adminurl t3://${hostname}:${port}
-user ${username} -password ${password}
-debug -verbose -deploy -upload
-source ${ear.file} -name ${j2ee.app.name}


However, at the time of deployment, I noticed that the heap size was not used for the Java process :-

javaw.exe -classpath weblogic.jar weblogic.Deployer -adminurl t3://localhost:7001 -user weblogic -password **** -debug -verbose -deploy -upload -source webapp1.ear -name webapp1

weblogic.Deployer invoked with options: -adminurl t3://localhost:7001 -user weblogic -debug -verbose -deploy -upload -source webapp1.ear -name webapp1


Hence, I hardcoded the heap size in the command in the Deployment Settings like this :-

${java} -Xms256m -Xmx512m
-classpath ${weblogic.jar} weblogic.Deployer
-adminurl t3://${hostname}:${port}
-user ${username} -password ${password}
-debug -verbose -deploy -upload
-source ${ear.file} -name ${j2ee.app.name}


At the time of depoyment, I noticed that the heap size as now being used correctly :-

javaw.exe -Xms256m -Xmx512m -classpath weblogic.jar weblogic.Deployer -adminurl t3://localhost:7001 -user weblogic -password **** -debug -verbose -deploy -upload -source webapp1.ear -name webapp1

weblogic.Deployer invoked with options: -adminurl t3://localhost:7001 -user weblogic -debug -verbose -deploy -upload -source webapp1.ear -name webapp1

After making this change, I was able to get a clean deployment from my JDeveloper 10.1.3.

.
.
.
[BasicOperation.execute():425] : Initiating deploy operation for app, webapp1, on targets:
Task 2 initiated: [Deployer:149026]deploy application webapp1 on examplesServer.
Task 2 completed: [Deployer:149026]deploy application webapp1 on examplesServer.
Target state: deploy completed on Server examplesServer
.
.
.
[ServerConnectionImpl.close():354] : Unregistered all listeners
[ServerConnectionImpl.closeJMX():374] : Closed JMX connection
[ServerConnectionImpl.closeJMX():386] : Closed Runtime JMX connection
[ServerConnectionImpl.closeJMX():398] : Closed Edit JMX connection
Elapsed time for deployment: 1 minute, 45 seconds
---- Deployment finished. ---- Jun 24, 2008 11:23:54 AM

Friday, June 20, 2008

WebLogic Server 10 : Deployment : Increase Server JVM Heap Space

I had to increase the WebLogic Server's JVM Memory Arguments to circument a problem.

The JVM Memory arguments are in the file " setDomainEnv.cmd " in the folder $WEBLOGIC_HOME\wlserver_10.0\samples\domains\wl_server\bin\

You can open the file in any Text Editor and scroll down to this line :-

set MEM_ARGS=-Xms256m -Xmx512m


You can alter the memory arguments to solve the problem. The combination that worked for me is tis :-

set MEM_ARGS=-512 -Xmx512m

WebLogic Server 10 : is the HTTP server a weblogic Server

I just hit a CommunicationException in my JDeveloper 10.1.3 :-

"
Caused by: javax.naming.CommunicationException [Root exception is java.net.ConnectException: http://localhost:7001: Destination unreachable; nested exception is: java.net.ProtocolException: Tunneling result unspecified - is the HTTP server at host: 'localhost' and port: '7001' a WebLogic Server?; No available router to destination] at weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:40) at weblogic.jndi.WLInitialContextFactoryDelegate.toNamingException(WLInitialContextFactoryDelegate.java:773) at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java:363) at weblogic.jndi.Environment.getContext(Environment.java:307) at weblogic.jndi.Environment.getContext(Environment.java:277) at weblogic.jndi.Environment.createInitialContext(Environment.java:200) at weblogic.jndi.Environment.getInitialContext(Environment.java:184) at weblogic.jndi.Environment.getInitialContext(Environment.java:162) at weblogic.deploy.api.spi.deploy.internal.ServerConnectionImpl.getContext(ServerConnectionImpl.java:330) at weblogic.deploy.api.spi.deploy.internal.ServerConnectionImpl.getEnvironment(ServerConnectionImpl.java:302) at weblogic.deploy.api.spi.deploy.internal.ServerConnectionImpl.init(ServerConnectionImpl.java:141) ... 11 more
"


I was trying to deploy an application from JDeveloper 10.1.3 to WebLogic Server 10. First, I created a connection to the WebLogic Server 10 using these connection settings :-


I then created a deployment profile for my Web Application. I right-clicked on the Deployment Profile and selected the option to directly deploy to my WebLogic Server. However, I kept getting this error.

I did some Googling & came across this post on the OTN JDeveloper Forums :-

http://forums.oracle.com/forums/thread.jspa?messageID=2134174&#2134174

To summarize Deepak's solution from the post,

"

JDeveloper 10.1.3.3 configures a connection with WebLogic server with the t3 protocol.The deployment profile has the connection protocol specified as http. Modify the connection protocol in the deployment profile.

1. In the Deployment Profile Properties window select the Platform>WebLogic 9.x node.
2. In the WebLogic 9.x Deploy command modify:
-adminurl http://${hostname}:${port}  

to
-adminurl t3://${hostname}:${port}  
"


I made this change in my Deployment Profile & it worked immediately.

WebLogic Server 10 : JDeveloper : Cannot instantiate class: weblogic.jndi.WLInitialContextFactory

"

Cannot instantiate class: weblogic.jndi.WLInitialContextFactory

"

I was trying to create a connection to WebLogic Server 10 from JDeveloper 10.1.3 & I encountered this error. The Connection Wizard threw this error when I wanted to test the connection.

The problem is simple - JDeveloper cannot find the class WLInitialContextFactory required to connect to my WebLogic Server.

The class is present in the JAR File weblogic.jar. The JAR file is present in the folder $WEBLOGIC_HOME/wlserver_10.0\server\lib.

I simply copied the weblogic.jar file from $WEBLOGIC_HOME\wlserver_10.0\server\lib and put it in JDEVELOPER_HOME\jdev\lib\ext

JDeveloper was able to find the JAR File & proceed with the connection without any hitch.

WebLogic Server 10 : Error 403--Forbidden

"

Error 403--Forbidden
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

"

I hit this error immediately after deploying and starting the application. The error is quire eloquent, but in my humble opinion, is not very clear about the reasons for the error.

I clicked on the "Testing" link for the application & simply clicked on the "Test Point" URL mentioned on the page :-

http://10.177.226.140:7001/webapp1

I worked on this for sometime & then it hit me :-

I have to supply the complete URL for my JSP.

I tried the complete URL & it worked.

http://10.177.226.140:7001/webapp1/First.jsp

I am just posting this for future reference to newcomers like me.

WebLogic Server 10 : 503--Service Unavailable

"

Error 503--Service Unavailable
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.5.4 503 Service Unavailable

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay may be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

Note: The existence of the 503 status code does not imply that a server must use it when becoming overloaded. Some servers may wish to simply refuse the connection.

"

I hit this error after deploying an application & trying out the URL for my JSP.

I have primarily worked on OC4J & expected that the steps would be pretty much the same. However, I hit this bug & was scracthing my head for quite sometime - until I realized it.

The Application has to be started after the deployment.

The application is not started by default ( as in OC4J ) & thus, was unavailable to service the requests.

I am just posting this for future reference to newcomers like me.

WebLogic Server 10 : Authentication Denied

"
Authentication Denied

The username or password has been refused by WebLogic Server. Please try again.

"
I just installed the WebLogic Server 10 & was excited to see the Welcome Screen pop-up on my browser. I then clicked on the "Start the Administration Console" button & the login page popped up.

I tried a couple of usernames and passwords, but I kept getting this error.



I finally tried this combination & it clicked :-

UserName : weblogic
Password : weblogic

Hurray ! I got into the WebLogic Server Administration Console.

Thursday, June 05, 2008

Problems in Configuration and Logging

" ...........
...........
Lock-Nah: The Book Of The Dead gives life.
Meela: And The Book Of The Living takes life away.
...........
...........
"


The dialogue between Lock-Nah and Meelah, from the movie The Mummy Returns sums up the state of the configuration files used in a software system. Often, I have observed that the most well-intentioned configuration files either end up as a "Book of the Dead" or as a "Book of the Living".

Configuration & Logging have always been the bone of contention & the heart of any discussion on software architecture. The questions always come up & hang in the air :-

- How will I configure that ?
- Where is the metadata for this ?
- How do I log this ?
- Can we use a universal format for the all the logging ?
- Where do I log the Exception Stack Traces ?
- .....
- .....
- .....

I just chanced upon this Blog entry by Dan Pritchett . The article talks about Metadata & the various decisions that need to be made while using Metadata. The article is nicely organized & well written.

Dan talks about two aspects of Metadata - Configuration & Telemetry ( Logging, actually ).

Configuration

Dan has clearly articulated the problem associated with distributed configurations, synchronizing between the configurations, etc. I have faced these issues many times in the past, especially with systems that contain lots of configuration files.

The key to get the system operational is to "turn the knobs" in the correct combination. Often, this kind of configuration mechanism falls into the realm of black magic : often, only a seasoned veteran master-architect can cast the correct arcane spell to tame the beast. The multitude of configuration files simply lay all the precise documentation to waste. The problem becomes even more complex when the system is replicated accross multiple servers : the arguments now move into a new space - how to maintain a "common" configuration & extend it to a specific "granular" configuration required by a single server.

Telemetry

Dan also touches upon the topic of Telemetry ( a term I haven't heard since my college days ! ). How do you measure / monitor the health of a system remotely ? Well, the only source of this information is the log files. The problem is simple - consider a System X that has parts A, B and C, & these parts emit log information in specific formats. How do you aggregate the information from these three different formats into a single format that can show up in a remote dashboard ?

I think these questions must be addressed very early in a Project. The questions raised by this article are extremely important & could save countless hours of effort involved during maintanence & debugging.

Overall, a very good article from Dan Pritchett. It's a must read for people who earn their pay by designing software systems.

Tuesday, April 08, 2008

Thinking Of Mathematics

"The world is too full of factors to discourage students who cannot see from pursuing a career in science and math; hopefully this article can serve to at least minimally offset that imbalance."


I was reading "Thinking Of Mathematics — An Essay On Eyes-free Computing" [ PDF version ] & found it inspiring. T. V. Raman's analysis of "Eyes-free mathematics" & his application of Herman Helmholtz's theories to attempt & understand his own creative thinking are excellent.

T.V Raman was unable to see since the age of 14. He narrates his thought process on problem solving, modeled on Herman Helmholtz's three stages of creativity: saturation, incubation and illumination. He shares his experiences on solving interesting problems like a Mental Calendar, Solving The Rubik’s Cube, etc.

The essay is truly a wonderful & inspiring read.

Wednesday, April 02, 2008

ORA-01940: cannot DROP a user that is currently logged in

" ORA-01940: cannot DROP a user that is currently logged in "

ORA-01940

We were trying to drop a user ( schema ) in our local Oracle Database & we suddenly hit the ORA-01940 error.

We closed all the SQL Clients ( Oracle SQL Developer, SQL* Plus, TOAD ) that we were using, but still the error persisted. We were quite flummoxed - until, we googled and landed on this article from Burleson Consulting.

We followed the advice in the article & quitely killed the "stale" sessions. We could then drop the schema and recreate it.

I have always admired the articles from Burleson Consulting & found the explanation of the ORA-01940 error very informative.

Tuesday, April 01, 2008

Groovy test ride

" Groovy is an agile and dynamic language for the Java Virtual Machine "


I have been following the Java scripting languages landscape for quite sometime now. I am simply overwhelmed with the sheer number of scriprting languages that can be run off the JVM. I was keenly following one such scripting language with interest - Groovy. I finally decided to take Groovy for a test ride, after reading a lot of interesting stuff on blogs & articles. I decided to try a simple example & see what I can learn from my experiment.

What's the Scenario ?

I have two database tables - EMP ( to keep details of employees ) and DEPT ( to keep details of departments ). I want to pull out details of an employee from the EMP ( Employee Number, Employee Name, Salary ) and DEPT ( Department Name ) tables and store it in another table named EMP_REPORT ( Employee Number, Employee Name, Salary, Department Name )

What am I going to use ?

  • Microsoft Windows XP [Version 5.1]
  • Java 1.5
  • Groovy 1.5.4
  • Oracle Database 10g Enterprise Edition Release 10.1.0.4.2
  • Oracle SQL Developer 1.2.1
What are the logical steps ?

1. Connect : to the Database.
2. Query : the tables EMP and DEPT using a SQL SELECT statement.
3. Results : get the Result Ser
3. Iterate : the result set and get each record.
4. Add : each record to the EMP_RECORDS table.

What about installation ?

The installation procedure for Groovy is very easy - download & unzip. If you have set the JAVA_HOME environment variable to point to your JDK installation directory, you can just proceed to Groovy's /bin directory and double click on GroovyConsole.bat. You can see a simple IDE that allows you to execute your Groovy code. You can use CTRL + R to execute the code and CTRL+W to clear the output window.

... and...What does the Groovy code look like ?

import groovy.sql.Sql
import groovy.xml.MarkupBuilder

def source = Sql.newInstance(
"jdbc:oracle:thin:user/password@host:port:sid",
"oracle.jdbc.driver.OracleDriver"
)

def target = Sql.newInstance(
"jdbc:oracle:thin:user/password@host:port:sid",
"oracle.jdbc.driver.OracleDriver"
)

def sourceEmployees = source.dataSet("EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO")
def targetEmployees = target.dataSet("EMP_REPORT")

sourceEmployees.each
{
targetEmployees.add( ID : it.empno , NAME : it.ename , SAlARY : it.sal , DEPARTMENT : it.dname )
}

My thoughts ?

Well, that was quite easy ! It took less that 10 minutes for me to setup Groovy & try the code. I only faced one problem - Groovy complained that it couldn't find the Database Driver class oracle.jdbc.driver.OracleDriver. I simply put ojdbc14.jar into my JAVA_HOME/jre/ext/lib folder as a workaround.

I found Groovy to be simple & much closer to Java than the other scripting languages touted for the JVM. I think I'll probably use it for prototyping something in Java/JEE in the future.

Monday, March 31, 2008

Asking questions on Forums

“The important thing is never to stop questioning.”
Albert Einstein

I was reading Shay Shmeltzer's and Hector Rivera Madrid's post on the generals rules on posting on User Forums. I don't want to summarize a list of my own as these gentlemen have already prepared a wonderful list of do's and don'ts.

I still have a bookmark to an old article - How to ask questions the smart way. The article is still being revised and maintained.

To summarize Shay's intentions :-

" I think there are some things that posters to the forums can do to make the whole experience of using the forums a lot better. "

Friday, March 21, 2008

Holi - 2008


It's Holi ! The festival of colors ! It's time to get drenched in a variety of colors !

Originally, Holi started out as a festival to celebrate good harvests. Now, it's more of a festival to have a good time :).

The day also marks Good Friday.

I am sitting at office trying to complete a pending task & suddenly, my colleagues smeared colors on my face. I am totally covered in colors & my laptop is sharing the same fate.

Well, I am looking forward to more fun & frolic during the weekend !

Self Appraisal

Another "gem" that I received in today's mail - thanks Vijay !:-

A little boy went into a drug store, reached for a soda carton and pulled it over to the telephone. He climbed onto the carton so that he could reach the buttons on the phone and proceeded to punch in eight digits (phone numbers).

The store-owner observed and listened to the conversation:

Boy: 'Lady, Can you give me the job of cutting your lawn?

Woman: (at the other end of the phone line): 'I already have someone to cut my lawn.'

Boy: 'Lady, I will cut your lawn for half the price of the person who cuts your lawn now.'

Woman: I'm very satisfied with the person who is presently cutting my lawn.

Boy: (with more perseverance): Lady, I'll even sweep our curb and your sidewalk, so on Sunday you will have the prettiest lawn in all of Palm beach, Florida.'

Woman: No, thank you.

With a smile on his face, the little boy replaced the receiver. The store-owner, who was listening to all this, walked over to the boy.

Store Owner: 'Son... I like your attitude; I like that positive spirit and would like to offer you a job.'

Boy: 'No thanks,

Store Owner: But you were really pleading for one.

Boy: No Sir, I was just checking my performance at the job I already have. I am the one who is working for that lady, I was talking to, and I was doing my 'Self Appraisal'

ORA-01000 maximum open cursors exceeded

" java.sql.SQLException : ORA-01000: maximum open cursors exceeded "

-- ORA-01000

I was recently asked my a colleague to help in resolving the ORA-01000 error. At a first glance, everything looked fine in the Java Code & it was baffling - it took sometime for enlightenment to illuminate the nature of the problem and one possible solution.

The program inherited by my colleague had two Java classes - Class A and Class B. Class A calls a method named insert() in Class B to save data into the database. Class A passed an ArrayList of Java Beans to the Class B's insert() method.

The logic to save the data was a plain - vanilla for loop :-

for ( int i = 0 ; i < number ; i++)
{

psSaveData = conOraleConnection.prepareStatement(insertSQL);
..........
..........
psSaveData.setString(1,dataBean.getId());
psSaveData.setString(2,dataBean.getName());
psSaveData.setString(3,dataBean.getAge());
..........
..........
psSaveData.executeUpdate();
}

Now, this piece of code was failing after the first 1000 rows !

We took sometime to methodically analyze the problem using an approach outlined at this link from BEA's Website. However, the problem persisted - either we missed something obvious or we were looking at something new. And then it occured to us :-

psSaveData = conOraleConnection.prepareStatement(insertSQL);

We finally figured out that the problem was caused by the statement marked in red. The line was actually telling the Oracle Database to precompile the same statement 1000 time !!

How does this matter ?

The Oracle Database contains a SQL Engine to deal with all SQL statements. The SQL Engine generally follows a two step process to execute a SQL Statement:-
  • parse : to check for syntax and semantic correctness.
  • execution plan : an optimized plan that details the instructions to execute the SQL statement.
The SQL Statement and the corresponding execution plan are stored together in a structure called a "Cursor". The Cursor is then stored in a special area of database memory called the "Shared Pool".

You can get handle to a cursor from a variety of languages like PL/SQL, Java, etc. You can then :-
  • Open the cursor.
  • Fetch the results
  • Close the cursor.
The Oracle database opens an "implicit cursor" for every SQL Statement that it encounters. Hence, a cursor is opened for every SELECT, INSERT, etc. statement that is issued to the SQL Engine.

Hence, you only need to prepare the "blueprint" once and execute it multiple times. The piece of code marked in red was preparing the "blueprint" 1000 times - as a result, 1000 cursors were opened !

We simply moved this line out of the for loop and solved one bottleneck.

We also noticed that the plain-vanilla JDBC Insert statement was not suitable for batch inserts. Well, that's another story :)


Thursday, March 20, 2008

Inspirations from Frogs

I was Googling around for something & came across this wonderful site about frogs. A page on the site is dedicated to "Frog Fables" - an eclectic of parables with a frog / toad as the topic of discussion.

I personally liked the story of "The Boiled Frog". I found it surprising that a frog's natural instincts are fine tuned to detect sudden changes in an environment, but not the slow changes that ultimately lead to the same change in the environment.

Well, this quote from the page, summarizes the story :-

" This parable is often used to illustrate how humans have to be careful to watch slowly changing trends in the environment, not just the sudden changes. Its a warning to keep us paying attention not just to obvious threats but to more slowly developing ones. "

Monday, March 17, 2008

Appending zeros in front of a number

I recently helped a colleague who had this simple requirement - to append zeros in front of a Number in a Java Method.

The purpose of the Method was to scan numbers between 1 and 999 and ensure that every number has three digits - the ones that have only two digits are appended by zeros.

The problem has multiple solutions & we were looking for the simplest possible solution. We tried a lot of solutions, starting with a simple for loop that counted the number of digits and appended zeros in front of it. We also looked at the Java API to see if a solution is already present.

However, we finalized two solutions that were very simple & elegant :-

Solution #1 ( JDK 1.5 onwards )

String.format("%03d", 1);
String.format("%03d", 10);
String.format("%03d", 100);


Solution #2 ( pre - JDK 1.5 )

NumberFormat objNumberFormat = new DecimalFormat("000");
objNumberFormat .format(Integer.parseInt( "1"));
objNumberFormat .format(Integer.parseInt( "10"));
objNumberFormat .format(Integer.parseInt( "100"));

We used Solution #2 to make the code reusable between JDK versions.