Thursday, November 12, 2009
Prototypejs 1.6 clash with JSON !!
This article could be a time-saver, prototype.js breaks Firefox 3.5 native JSON
Monday, November 02, 2009
Prototype - Event.fire exception to be handled for IE
Exception was being thrown in Event.fire API that needed a special treat.
The highlighted workaround worked for me:
fire: function(element, eventName, memo) {
// ...
if (document.createEvent) {
element.dispatchEvent(event);
} else {
try{
element.fireEvent(event.eventType, event);
} catch(error) {
// Error: No such interface supported (IE)
element.fireEvent(event.eventType);
}
}
return event;
}
Example:Event.fire('myhidden_element_id', 'custom:change');Saturday, October 31, 2009
mysql-java-connector: ResultSet getObject failure on Timestamp column if null
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
Class.forname("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://host:port/database",
"username", "password");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT timestamp_column FROM mytable");
while(rs.next()) {
rs.getObject("timestamp_column");
}The cause of the failure was due to null value in timestamp_column !
The solution suggested about (zeroDateTimeBehavior=convertToNull) in the article, helped me overcome the failure.
All you need to do is:
Connection connection = DriverManager.getConnection(
"jdbc:mysql://host:port/database?zeroDateTimeBehavior=convertToNull",
"username", "password");Wednesday, October 28, 2009
Eclipse Editor - Setting Line Delimiter Style
Finally, found the way of setting the line preferences for Eclipse.
It is located under: Windows > Preferences > General > Workspace

Tuesday, September 15, 2009
Lynx - Text Only Browser for Windows!
Got hold of Lynx on windows, which is a cool text browser I have been using on remote servers!
Well, its easy to get started, download and configure the lynx.bat and lynx.cfg files.
Friday, September 11, 2009
PHPTAL - Template Attribute Language for PHP
Thursday, August 27, 2009
Doc Comment could be a source of data!!!
PHP data file: CommentDataClass.php
/**Retrieving data: Data.php
Doc Comment could be a SOURCE OF DATA
This could be your data in string format!!
*/
class CommentDataClass { }
?>
include_once 'CommentDataClass.php';Well, this is just for fun, we don't recommend it for serious use :)
// Taking advantage of PHP 5.x Reflection,
// Refer: http://in.php.net/oop5.reflection
$reflectedClass = new ReflectionClass('CommentDataClass');
if(preg_match("/\/\*\*(.*)\*\//s",
$reflectedClass->getDocComment(), $matches)) {
$data = $matches[1];
$data = trim($data);
var_dump(explode("\n", $data));
}
?>
Friday, July 31, 2009
Apache 2.0 with PHP 5.3.0 on Windows
The builds for windows is available at http://windows.php.net/download/
Download the VC6 x86 Build of PHP 5.3.0 build and unzip.
NOTE: VC9 x86 Build of PHP 5.3.0 build might not work with Apache 2.0 !!
You will need to make the following changes in your httpd.conf
LoadModule php5_module "c:/path_to_your/5.3.0/php5apache2.dll"
PhpIniDir "c:/path_to_your/5.3.0"
ScriptAlias /php/ "c:/path_to_your/5.3.0"
Tuesday, July 21, 2009
Gmail survey message - inconsistent !!!

Clicked on it to participate and was disappointed to get this message...

How did inconsistent behavior creep in??
Thursday, July 02, 2009
Playing with Camtasia project file
Before turning off the system, I moved the images into another drive.
In the morning, I opened the .camproj (Camtasia project) file and to my surprise all the images in it gone missing :(
A dialog box was presented to search and point location for each image. I had almost 50+ images!
With curiosity I opened (Introduction.camproj) in text editor it was a simple XML file :)
The imported images were looking like:
<clipbin_object>
<clipname>C:\Users\power\Desktop\MoreOnProduct\Step1.png</clipname>
</clipbin_object>
To keep things simple, I copied (Introduction.camproj) to the folder where all screenshots were present under directory images/
Opened Introduction.camproj in gvim and triggered the following command
:%s/C:\\Users\\power\\Desktop\\MoreOnProduct\\Step1.png/images/g
It reflected as:
<clipbin_object>
<clipname>images\Step1.png</clipname>
</clipbin_object>
Finally I got the video to the original state.
Wednesday, March 18, 2009
Scrolling with row Headings Fixed - in Spreadsheet
Select cell in Excel sheet (OpenOffice calc) and Click on Window > Freeze,
this way you can make the rows below the selected cell scroll beneath it.
1. For Horizontal Freeze - Select only first cell
2. For Horizontal & Vertical Freeze - Select any other cell.
For Reference: http://www.learnopenoffice.org/CalcTutorial13.htm
Friday, January 09, 2009
Turning On Mysql Query Logging
[mysqld]
log = /var/log/mysqld-all.log
Follow the steps given below:
1. chown mysql:mysql /var/log/mysqld-all.log
2. chmod o-r /var/log/mysqld-all.log
3. /etc/init.d/mysqld restart
Now when you execute sql you should see the log :)
Friday, January 02, 2009
Happy New Year 2009
Sunday, November 04, 2007
VMware on Fedora Core 7
Monday, October 29, 2007
SVN - Trac - Apache Setup
you can download it from here.
Update: Added information of setting up read-writer permission for SVN through Access file version2 here.
Wednesday, September 12, 2007
diffdir - compute diff between directory
and create filter out files that has modifications or newer in the source directory.
It is available on code.google.com subversion http://diffdir.googlecode.com/svn/
You can download the application here.
Sunday, September 09, 2007
Useful Windows Tools
StickyNotes
* Add a note and right on it to find more options!
* You can customize each note.
* Set Alarm
* Load and Save Notes from File.
* And Many More... see documentation
http://hottnotes.com/
ttp://sourceforge.net/projects/s-notes/
Alarm Clock:
by Cinnamon Software
*nix utilities
Commonly used *nix commands for windows:
UnxUtils @sourceforge or UnxUtils
Check out most popular tools here:
Open Source For Mac and Windows
Learn more about Equivalent Linux Software on Windows
Thursday, September 06, 2007
Skype doesn't let Apache Start!
Skype by default uses port 80 and port 443 for incoming connections,
unfortunately we want the same ports used for Apache in general.
You can change the preferences of Skype to work on different port in the preferences,
(Tools -> Options)
and keep your Apache running on port 80 or 443.
Some references:
http://hasin.wordpress.com/2007/06/28/damn-why-the-hell-skype-is-blocking-port-80/
[Thanks for Puneeth to figure out about changing skype preference on port]
Wednesday, September 05, 2007
Lanuchy - Keystoke launcher for windows
ALT+SPACE any where will bring up the launchy.
Right Click on Launchy window,
* You can configure Directory to index for searching and
also set the extensions to look for!
* Hotkey - configure it if you want Launchy to appear other than ALT+SPACE
ESC will push back Launchy.
Learn more on using launchy here.
[Are you on linux? Then have a look at katapult.
Tuesday, August 21, 2007
Database Comparsion - dbdiff
Monday, July 23, 2007
Setting up Repository
Steps to follow to setup CVS:
1. mkdir /home/cvsfolder
2. export CVSROOT=/home/cvsfolder
3. cvs init
Initialize your cvs folder
4. chown -R ownername:groupname /home/cvsfolder
5. chmod -R g+rwxs /home/cvsfolder
This is a important step. Here we are making the directory sticky.
When a user commits a file to cvs, the username might change but the
groupname still remains the same.
If you don't follow this step, you might end up in a situation where a developer
checks in the file and other developer can't commit the same file.
Import Project to CVS
1. mkdir /project/TestProject
2. touch /project/TestProject/README.txt
3. export CVSROOT=/home/cvsfolder
4. cd /project/TestProject
5. cvs import -m "Some initial comment on the project" TestProject youcompany release_tag
Your TestProject is in CVS now.
Checking out the from CVS
1. export CVSROOT=/home/cvsfolder
2. cvs checkout TestProject
Checking out from Remote Server CVS
1. export CVS_RSH=ssh
2. cvs -d:ext:yourname@server.com:/home/cvsfolder checkout TestProject
Monday, July 02, 2007
Flash Object and z-index.
Find more details on
TechNote
Flash content and z-index.
Experimenting with Flash content and z-index.
Thursday, June 07, 2007
MXML Autocomplete In Eclipse
1. First look if you have mxml2.xsd file in the flex installation directory. If you don't have
then get it here.
[NOTE: If you don't have webtools for eclipse, you will have to install it, follow the method suggested in Step 1 in the link
for your eclipse version.]
2. Window -> Preferences -> Web And XML -> XML Catalog
Add User Specified Entries
URI:
Key Type: Namespace Name (Its autofilled)
Key : http://www.adobe.com/2006/mxml (Its autofilled)
3. Window -> Preferences -> General -> Editors -> File Association
Add File Types: *.mxml (Click on Add next to listed file preferences and add it)
Associate Editor: XML Editor (Click on Add under Associate editors and select it)
4. Window -> Preferences -> General -> Content Types
Under Text Edit -> XML, Add *.mxml
You should get drop down list if you do: <mx: type CTRL+SPACE within
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
</mx:Application>
References:
http://www.straker.co.nz/shadozoom/blog/2005/editing-mxml-files-with-eclipse-3.1.cfm
http://cfsilence.com/blog/client/index.cfm/2007/3/26/Setting-Up-Eclipse-For-Flex-2
Friday, May 18, 2007
Roner - Rounded Corner Generator
Came across this article later, Rounded and Shaded Corners
Modified the source Tapestry Contrib, fixed few transparency bug and enhanced few more options.
This project is on google's Subversion Repository reach it via http://roner.googlecode.com/svn/
Roner Documentation
Tuesday, May 15, 2007
Compact Policy For Cookies
http://www.w3.org/TR/P3P/
http://www.sitepoint.com/article/p3p-cookies-ie6/2
http://www.duxcw.com/faq/webmastr/privhttp.htm
http://www.microsoft.com/windows/ie/ie6/using/howto/privacy/config.mspx
http://www.w3.org/TR/P3P/#guiding_principles
http://www.eder.us/projects/p3p-gen/
http://www.oreillynet.com/pub/a/javascript/2002/10/04/p3p.html
Look at the source code, to get more information about P3P Header: http://www.eder.us/projects/p3p-gen/p3p-gen.tar.gz
Wednesday, April 18, 2007
Business Card SMS
Send Business Cards
With this handy tip you can save your friends the trouble of storing your numbers.
A business card is a special SMS message which is composed as follows:
//SCKE2 BEGIN:VCARD N:name TEL:number END:VCARD
The receiver will see the text BUSINESS CARD RECEIVED displayed on his/her. phone.
For more information look at SMS tips
Sunday, April 08, 2007
StopWatch -- A Mobile Java Application
Simply copy the StopWatch.jar file to your mobile, via DataCable/Bluetooth/Infrared.
Start the application and you should see it working.
I have tested it on Nokia 6030, Let me know if you had any feedback.
This project is on google's Subversion Repository reach it via http://stop-watch.googlecode.com/svn/
Thursday, March 29, 2007
Using stmp.gmail.com To Send Mail
Please use vaild email address.
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
/**
* @author prasad
*/
public class MailInfo {
public void send() throws EmailException {
Email email = new SimpleEmail();
String authuser = "--------@gmail.com";
String authpwd = "**********";
// Very Important, Don't use email.setAuthentication()
email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
email.setDebug(false); // true if you want to debug
email.setHostName("smtp.gmail.com");
email.getMailSession().getProperties().put(
"mail.smtp.starttls.enable", "true");
email.setFrom("++++++++@gmail.com", "SenderName");
email.setSubject("TestMail");
email.setMsg("This is a test mail?");
email.addTo(".......@gmail.com", "ToName");
email.send();
}
}
Wednesday, March 28, 2007
JavaProxy -- HTTP Proxy In Java
After checking out HTMLParser library,
I got my implementation of JavaProxy working. Here is the download link.
Just copy the JavaProxy.war file into your Tomcat/webapps folder and you should be able to use it,
using http://localhost:8080/JavaProxy/
I have released it under Apache License 2.0, so make the best use of it.
Let me know if you liked it or found some use in your application.
I have got this project on google's Subversion Repository http://java-proxy.googlecode.com/svn/
[NOTE: Steps to import your project on code.google.com
- To host your project on googlecode, signin for an account at http://code.google.com/hosting/
- Create a new project (myproject).
- Go to MyProfile (note down Username) and under Settings (note down Password).
- From your terminal type (assuming your are under project folder):
svn import -m "Initial Import" . https://myproject.googlecode.com/svn/trunk --username Username
You will be prompted for Username and Password, enter the one you had notedown. - Now your code is in subversion repository.
Sunday, March 11, 2007
Eclipse Profiler Plugin
Download link is here.
I could not get the plugin working with eclipse-3.2 but I could see the Profiler perspective as described when I tried with eclipse-3.1.
When I tried to run the profiler I got some error like this:
Plug-in unable to load class ru.nlmk.eclipse.profiler was unable to load class
ru.nlmk.eclipse.profiler.launch.ProfilerLaunchConfigurationDelegate.
Check out more discussion on this problem here.
I tried to use the bug fixed plugin for eclipse-3.1, use this link.
After getting this patched version of plugin:
1. Unzip it to eclipse/plugin folder.
2. For windows:
Copy ProfilerDLL.dll to ${JAVA_HOME}/jre/bin folder
For Linux Box:
Get libProfilerDLL.so from native/profiler_linux.tgz and copy it to libProfilerDLL.so in native/profiler_linux.tgz to ${JAVA_HOME}/jre/lib/i386/
[NOTE] I had to recompile a new version of libProfilerDLL.so. Its simple to do. Just set the right path for your java installation in the shell script m [you get it after untaring native/profiler_linux.tgz], execute it (you will need right permission to copy the shared library)
Shell script m (used to recompile and copy libProfilerDLL.so)
#!/bin/sh
export JAVA_HOME=/usr/java/j2sdk1.4.2_06
g++ -O0 -DLINUX -shared -Wall -I. -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux ProfilerDLL.cpp -o libProfilerDLL.so
cp libProfilerDLL.so ${JAVA_HOME}/jre/lib/i386/libProfilerDLL.so
Enjoy Profiling!
Are you hit by Email-Worm?
Although Anti-Virus cleaned up this worm, but I had to spend sometime to get the system configuration back to normal. Here are few links which helped me in the process.
Email-Worm.Win32.Brontok Virus:
http://activepanel.blogspot.com/2006/01/brontok-rontokbro-korbo-b-mytob-virus.html
and more about similar virus W32.Rontokbro@mm:
http://drvamsikrishna.blogspot.com/2007/02/solution-for-folder-options-missing_28.html
My system configuration has landed to proper state, I can now breathe easy, (Quite successfully avoided usual Windows RE-INSTALL!)
Wednesday, February 28, 2007
Tomcat Cache Control Customization
If we allow Tomcat DefaultServlet to serve the static resource, it sends back ETag header which is used for cache control on the client browser. The problem with this is client (browser) will send request to check if the file is modified each time we refresh the page. This will add overhead to our application as well as server.
We might want to completely avoid client browser (if cache is enabled) from requesting a resource until sometime, in such case right cache control headers should be sent back. Here is our new CustomFileServlet which add custom cache headers if the resource served is javascript or css file and such resource will asked to cache for a day.
package com.example.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.servlets.DefaultServlet;
public class CustomFileServlet extends DefaultServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (processRequest(request, response)) {
super.doPost(request, response);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (processRequest(request, response)) {
super.doGet(request, response);
}
}
public boolean processRequest(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String fileURI = "";
if (requestURI.indexOf(contextPath) != -1) {
// Request URI is CONTEXTPATH + RESOURCE URI
fileURI = requestURI.substring(
requestURI.indexOf(contextPath)
+ contextPath.length());
}
File file = new File(request.getSession()
.getServletContext().getRealPath(fileURI));
String lowerfile = file.getAbsolutePath().toLowerCase();
boolean isBasePath = "/".equalsIgnoreCase(fileURI);
boolean isJSFile = lowerfile.endsWith(".js");
boolean isCSSFile = lowerfile.endsWith(".css");
boolean customServing = (!isBasePath) && (isJSFile || isCSSFile);
if(customServing) {
String mimetype = request.getSession()
.getServletContext().getMimeType(fileURI);
response.setContentType(mimetype);
// Required Cache Control Headers
String maxage = "86400"; // One day in Seconds
response.setHeader("Cache-Control", "max-age="+ maxage);
long relExpiresInMillis = System.currentTimeMillis() + (1000 * Long.parseLong(maxage));
response.setHeader("Expires", getGMTTimeString(relExpiresInMillis));
response.setHeader("Last-Modified", getGMTTimeString(file.lastModified()));
// Serve the file content
FileInputStream fis = new FileInputStream(file);
OutputStream ostream = response.getOutputStream();
streamIO(fis, ostream);
fis.close();
ostream.flush();
ostream.close();
return false; // We have taken care of file serving.
}
return true; // Let DefaultServlet handle file serving
}
public static String getGMTTimeString(long milliSeconds) {
SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'");
return sdf.format(new Date(milliSeconds));
}
public static void streamIO(InputStream is, OutputStream os)
throws IOException {
byte[] bytes = new byte[2048];
int readlen = -1;
while ((readlen = is.read(bytes)) != -1) {
os.write(bytes, 0, readlen);
os.flush(); // Let us flush after bluk write
}
}
Customize Tomcat's Static File Serving
If you want to customize file serving the following steps need to be followed.
1. Mapping in web.xml for you application
<servlet>
<servlet-name>CustomFileServlet</servlet-name>
<servlet-class>com.example.servlet.CustomFileServlet</servlet-class>
<init-param>
<param-name>listing</param-name>
<param-value>true</param-value>
<!-- allow browsing directory inside web application -->
</servlet>
<servlet-mapping>
<servlet-name>CustomeFileServlet</servlet-name>
<url-pattern>/</url-pattern>
<!-- Maps all request except the ones which are mapped separately -->
</servlet-mapping>
2. Enable privilege for the application (since server library class is used).
Here is an example context file I created for such a application (Tomcat/conf/Catalina/localhost/customapp.xml)
<?xml version="1.0"?>
<context path="/customapp" docbase="/home/prasad/CustomApp/web" privileged="true" reloadable="true"></context>
3. Write a CustomFileServlet class.
package com.example.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.servlets.DefaultServlet;
public class CustomFileServlet extends DefaultServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (processRequest(request, response)) {
super.doPost(request, response);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (processRequest(request, response)) {
super.doGet(request, response);
}
}
public boolean processRequest(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String fileURI = "";
if (requestURI.indexOf(contextPath) != -1) {
// Request URI is CONTEXTPATH + RESOURCE URI
fileURI = requestURI.substring(
requestURI.indexOf(contextPath) +
contextPath.length());
}
boolean checkPassed = false;
// DO SOME CHECKS BEFORE SERVING FILE...
return checkPassed;
}
Thursday, December 14, 2006
mod_gzip for Apache
Install mod_zip if you don't have it already:
apt-get install libapache-mod-gzip
Load the module mod_gzip: (add this line in httpd.conf or modules.conf)
LoadModule gzip_module /usr/lib/apache/1.3/mod_gzip.so
Look at the example http://schroepl.net/projekte/mod_gzip/config.htm configuration file.
Here is the configurtaion I added:
<IfModule mod_gzip.c>I had to add the configuration line mod_gzip_item_include uri .* until then I saw only mod_gzip: DECLINED:EXCLUDED In:0 -< Out:0 = 0 pct. in the mod_zip.log.
mod_gzip_on Yes
mod_gzip_can_negotiate Yes
mod_gzip_static_suffix .gz
AddEncoding gzip .gz
mod_gzip_command_version '/mod_gzip_status'
mod_gzip_keep_workfiles No
mod_gzip_minimum_file_size 500
mod_gzip_maximum_file_size 500000
mod_gzip_maximum_inmem_size 60000
mod_gzip_handle_methods GET POST
mod_gzip_item_exclude reqheader "User-agent: Mozilla/4.0[678]"
mod_gzip_item_include file \.html$
mod_gzip_item_include file \.js$
mod_gzip_item_include file \.css$
mod_gzip_item_exclude mime ^image/
mod_gzip_item_include mime ^text/
# This was very important to get things working
mod_gzip_item_include uri .*
mod_gzip_dechunk Yes
LogFormat "%h %l %u %t \"%V %r\" %<s %b
mod_gzip: %{mod_gzip_result}n In:%{mod_gzip_input_size}n -<
Out:%{mod_gzip_output_size}n = %{mod_gzip_compression_ratio}n
pct." common_with_mod_gzip_info2
CustomLog /var/log/apache/mod_gzip.log common_with_mod_gzip_info2
</IfModule>
Look at http://www.debian-administration.org/articles/31 which reports problem with mod_gzip and mod_ssl, so added this line of configuration as well. Add this only if you enabled ssl access for your server.
<VirtualHost *:443>
<IfModule mod_ssl.c>
...
</IfModule>
<IfModule mod_gzip.c>
mod_gzip_on No
</IfModule>
</VirtualHost>
NOTE: With Apache2 you can use mod_deflate for the gzip compression. To get more details look at
http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
Locale Dependent DateFormat
The following piece of jython code which was working fine on my machine failed to work on debian server.
import java.text.DateFormat as DateFormat
format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
format.setLenient(1);
print format.parse('Nov 6, 2006 3:23:54 PM');
I was getting this exception:
Traceback (innermost last):
File "<string>", line 5, in ?
java.text.ParseException: Unparseable date: "Nov 6, 2006 3:23:54 PM"
at java.text.DateFormat.parse(DateFormat.java:335)
...
I looked at the default Locale that was used and it was: [command used: locale]
LANG=en_IN
LC_CTYPE="en_IN"
LC_NUMERIC="en_IN"
LC_TIME="en_IN"
LC_COLLATE="en_IN"
LC_MONETARY="en_IN"
LC_MESSAGES="en_IN"
LC_PAPER="en_IN"
LC_NAME="en_IN"
LC_ADDRESS="en_IN"
LC_TELEPHONE="en_IN"
LC_MEASUREMENT="en_IN"
LC_IDENTIFICATION="en_IN"
LC_ALL=
I did the following and got the piece of code working:
export LC_CTYPE="en_US.UTF-8"[If this does not solve try export LC_TIME="en_US.UTF-8"]
After this I could got the following output:
Mon Nov 06 15:23:54 IST 2006
Make sure you set the right LOCALE before using any API that depends on SYSTEM LOCALE information. Few Java API's allows you to specify the Locale as an argument use it when required.
More details about Java 1.3 Locale
I found a related post Don't forget to specify the locale
Wednesday, November 29, 2006
StackOverflowError When Instantiating A Class
public class FirstClass {
public FirstClass() {
SecondClass secondClass = new SecondClass();
}
public static void main(String[] args) {
/* Instanstiating FirstClass ends with StackOverflowError */
FirstClass firstClassInstance = new FirstClass();
}
}
public class SecondClass {
public SecondClass() {
FirstClass firstClassInstance = new FirstClass();
}
}We are trying to instantiate FirstClass object inside main function, FirstClass constructor tries to instantiate SecondClass object and SecondClass constructor tries to instantiate FirstClass object which ends up in a busy endless situation and hence StackOverflows.
Although this is not a common situation of programming, such mistakes or piece of code will be hard to figure out especially when writing Web Application where things are little hard to debug.
If you like to look at the source of this example, check out here.
Thursday, November 09, 2006
Javascript Function Call Surprised Me
I was taken by surprise when I observed this:
When I pass Array parameter from iframe page to its parent the instanceof function calls works quite diffrent on different browser and its version :(
I have isolated the problem in the following page:
http://www.geocities.com/prasad20002005/TestIFrameCall/parent.html
Thanks to Pramod who sent me this link: http://www.thescripts.com/forum/thread91190.html
where the same issue was discussed.
Saturday, October 21, 2006
DataMashups Service Beta
Data Mashups is a "Online Service for Enterprises" from Applibase, Inc.
Update: DataMashups gets listed as "The Best Web 2.0 Software of 2006" on Dion Hinchcliffe's Blog
Thursday, September 07, 2006
VirtualHost with ServerAlias
I was setting up VirtualHost for my Apache server with ServerAlias, as shown below:
<virtualhost *:80>This was the first time I was playing with VirtualHost configuration and ServerAlias, I got http://myserver.com working but http://myname.myserver.com or http://myadmin.myserver.com were not working.
ServerName myserver.com
ServerAlias myserver.com, *.myserver.com
DocumentRoot /path/to/directory
</virtualhost>
I realized I had missed one step which was stated in the documentation:
"Of course, you can't just make up names and place them in ServerName or ServerAlias. You must first have your DNS server properly configured to map those names to an IP address associated with your server."
DNS Mapping for the subdomain's was the problem. I noticed, DNS mapping was done for myserver in com domain something like this:
mysever IN A 192.168.0.XX
but there was no mapping for my subdomain's. I added a CNAME record in the DNS, something like this
*.myserver IN CNAME myserver[Please refer to documentaion for adding CNAME DNS entry, it might vary. ]
Once I updated my DNS Server, the ServerAlias started to work.
Few of the DNS Servers I tried: Posadis, BIND .
Saturday, April 29, 2006
MySql Getting LastInsertId
A simple table for our discussion would be.
create table autotable (id int auto_increment unique, primary key (id));
How do you get the last insert id when you insert a tuple?
This function will try to get the last insert id information given the prepared statement (for MySql JDBC driver). If the information is not available, the -1 value is returned.
public Integer getLastInsertId(PreparedStatement ps) {
int lastInsertId = -1;
PreparedStatement lastInsertIdPs =
ps.getConnection().prepareStatement("SELECT LAST_INSERT_ID()");
ResultSet rs = lastInsertIdPs.executeQuery();
while(rs.next()) {
lastInsertId = rs.getInt(1);
}
return new Integer(lastInsertId);
}
Let us execute the prepared statement:
PreparedStatement preparedStatement =
connection.prepareStatement("insert into autotable (id) values (?)");
preparedStatement.setObject(1, new Integer(1));
preparedStatement.execute();
Integer lastInsertId = getLastInsertId(ps);
The lastInsertId value will be 0 in this case, though MySql inserts value 1 for the auto_increment field (id) of the table.
How do we fix this mismatch?
You have to make sure you will not insert values to auto_increment field, in which case MySql generates the value and you can get the generated value using the getLastInsertId function.
So the above piece of code should be written like this:
PreparedStatement preparedStatement =
connection.prepareStatement("insert into autotable (id) values (?)");
preparedStatement.setObject(1, null); // Let MySql generate the value for this field
preparedStatement.execute();
Integer lastInsertId = getLastInsertId(ps);
lastInsertId value will now be 1 (auto generated value for this insert).
Tuesday, March 07, 2006
Mplay - Mplayer Console Frontend
Monday, March 06, 2006
Working with Sablecc
"an object-oriented framework that generates compilers (and interpreters) in the Java programming language".
I started with Etienne Gagnon's Master thesis which is quite well written. I was pretty convinced when I got my first program working with Sablecc. I decided to document the steps I followed which can serve as a tutorial to start working with Sablecc. Here is the link for my tutorial(pdf) and first application INIParser(zip)
Reference links:
Mistaeks I Hav Made
Sablecc Wiki
Resource links:
Sablecc-3-beta.3
Sablecc downloads
Sablecc Home
Tuesday, February 21, 2006
Extension for TrimPath
I just extended TrimPath object by adding the function processTemplateFile, which does and XMLHttpRequest and fetch the jstfile and merge it with the context. You can pass function to get callback with processed template, response status and status text or pass dom element whose innerHTML will be updated once the template is processed.
Look at the extension I have added exttemplate.js
Example:
function mergeWithFile(trmfile, context, getcallback) {
var resultdiv = document.getElementById("result");
if(getcallback != null and getcallback == false)
TrimPath.processTemplateFile(trmfile, context, resultdiv);
else
TrimPath.processTemplateFile(trmfile, context, handler);
function handler(mergedJST, status, statusText) {
if(mergedJST == null) {
mergedJST = "HTTP STATUS: " + status + "," + statusText;
}
resultdiv.innerHTML = mergedJST;
}
}
function mergeWithoutCallback() {
var context = { values : ["prasad", "me"] };
mergeWithFile("jstfiles/mytemplate.jst", context, false);
}
function mergeWithCallback() {
var context = { values : ["prasad", "me"] };
mergeWithFile("jstfiles/mytemplate.jst", context);
// Same as
// mergeWithFile("jstfiles/mytemplate.jst", context, true);
}
Monday, February 20, 2006
Tomcat WebApplication Context File
For this to work, you should have the xml file (name same as "application path"+ ".xml") in Tomcat/conf/Catalina/localhost directory, you don't need to put the war file under Tomcat/webapps.
Let say, our web application directory is "/home/prasad/apps/TestApp/web" and
we like to access it as "http://localhost:8080/testapp". Then, you have to create the "testapp.xml" in Tomcat/conf/localhost directory with the following content in it:
<xml version="1.0">
<Context path="/testapp"
docBase="/home/prasad/apps/TestApp/web"
reloadable="true" />
The reloadable attribute is the one the allows reloading of context when the class file changes. docBase attribute should point to the web directory (which has child directory named WEB-INF), otherwise Tomcat can delete the context file, as its not valid.
Creation of context file is useful when you want to secure you web application, ie. apply security constraints to access files of you web application and you want to Tomcat to use your tables to authenticate user access. Here is how you can setup Tomcat's JDBC authentication:
<?xml version="1.0"?>
<Context path="/testapp"
docBase="/home/prasad/apps/TestApp/web"
reloadable="true">
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="jdbc.DatabaseDriver"
connectionURL="jdbc:protocol:appauthdb"
connectionName="admin" connectionPassword="admin"
userTable="utable" userNameCol="uname" userCredCol="passwd"
userRoleTable="rtable" roleNameCol="rname"/>
</Context>
Table Structure:
create table utable (uname varchar(255), passwd varchar(255), primary key(uname, passwd))
create table rtable (uname varchar(255), rname varchar(255))
This basically sets up Realm for this web application. [By default, there is Realm defined for entire Engine or Host in Tomcat/conf/server.xml] You are basically setting the context to use JDBC Realm and acess appauthdb database tables utable and rtable to authenticate the user.
To check out the Realm usage you have to define the security-constraint in web.xml file in (/home/prasad/apps/TestApp/WEB-INF/web.xml).
<security-constraint>
<web-resource-collection>
<web-resource-name>Entire Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>appuser</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<!-- Commented
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/error.html</form-error-page>
</form-login-config>
-->
</login-config>
We defined the security contraint for the entire web application (url-pattern) and all user with role (role-name) appuser can access the resource of web application. Once done add values to utable and rtable.
insert into utable(uname, passwd) values ('prasad', 'somepwd')
insert into rtable(uname, rname) values ('prasad', 'appuser')
When you visit, http://localhost:8080/testapp, you get a HTTP Authentication dialog box, and you can see only 'prasad' is allowed to use the application.
Hope this piece of information is useful.
Wednesday, February 15, 2006
IE supports Conditional Comments
Well the article gives the complete details about conditional comments.
Brief:
IE supports if conditional construct within the HTML comment.
Example, to include a stylesheet when HTML is displayed in IE.
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="cssfiles/forie.css"/>
<![endif]-->
<!--[if !IE 7]>
<script type="text/javascript">
document.write("<b>IE Version Used is not 7</b>");
</script>
<![endif]-->
Thursday, February 09, 2006
Feed discovery extension
<link rel="alternate" type="application/rss+xml"
title="MySiteMainFeed" href="http://localhost.com/main.xml" />
The difficulty with this is, you have to specify link rel="alternate" for each of the feed available on the site. To simplify this we can have link rel="alternate" type="application/feedlist+xml" on the page which provides list of available feeds on your site.
Example:
<link rel="alternate" type="application/feedlist+xml"
title="MySiteMainFeed" href="http://localhost.com/feedlist.xml" />
feedlist.xml will be:
<?xml version="1.0"?>
<feedlist>
<link rel="alternate" title="RSS Content" type="application/rss+xml"
href="http://localhost.com/rss_feed.xml"/>
<link rel="alternate" title="Atom Content" type="application/atom+xml"
href="http://localhost.com/atom_feed.xml"/>
<link rel="alternate" title="Comment" type="application/rss+xml"
href="http://localhost.com/comment_rss_feed.xml"/>
</feedlist>
Sunday, January 29, 2006
Javascript and Java Comparision
I was working with Java at the same time, writing some Servlet Code. I found most of the features is very simple to learn in javascript. If you are familar with Java then things are even more simpler.
I have written some sort of comparision between few things of java and javascript. Here is the link: JavascriptAndJava
Tuesday, January 24, 2006
Design Self Refreshing HTML Page
I found html meta to be useful in such case. The <meta http-equiv='refresh' content='1; url="clientreq"'> when included in HTML page will timeout the page every 1 second (specified value in content) and the request is sent to the specified url (clientreq). Taking advantage of this feature I designed a model where the client can get the feedback on the progress of the response.
The design was, ClientServlet will redirect to progress.jsp with status message if it is not ready to send response (busy in doing the lookup). Once ClientServlet has finished its lookup it sends the actual response to the client instead of redirect.
Task of progress.jsp is just to send the HTML page with the status message along with <meta http-equiv='refresh' content='1; url="clientreq"'>. Which makes frequent request to the ClientServlet to get the status or response.
The lookup work was moved to the class AsyncHandler, which spans a new thread when it is started and gives the status of its work.
First ClientServlet creates AsyncHandler and puts into the session after starting it. A redirect is sent to progress.jsp with status message. For subsequent request, ClientServlet checks the status of AsyncHandler and decides whether to redirect to progress.jsp or send actual response.
Snippet of my Servlet code:
private void processRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception {
final String HANDLER_KEY = "Client_Async_Handler";
HttpSession session = req.getSession();
AsyncHandler ah =
(AsyncHandler) session.getAttribute(HANDLER_KEY);
if(ah == null) {
ah = new AsyncHandler();
ah.start();
session.setAttribute(HANDLER_KEY, ah);
res.sendRedirect("progress.jsp?msg=" +
URLEncoder.encode(ah.getStatus(), "utf-8"));
return;
} else {
if(ah.done()) {
sendResponse(res, ah);
session.setAttribute(HANDLER_KEY, null);
ah = null;
return;
} else {
res.sendRedirect("progress.jsp?msg=" +
URLEncoder.encode(ah.getStatus(), "utf-8"));
return;
}
}
}
Snippet of progress.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv='refresh' content='1; url="clientreq"'>
<title>Please Wait</title>
</head>
<body>
<%= req.getParameter("msg") %>
</body>
</html>
Monday, December 26, 2005
Static Initializer in Java
/* Initializer.java */
package staticinit;
/**
* A simple class to demonstrate the working of static block of code
* that is used to initialize the static class variables.
* @author prasad
*/
public class Initializer {
/** Initialize the class variables. */
public Initializer() {
firstClassVar = "VALUE_NOT_NULL";
secondClassVar = "VALUE_NOT_NULL";
thirdClassVar = "VALUE_NOT_NULL";
fourthClassVar = "VALUE_NOT_NULL";
}
/** Initialize the static variables. */
static {
firstStaticVar = "STATIC_NOT_NULL";
secondStaticVar = "STATIC_NOT_NULL";
}
/** Static variables. */
private static String firstStaticVar = null;
private static String secondStaticVar;
/** Class variables. */
private String firstClassVar = firstStaticVar;
private String secondClassVar = secondStaticVar;
private String thirdClassVar = null;
private String fourthClassVar;
/** Examine and display the values. */
public void display() {
System.out.println("firstStaticVar -> " + getValue(firstStaticVar));
System.out.println("secondStaticVar -> " + getValue(secondStaticVar));
System.out.println("firstClasssVar -> " + getValue(firstClassVar));
System.out.println("secondClassVar -> " + getValue(secondClassVar));
System.out.println("thirdClassVar -> " + getValue(thirdClassVar));
System.out.println("fourthClassVar -> " + getValue(fourthClassVar));
}
private String getValue(Object value) {
return (value == null)? "is null": value.toString();
}
/** Main entry point. */
public static void main(String[] args) {
Initializer initializer = new Initializer();
initializer.display();
}
}
Which of the variable(s) will have the value "null" in the function display()?
a) firstStaticVar
b) secondStaticVar
c) firstClassVar / secondClassVar / thridClassVar / fourthClassVar
d) none of the above
You are right if you had selected the option (a).
Why only firstStaticVar is "null"?
When the class is instantiated, before constructor is called the variables are defined (which takes the default value) and then the static initialization are performed inorder. The static initialization can be static block of code or inline assignment etc. In the above code, after static block of code is executed, firstStaticVar is re-assigned by the "inline assignment". Next secondStaticVar has no "inline assignment" so the previous initialized value is retained. Next all firstClassVar and thridClassVar are inline initialized. After this, the constructor is called which will re-initialize all the ClassVar's. When the constructor finishes its work only firstStaticVar will have the value "null".
Things like this can result in bugs which would be hard to figure out or debug. A simple solution would be to declare variables (with or without initialization) before any "code block" that access it.
Friday, December 16, 2005
Size in TB on a GB hard disk

I was really taken by surprise when I saw "2TB", I have used more space than I really have (80GB) O:-) I did "du -csh /home" which showed "7.7G".
