Turtles Galore

Blog Entries

Sunday, June 28, 2009

Interesting Quote

Re-use before Buy
Buy before build,
Build for Re-use
               
- John Zachman

Tuesday, May 19, 2009

Checking the file association in Windows from Command line

Checking the file association in Windows:

The "assoc" will let you know the file type associated with the extension
C:\>assoc .txt
.txt=txtfile

Now the "ftype" displays or modifies file types used in file extension associations
C:\>ftype txtfile
txtfile=%SystemRoot%\system32\NOTEPAD.EXE %1

Sunday, October 19, 2008

When two in Tango ...



When you look in to my eyes...
.. eye lids stop flittering
.. heart beats fast
.. minds freezes the frame of yours in my eye lids

Let us tango together..
.. the way no one did
.. the way no one will
.. let the eyes be in to my eyes

Let us not stop this...
.. as long as the clock ticks
.. as long as the earth rotates
.. as long as we can with stand standing

If you feel it is the last step we make ..
.. let our eyes lock together
.. let the warm hug seize the air separting us
.. let the God feel jealous of us

Let the tago continue ...
Let the eyes lock one another...
Let the time ends ...

Appropriate English Usage 1

When some one acknowledges me by saying "Thank you!",  my immediate reply used to be "No problem!". Today I learned that it is not traditional and sounds less polite.

Tuesday, October 14, 2008

Yahoo Query Language (YQL)

You may be interested of this Yahoo Query Language (YQL)  . This is really intereting as they are not exposing their database tables but enabling their domain model ( structured data) using SQL. Behind the scenes they can map to their tables or what ever it could be.

Yahoo! makes a lot of structured data available to developers, primarily through its web services. These services require developers to locate the right URLs and documentation to access and query them which can result in a very fragmented experience. The YQL platform provides a single endpoint service that enables developers to query, filter and combine data across Yahoo! and beyond. YQL exposes a SQL-like SELECT syntax that that is both familiar to developers and expressive enough for getting the right data. Through the SHOW and DESC commands we enable developers to discover the available data sources and structure without opening another web browser.

Wednesday, October 08, 2008

No One Needs to Know by Shania Twain

Tuesday, October 07, 2008

OMG - I Will Kill Her


Is that Agony or Jealousy?

Nice Song

Bit Girl y though!

Saturday, September 27, 2008

LOBO - I'D LOVE YOU TO WANT ME

Thursday, September 25, 2008

Testing Dog shit - Bull shit

Officials in an Israeli city are using DNA analysis to track dog owners who allow their pets to foul the streets.

Read more here!

On the other side people are suffering with no food and some got abundant money test the shit.

Sunday, September 21, 2008

What is certain is not certain!!!

Every human being wants is, feeling happy every second we live and feel innocent and try to feel innocent as the consciousness becomes devils advocate at every step we make. From the moment we wake up till we retire to sleep the uncertain thing is how to be happy. No matter what - every effort boils down to our own happiness. This is not debate on - what is good? what is not? or, Being selfish is good or bad?.

Apart from the inflection points that intrude we make our life complex in all aspects just to keep ourself happy and finally sacrificing it.

How to be happy? For certain, there is no blueprint as solution to this problem.

Ease your mind by reducing uncertainties. Again there is a lot of thought process involved to achieve this that really make life unhappy as it is very difficult to make choices.

Feel proud and be happy where you stand now rather than feeling sad about it.
Know yourself ...
Keep the faith in you...
Remember! you can do...
Forget the fatigue of failure...
Work on what is true... what is noble... what is real...
Enjoy of the little success rather that feeling bad of failure ....
Never feel sorry for yourself...
Never pity yourself for your situation...
Have the passion to live ...
Keep the passion to be happy...
Remove the sorrow from your brain...

Always the certain is "Life moves on - Time goes on". So live in reality. And know you are the luckiest always! What you think is what you get!

Saturday, September 13, 2008

Yael Naim

Beauty!

Today we casually entered the Apple show room on our way to Central Park. I was shocked for a moment as I saw more people than people at Port Authority in the peak hours. After making my way into the apple showroom I understood it is due to the new IPod release. From a 2 year or so - cute little girl to 80 years plus women (Hah! don't think that way - accidental coincidence both where females) fascinated and engrossed in the touch of Apples IPod. It is like they are more impressed and engrossed in the IPod rather than the song it is playing. Really it is the marvels of innovation. After that we went to Central park and I was again surprised with the Opera by a girl who is continuously singing with small breaks in between. But it is a real surprise that she is not bothered about the strange question marked faces around and her attention is intact on the song that she is singing. Not a single way out with the snaps people are shooting at her. What I realized she is 100% confident. After few moments, I diverted my mind to the nature around. All the thoughts made their way in to other aspect - the beauty (ah! not of that girl but of central park). Again a bit of introspection - can I be like that confident? These sinusoidal waves didn't touch me as I was already smitten by beauties - IPod, Central park and the bridge in the central park.

Friday, September 05, 2008

Subversion related files maven-war-plugin

Today I found the subversion related files are being copied to classes and war file that is generated.

Here is the way to filter the .svn folder:

<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<warName>crm_itools</warName>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<resource>
<excludes>
<exclude>.svn</exclude>
</excludes>
</resource>
</configuration>
</plugin>

Wednesday, July 02, 2008

My first maven2 plug-in XML2XSD(maven-xml2xsd-plugin)

Trang api allows to produce XSD from sample XML files.

Say Echo1.xml, Echo2.xml, Echo3.xml are sample xml files and Echo.xsd is the schema name to generate. The we can use Trang to generate the xsd as shown below.
java -jar trang.jar Echo1.xml Echo2.xml Echo3.xml Echo.xsd 

I needed a maven plug-in to do this work along with the project build.

Here is the code for my maven2 plug-in.

Xml2XsdMojo 
[sourcecode language='java']
package com.ascendant.maven2.mojo;

import java.util.ArrayList;
import java.util.List;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.StringUtils;

import com.thaiopensource.relaxng.translate.Driver;

/**
 * Creates Xml Schema Document based on the input xml files.
 * 
 * @goal generate
 */
public class Xml2XsdMojo extends AbstractMojo {

    /**
     * @parameter expression="${xmlFiles}"
     */
    private String xmlFiles;

    /**
     * @parameter expression="${xsdFile}"
     */
    private String xsdFile;

    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("xml files:" + xmlFiles);
        getLog().info("xsd file:" + xsdFile);

        String[] cmdArgs = (xmlFiles + ", " + xsdFile).split(",");
        List<String> fileLocations = new ArrayList<String>();
        for (String file : cmdArgs) {
            fileLocations.add("src/main/resources/"+StringUtils.strip(file));
        }

        Driver.main(fileLocations.toArray(new String[fileLocations.size()]));
        getLog().info(xsdFile + " generated.");
    }
}

[/sourcecode]


Maven POM
---------
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.ascendant.maven2</groupId>
 <artifactId>maven-xml2xsd-plugin</artifactId>
 <packaging>maven-plugin</packaging>
 <name>xml2xsd</name>
 <version>1.0-SNAPSHOT</version>
 <description>XML2XSD Maven Plugin</description>
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.5</source>
     <target>1.5</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-plugin-plugin</artifactId>
    <version>2.3</version>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>org.apache.maven</groupId>
   <artifactId>maven-plugin-api</artifactId>
   <version>2.0.9</version>
  </dependency>
  <dependency>
   <groupId>org.apache.maven</groupId>
   <artifactId>maven-project</artifactId>
   <version>2.0.9</version>
  </dependency>
  <dependency>
   <groupId>commons-lang</groupId>
   <artifactId>commons-lang</artifactId>
   <version>2.3</version>
  </dependency>
  <dependency>
   <groupId>com.thaiopensource</groupId>
   <artifactId>trang</artifactId>
   <version>20030619</version>
  </dependency>
 </dependencies>
</project>

Usage:
<plugins>
 <plugin>
  <groupId>com.ascendant.maven2</groupId>
  <artifactId>maven-xml2xsd-plugin</artifactId>
  <version>1.0-SNAPSHOT</version>
  <configuration>
   <xmlFiles>echoRequest.xml, echoResponse.xml</xmlFiles>
   <xsdFile>echo.xsd</xsdFile>
  </configuration>
 </plugin>
</plugins>
[/CODE]
Add the above section to your project pom.

Command to generate XSD:
mvn com.ascendant.maven2:maven-xml2xsd-plugin:1.0-SNAPSHOT:generate

Sunday, June 15, 2008

Really scary stuff

Finding the solution - Explore the possibilities

Pigeon Solves Classic Problem

Thursday, May 15, 2008

Power of bean factory-method Spring Framework

Even though bit old article(http://www.jroller.com/raible/entry/sending_velocity_based_e_mail) it helped me.

SimpleMailMessage encapsulation does a great job with the power of Spring.

<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from"><value><![CDATA[Human Resources <hr@raibledesigns.com>]]></value></property>
<property name="subject"><value>Your application has been received</value></property>
</bean>

But how to configure to adress?

<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.from}" />
<!-- @ See org.springframework.mail.SimpleMailMessage.setTo(String) -->
<property name="to" value="a@aol.com"/>
<property name="subject" value="${mail.subject}" />
<property name="replyTo" value="${mail.replyTo}" />
</bean>

Well that is good. And to send multiple address this works fine.

<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.from}" />
<!-- @ See org.springframework.mail.SimpleMailMessage.setTo(String[]) -->
<property name="to">
<list>
<value>a@aol.com</value>
<value>b@aol.com</value>
<value>c@aol.com</value>
</list>
</property>
<property name="subject" value="${mail.subject}" />
<property name="replyTo" value="${mail.replyTo}" />
</bean>


I wanted to send the email to multiple people and also the would like to pull the data from app.properties file.

<context:property-placeholder location="classpath:app.properties" />

I am not sure how to induce comma delimited emails as to address. Bean Factory Method helped me to finish this:

<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.from}" />
<!-- @ See org.springframework.mail.SimpleMailMessage.setTo(String[]) -->
<property name="to">
<bean factory-method="split" class="org.apache.commons.lang.StringUtils">
<constructor-arg value="${mail.to}"/>
</bean>

</property>
<property name="subject" value="${mail.subject}" />
<property name="replyTo" value="${mail.replyTo}" />
</bean>

Friday, April 18, 2008

Power of bit operations

Today I received a puzzle:

Let's say variable x is defined as an int and its value is a positive number.
Write an expression that will be true, if and only if, x is a power of 2.
It should be a simple boolean expression.

It does not have to be java.
Could be C or Perl or any other reasonable language

Try to refrain from code like

private boolean isPowerOfTwo(int x) {
// many lines of code go here
}

Here you go:

public class Test {

public static void main(String[] args) {
int x = 31;
System.out.println(Math.floor(Math.log10(x) /Math.log10(2)) == Math.ceil(Math.log10(x) /Math.log10(2)));

// Simplest Solution
System.out.println((x & (x-1)) == 0);
}
}

Monday, March 24, 2008

Innovative Publishing Website Issuu.com

Friday, January 25, 2008

Nice Tip

It is good when downstream changes are more expensive then you are willing to spend some complexity now, in order to gain flexibility in the future.

Friday, August 03, 2007

WTF 1

I was looking at the code in one of the projects:

[CODE]
private int getParamAsInt(HttpServletRequest request, String param,
int defaultValue) {
String pageNumber = request.getParameter(param);
if (pageNumber == null) return defaultValue;
int iPageNumber = 1;
try {
iPageNumber = Integer.parseInt(pageNumber);
} catch (Exception e) {
iPageNumber = defaultValue;
}
return iPageNumber;
}
[/CODE]

What is wrong with the code?

1) Cannot test unless you use mock HttpServletRequest
2) No reusability
3) Unnecessary variable declaration.


[CODE]
private int geAsInt(String value, int defaultValue) {
if (value == null)
return defaultValue;

try {
return Integer.parseInt(value);
} catch (Exception e) {
return defaultValue;
}
}
[/CODE]

Multiple return statements still ugly. But fair than before.

Saturday, July 14, 2007

Spotted bunnies near to my office bus stop...




Saturday, June 30, 2007

Freemarker support by Spring Modules

Spring Modules support for template engines is excellent.

The code base is organized into the following packages with nice abstraction.
1) Providers
2) Sources
3) Resolvers
4) Support

Providers: Supports Freemarker, Velocity, Groovy, Stemp, Webmacro and XSLT template engines.
Sources: Template as String, as File and Spring Resource.
Resolvers: Bunch of resolvers to resolve the template.
Support: Template and TemplateSet support classes.

Here is the class which I wrote to support RegularExpression based resolvers.

/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.ascendant.template.resolvers;

import java.io.IOException;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springmodules.template.TemplateSource;
import org.springmodules.template.TemplateSourceResolver;
import org.springmodules.template.sources.ResourceTemplateSource;

/**
* A TemplateSourceResolver based on
*
* @author Ramesh Mandaleeka
*/
public class PathMatchingTemplateSourcePatternResolver implements TemplateSourceResolver, InitializingBean {

private String locationPattern;
private PathMatchingResourcePatternResolver resolver;

/**
* Default constructor (javabean support).
*/
public PathMatchingTemplateSourcePatternResolver() {
resolver = new PathMatchingResourcePatternResolver();
}

public PathMatchingTemplateSourcePatternResolver(String locationPattern) {
this.locationPattern = locationPattern;
resolver = new PathMatchingResourcePatternResolver();
}

public void afterPropertiesSet() throws Exception {
if ( locationPattern == null || "".equals(locationPattern)) {
throw new Exception("Required property 'locationPattern' is not set");
}
}

public final TemplateSource resolveTemplateSource(String name) {

TemplateSource templateSource = null;

if ( name == null || "".equals(name)) {
templateSource = null;
} else {
// Do I need to check 'locationPattern' is null or not? nah!
try {
Resource[] resources = resolver.getResources(locationPattern);
for (int counter = 0; counter < resources.length; counter++) {
if ( name.equals(resources[counter].getFilename())) {
templateSource = new ResourceTemplateSource(resources[counter]);
break;
}
}

} catch (IOException e) {
e.printStackTrace();
}
}
return templateSource;
}

//============================================== Setter/Getter =====================================================

public String getLocationPattern() {
return locationPattern;
}

public void setLocationPattern(String locationPattern) {
this.locationPattern = locationPattern;
}
}

The config file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<bean id="pathMatchingTemplateSourcePatternResolver"
class="org.springmodules.template.resolvers.PathMatchingTemplateSourcePatternResolver">
<property name="locationPattern" value="classpath*:*.ftl"></property>
</bean>
</beans>

The Client class:
package com.ascendant.templates;

//~--- non-JDK imports --------------------------------------------------------

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springmodules.template.Template;
import org.springmodules.template.TemplateSet;
import org.springmodules.template.providers.freemarker.FreemarkerTemplateSetFactoryBean;
import org.springmodules.template.resolvers.PathMatchingTemplateSourcePatternResolver;


public class App {

public static void main(String[] args) {
try {
// Prepare properties
Properties p = new Properties();
p.put("datetime_format", "EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'");

// set properties
FreemarkerTemplateSetFactoryBean ftsfBean = new FreemarkerTemplateSetFactoryBean();
ftsfBean.setSettings(p);

// reuse true
ftsfBean.setReuseTemplateSet(true);

// get template file as Resource
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/com/sonybmg/applicationContext.xml");
ftsfBean.setTemplateSourceResolver((PathMatchingTemplateSourcePatternResolver)applicationContext.getBean("pathMatchingTemplateSourcePatternResolver"));
ftsfBean.afterPropertiesSet();

TemplateSet ts = (TemplateSet) ftsfBean.getObject();
Template t = ts.getTemplate("test.ftl");

// Build the data-model
Map root = new HashMap();
root.put("message", "Hello World!");
root.put("date", new Date());
System.out.println(t.generate(root));
} catch (Exception e) {
e.printStackTrace();
}
}
}

test.ftl

<html>
<head>
<title>FreeMarker Example Web Application 1</title>
</head>
<body>
${message} ${date?datetime}
</body>
</html>

Sunday, June 17, 2007

Really funny one

Saturday, June 09, 2007

The cooks thesaurus

The Cook's Thesaurus is a cooking encyclopedia that covers thousands of ingredients and kitchen tools. Entries include pictures, descriptions, synonyms, pronunciations, and suggested substitutions.

Check it here:
http://www.foodsubs.com

Monday, May 28, 2007

Desert Rose....

My favorite song

Thursday, May 03, 2007

Gang Of Four Software Design Patterns Crossword

Today I saw a puzzle based on Gang of Four(GOF) design patters. Here is the screenshot of it.



You can go and give it a shot:
Gang Of Four Software Design Patterns Crossword

Wednesday, April 11, 2007

Configuring CruiseControl on Windows

Today I found a nice screencast on Configuring CruiseControl on Windows. See below:

Sunday, February 25, 2007

Birds on the tree...



by Me.

Monday, December 18, 2006

Appfuse2.0 backend as oracle

Configuring Appfuse 2.0 with oracle backend.

Assumption:
Database tables are there already.

Step 1:
Remove appfuse from local maven repository
In my case: .m2\repository\org\appfuse

Step 2:
Install Oracle Driver to your local repository:
mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=oracle.jdbc -DartifactId=ojdbc14 -Dversion=10.1.0.5 -Dpackaging=jar -DgeneratePom=true

Step 3:
mvn archetype:create -DarchetypeGroupId=org.appfuse -DarchetypeArtifactId=appfuse-archetype-basic -DarchetypeVersion=1.0-SNAPSHOT -DgroupId=com.sonybmg -DartifactId=archipelago -DremoteRepositories=http://static.appfuse.org/repository

Step 4:
cd archipelago

Step 5:

Change pom.xml

Comment:
<!--
<jdbc.groupId>mysql</jdbc.groupId>
<jdbc.artifactId>mysql-connector-java</jdbc.artifactId>
<jdbc.version>5.0.3</jdbc.version>
-->

Add:
<jdbc.groupId>oracle.jdbc</jdbc.groupId>
<jdbc.artifactId>ojdbc14</jdbc.artifactId>
<jdbc.version>10.1.0.5</jdbc.version>

Add just after junit dependency:

<dependency>
<groupId>${jdbc.groupId}</groupId>
<artifactId>${jdbc.artifactId}</artifactId>
<version>${jdbc.version}</version>
<scope>war</scope>
</dependency>

Step 6:

cd to archipelago/src/main/resources/
Rename jdbc.properties to database.properties :

Open archipelago/src/main/resources/database.properties :

Remove entries:


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/appfuse?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8
jdbc.username=test
jdbc.password=test

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
# Bryan why can't I use MySQL5InnoDBDialect here?
hibernate.connection.username=test
hibernate.connection.password=test
hibernate.connection.url=jdbc:mysql://localhost/appfuse?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8
hibernate.connection.driver_class=com.mysql.jdbc.Driver



Add entries:

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=<<JDBC URL>>
jdbc.username=Archi3
jdbc.password=archi3

hibernate.dialect=org.hibernate.dialect.Oracle9Dialect
hibernate.connection.username=Archi3
hibernate.connection.password=archi3
hibernate.connection.url=<<JDBC URL>>
hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver


Note: Replace <<JDBC URL>> with your Oracle JDBC Url.

Step 7:
mvn war:inplace

Step 8:
Copy archipelago\src\main\webapp\WEB-INF\classes\database.properties to
1) archipelago\target\war\work\appfuse-spring-2.0-SNAPSHOT\WEB-INF\classes\database.properties
2) archipelago\target\war\work\appfuse-web-common-2.0-SNAPSHOT\WEB-INF\classes\database.properties

Step 9:
mvn jetty:run

Tip: Create a folder structure with only the property files and other file you modified. Copy the whole directory every time to the work when ever you use mvn war:inplace command.

Friday, November 17, 2006

Macaca mulatta

Macaca mulatta - Scientific name of monkey.

Here is a nice site I found today Animal Diversity Web. an online database of animal natural history, distribution, classification, and conservation biology.

Monday, November 13, 2006

Speeches & Lectures by Mr. APJ Abdul Kalam

To be honest, I am sure, I'm motivated, influenced by good and bad in the same fashion. And the ascertainment of the influences will be lasting long in case of a bad influence.

Let us from bad influences to good. Here are the speech archives delivered by Mr. APJ Abdul Kalam:
http://presidentofindia.nic.in/scripts/speecheslectures.jsp

Sunday, November 12, 2006

Aptana - JavaScript-focused IDE

Today I encountered a nice tool called Aptana the JavaScript-focused IDE. There is an eclipse plugin also available. Certainly I am going to use it for the dimensions web application I am working on.

Aptana is a robust, JavaScript-focused IDE for building dynamic web applications. Highlights include the following features:

* Code Assist on JavaScript, HTML, and CSS languages, including your own JavaScript functions

* Outliner that gives a snapshot view of your JavaScript, HTML, and CSS code structure

* NEW: FTP/SFTP uploading, downloading and synchronization

* Error and warning notification for your code

* Support for Aptana UI customization and extensions

* Cross-platform support

Thursday, October 26, 2006

Naked Truth about programming

Today I encountered a quote. Really naked truth...

“Programming is like sex, one mistake
and you have to support it for
the rest of your life. ”

- Michael Sinz

Wednesday, October 25, 2006

Yahoo! Bookmarks !!!

Yahoo bookmarks released http://beta.bookmarks.yahoo.com/tools/ a bookmarks site.

Sunday, October 22, 2006

E-Diwali Running and drinking milk man!!!




I'm away from India form the past one year. Yeah!!! Diwali celebrations!!!

Huh!!! confined with flash animated crackers. To get a feel of it crackers kept the volume to the max.

Money, money, money!!! Running and drinking milk man!!!.

Songbird™ - Desktop Web player built from Mozilla!!!

Today I found a nice tool Songbird™ is a desktop Web player, a digital jukebox and Web browser mash-up. Like Winamp, it supports extensions and skins feathers. Like Firefox®, it is built from Mozilla®, cross-platform and open source.

Download is available at http://www.songbirdnest.com/

Thursday, September 07, 2006

Free Service-oriented Architecture for Dummies book

You can get the book Service-oriented Architecture for Dummies from the following URL: https://www14.software.ibm.com/webapp/iwm/web/preLogin.do?lang=en_US&source=swg-soa

All you need is just registering to the IBM site.

GTDMail

Today I found an excellent firefox plugin: GTDGmail is a Firefox extension that integrates the highly effective methodology of "Getting Things Done" into the popular email service Gmail.

Tuesday, September 05, 2006

Spider in the window

Spider in the window
Sep 5, 2006 - 8 Photos

Sunday, August 27, 2006

Thread States

Thursday, August 24, 2006

Weight watchers!!!

Here is one site for weight watchers http://www.sparkpeople.com/. You can get free diet plan.

TNS Ping

How can we ensure that the entries in tnsnames.ora is correct?


The tnsping utility enables to test the individual entries(alias) of tnsnames.ora. Just at the command prompt execute:


tnsping <<alias>>


TNS: Transient Network Substrat a protocol where oracle uses to communicate with the server.


Which will specify if the host is reachable or not. And also helps you to find out which tnsnames.ora file is being used in case mutiple oracle home are there.


About tnsnames.ora

This file contains the syntax information for the entries to be put in any tnsnames.ora file The entries in this file are need based. There are no defaults for entries in this file that Sqlnet/Net3 use that need to be overridden


Typically you could have two tnsnames.ora files in the system, one that is set for the entire system and is called the system tnsnames.ora file, and a second file that is used by each user locally so that he can override the definitions dictated by the system tnsnames.ora file.


The entries in tnsnames.ora are an alternative to using the names server with the onames adapter. They are a collection of aliases for the addresses that the listener(s) is(are) listening for a database or several databases.

Interesting sequence of words

Read the sentence carefully...


"I do not know where family doctors acquired illegibly perplexing handwriting nevertheless, extraordinary pharmaceutical intellectuality counterbalancing indecipherability, transcendentalizes intercommunications' incomprehensibleness."


In the above sentence the Nth word has N letters. e.g. 3rd word has 3 letters, 8th word has 8 letters and so on.

Coverting stack trace of an exception in to a String

Today I am executing some batch jobs. I need to log the batch starting and ending events in to the DB. In case of an exception I need to insert the exception stack trace in to the Database.


Here is the method to get the stack trace as a String:


public static String getStackTraceAsString(Throwable exception) {

// can use ByteArrayOutputStream baos = new ByteArrayOutputStream();

StringWriter sw = new StringWriter();

PrintWriter pw = new PrintWriter(sw);

exception.printStackTrace(pw);

sw.close();


return pw.toString();

}


We can use java.io.ByteArrayOutputStream or java.io.StringWriter.

variable args

Today I though of learning about the new features in J2SE 5.0.


The varargs feature described below:


http://java.sun.com/developer/JDCTechTips/2005/tt0104.html


One of the examples :


public class WhichOne {


WhichOne(Integer... size) {

System.out.println("Var Args version.");

}


WhichOne(int i, int j) {

System.out.println("Version with int args.");


}


WhichOne(Integer i, Integer j) {

System.out.println("Version with Integer args.");

}


public static void main(String[] args) {

System.out.println("Call w/ two arg:2,3");

new WhichOne(2, 3);

System.out.println("Call w/ Integer two arg: 2,3");

new WhichOne(new Integer(2), new Integer(3));

}


}


Even with the varargs version of the constructor, the most specifically-matching constructor is called. So only WhichOne(int i, int j) and WhichOne(Integer i, Integer j) constructors are the specific ones so they will be called.


But if we removed WhichOne(Integer i, Integer j) and execute the program Autoboxing comes in to the picture and we get


Call w/ two arg:2,3

Version with int args.

Call w/ Integer two arg: 2,3

Version with int args.


rather than the var arg version. When dealing with primitive classes and the corresponding wrapper classes autoboxing is done.


and the another example:


public class VarGreeter5 {

public static void printGreeting(String[] names) {
for (String n : names) {
System.out.println("Hello " + n + ". ");
}
}

public static void main(String... args) {
printGreeting("Paul", "Sue");
}
}

won't compile as the printGreeting("Paul", "Sue"); statement is a call to a method printGreeting which takes two arguements String, String. And the class is not having any such method.
}

Yet another Java Puzzle

public class Test

{

public static void main(String[] args)

{

double d1 = Double.MAX_VALUE;

double d2 = Double.MAX_VALUE + 1;

System.out.println(d1 == d2);

}

}


Surprise to me: The answer is true

Yet another Java Puzzle

What will be the output of the following:

public class Test

{

public static void main(String[] args)

{

System.out.println(Integer.MAX_VALUE + 1);


System.out.println(Long.MAX_VALUE + 1);

System.out.println(Long.MAX_VALUE + 1L);


System.out.println(Double.MAX_VALUE + 2);

System.out.println(Double.MAX_VALUE + 2.0D);


System.out.println(Float.MAX_VALUE + 2);

System.out.println(Float.MAX_VALUE + 2.0F);


System.out.println( (Double.MAX_VALUE + 1.0D == Double.MAX_VALUE + 2.0D) );

}

}


---------- java1.4 ----------

-2147483648

-9223372036854775808

-9223372036854775808

1.7976931348623157E308

1.7976931348623157E308

3.4028235E38

3.4028235E38

true


---------- java5 ----------

-2147483648

-9223372036854775808

-9223372036854775808

1.7976931348623157E308

1.7976931348623157E308

3.4028235E38

3.4028235E38

true


The result is type int only if both operands are type int. Even if we multiply two int values, the product is an int, not a long. Integer arithmetic never throws an exception if an overflow occurs. The only exception that it does throw is an ArithmeticException if we attempt to divide by zero during a division or a remainder operation.

Mozilla Fileupload tweak

Today I unexpectedly pasted File upload in the address bar in Mozilla. And immediately it showed me http://validator.w3.org/file-upload.html


Update: It is a the search result of the webpage for the text I pasted.

Fallback mechanism

Today I started WebWork framework. Here is the class that captured by attention com.opensymphony.webwork.util.WebWorkTypeConverter.


public Object convertValue(Map context, Object o, Class toClass) {



if (toClass.equals(String.class)) {



return convertToString(context, o);



} else if (o instanceof String[]) {



return convertFromString(context, (String[]) o, toClass);



} else if (o instanceof String) {



return convertFromString(context, new String[]{(String) o}, toClass);



} else {



return performFallbackConversion(context, o, toClass);



}



}


protected Object performFallbackConversion(Map context, Object o, Class toClass) {



return super.convertValue(context, o, toClass);



}


Fallback mechanism is something a final resort kid of. In the above code we are using various conditions, if everything is failed as a final attempt we are calling performFallbackConversion() which will delegate the call to the super class. In this case we are falling back on the parent class.

Javascript and Java method difference

In Java:


String s = "010"; System.out.println(Integer.parseInt(s));


Output: 10


In Javascript:


alert(parseInt('010'));


Output: 8


The Integer.parseInt() method parses the String argument and returns a signed decimal integer, where as parseInt() in javascript treats the String as an octal number as it is preceded by 0 and evaluates to 8.

Java Script Pop-up window

Here is the good way to open a popup window when we click on an hyperlink:


<a href="www.google.com" target="popup" onclick="window.open(this.href, 'popup', 'width=240,height=180,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0').focus(); return false;">test link</a>

Java Questions

Here are some tough java questions:


Question 1:

Assume a class Person with :


...

private String surName = "Doe";


public Person(String surName) {



surName = surName;



}


public String getSurName() {



return surName;



}

...


and a code fragment :

...

Person p1 = new Person(null);

Person p2 = new Person("Smith");


System.out.println(p1.getSurName());

System.out.println(p2.getSurName());


what output will this produce?


If your answer is :

null

Smith

you are wrong. It will print

Doe

Doe


Reason: Shadowing of varibles. The parameter is local variable and is shadowing a global variable. So the assignment surName = surName; will cause no effect. The fix: this.surName = surName; or change the paramter name so that it won't match with instance varible name.


Question 2:


public class Test {



private static String name;




public static void main(String[] args) {





if ( name instanceof String) {



System.out.println("Name is a String");



} else {



System.out.println("Surprising!!! not tell what it is?");



}



}



}


The output is : Surprising!!! not tell what it is?


Reason: The instanceof operator checks the type of the value at the Runtime.


Question 3:


What will happen if we execute the following 3 statements?

String s = "1.0";

Integer i = new Integer(s);

System.out.println(i);


The output: Compiles. But throws java.lang.NumberFormatException


Question 4:


When running the method main in the following class, what is the output?


public class StaticFieldsAndMethods {



static int counter () {



return counter;



}


static int i = counter ();

static int counter = 1;


public static void main (String[] args) {



System.out.print ("i = " + i);



}



}


Output: i=0


Reason: Static field counter may be used in static method before its declaration in a class.

Invocation of method counter occurs before initialization of the field counter, so method counter returns default value of the field counter (namely 0).


Question 5:


What will be the output:


public class Test {



public static void main (String[] args) {



employee(1.0f/0);



}




public static void employee(float monthly_salary) {



if (monthly_salary >= 0.0) {



System.out.println( 12.0 * monthly_salary);



}

else



throw new IllegalArgumentException("illegal monthly salary");




}



}


Output: Infinity


Reason: Infinity is a legal value for float.

Notepad Easter Egg!!!

If you haven't seen this...



1) Open an empty notepad file.

2) Type "Bush hid the facts" (without the quotes and dont press enter after the line)

3) Save it as whatever you want.

4) Close it, and re-open it.



Is it just a really weird trick/bug?

-Xlint: option failure in J2SE 1.5.0_06

The -X options are non-standard and we must not rely on them.


The following class has case statement with out break. This fallthrough can be suppress using @SupressWarning("fallthrough") annotation.


public class Test {



public static void main(String[] args) {



System.out.println("Hello World!");

int i = 3;

switch(i) {



case 3: System.out.println(3);

case 2: System.out.println(2);

case 1: System.out.println(1);

case 0: System.out.println(0);

default: System.out.println(1);



}



}



}


Let us compile the class above as: javac -Xlint:all Test.java


The compilation process will give 4 warnings.


Note: -Xlint:{all,deprecation,unchecked,fallthrough,path,serial,finally,-deprecation,

-unchecked,-fallthrough,-path,-serial,-finally}Enable or disable specific warnings


Now let us disable unchecked warnings. That has nothing to do with fallthrough.


javac -Xlink:-unchecked Test.java


The above compilation will not give an warnings.

Annotations in J2SE5.0

Possible annotation targets are the following declared in the ElementType enum:


ElementType.CONSTRUCTOR : for declared constructors

ElementType.ANNOTATION_TYPE : for annotation interfaces

ElementType.FIELD : for declared fields

ElementType.LOCAL_VARIABLE : for local variable declarations

ElementType.METHOD : for declared methods

ElementType.PARAMETER : for declared parameters

ElementType.PACKAGE : for package declarations

ElementType.TYPE : for classes, interfaces and enums.


The correct sintax for creating custom annotations follows:


RetentionPolicy enum:


RetentionPolicy.CLASS: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

RetentionPolicy.RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

RetentionPolicy.SOURCE: Annotations are to be discarded by the compiler.


@Retention(RetentionPolicy.RUNTIME) // can be RUNTIME,CLASS or SOURCE

@Target(ElementType.CLASS) //can be CLASS,METHOD,FIELD,PACKAGE,etc...

@Documented

public @interface MyAnnotation {

public String value();

public String otherAttribute();

}


JVM will instance annotations at runtime for setting and retrieving values from them through the reflection API.

Widening Primitive Conversion

Widening Primitive Conversion

Narrowing Primitive Conversions

Narrowing Primitive Conversions

Covariant Return Types

New feature in J2SE 5.0


Consider the following classes:


class Super {



public Object getValue() {





return new Object();





}



}


class SubClass extends Super {



public String getValue() {





return new String("Dude");





}



}


public class Test {



public static void main(String[] args) {





Super s = new SubClass();






System.out.println(s.getValue());





}



}


Now compile the Test class using the following command :


javac -source 1.4 Test.java


output:

Test.java:8: getValue() in SubClass cannot override getValue() in Super; attempting to use incompatible return type

found : java.lang.String

required: java.lang.Object

public String getValue() {

^

1 error


Now compile it using the following command:

javac -source 1.5 Test.java


Now this will compile. There will be no compile time or runtime exception.


We can return a sub class for a overriden methods return type.

Intersection of two ArrayLists

Consider this scenario:


We got two lists with set of records. We wanted the records, that exists in both the lists.


import java.util.*;

class Test

{



public static void main(String[] args) {



List<String> l1 = new ArrayList<String>();

l1.add("1");

l1.add("2");

l1.add("3");List<String> l2= new ArrayList<String>();

l2.add("4");

l2.add("2");

l2.add("3");


List<String> l3 = l2;

l3.retainAll(l1);

System.out.println(l3);



}



}


The boolean retainAll(Collection c) of Collection interface does the job.


Want to get unique records in the combined list:


class Test

{



public static void main(String[] args) {



List<String> l1 = new ArrayList<String>();

l1.add("1");

l1.add("2");

l1.add("3");List<String> l2= new ArrayList<String>();

l2.add("4");

l2.add("2");

l2.add("3");




// merget l1 in to l2

l2.addAll(l1);




// use TreeSet to eliminate the duplicates...

l2 = new ArrayList<String>(new TreeSet<String>(l2));

System.out.println(l2);



}



}

Boxing and Unboxing

The boxing of an int value in the range from −128 to 127 returns an object with not just the same value, but also the same identity.


public class Test {

public static void main(String [] args) {

Integer i1 =600; // boxing
Integer j1= 600; // boxing

assert i1 !=j1;

Integer i2 =1; // boxing
Integer j2= 1; // boxing

// same object references as the value is in range of -127 to128
assert i2 ==j2;

}

Time Management Tool

Do you need to send status reports? How much time you worked and activities you did in a week to your boss? Certainly you are dead to do that kind of tracking. Here is a excellent tool I found which will do the Job the best.


What you need to do is enter a task name and start doing the job. When you want start a new task enter that task. Finally it shows how much time you spent on each task on what day and what time.


http://tinytimetracker.sourceforge.net/php/

Finding encoding of the file reading

import java.nio.charset.Charset;

import java.io.InputStreamReader;

import java.io.FileInputStream;

import java.io.File;




// Returns the canonical name of the encodingtype used in this JVM instance.
String defaultEncoding = Charset.defaultCharset().name();



or



String defaultEncoding = new InputStreamReader(new FileInputStream(new File("c:\\defragmentlog.txt"))).getEncoding();

Java version of feed2js using Rome!!!

The feed2js was developed in php. Here is the java version of feed2js.

Major chunk of work was done by org.apache.commons.lang.StringEscapeUtils and Rome

Filed a bug at the Java Developer Connection

Today I filed a bug at the Java Developer Connection. Here are the details:


import java.util.*;


public class Test {


public static void main(String[] args) {
int a [] = {1,2,3}; int b[] ={4,5,6}; System.out.println(Arrays.asList(a,b));
}

}


This simple program caused exception in the java compiler. That means I am not able to compile the above class. A small modification works fine:


import java.util.*;


public class Test {


public static void main(String[] args) {
Integer a [] = {1,2,3}; Integer b[] ={4,5,6}; System.out.println(Arrays.asList(a,b));
}

}


This problem persists with all the primitive types I guess. I tested for short and int variations.

Wufoo - Making forms easy, fast & fun.

Here is a website to create html forms quickly.
Wufoo - Making forms easy, fast & fun.
Search

About Me

Ramesh Mandaleeka
Innovation is my passion. Java, J2EE are the foundations of my trade. Spring framework, Hibernate, Open Standards are the tools of my trade. I enjoy coding and designing enterprise applications. I am on the run to become an IT Enterprise Architect.

Subscribe feeds via e-mail
Subscribe in your preferred RSS reader

Categories

Subscribe RSS Feed Recent Comments

Technorati

Technorati
My authority on technorati
Add this blog to your faves