Wednesday, May 25, 2016

Some basic experiments with dojo/_base/lang

The important pointers to remember about this package are, this provides following functionalities
Clone – helps clone a node to an other. A literal copy
Delegate – helps create a bounded subclassed object. Changes are reflected to child when parent object is changed, provided, its done in the oops way *(note1:refer note below)
exists getObject setObject
extend mixin partial – extend works with prototype, mixin with properties and partial helps overload functions with ease
hitch – force scope for an object
replace – A huge feature. Lot of varities and customizations are possible. Refer the following html code to understand what it does

var lang=require("dojo/_base/lang")
var obj = { a:"b", c:"d" };
var thing = lang.delegate(obj);
thing; //:is a {a: "b", c: "d", e: "f"}
obj = { a:"b", c:"d" , g:"h"};
thing; //:is still a {a: "b", c: "d", e: "f"} – note g:”h” did not get updated as it was not done in the oops way.

Use the following html file and watch the logs that gets printed. Then run through the code that produced them. This will you understand what does what
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dojo Lang</title>

<script src="//"
data-dojo-config="async: true"></script>

//lang.extend & lang.mixin
require([ "dojo/_base/lang", "dojo/json" ], function(lang, json) {
// define a class
var myClass = function() {
this.defaultProp = "default value";
myClass.prototype = {};
console.log("the class (unmodified):", json

// extend the class
lang.extend(myClass, {
"extendedProp" : "extendedValue"
console.log("the class (modified with lang.extend):", json

var t = new myClass();
// add new properties to the instance of our class
lang.mixin(t, {
"mixin property" : "myValue"
console.log("\nmixin does not bother protoype")
console.log("the instance (modified with lang.mixin):", json

require([ "dojo/_base/lang" ], function(lang) {
// define an object (intentionally global to demonstrate)
foo = {
bar : "lang.getObject() value"

console.log("" + lang.getObject(""));// returns "some value"

// get the "foo.baz" property, create it if it doesn't exist
console.log(lang.getObject("foo.baz", true)); // returns foo.baz - an empty object {}

// get the "bar" property of the foo object
console.log(lang.getObject("bar", false, foo)); // returns "some value"

//helps create over loaded function
console.log('\n****Overload functions using lang.partial****')
require([ "dojo/_base/lang", "dojo/request" ], function(lang, request) {
var dataLoaded = function(funcName, someFirstParam, data, ioargs) {
if (!funcName || funcName == '')
funcName = 'dataLoaded';
console.log(funcName + "::someFirstParam=" + someFirstParam);
console.log(funcName + "::data=" + data);
console.log(funcName + "::ioargs=" + ioargs);

console.log('\ndataLoaded() gives following logs');
var partialDataLoaded = lang.partial(dataLoaded, "partialDataLoaded",
console.log('\npartialDataLoaded() gives following logs');
console.log('\npartialDataLoaded("myData") gives following logs');

[ "dojo/_base/lang", "dojo/dom", "dojo/_base/array",
"dojo/domReady!" ],
function(lang, dom, array) {

replacedString = lang.replace(
"Hello, {name.first} {name.last} AKA {nick}!", {
name : {
first : "Karthikeyan",
middle : "X",
last : "Alagirisamy"
nick : "AK"
console.log('replacedString=' + replacedString);
replacedString = lang.replace("Hello, {0} {2} AKA {3}!", [
"Karthikeyan", "X", "Alagirisamy", "Manda" ]);
console.log('replacedString=' + replacedString);

console.log('\n*** replace with a function');

// helper function for complex replace
function sum(a) {
var t = 0;
array.forEach(a, function(x) {
t += x;
return t;

var complexReplace = lang
"{count} items averaging {avg} per item ranging from {min} to {max} with a total sum of {sum}.",
payments : [ 11, 16, 12, 24, 99,
46, 8, 82 ]
}, function(_, key) {
switch (key) {
case "count":
return this.payments.length;
case "min":
return Math.min.apply(Math,
case "max":
return Math.max.apply(Math,
case "sum":
return sum(this.payments);
case "avg":
return sum(this.payments)
/ this.payments.length;

console.log("complexReplace = " + complexReplace);

console.log("\n***Replace using custom patterns");
var customReplace = lang
.replace("Hello, %[0] %[2] AKA %[3]!", [ "Robert", "X",
"Cringely", "Bob" ], /\%\[([^\]]+)\]/g);
console.log("customReplace=" + customReplace);

console.log("\n***Escaping Substitutions");
function safeReplace(tmpl, dict) {
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name) {
return lang.getObject(name, false, dict);

// perform the substitution
return lang.replace(tmpl, function(_, name) {
if (name.charAt(0) == '!') {
// no escaping
return fn(_, name.slice(1));
// escape
return fn(_, name).replace(/&/g, "&")
.replace(/</g, "<").replace(/>/g, ">").replace(
/"/g, '"');

// we don't want to break the Code Glass widget here
var bad = "{script}alert('Let\' break stuff!');{/script}";

// let's reconstitute the original bad string
bad = bad.replace(/\{/g, "<").replace(/\}/g, ">");

// now the replacement
var escapedSubstitution = safeReplace("<div>{0}</div", [ bad ]);
console.log('escapedSubstitution=' + escapedSubstitution);

console.log('\n****Formatting Substitutions');
function format(tmpl, dict, formatters) {
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name) {
return lang.getObject(name, false, dict);

// perform the substitution
return lang.replace(tmpl,
function(_, name) {
var parts = name.split(":"), value = fn(_,
if (parts.length > 1) {
value = formatters[parts[1]](value, parts
return value;

// simple numeric formatters
var customFormatters = {
f : function(value, opts) {
// return formatted as a fixed number
var precision = opts && opts.length && opts[0];
return Number(value).toFixed(precision);
e : function(value, opts) {
// return formatted as an exponential number
var precision = opts && opts.length && opts[0];
return Number(value).toExponential(precision);

// that is how we use it:
var output1 = format(
"pi = {pi}<br>pi:f = {pi:f}<br>pi:f:5 = {pi:f:5}", {
pi : Math.PI,
big : 1234567890
}, customFormatters);

var formatingSubEx1 = format(
"pi = {pi}<br>pi:f = {pi:f}<br>pi:f:5 = {pi:f:5}", {
pi : Math.PI,
big : 1234567890
}, customFormatters);

var formatingSubEx2 = format(
"big = {big}<br>big:e = {big:e}<br>big:e:5 = {big:e:5}",
pi : Math.PI,
big : 1234567890
}, customFormatters);

console.log("formatingSubEx1=" + formatingSubEx1);
console.log("formatingSubEx2=" + formatingSubEx2);

var obj={};
lang.setObject("parent.child.prop", "some value", obj);
console.log("obj.parent.child.prop=" + obj.parent.child.prop);

function show(str) {
console.log("|" + lang.trim(str) + "|");
show("   one");
show("two ");
show("   three ");
show("\f\n\r\t\vF I V E\f\n\r\t\v");

isString() Checks if the parameter is a String
isArray() Checks if the parameter is an Array
isFunction() Checks if the parameter is a Function
isObject() Checks if the parameter is a Object
isArrayLike() Checks if the parameter is like an Array
isAlien() Checks if the parameter is a built-in function


Console shall produce the following output
the class (unmodified): {}
dojo_base_lang.html:25 the class (modified with lang.extend): {"extendedProp":"extendedValue"}
mixin does not bother protoype
dojo_base_lang.html:34 the instance (modified with lang.mixin): {"defaultProp":"default value","mixin property":"myValue"}
dojo_base_lang.html:46 value
dojo_base_lang.html:49 Object {}
dojo_base_lang.html:52 lang.getObject() value
****Overload functions using lang.partial****
dataLoaded() gives following logs
dojo_base_lang.html:62 dataLoaded::someFirstParam=undefined
dojo_base_lang.html:63 dataLoaded::data=undefined
dojo_base_lang.html:64 dataLoaded::ioargs=undefined
partialDataLoaded() gives following logs
dojo_base_lang.html:62 partialDataLoaded::someFirstParam=firstValue
dojo_base_lang.html:63 partialDataLoaded::data=undefined
dojo_base_lang.html:64 partialDataLoaded::ioargs=undefined
partialDataLoaded("myData") gives following logs
dojo_base_lang.html:62 partialDataLoaded::someFirstParam=firstValue
dojo_base_lang.html:63 partialDataLoaded::data=myData
dojo_base_lang.html:64 partialDataLoaded::ioargs=undefined
dojo_base_lang.html:92 replacedString=Hello, Karthikeyan Alagirisamy AKA AK!
dojo_base_lang.html:95 replacedString=Hello, Karthikeyan Alagirisamy AKA Manda!
*** replace with a function
dojo_base_lang.html:133 complexReplace = 8 items averaging 37.25 per item ranging from 8 to 99 with a total sum of 298.
***Replace using custom patterns
dojo_base_lang.html:139 customReplace=Hello, Robert Cringely AKA Bob!
***Escaping Substitutions
dojo_base_lang.html:169 escapedSubstitution=<div><script>alert('Let' break stuff!');</script></div
****Formatting Substitutions
dojo_base_lang.html:225 formatingSubEx1=pi = 3.141592653589793<br>pi:f = 3<br>pi:f:5 = 3.14159
dojo_base_lang.html:226 formatingSubEx2=big = 1234567890<br>big:e = 1e+9<br>big:e:5 = 1.23457e+9
dojo_base_lang.html:231 obj.parent.child.prop=some value
dojo_base_lang.html:235 |one|
dojo_base_lang.html:235 |two|
dojo_base_lang.html:235 |three|
dojo_base_lang.html:235 |four|
dojo_base_lang.html:235 |F I V E|

Tuesday, August 25, 2015

This compilation unit is not on the build path of a Java project

Problem: Eclipse Showing error message - "This compilation unit is not on the build path of a Java project"
If you import a project as a General Project, it wont have the java nature and that will be a problem. In my case this was true . And rectifying the same will be as follows,
 Add the below lines in the .project file of your workspace and refresh.

Thursday, May 14, 2015

Deploying dojo in Apache Tomcat

Well this is something that I did not want to reinvent and so I searched for the same in the internet aggressively for hours. Guess I am a little dumb. Though I found pages relating to the same, I did not find what I was looking for and instead I found this advice in multiple pages. Guess I am a little smart to understand this advice and hence I ended up working on it and found something that I can remember for a long time J. Really feels a little happy insideJ
My aim is to deploy dojo somewhere in the root directory of the tomcat server, so it becomes automatically available for all the applications that are deployed in the server. I had previously done such things using IIS servers and lotus domino servers. Lotus domino servers have classy ways and it actually comes with dojo inbuilt. Well trying not to deviate from the topic, actually I did not find a solution and ended up finding a work around.
I understand that the Dojo files needs to be deployed in the eclipseWorspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps directory to be available to the apps in the workspace. I know I can write software to do that and I know it could be the most dumbest thing I would have done in a long time. lol.
So I tried creating a separate web project which serves as a content management system for dojo and tried including the same in my other apps. The problem is though they worked, the huge size of dojo and its allied packages like dgrid 40+ MB really messed with my patience when the server had to republish them every time.
Necessity is the mother of all inventions, someone said. I know I did not invent this, but atleast reinvented it lol, created a separate workspace, with a separate server serving dojo packages and used them in my other workspaces holding my apps which required dojo.
Hurray, that’s my answer. lol. Stop, stop!!! don’t scold me.
Create a new workspace and create a new dynamic web application. Now import the dojo folder into the webContent folder of that app as illustrated by the following screen shot
Add your dojo application to the server, by right clicking on the server and click on “add or remove” and run it as illustrated by the following screen shot.
Now go and include this dojo package in your application as illustrated in the following screen shot
Hope you don’t scold me now. At least it’s what I use :@

Tuesday, May 12, 2015

A simple dojo JSONP example

Well I almost got sick of find out the missing link. The missing link I am talking about is something like “What the hell am I missing for a dojo JSONP request to work?” as I was trying those examples provided in 
Thanks to the post by Jason Schock  titled “So how does JSONP really work?”. With little tinkering I understood how native plain JSONP requests work.
All that was provided in the dojotookit websites says to use jsonp:’callback’ in the script request and that kept failing miserably even though I was able to see responses in the chrome’s developer tool->network tab->response tab of urls that have been hit from the page.
So the trick is to define a variable whose scope is available for both your dojo’s request – script’s jsonp request and callback function definition.
Following is my html file that creates this Jsonp request to a data.jsonp.js file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dojo Topic</title>
<script src="//"
       data-dojo-config="async: true"></script>

.output {
       border: 2px solid green;
       margin: 10px;
       padding: 10px;
       color: #eeeeee;
       background-color: #000000;
       width: 500px;
       min-height: 200px;
       var jsonpRespData = null;
       require([ "dojo/request/script", "dojo/dom", "dojo/dom-construct",
                     "dojo/json", "dojo/on", "dojo/domReady!" ], function(script, dom,
                     domConst, JSON, on) {
              on(dom.byId("startButton"), "click", function() {
           "<p>Requesting...</p>", "output");
                     script.get("/DojoCracker/data/data.jsonp.js", {
                           //jsonp : "dojo_request_script_callbacks.dojo_request_script0",
                           query: {
                                  "callback" : "mycallback"
                                  function(data) {
                               "<p>response data: <code>"
                                                       + JSON.stringify(jsonpRespData) + "</code></p>",
                                  },function(error) {
                               "<p>Error: <p>"
                                                       + error.response.text + "</p></p>",
       function mycallback(data){
              jsonpRespData = data

       <div id="output" class='output'></div>
       <button type="button" id="startButton">Start</button>
The closure in the my data.jsonp.js file as  follows
//dojo_request_script_callbacks.dojo_request_script0({ - will come to this later
              "identifier" : "abbr",
              "label" : "name",
              "items" : [ {
                     "abbr" : "ec",
                     "name" : "Ecuador",
                     "capital" : "Quito"
              }, {
                     "abbr" : "eg",
                     "name" : "Egypt",
                     "capital" : "Cairo"
              }, {
                     "abbr" : "sv",
                     "name" : "El Salvador",
                     "capital" : "San Salvador"
              }, {
                     "abbr" : "gq",
                     "name" : "Equatorial Guinea",
                     "capital" : "Malabo"
              }, {
                     "abbr" : "er",
                     "name" : "Eritrea",
                     "capital" : "Asmara"
              }, {
                     "abbr" : "ee",
                     "name" : "Estonia",
                     "capital" : "Tallinn"
              }, {
                     "abbr" : "et",
                     "name" : "Ethiopia",
                     "capital" : "Addis Ababa"
              } ]

So here is the explanation.  When you look into the html code you will be able to find the following
<![if !supportLists]>1.       <![endif]>First a variable is simply declared and initialized to null – “var jsonpRespData = null;”
<![if !supportLists]>2.       <![endif]>Then comes the dojo code with jsonp callback definition -
query: {"callback":"mycallback"}
<![if !supportLists]>3.       <![endif]>Then there is this function definition mycallback(data)
<![if !supportLists]>4.       <![endif]>Then back in the jsonp success callback I use - JSON.stringify(jsonpRespData)

And that’s what I see on the screen

So why bother this much when its not documented in the dojotoolkit website. Well when I use the param jsonp:’callback’ as such as described in the dojotoolkit website, I see the following on the screen
And this error on regarding the closure defined in the data.jsonp.js  file and I don’t get a hold on the response even though I see it in the response and preview tab
Well something tells me that I still miss a link o.0

This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful. Where permitted by applicable law, this e-mail and other e-mail communications sent to and from Cognizant e-mail addresses may be monitored.