Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

25 May 2012

Showing Memory status using Dojo Pie chart


Widget Tree strucuture

.
|-- dijit
|   |-- _base
|    ...
|-- dojo
|   |-- _base
|   ...
|-- dojox
|   |-- analytics
|    ...
`-- widgets
    `-- admin
        |-- MemoryStatus.js
        `-- memoryStatus.tmpl


1. Source code for MemoryStatus.js

require(
    [
        "dojo/_base/declare", "dojo/parser", "dojo/ready",
        "dijit/_WidgetBase",  "dijit/_TemplatedMixin",
        "dijit/_WidgetsInTemplateMixin", "dojo/html",


        // Require the theme of our choosing
        "dojox/charting/themes/Claro",

        "dojox/charting/Chart",
        //     We want to plot a Pie chart
        "dojox/charting/plot2d/Pie",
                   
        // Retrieve the Legend, Tooltip, and MoveSlice classes
        "dojox/charting/action2d/Tooltip",
        "dojox/charting/action2d/MoveSlice",

        //    We want to use Markers
        "dojox/charting/plot2d/Markers",

        //    We'll use default x/y axes
        "dojox/charting/axis2d/Default",
       
        "dojox/charting/widget/Legend"
    ],
      
    function(declare, parser, ready, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, html){

        declare("widgets.admin.MemoryStatus", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin ], {
            templatePath: "js/dojo/widgets/admin/memoryStatus.tmpl",
            widgetsInTemplate : true,
            memsize: 3851124,
            used : 2375716,
            shared : 0,
            buffers : 268604,
            cached: 619712,

            postCreate : function (args, farg)
            {
                this._set();
            },

            getData : function()
            {
                var free = this.memsize-this.used;
                return [
                    { "x": "1", "y": this.used, text : "Memory used" ,  tooltip : "Memory used : " + this.bytesToSize(this.used)},
                    { "x": "2", "y": free,      text : "Free memory" , tooltip: "Free Memory: " + this.bytesToSize(free) }
                ];
            },

            _set : function()
            {
                if (this.loaded == true ) {
                    return;
                }
                this.loaded = true;
                var chart = new dojox.charting.Chart(this.graphicalNode);
                chart.setTheme(dojox.charting.themes.Claro);
                chart.addPlot("default", {type: 'Pie', markers: true, labelOffset: -20});
                chart.addSeries("Memory", this.getData());

                // Create the tooltip
                var tip = new dojox.charting.action2d.Tooltip(chart, "default");

                // Create the slice mover
                var mag = new dojox.charting.action2d.MoveSlice(chart,"default");

                chart.render();

                var legend = new dojox.charting.widget.Legend({ chart: chart }, this.legendsNode);
               
            },

            bytesToSize: function (kbytes) {
                    var bytes = kbytes * 1024;
                    var sizes = [ 'n/a', 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                    var i = +Math.floor(Math.log(bytes) / Math.log(1024));
                    return  (bytes / Math.pow(1024, i)).toFixed( i ? 1 : 0 ) + ' ' + sizes[ isNaN( bytes ) ? 0 : i+1 ];
            }

        });

        ready(function(){
            // Call the parser manually so it runs after our widget is defined, and page has finished loading
            parser.parse();
        });

    }
);

2. Source code for memoryStatus.tmpl

<div id="${id}">
    <div data-dojo-attach-point='graphicalNode'></div>
    <div data-dojo-attach-point='legendsNode'></div>
</div>


3. Using widget in HTML sample code

<html>
<head>
    <title> Memory status: </title>

    <link rel="stylesheet" type="text/css" href="/test1/js/dojo/dojo/resources/dojo.css"/>
    <link rel='stylesheet' type="text/css" hfre='text1/js/dojo/dijit/themes/tundra/ProgressBar.css'/>
    <link rel="stylesheet" href="/test1/js/dojo/dijit/themes/tundra/tundra.css"></link>
    <script src="/test1/js/dojo/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: false" ></script>

    <script type='text/javascript'>
        require(["dijit/registry", "dojo/parser", "widgets/admin/MemoryStatus",
                "dojo/domReady!"], function(registry, parser) {
                    // Explicitly parse the page
                    //parser.parse();

                });
    </script>
    
</head>
    <body class='tundra'>

        <br>
        <h1> Memory usage: </h1>
        <br>
        <div data-dojo-type="widgets.admin.MemoryStatus" memsize=3851124 used=2396496 style="width:400px:margin:50px"></div>

        <br><br>
        <div data-dojo-type="widgets.admin.MemoryStatus" memsize=3851124 used=3680680 style="width:400px"></div>
    </body>
</html>


4. Sample output


Showing disk usage using Dojo Progress bar


Widget directory strcuture :
.
|-- dijit
|   |-- _base
|    ...
|-- dojo
|   |-- _base
|   ...
|-- dojox
|   |-- analytics
|    ...
`-- widgets
    `-- admin
        |-- FileSystemStatus.js
        `-- fileSystemStatus.tmpl


1. Source code for FileSystemStatus.js

require(
    [
        "dojo/_base/declare", "dojo/parser", "dojo/ready",
        "dijit/_WidgetBase",  "dijit/_TemplatedMixin",
        "dijit/_WidgetsInTemplateMixin", "dojo/html",
        "dojo/dom-class", "dojo/query", "dojo/NodeList-dom",
        "dijit/ProgressBar",
    ],
      
    function(declare, parser, ready, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, html, domClass,query){

        declare("widgets.admin.FileSystemStatus", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin ], {
            templatePath: "js/dojo/widgets/admin/fileSystemStatus.tmpl",
            widgetsInTemplate : true,

            filesystem : "tmpfs",
            mountedon : "/dev/shm",
            fssize : 255204,
            used: 0,
            isloaded: false,

            postCreate : function (args, farg)
            {
                this._set();
            },

            _set : function()
            {
                if(this.isloaded)
                return true;

                //html.set(this.textNode_fs, this.filesystem);
                html.set(this.textNode_mo, this.mountedon);
                html.set(this.textNode_size, "" + this.bytesToSize(this.fssize));
                var free = (this.fssize - this.used);
                var percentage = ((this.used/this.fssize) * 100);
                percentage = dojo.number.format(percentage, {places:2})
                html.set(this.textNode_free, "" + this.bytesToSize(free));
                this.graphicalNode.set("value", percentage);
                if (percentage >= 60.00) {
                    query(".dijitProgressBarTile", this.graphicalNode.domNode).addClass("red");
                    query(".dijitProgressBarTile", this.graphicalNode.domNode).removeClass("dijitProgressBarTile");
                } else if (percentage > 20.00){
                    query(".dijitProgressBarTile", this.graphicalNode.domNode).addClass("orange");
                    query(".dijitProgressBarTile", this.graphicalNode.domNode).removeClass("dijitProgressBarTile");
                } else {
                    query(".dijitProgressBarTile", this.graphicalNode.domNode).addClass("green");
                    query(".dijitProgressBarTile", this.graphicalNode.domNode).removeClass("dijitProgressBarTile");
                }
                this.isloaded = true;
            }, 


         bytesToSize: function (kbytes) {
               var bytes = kbytes * 1024;
               var sizes = [ 'n/a', 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
               var i = +Math.floor(Math.log(bytes) / Math.log(1024));
               return  (bytes / Math.pow(1024, i)).toFixed( i ? 1 : 0 ) + ' ' + sizes[ isNaN( bytes ) ? 0 : i+1 ];
            }

        });

        ready(function(){
            // Call the parser manually so it runs after our widget is defined, and page has finished loading
            parser.parse();
        });

    }
);






2. Code for fileSystemStatus.tmpl

<div id="${id}">
    <span style='font-size:14px;'>
        <span data-dojo-attach-point='textNode_mo'></span>
    </span> <br/>
    <span data-dojo-attach-point='graphicalNode' data-dojo-type="dijit.ProgressBar"></span>
    <span data-dojo-attach-point='textNode_free'></span> free of <span data-dojo-attach-point='textNode_size'></span> 
</div>


3. Using widget in HTML, html page code :
<html>
<head>
    <title> File system status: </title>

    <link rel="stylesheet" type="text/css" href="/test1/js/dojo/dojo/resources/dojo.css"/>
    <link rel='stylesheet' type="text/css" hfre='text1/js/dojo/dijit/themes/tundra/ProgressBar.css'/>
    <link rel="stylesheet" href="/test1/js/dojo/dijit/themes/tundra/tundra.css"></link>
    <script src="/test1/js/dojo/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: false" ></script>

    <STYLE type='text/css'>

    .red {
            /*
            background: url("/test1/reddark.jpg") repeat-x scroll center center #F0F0F0;
            */
            background :     #880000 ;
            background-color: #880000;
            color  : white;
            width  :  100%;
            bottom : 0;
            height : auto;
            rigt    : 0;
            top     : 0;
            left   : 0;
            margin : 0;
            overflow: hidden;
            padding : 0;
            position: absolute;
        }

    .orange {
            background: #f1a165;
            background-color: #f1a165;
            color : #f1a165;
            width  :  100%;
            bottom : 0;
            height : auto;
            rigt    : 0;
            top     : 0;
            left   : 0;
            margin : 0;
            overflow: hidden;
            padding : 0;
            position: absolute;
    }

    .green {
            background: 00CC33;
            background-color: 00CC33;
            color : #f1a165;
            width  :  100%;
            bottom : 0;
            height : auto;
            rigt    : 0;
            top     : 0;
            left   : 0;
            margin : 0;
            overflow: hidden;
            padding : 0;
            position: absolute;
    }


    </STYLE>



    <script type='text/javascript'>
        require(["dijit/registry", "dojo/parser", "widgets/admin/FileSystemStatus",
                "dojo/domReady!"], function(registry, parser) {
                    // Explicitly parse the page
                    //parser.parse();

        });
    </script>
   
</head>
    <body class='tundra'>

        <br>
        <h1> File system disk space usage </h1>

        <hr>
        <br>

        <div data-dojo-type="widgets.admin.FileSystemStatus" filesystem='/dev/sda7' mountedon='/home' fssize=49213248 used=2396496 style="width:400px"></div>
        <br>
        <br>

        <div data-dojo-type="widgets.admin.FileSystemStatus" filesystem='/dev/sda6' mountedon='/var' fssize=49213248 used=6259304 style="width:400px"></div>
        <br>
        <br>

        <div data-dojo-type="widgets.admin.FileSystemStatus" filesystem='/dev/sda5' mountedon='/media/Win7_Data' fssize=104857596 used=72896228 style="width:400px"></div>
        <br>
        <br>

        <div data-dojo-type="widgets.admin.FileSystemStatus" filesystem='/dev/sda3' mountedon='/media/Win7' fssize=104857596 used=26179940 style="width:400px"></div>
    </body>

</html>



4. Sample output : 

24 May 2012

Creating a custom Dojo Widget with Dojo 1.7


Dojo widgets can be placed under dojo root directory.
Sample directory strcuture for creating a sample widget is like

dojo
  - dijit
  - dojo
  - dojox
  - mywidget
      - TestWidget.js
      - widget.tmpl



Sample widget code ( TestWidget.js)

require (
// Define the dependancies
    [
        "dojo/_base/declare", "dojo/parser", "dojo/ready",
        "dijit/_WidgetBase",  "dijit/_TemplatedMixin",
        "dijit/_WidgetsInTemplateMixin",
        "dijit/layout/BorderContainer",
        "dijit/layout/AccordionContainer",
        "dijit/layout/TabContainer",
        "dijit/layout/ContentPane"
    ],
   
    // Pass them as argument to declare function

    function(declare, parser, ready, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin){
   
        // Actual Widget body goes here
        declare("mywiget.TestWidget", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin ], {

            // gives the path for template to use
            templatePath: "js/dojo/mywidget/widget.tmpl",
   
           // If want to use template String instead
           // templateString: "<div>MyWidget<div>;

            widgetsInTemplate : true,

            postCreate : function (args, farg)
            {
                //this.inherited('postCreate', arguments);
            },

            }
        });

        ready(function(){
            // Call the parser manually so it runs after our
           //  widget is defined, and page has finished loading
            parser.parse();
        });
    }
);



Sample widget template code (widget.tmpl)

<div id="${id}" style='height:100%; width:100%'>
    <div data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="liveSplitters:false, design:'sidebar'" style='height:100%; width:100%'>
        <div data-dojo-type="dijit.layout.AccordionContainer" data-dojo-props="region:'leading', splitter:true, minSize:20" style="width: 300px;">
            <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:'Tab1', style:'padding:10px;display:none;'">
                    Tab 1 Content
            </div>
        </div>
        <div data-dojo-type="dijit.layout.TabContainer" data-dojo-props="region:'center', tabStrip:true">
            <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="title:'Tab1', style:'padding:10px;display:none;'">
                Tab 1 content
            </div>
        </div>
    </div>
</div>




Using Widget in html page:

<html>
<head>
    <title> My widget : test</title>

    <link rel="stylesheet" type="text/css" href="js/dojo/dojo/resources/dojo.css"/>
    <link rel="stylesheet" href="js/dojo/dijit/themes/tundra/tundra.css"></link>

    <script src="js/dojo/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: false" ></script>

    <script type='text/css'>
    </script>

    <script type='text/javascript'>
        require(["dijit/registry", "dojo/parser", "mywidget/TestWidget",
                "dojo/domReady!"], function(registry, parser) {
                    // Explicitly parse the page
                    //parser.parse();

        });
    </script>
   
</head>
    <body class='tundra'>
        <span data-dojo-type="mywidget.TestWidget"></span>
    </body>
</html>


06 March 2012

Uploading file using Dojo and CGI AJAX

Sample Html file: (upload.html)

<html>
    <title>Upload file </title>
    <link href="/css/sitestyles.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="/js/dojo/dojo/resources/dojo.css"/>
    <link rel="stylesheet" type="text/css" href="/js/dojo/dijit/themes/tundra/tundra.css"/>
    <script type="text/javascript" src="/js/dojo/dojo/dojo.js" djConfig="parseOnLoad: true"></script>

    <script type="text/javascript">
    dojo.require("dijit.form.Form");
    dojo.require("dijit.form.Button");
    dojo.require("dojox.form.FileUploader");
    dojo.require("dijit.form.Button");
    dojo.require("dojo.parser");

    //using this early for the forceNoFlash test:
    dojo.require("dojox.embed.Flash");

    // Function to upload the file to server
    function doUpload () {
        var f0 = dijit.byId('btn0');
        console.log("doUpload")
        dojo.byId("fileToUpload").innerHTML = "uploading...";

        // If we want to send other fields along with the file
        // use submit method other use simple f0.upload() method
            f0.submit(dijit.byId('logoForm').domNode);
    }

    dojo.addOnLoad(function() {
        var f0 = dijit.byId('btn0');
       
        // Show file selected in div
        // data contains list of files selected
        dojo.connect(f0, "onChange", function(data){
        console.log("DATA:", data);
        var n = dojo.byId('fileToUpload');
        n.innerHTML = "";
        dojo.forEach(data, function(d){
            n.innerHTML += d.name
        });
        });

        // When file upload is in progress
        // Showing status inprogress
        dojo.connect(f0, "onProgress", function(data){
        console.warn("onProgress", data);
        var n = dojo.byId('fileToUpload');
        n.innerHTML = 'Uploading file';
        });

        //
        // Show the uploaded image
        // on successful upload of image
        //
        dojo.connect(f0, "onComplete", function(data){
        console.log("Uploaded file");
        var uf = dojo.byId('fileToUpload');
        var d = data[0];
        if ( d.status == "0" ) {
            uf.innerHTML = "<img src='" + data[0]['file'] + "'/>";
        } else {
            uf.innerHTML = d.message;
        }
        console.log(data);
        });
    });
    </script>

<body class='tundra'>
<center>

    <!-- Will show the status of file upload -->
    <table border='1' width='30%'>
    <tr>
    <td align='center'>
    <div id="uploadedFile"></div>
    <br>

    <!-- Other data to send to server along with file -->
    <form id='logoForm' dojoType='dijit.form.Form' accept="image/gif,image/jpeg">
        <div class='disabled'>
        <input name='action' value='upload' type='input'>
        </div>
    </form>
    <br>
    <!-- Show uploaded file -->
    <div id="fileToUpload"></div>
    <br>
    <!-- File uploader dijit -->
    <div id="btn0"
        dojoType="dojox.form.FileUploader"
        force="html"
        uploadOnChange=false isdebug=true htmlFieldName=orglogo
        uploadUrl="/sampleapp/upload-file" >
        Browse
    </div>
    <br>
    <div dojoType='dijit.form.Button' label='Upload' onClick='doUpload()'></div>
    <br>
    <br>
    </td>
    </tr>
    </table>
</center>
</body>
</html>


HTML tag


div id btn0 is File upload dijit with following properties :
force="html" if "html" html file uploader is used to upload file.
To use flash uploader set to "flash"

uploadOnChange=false If true selected file will be uploaded as soon as selected.

htmlFieldName=orglogo Name of html field under which the file-content to send

uploadUrl="/sampleapp/upload-file" Upload URL


Java script function:

dojo.connect(f0, "onChange", function(data){
});


Function used to display the selected file. This function will be called when file
browser dialoug is opened and we select a file. data will look like
[{ name="icon-server.png", size=0}]

dojo.connect(f0, "onProgress", function(data){
})

Function will be called when file uploading is in progress data will contain the
list of files. data will look like
[{bytesLoaded=1, bytesTotal=1, name="icon-server.png", percent=100, size=0, type=""}]

dojo.connect(f0, "onComplete", function(data){
})

Function will be called with server finishes the file process. It doesn't mean
successful file upload. You need send correct message and need to check from
data. data will look like
[{ status=0, file="/var/tmp/icon-server.png"}]

Server should send response in following format only and the should set header
Content-type: text/html.

Response format for success
<textarea>{"status":0,"file":"/var/tmp/a.xcf","message":null}</textarea>

Response format for error
<textarea>{"status":1,"file":"/var/tmp/a.xcf","message":"Invalid file format"}</textarea>

Response should be written in "textarea" tag

To send other form fields along with file use
var formdomNode = dijit.byId("logoForm").domNode;
dijit.byId("btn0").submit(formdomNode)


If you don't want any other field to send along file use
dijit.byId("btn0").upload() method


Sample server side code using Perl CGI
upload-file cgi


#!/usr/bin/perl -w

use strict;

use CGI;
my $result = {status => 1};

my $cgi = new CGI;
my $action = $cgi->param('action');

print "Content-type: text/html \n\n";

if ($action eq "upload") {

    #
    # Set MAX max upload limit
    #
    $CGI::POST_MAX = 1024 * 5000;


    my $msg;
    my $status = 0;
    my $INTERNAL_ERR = "Internal error";

    # What is field having file contain
    my $fieldname = 'orglogo0';
    my $filename = $cgi->param($fieldname);
    if (! $filename) {
    $msg = "File size exceded";
    }

    # Get file upload handle
    my $upload_filehandle = $cgi->upload($fieldname);
    my $uploadfilepath = "/var/tmp/$filename";

    # Write the file to disk
    if (open(UPLOADFILE, ">$uploadfilepath")) {
    if (! binmode UPLOADFILE)  {
        $msg = $INTERNAL_ERR;
    } else {
        while (<$upload_filehandle>) { 
        print UPLOADFILE;
        } 
        unless (close UPLOADFILE) {
        $msg = $INTERNAL_ERR;
        }
    }
    } else {
    $msg = $INTERNAL_ERR;
    }

    if ($msg) {
    $status = 1;
    }

    # Send status to client
    my $out = {
        file => $uploadfilepath,
        status => $status, 
        message => $msg
        };

    #
    # To handle cross platform problem dojo need the response in following format.
    # Reference: http://dojotoolkit.org/reference-guide/dojox/form/FileUploader.html
    #
    print "<textarea>". JSON::to_json ($out)."</textarea>";
    exit 0;

}

$result->{message} = "command not found";
print "<textarea>" . JSON::to_json($result) . "</textarea>"; 



07 January 2011

Writing custom Dojo widgets

Key terms:

Dijit :a dijit is any Dojo class that inherits from a foundational class from Dijit called _Widget. This class is part of the toolkit’s foundational dijit module, so the fully qualified name of the class is dijit._Widget.

Dijit is collection of css, javascript and HTML code.
Directory structure may be like:
 
+--dojo 
+  `--- customdijit
 +      `+--- TestDijit.js
 +       +--- templates
 +       +    `--- testdijit.html
 +       +--- themes 
 +             `--- testdijittheme.css
 +--dijit 
+--dojox 
 
TestDijit.js contains the Dijit class that extends the dojo foundation class _Widget.
testdijit.html contains the html code.
testdijittheme.css applies the theme for the dijit.

Source code for TestDijit.js

dojo.provide('customwidget.TestDijit')

dojo.declare("customwidget.TestDijit",  [dijit._Widget, dijit._Templated],
{
    // Template path for the template used for creating widget
    templatePath : dojo.moduleUrl('customwidget.template', 'testdijit.html'),

    // widget contains other Dojo widgets so set it to true
    widgetsInTemplate : true,

    // Language by default it is EN : English
    lang : 'EN',

     // This function is called after the widgets in templates are created
     // Hear we can add custom events, can used for initialization
     postCreate: function(args, frag)
     {
         this.inherited('postCreate', arguments);
     },
   
     // Function in widget will be called on button click 
      clickEvent : function()
      {
         alert("Button Click event");
     }
});


Sample template file: testdijit.html

<div id="${id}">
<!-- clickEvent will be fired when we click on button -->
<input dojoattachevent="onClick: clickEvent" dojotype="dijit.form.Button" label="Search" />

</div>


How to use the Dijit in HTML page

1. Load the module using dojo.require


<head>
<title>Testing Custom Widgets </title>
<link rel="stylesheet" type="text/css" href="/js/dojo/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href="/js/dojo/dijit/themes/tundra/tundra.css"/>
<script type="text/javascript" src="/js/dojo/dojo/dojo.js" djConfig="parseOnLoad:true"> </script>
<script type="text/javascript">

dojo.require("customwidget.TestWidget");

dojo.addOnLoad(function() {
});
</script>
</head>

<body>
<div dojoType='customwidget.TestWidget'/>
</body>

How to handle the date field in Apache Solr

Default Date format for Solr Date field is yyyy-MM-dd'T'HH:mm:sss'Z

Defining the date field in schema.xml of apache solr 
< field name="Date" datetimeformat="yyyy-MM-dd'T'HH:mm:sss'Z'" 
indexed="true" multivalued="false" stored='true' type="date"> </field>

Creating Date in Java application in required format,
the default Date format of java.util.Date is same as above so no need to format it.

we can directly add date like

SolrInputDocument doc = new SolarInputDocument();
doc.add("Date", new Date(), 0.3f);

or parsing date string using Date formater:

Date date = new Date();
String formatedDate = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss'Z'")).format(date);

06 January 2011

Writing Object oriented Javascript Programming Using DOJO

Writing custom classes using DOJO
writing a simple class
 

> dojo.provide("com.test.Utils");


this will denote which class we are creating.

dojo.declare("com.test.utils, null,
{
   var1 : val1,
   ..

   constructor : function()
   {
     // Initialize the class variable here ..
   }

   // Writing class functions
   function1 : function ()
   {

   }
});


Note this class must be placed under dojo/com/test/ directory and name of js file should be Utils.js. Dojo loads class cosidering dojo as base directory.

Sample class: This class provides some utility functions
// file name: com/test/Utils.js 


dojo.provide('com.test.Utils');


dojo.declare('com.test.Utils', null,
{
   // Initialize the class variables
    constructor : function(ds)
    {
        this.oneByte = 8;

        this.oneKB   = 1024;
        this.oneMB   = 1024 * 1024;
       
this.oneGB   = 1024 * 1024 * 1024;
       
this.oneTB   = 1024 * 1024 * 1024 * 1024;
        this.onePB   = 1024 * 1024 * 1024 * 1024 * 1024;
    },

    // Converts the supplied bytes in Words
    sizeInWord : function(size)
    {
        try {
           size = parseInt(size);
        } catch (e) {
       
    return "-";        }
        if (size == undefined)
       
    return "-";
   
    if (size < this.oneKB) {
       
    return Math.round(size/this.oneByte) + " Bytes";
   
    }
   
    if (size < this.oneMB) {
       
    return Math.round(size/this.oneKB) + " KB";
   
    }
   
    if (size < this.oneGB) {
        
    return Math.round(size/this.oneMB) + " MB";
   
    }
   
    if (size < this.oneTB) {
       
    return Math.round(size/this.oneGB) + " GB";
        }

   
    if (size < this.onePB) {
       
    return Math.round(size/this.oneTB) + " TB";
   
    }

  
      return "INFINITE";
    },

    // convert the provided array to string
    arrToStr: function(input)
    {
   
    if (input == undefined)
       
    return "";

        var str = "";
   
    if (dojo.isArray(input)) {
       
    for (var i = 0; i < input.length; i++) {
       
        str += this.escapeHTMLCodes(input[i]);
            }       
   
        return str;
        }   
        return "";
    },

    // escapes the HTML characters
    escapeHTMLCodes: function (str)
    {
   
    if (str == "" || str == undefined)
       
    return "";

   
    str = str.replace(/&/g, "&amp ;").
   
    str = str.replace(/>/g, "&gt ;");
   
    str = str.replace(/</g, "&lt ;")
   
    str = str.replace(/"/g, "\"");
   
    return str;
    },

    // format the given date in required format
    formatDate: function(date, dateFormat)
    {
   
    var fdate;
   
    if (dateFormat == undefined)
       
    return "-";
   
    try {
       
    fDate = dojo.date.locale.format(new Date(date),
                       {datePattern: dateFormat});
        } catch (e) {
   
        cosole.error(e);
       
    return "-";
        }
   
    return fDate;
    },

   // format the given date in given date and time format
    formatDateAndTime : function(date, dateFormat, timeFormat)
    {
   
    var fdate;
   
    if (dateFormat == undefined)
       
    return "-";
   
    try {
       
    fDate = dojo.date.locale.format(new Date(date),
           
    {datePattern: dateFormat, timePattern: timeFormat});
        } catch (e) {
   
        cosole.error(e);
       
    return "-";
        }
        return fDate;
    },

    // Trim the string
    trimToLength : function(str, start, len)
    {
   
    if (str == undefined || str == "")
       
    return "";
   
    return str.substring(start, len);   
    }
});



How to Use the class in HTML page:

1. Load the module
   dojo.require("com.test.Utils");

2. Using the class

   dojo.addOnLoad(function() {

      //create instance of the class
      var utils = new com.test.Utils();
      alert(utils.sizeInWords(10240)); // show 1 MB
      alert(utils.formatDate(new Date(), "dd MMMM yyyy")
     // will show current date in dd MMMM yyyy format
       ...
   });

30 December 2010

Sending post xml-http request (AJAX) Using Dojo

function requestServer ()
{
        var query = "field=vale&field1=val1&..."
        var request = {};
        request['url'] = "server url ";
        request['handleAs'] = "xml";   // can be json,text,html
        request['load'] = showResult;  // which function to call on getting response from server
        request['error'] = showError;  // for any error which function to call
        request['postData'] = query;   // Send query to server
        dojo.rawXhrPost(request);   // Actuall call the XML-HTTP request
}

function showResult (response)
{
    alert(response)
}

function showError(response)
{
        alert("Error : " + response);
}

Client side validation: Using Regular expression in Java-script

Some sample regular expressions:

1. FQDN (Fully qualified domain name):
^[a-z0-9-_]+(\.[a-z0-9-_]+)*\.([a-z]{2,4})$

2. IP- Address:
(((25[0-5])|(2[0-4][0-9])|([01]?[0-9][0-9]?))\\.){3}((25[0-5])|(2[0-4][0-9])|([01]?[0-9][0-9]?))

3. IP address with subnet mask (255.255.255.255/24) form:
^(((25[0-5])|(2[0-4][0-9])|([01]?[0-9][0-9]?))\\.){3}((25[0-5])|(2[0-4][0-9])|^([01]?[0-9][0-9]?))[/](([1-2]?[0-9])|([3][0-2]))$

4. Email address:
^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$

5. Word:
^\w+$


How to use regular expression in Java script:
Create Regex object:
var regxpVal =  new RegExp("REGULAR-Expression");

Validate Value:
if (! regxpVal.test("value to test")) {
   alert("Invalid Value provided");
}

Example:
var fqdnRegex = new RegExp("^[a-z0-9-_]+(\\.[a-z0-9-_]+)*\\.([a-z]{2,4})$");

if (! fqdnRegex.test("google.com")) {
  alert("google.com is not valid fqdn");
}

alert("google.com is valid fqdn");