Thursday, July 31, 2008

Quote

The squeaking wheel doesn't always get the grease. Sometimes it gets replaced.
- Vic Gold

Thursday, July 17, 2008

Ajax -loading javascript via AJAX

Ajax is the buzz word we are hearing around these days. Ajax is asynchronous javascript. Its the key ingradiant in making webapplications rich/ single page applications. What happens is that based on the events the user makes on the UI an asynchronous requests go to the server in the backend which does the processing and replies back. All this happens with out any page refresh/ with out stopping/pausing any of the user activities on the UI. We see this esp in creating a new logins in yahoo/ gmail -it reports name already exists/ strength of the password set.

The facility comes with a cost:
The main issue with ajax is: say you have one.html with one.js and two.html with two.js files. Say, two.html when opened in IE displays a calendar (using client side js). Now when the two.html is loaded in one.html by ajax the calendar will not be rendered!!! Mozilla gets the two.js but not loads them... IE does'nt even do this. The general way of handling such issues is by including the two.js in one.html along with one.js.

Yeak!!!! what a dirty solution! The Yeak... 'cos why should the parent one.html know the existince of two.js at all?? Moreover... say the two.js is not always required/ say we have multiple js files three.js and four.js (each of them very big) and the user either uses three.js or four.js but not both... then by the above apporach we would include all the js-s in one.html forcing the browser to load all of them before hand.... so the page not only loads un-necessary js files but also takes a lot of time to load/ render... this has severe issues w.r.t performace and user experiance. Now imagine a case where we display 10 ajax pages each with its own sets of javascript!!! Here we developed a similar application and the initial page loads 19 (5+5+4+5) javascript files which made the page response time: 10.25 seconds on an avg. There should be a better soln.

A Refined solution:
Let the initial page load only one.js and by on-demand loading (or lazy-loading) lets load the required js files. This we can do by DOM-modifications or loading js files by eval function. I found a useful link On-Demand Javascript.

Dom Modifications:
Here the HTML DOM is modified and a script tag is written to its bottom as:

by using

once the writing to dom is done it will get the required js file and load it. The point is that the user should keep in mind to delete such codes when no longer being used. Good one.

XMLHttpRequest-Based On-Demand Javascript
In this case the js file is called and the text part of it is eval()-ed. I understood it only to this extent. eval(): is a function in java script which can be used to create dynamic javascript behavior.
eg:
var alrt = 'alert("hi")';
eval(alrt);

in this case the string alrt is taken evaluated and loaded resulting into an alert of hi. This is the same as writing alert('hi');

Example:

I used YUI -loader to do all this donkey work for me. FInally the code became so simple and clean after using this... I am amazed !!!! Its as follows.




testLoad.html

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<link rel="stylesheet" type="text/css"

href="/yui/yui/assets/dpSyntaxHighlighter.css">

<script type="text/javascript" src="/yui/yui/build/yahoo/yahoo-debug.js">script>

<script type="text/javascript" src="/yui/yui/build/event/event-debug.js">script>

<script type="text/javascript" src="/yui/yui/build/dom/dom-debug.js">script>

<script type="text/javascript"

src="/yui/yui/build/yuiloader/yuiloader-beta-debug.js">script>

head>

<body id="yahoo-com" class=" yui-skin-sam">

<div id="custom-doc" class="yui-t2">

<div id="bd">

<div id="ajaxContainer">div>

div>

div>

body>

<script type="text/javascript" src="basic.js" >script>

html>




basic.js

Load = function(pageToLoad, whereToLoad) {

var childContainerCount = 0;

var scriptArr = new Array();

var isRemoteJsFile = false;

var loader = new YAHOO.util.YUILoader( {

require : [ 'connection' ],

base : [ '/yui/yui/build/' ],

onFailure : function(o) {

alert("error: " + YAHOO.lang.dump(o));

},

onSuccess :fire

});

loader.insert();

function lookupScript(text, index) {

scriptArr = text.toLowerCase().split(');

var js = scriptArr[index];

var jsEnd;

var jsStart;

jsStart = js.indexOf('src');

if (jsStart != -1) {

jsEnd = js.indexOf('.js');

// loading the js file

js = js.substring(jsStart + 3, jsEnd + 3);

js = js.replace('=', '');

js = js.replace('"', '');

//js = js.replace(/^\s\s*/, '').replace(/\s\s*$/, '');// trim

loadJs('yahooLang', '/yui/yui/build/yahoo/yahoo-min.js');

js = YAHOO.lang.trim(js);

} else {

// loading script body

jsStart = js.indexOf('>');

jsEnd = js.indexOf(');

js = js.substring(jsStart + 1, jsEnd);

}

return js;

}

var loadJs = function(name, jsPath, initFunc) {

loader = new YAHOO.util.YUILoader();

loader.addModule( {

name :name,

type :"js",

fullpath :jsPath,

varName :initFunc

});

loader.filter = {

'searchExp' :"-min\\.js",

'replaceStr' :"-debug.js"

};

loader.require(name);

loader.insert( {

onSuccess : function() {

if(initFunc != null && initFunc != undefined){

eval(initFunc + "()");

}

}

});

};

function fire() {

var parentDiv = document.getElementById(whereToLoad);

var childDiv = document.createElement('div');

childDiv.setAttribute('id', 'childContainer' + childContainerCount++);

if (!whereToLoad && whereToLoad != undefined)

parentDiv.appendChild(childDiv);

var handleSuccess = function(o) {

if (o.responseText !== undefined) {

scriptArr = o.responseText.toLowerCase().split(');

childDiv.innerHTML = o.responseText;

// loading each of the scripts of ajax file

for ( var i = 1; i <>

var js = lookupScript(o.responseText, i);

if (js.indexOf('.js') == -1) {

eval(js);

} else {

loadJs('ajaxJs' + i, js, 'initJs');

}

}

}

}

var handleFailure = function(o) {

if (o.responseText != undefined) {

alert('error');

}

};

var callback = {

success :handleSuccess,

failure :handleFailure,

argument : {

foo :"foo",

bar :"bar"

}

};

function makeRequest() {

var request = YAHOO.util.Connect.asyncRequest('POST', pageToLoad,

callback);

}

makeRequest();

}

};

Load('/yui/yui/examples/yuiloader/one.html', 'ajaxContainer');



This will load a html page which has an inline content and an included external js file. Our aim is to be able to load them.

one.html

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE> New Document TITLE>

<script src="/yui/yui/examples/yuiloader/one.js" >

script>

<script>

alert('hi hi hi hi 4');

script>

HEAD>

<BODY>

<font color="#FF0000" > 22222222222222 font>

BODY>

HTML>



one.js

function initJs(){

alert ('inside 2');

}




Solving Memory problems

Issue:
CPU takes 100% usage and eclipse hangs.

Cause:lipse Project Release Notes 3.4
By default, Eclipse will allocate up to 256 megabytes of Java heap memory.
This should be ample for all typical development tasks. However, depending on
the JRE that you are running, the number of additional plug-ins you are using,
and the number of files you will be working with, you could conceivably have to
increase this amount. Eclipse allows you to pass arguments directly to the Java
VM using the -vmargs command line argument, which must follow all
other Eclipse specific arguments. Thus, to increase the available heap memory,
you would typically use:

eclipse -vmargs -Xmx<memory size>

Fix:
  1. Make a shortcut to the eclipse on desktop
  2. under target give: C:\pathToEclipse\eclipse\eclipse.exe -vmargs -Xmx768M
  3. For me even 512 was giving issues. Dont forget the M to the end else it would take it as Bytes!

Monday, July 14, 2008

Eclipse Ganymede

Seeing this new product i was exited... in fact it has a few exiting features in it. you can convert an ordinary file system project into dynamic web project (Eclipse europa didnt have this feature); bread crumps, remote system, terminal (i think u can configure the linux samba server and associate it with this... had not done thsi.. but with the docs is felt this is what i felt like) and javascript support.

Java script support is more refined than the other tools that i had seen (aptana, jseclipse). you can check the available methods, scope of variables .. syntax errors etc... navigating to the source (f3) etc. But theres a big pain in the neck!!!! The tool is hanging whenever i open a javascript file. THis is happening only recently.... till then all happies... then i tried updating the new patches from the eclipse and now the cpu is 100% used.. all the system hangs.. huh!!!

now i retook the eclipse from the site.. and again configured ... now i see that cpu is only 50% consumed but eclipse is still hanging when ever i open a js file. not sure why this is happeing. i have configured abt 4 huge projects in eclipse 3 of them are pure java the last one all jsps and js-s (abt 100 jsps and 50 js) i am not sure if this is the issue... what ever ..... when ever i open a js file the eclipse hangs... hanging me.. i wait .. wait.. wait.. indefinitely and finally end task... huh!!! today i did it atleast 4 times...

---------

hey got a soln.. though dirty one: i had included YUI in the build path of javascript now i removed it and all is working fine... (yeak!!!! so i cant have YUI in build path??? terrible isnt it??)

Friday, July 4, 2008

Team outing to cruise (Tankbund lake + double decker boat)

yesturday eve we went for a outing on the 'cruise of tankbund' The Queen Bhagyamthi. We booked the boat for the night... from 9:00 to 11:00 pm. had drinks (coke etc), snax, and dinner.

The party was rocking... in fact i learnt that i don't know how to dance... in reality i was thinking that i dance well... not orsom though... but some spy(Arudra) had taken the video of my dance on the party and shown it to me... now i change my idea...: i am an upcoming dancer... :)

Eclipse Ganymede

Seeing this new product i was exited... in fact it has a few exiting features in it. you can convert an ordinary file system project into dynamic web project (Eclipse europa didnt have this feature); bread crumps, remote system, terminal (i think u can configure the linux samba server and associate it with this... had not done thsi.. but with the docs is felt this is what i felt like) and javascript support.

Java script support is more refined than the other tools that i had seen (aptana, jseclipse). you can check the available methods, scope of variables .. syntax errors etc... navigating to the source (f3) etc. But theres a big pain in the neck!!!! The tool is hanging whenever i open a javascript file. THis is happening only recently.... till then all happies... then i tried updating the new patches from the eclipse and now the cpu is 100% used.. all the system hangs.. huh!!!

now i retook the eclipse from the site.. and again configured ... now i see that cpu is only 50% consumed but eclipse is still hanging when ever i open a js file. not sure why this is happeing. i have configured abt 4 huge projects in eclipse 3 of them are pure java the last one all jsps and js-s (abt 100 jsps and 50 js) i am not sure if this is the issue... what ever ..... when ever i open a js file the eclipse hangs... hanging me.. i wait .. wait.. wait.. indefinitely and finally end task... huh!!! today i did it atleast 4 times...

---------

hey got a soln.. though dirty one: i had included YUI in the build path of javascript now i removed it and all is working fine... (yeak!!!! so i cant have YUI in build path??? terrible isnt it?? )

Sunday, March 30, 2008

JUNIT with Struts 2

lets c how to write Junit test cases for an application written in Struts2. The biggest problem i encountered is that theres hardlt any documentation abt this... by struggling over the net i discovered a way to circumvent the problem. The code goes as follows.

basically here we are see if the Entries made in Struts.xml (i.e. that we give using <> tag etc... ) is working fine or not.

Create a base Test case:
package com.company

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.mock.MockServletConfig;
import org.apache.struts.mock.MockServletContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.util.StrutsTestCaseHelper;

import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;

import junit.framework.TestCase;

public class BaseS2TestCase extends TestCase {
private Dispatcher dispatcher;
protected ActionProxy proxy;
protected static MockServletContext servletContext;
protected static MockServletConfig servletConfig;
protected HttpServletRequest request;
protected HashMap requestParameters = new HashMap();
protected HttpServletResponse response;

public BaseS2TestCase(String name) {
super(name);
}

/**
* Creates action class based on namespace and name
*
* @param clazz
* Class for which to create Action
* @param namespace
* Namespace of action
* @param name
* Action name
* @return Action class
* @throws Exception
* Catch-all exception
*/
@SuppressWarnings("unchecked")
protected T createAction(Class clazz, String namespace, String name)
throws Exception {
dispatcher = StrutsTestCaseHelper.initDispatcher(null);
// dispatcher = Dispatcher.getInstance();
proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class)
.createActionProxy(namespace, name, null, true, false);
proxy.getInvocation().getInvocationContext().setParameters(
requestParameters);

// do not execute the result after executing the action
proxy.setExecuteResult(true);

// set the actions context to the one which the proxy is using
ServletActionContext.setContext(proxy.getInvocation()
.getInvocationContext());
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
ServletActionContext.setServletContext(servletContext);
return (T) proxy.getAction();
}

/**
* The method(X) mentioned in < name="..." method="X" class="C"> tag is
* invoked on the class(C) and the string-result is returned.
*
* @return: action result, eg: SUCCESS, FAILURE etc as returned by the
* action method
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
protected String execActionMethod() throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
Object action = proxy.getAction();
Method method = action.getClass().getMethod(proxy.getMethod(), null);
Object result = method.invoke(action, null);
return (String) result;
}
}


and now extend this class and get the juint running :)

public class newTest extends EdsBaseTestCase {

public EdsWizardTest(String name) {
super(name);
}

protected void setUp() throws Exception {
super.setUp();
}

protected void tearDown() throws Exception {
super.tearDown();
}

public void testEventAttributes() throws Exception {
EdsWizard action = createAction(EdsWizard.class, "/eds",
"eventAttributes");
// String method = proxy.getMethod();
String exec = execActionMethod(); // action.eventAttributes();
assertEquals(exec, "success");
}
}

Thats it. You are done. Please let me know if u see any issues with this approach.

cheers,
coffee

Monday, March 10, 2008

Dirty IE.... IE7: All crap.

Open source products are far better. We buy Mocrosoft products and finally screw up our selves totally. Today i was totally working with div tags and now i understand that the bug is in IE7 and not my code. Aaaaah!!!! big pain !!!!

Sunday, March 2, 2008

Sun Tech days

I had been to suntech days held at Hyderabad International convocation center. It was good... though only 50% of the technologies presented were of use to me... i still like the visit. A fashion show was done to entertain the pple here... the bad thing is that the way the models were projected... i felt like they are being shown as an objects rather human beings... I was very angry with it..... wanted ot post this on the Sun forums....

How ever to the middle of the show the Sun guy came up and took the mike trying to anchor the event... his words tried to mitigate the effect... and i felt better... But what ever i wanted to ask the sun guys as to how far was it right to give such a bad projection about women! but had no chance to do it...

The biggest and immediate use i found by the tech days was the advantages of taking up the Java 6 ... its internals... Ruby and ruby on rails.... Here at my company we have CI running every night and i often used to wonder why its written in Ruby when it could be done on java too... (by java process) Netbeans IDE, was one the ohter things.... though i wouldnt go for it in the near future... the cool thing abt this ide was the profiling tool inbuilt into it. I remember the eclipse and its profiling plugin... which never works... wasted abt a weeks time of mine.... netbeans does it very nicely... with much improved features....

The worst of all the presentations was the Ajax framework: woodswork and dyna faces for JSF. It was a very important session for me... but the session was screwed up.... The next bad one was the last session on glass fish... he started by saying: "i know most of u are not interested... weekend ... and every ones planning for a picture.. this being the last session..... even i feel the same" OOPS! what a dirty introduction is it!!!!

in btw i attended one of the solaris sessions it was good.. shifting to linux itself.... i would nt enourage ... forget solaris...

finally, i felt like glassfish and solaris could be fruitful only if you can afford support for the sun guys... and if i remmeber it right it could cost u as much as 4500$ ... quite costly... :( and more over now i am using tomcat since 3 years and *known devil is better than unknown devil*. I already have a bad experience using ICEFACES -open source technology on JSF...

Friday, February 22, 2008

surprising experience with Struts2

The action class has a Dto, which contains a Map&lt;String, String&gt; object. I want to 'put' an entry into it from the UI layer /jsp. or in otherwords... i will say &lt;s:textfield name="dto.map['xyz']" /&gt; and say the user enters 123 into the text field then it will result into an entry: ["xyz","123"]. Till here things are fine but in one case this wouldn't work...!!! Its a catch.


suppose the dto is enclosed in session scope then the same would result into ["xyz",""] i.e. null string. I found that this is never getting updated and when i removed the dto from the session scope then it gave ["xyz","123"] result. so whats the session scope doing here?

i tried thisway in the jsp:
&lt;s: textfield name="dto.map['xyz']" /&gt;
&lt;s:property value="dto.map" /&gt;

this resulted a textbox and a text: [xyz,''] thats the catch: i.e. when the jsp is being rendered itself the map is being put with key xyz if its not present in the map. and for this reson the text [xyz,] is being printed... supposing that this is not the case then it would have rendered a text as [,] i.e. empty map.

for this reason when the textbox is trying to put the value into the map, as the key is already present its unable to do so...

To discover this it took me 2 days of effort.. may b it saves some of ur efforts and stops u from reinventing the wheel...

thats for now.. watch the space for more interesting things to come up...