Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, April 3, 2013

Error Handling in Jaggery

Proper error handling is a key points in any application. If you are using WSO2 Jaggery, then you might have also come up with the same requirement.

Jaggery is JavaScript, hence try, catch and finally blocks can be used within your code as you usual. Also,  passed JavaScript Error object can be used to get a brief information about the error. But, as we are dealing with a server side environment, we might need to know additional details about the errors, such as stacktrace, line numbers etc.

Using the additional properties/methods which can be found in the passed Error object, error details can be accessed as below.
var log = new Log();

try {
    parse(null); //code where exception is thrown
} catch (e) {
    log.error(e.lineNumber); // Error occured line number
    log.error(e.fileName); // Error occured script name
    log.error(e.stack); // Executed JavaScript file stack
    log.error(e.message); // JavaScript error message

    log.error(e.rhinoException); // Rhino exception object
    log.error(e.javaException); // Java excepton object

    log.error(e); // Logs the stack trace

    print(e); // prints the stack trace
} finally {
    log.info('finally :)');
}


Thursday, March 14, 2013

Logging in Jaggery

In Jaggery, you can log with different levels i.e. debug, info, warn, error, fatal which can be enabled/disabled using the logLevel parameter in the jaggery.conf.
{
    "welcomeFiles" : ["index.html"],
    "logLevel" : "debug"
} 

Logging can be done with the desired log level using log.debug(), log.info(), log.warn(), log.error() and log.fatal() methods. Also, whether the debug logs are enabled can be checked using log.isDebugEnabled().
var log = new Log();

if(log.isDebugEnabled()) {
    log.debug('This is a debug log');
}

log.info('This is an info log');
log.warn('This is a warning log');
log.error('This is an error log');
log.fatal('This is a fatal log');

Get Environment Variables and System Properties in Jaggery

Environment variables and system properties can be read using the process module as below.
var process = require('process');

print(process.getEnvs()); // json object
print(process.getEnv('PATH')); // string
print(process.getProperties()); // json object
print(process.getProperty('jaggery.home')); // string

How to Generate a UUID in Jaggery

A UUID can be generated in WSO2 Jaggery server using the uuid module as below.
var uuid = require('uuid');
var id = new uuid.UUID();

print(id.toString()); // 0af9cb30-f660-4d5c-8d39-28cf87c7e574

How to Execute Tasks in WSO2 Jaggery

If you have come across the requirement of executing timer tasks within a Jaggery code, then you can use the following code to do that. These are the same set of functions that you have in the browser.

You can also use clearTimeout and clearInterval functions to stop the task execution.

One time tasks
setTimeout(function() {
     var log = new Log();
     log.info('setTimeout() is executed after 2s');
}, 2000);  
Recurring tasks
setInterval(function() {
     var log = new Log();
     log.info('setInterval() is being executed within 4s intervals');
}, 4000);

Thursday, June 16, 2011

XML to JSON and JSON to XML Conversion in Javascript

When we deal with today's highly ajax based web application developments, dealing with XMLs within your page might be a little bit tedious task. As all of us know, JavaScript doesn't have a proper way to deal with XMLs(although recent specs supports E4X, it hasn't implemented in all browsers). If we can convert the XML into a JSON format, then it will be a great relief for web developers.

Although there are many XML to JSON notations available, all of them tends to ignore xml namespaces, but Badgerfish. So, I thought of writing a JavaScript code which does the XML to JSON conversion and wise-versa. If you want to get the Javascript code for XML to JSON, then go though my blog post XML to BadgerFish Conversion in Javascript. In this post, I will give you the function which converts JSON back to it's original XML.

Using these xml2bf and bf2xml functions, you will get the most flexibility with XML in your web developments.
function bf2xml(json) {
    if (typeof json !== "object") return null;
    var cloneNS = function(ns) {
        var nns = {};
        for (var n in ns) {
            if (ns.hasOwnProperty(n)) {
                nns[n] = ns[n];
            }
        }
        return nns;
    };
    var processLeaf = function(lname, child, ns) {
        var body = "";
        if (child instanceof Array) {
            for (var i = 0; i < child.length; i++) {
                body += processLeaf(lname, child[i], cloneNS(ns));
            }
            return body;
        } else if (typeof child === "object") {
            var el = "<" + lname;
            var attributes = "";
            var text = "";
            if (child["@xmlns"]) {
                var xmlns = child["@xmlns"];
                for (var prefix in xmlns) {
                    if (xmlns.hasOwnProperty(prefix)) {
                        if (prefix === "$") {
                            if (ns[prefix] !== xmlns[prefix]) {
                                attributes += " " + "xmlns=\"" + xmlns[prefix] + "\"";
                                ns[prefix] = xmlns[prefix];
                            }
                        } else if (!ns[prefix] || (ns[prefix] !== xmlns[prefix])) {
                            attributes += " xmlns:" + prefix + "=\"" + xmlns[prefix] + "\"";
                            ns[prefix] = xmlns[prefix];
                        }
                    }
                }
            }
            for (var key in child) {
                if (child.hasOwnProperty(key) && key !== "@xmlns") {
                    var obj = child[key];
                    if (key === "$") {
                        text += obj;
                    } else if (key.indexOf("@") === 0) {
                        attributes += " " + key.substring(1) + "=\"" + obj + "\"";
                    } else {
                        body += processLeaf(key, obj, cloneNS(ns));
                    }
                }
            }
            body = text + body;
            return (body !== "") ? el + attributes + ">" + body + "</" + lname + ">" : el + attributes + "/>"
        }
    };
    for (var lname in json) {
        if (json.hasOwnProperty(lname) && lname.indexOf("@") == -1) {
            return processLeaf(lname, json[lname], {});
        }
    }
    return null;
}

Tuesday, February 22, 2011

Parse XML String into DOM with Javascript

You can use following function to convert any XML string into a DOM object from a browser.
function parseXML(xml) {
    xml = xml.replace(/^[\s\n\r\t]*[<][\?][xml][^<^>]*[\?][>]/, "");
    var doc;
    if (window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = false;
        doc.loadXML(xml);
    } else
        doc = (new DOMParser()).parseFromString(xml, "application/xml");
    return doc;
}

Online XML to JSON Converter using Badgerfish Notation

I have hosted an online XML to JSON converter at http://gogooog.com. It has been implemented purely with Javascript. You can read about the xml to badgerfish conversion at http://ruchirawageesha.blogspot.com/2011/01/xml-to-badgerfish-converter-in.html.

Friday, January 28, 2011

XML to BadgerFish Conversion in Javascript

Recently I came across the need of converting an xml into a JSON format. There I used BadgerFish notation to transform the xml into JSON.

You can use following Javascript function to convert any DOM node into the relevant BadgerFish notation. You can convert any XML string into a DOM object using method described at Parse XML String into DOM with Javascript

Please find the hosted version of XML to Badgerfish converter at gogooog.com
function xml2bf(node) {
    var json = {};
    var cloneNS = function(ns) {
        var nns = {};
        for (var n in ns) {
            if (ns.hasOwnProperty(n)) {
                nns[n] = ns[n];
            }
        }
        return nns;
    };
    var process = function (node, obj, ns) {
        if (node.nodeType === 3) {
            if (!node.nodeValue.match(/[\S]+/)) return;
            if (obj["$"] instanceof Array) {
                obj["$"].push(node.nodeValue);
            } else if (obj["$"] instanceof Object) {
                obj["$"] = [obj["$"], node.nodeValue];
            } else {
                obj["$"] = node.nodeValue;
            }
        } else if (node.nodeType === 1) {
            var p = {};
            var nodeName = node.nodeName;
            for (var i = 0; node.attributes && i < node.attributes.length; i++) {
                var attr = node.attributes[i];
                var name = attr.nodeName;
                var value = attr.nodeValue;
                if (name === "xmlns") {
                    ns["$"] = value;
                } else if (name.indexOf("xmlns:") === 0) {
                    ns[name.substr(name.indexOf(":") + 1)] = value;
                } else {
                    p["@" + name] = value;
                }
            }
            for (var prefix in ns) {
                if (ns.hasOwnProperty(prefix)) {
                    p["@xmlns"] = p["@xmlns"] || {};
                    p["@xmlns"][prefix] = ns[prefix];
                }
            }
            if (obj[nodeName] instanceof Array) {
                obj[nodeName].push(p);
            } else if (obj[nodeName] instanceof Object) {
                obj[nodeName] = [obj[nodeName], p];
            } else {
                obj[nodeName] = p;
            }
            for (var j = 0; j < node.childNodes.length; j++) {
                process(node.childNodes[j], p, cloneNS(ns));
            }
        } else if (node.nodeType === 9) {
            for (var k = 0; k < node.childNodes.length; k++) {
                process(node.childNodes[k], obj, cloneNS(ns));
            }
        }
    };
    process(node, json, {});
    return json;
}

Wednesday, January 26, 2011

All about Javascript Functions

If you're a Javascript fan, it's worth reading JavaScript, 5 ways to call a function which nicely explains must to know concepts behind Javascript functions.

Thursday, July 29, 2010

Regular Expressions with Javascript

Here is an excellent demonstration of Regular Expression usage in Javascript.

http://lawrence.ecorp.net/inet/samples/regexp-format.php

Sunday, December 6, 2009

Serialize Javascript to PHP

When interacting Javascript with PHP, you might need to serialise any Javascript data type into the PHP serialized format, where it can be unserialized using PHP. The following function will serialize any Javascript data.
function serialize(mixed_value) {
    var _getType = function(inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
        case "function":
            val = "";
            break;
        case "null":
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") {
                    continue;
                }

                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}
The code fragment below will do the serializing in Javascript and the later code will unserialize it in PHP.
var array = ["ruchira", "wageesha"];
//serialize value
var serialize_array = serialize(array);
$array = unserialize($_POST['array']);

Friday, September 11, 2009

Javascript Popup - close after redirect

If you want to redirect the popup window to another location (a page or a file download) and then close the window, you can simply use the following javascript.
<script type="text/javascript">
    window.opener.location = "new_page.htm";
    window.close();
</script>

Monday, May 25, 2009

PNG Tranparency in IE6

1 . First Download this Zip file and unzip

2 . Copy and paste iepngfix.htc and blank.gif into your website folder.

3 . Copy and paste this into your website's CSS or HTML:
<style type="text/css">
    img, div { behavior: url(iepngfix.htc) }
</style>
That CSS selector must include the tags/elements on which you want PNG support -- basically, give it a comma-separated list of tags you use. It must also include the correct path to the .HTC relative to the HTML document location (not relative to the CSS document!). For instance, yours may look like this:
<style type="text/css">
    img, div, a, input { behavior: url(/css/resources/iepngfix.htc) }
</style>
4 . If your site uses subfolders, open the .HTC file in a text editor like Windows Notepad and change the blankImg variable to include a correct path to blank.gif like so:
IEPNGFix.blankImg = '/images/blank.gif';
Again the path is relative to the HTML file. Otherwise, you will see a "broken image" graphic!

5 . If you want support for CSS1 background-repeat and background-position, make sure you include the add-on .JS file in your <head>:
<script type="text/javascript" src="iepngfix_tilebg.js"></script>
Otherwise, background images will work but won't repeat or position.

You can view two other methods at
http://jquery.andreaseberhard.de/pngFix/
http://koivi.com/ie-png-transparency/