11 August 2015

Accessing SSL site using Java HttpsURLConnection class

1.       Get certificate:





Click on marked Certificate button














Click on View Certificates



















Click on View Certificate

Copy certificate to file:






















Click on next
Enter file name e.g. C:\Users\PGadekar\Desktop\gmail.cer


Click on next


Click on finish






2.       Create keystore from gmail.cer file

-          Create directory
Ø  mkdir C:\TEMP\cert
-          Copy certificate to this directory
Ø  copy C:\Users\PGadekar\Desktop\gmail.cer C:\Temp\cert
Ø  cd C:\Temp\cert
-          Create key store using java keystore command
Ø  keytool -import -alias "GMAIL-Certificate-1" -file  gmail.cer -keystore gmailstore



We can check if certificate is added to store successfully or not by using kestory list command.



3.       Accessing the HTTPs pages
In java program
We can get certificate using following method
public static void getCertDetails() {
       String keystoreFilename = "C:\\TEMP\\cert\\gstore";
       char[] password = "changeit".toCharArray();
       String alias = "GMAIL-Certificate";
       FileInputStream fIn;
       try {
              fIn = new FileInputStream(keystoreFilename);
              KeyStore keystore = KeyStore.getInstance("JKS");
              keystore.load(fIn, password);
              Certificate cert = keystore.getCertificate(alias);
              System.out.println(cert);
       } catch (Exception e) {
              e.printStackTrace();
       }
}

                Accessing page using ssl

Create SSL Factory
public static SSLSocketFactory getSSLFactory() throws Exception {
       String keystoreFilename = "C:\\TEMP\\cert\\gmailstore";
       char[] password = "changeit".toCharArray();
       FileInputStream fIn = new FileInputStream(keystoreFilename);
       KeyStore keystore = KeyStore.getInstance("JKS");
       keystore.load(fIn, password);

       TrustManagerFactory tmf = TrustManagerFactory
                     .getInstance(TrustManagerFactory.getDefaultAlgorithm());
       tmf.init(keystore);
       SSLContext ctx = SSLContext.getInstance("TLS");
       ctx.init(null, tmf.getTrustManagers(), null);
       SSLSocketFactory sslFactory = ctx.getSocketFactory();

       return sslFactory;
}

Set the SSL factory to HttpsURLConnection connection object
public static void sendSSLRequest() throws Exception {
       SSLSocketFactory sslFactory = getSSLFactory();
       String reqURL = "https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier";
       URL url = new URL(reqURL);
       HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
       c.setSSLSocketFactory(sslFactory);
       HttpURLConnection conn = c;
       conn.setDoInput(true);
       conn.setRequestMethod("POST");
       conn.setDoOutput(true);
       OutputStream post = conn.getOutputStream();
       OutputStreamWriter outputWriter = new OutputStreamWriter(
                     conn.getOutputStream());

       //outputWriter.write(postContent);
       outputWriter.flush();
       outputWriter.close();
       post.flush();
       post.close();

       BufferedReader in = new BufferedReader(new InputStreamReader(
                     conn.getInputStream()));
       String inputLine, response = "";
       while ((inputLine = in.readLine()) != null) {
              response += inputLine;
       }
       in.close();
       System.out.println("URL: " + reqURL);
       System.out.println("*********************************** START");
       System.out.println(response);
       System.out.println("*********************************** END");
}

Output:
*********************************** START
  .. OUTPUT TRUNCATED  ..

*********************************** END

Add above method to following test class

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class TestKeyStore {

       public static void main(String[] args) {
              try {
                     //getCertDetails();
                     sendSSLRequest();
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }

                //getCertDetails();
                // sendSSLRequest();
}


14 May 2015

Adding HTTP headers using Java HTTP web filters

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.
filters can be used to transform the response from a servlet or a JSP page.

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. A filter config contains initialization data.
The most important method in the Filter interface is the doFilter method, which is the heart of the filter. Filers are header for :
  • Examines the request headers
  • Customizes the request object if it wishes to modify request headers or data or block the request entirely
  • Customizes the response object if it wishes to modify response headers or data
Response Header Filter:
This filter will add the configured list headers to response for mapped URLS.

Configuration file: WEB-INF\response-headers.xml

<?xml version="1.0" encoding="UTF-8" ?>
<response-header-mapper>
 <!-- generic rule for all html requests -->

 <mapping url="(.*).html">
  <header key="X-ServerName" value="MyServer" />
  <header key="Content-Type" value="text/html" />       
  <!-- cache all the html pages for one hour -->
  <header key="Cache-Control" value="private, max-age=3600" />
 </mapping>
 

 <!-- generic rule for all js requests -->
 <mapping url="(.*).js">
  <header key="X-ServerName" value="MyServer2" />
  <header key="Content-Type" value="text/javascript" />       
  <!-- cache all the js pages for 2 hour -->
  <header key="Cache-Control" value="private, max-age=7200" />
 </mapping>
</response-header-mapper>


In above configuration files we have applied header 'X-ServerName', 'Content-Type', 'Cache-Control' to URLS containing '(.*).html' pattern. So filter will add all these headers to html files

ResponseHeaderFilter.java

import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.util.Map.Entry;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;

import org.w3c.dom.*;
public class ResponseHeaderFilter implements Filter {
 HashMap<Pattern, LinkedHashMap<String, String>> headerPatternRules;

 /**
  * Create URL rules to Header mapping
  * It will create map with URL pattern as key
  * and value will be list of headers to apply
  *  
  * @param xmlFile relative path XML configuration file
  *
  * @return Rule to Header Mapping
  */
 public static HashMap<Pattern, LinkedHashMap<String, String>> getRules( String xmlFile) {
  HashMap<String, LinkedHashMap<String, String>> rules =
    new HashMap<String, LinkedHashMap<String, String>>();
  try {
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(xmlFile);
   doc.getDocumentElement().normalize();
 
   NodeList mappings = doc.getElementsByTagName("mapping");
   for (int i = 0; i < mappings.getLength(); i++) {
    Node mapping = mappings.item(i);
    String urlPattern = mapping.getAttributes().getNamedItem("url").getNodeValue();
    NodeList headers = mapping.getChildNodes();
    LinkedHashMap<String, String> rule = rules.get(urlPattern);
    if (rule == null) {
     rule = new LinkedHashMap<String, String>();
    }
    for (int j = 0; j < headers.getLength(); j++) {
     Node header = headers.item(j);
     if (header.getNodeType() == Node.ELEMENT_NODE) {
      String headerName = header.getAttributes()
        .getNamedItem("key").getNodeValue();
      String headerValue = header.getAttributes()
        .getNamedItem("value").getNodeValue();
      rule.put(headerName, headerValue);
     }
    }
    rules.put(urlPattern, rule);
   }

   System.out.println("*** Rules: " + rules);
   return toRulePattern(rules);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * Compile all the URL patterns
  *
  * @param rules Map of URL pattern and associated List of headers 
  *
  * @return Map of compiled URL pattern and associated List of
  * headers to add
  */
 public static HashMap<Pattern, LinkedHashMap<String, String>> toRulePattern(
   HashMap<String, LinkedHashMap<String, String>> rules) {
  HashMap<Pattern, LinkedHashMap<String, String>> patterRules =
    new HashMap<Pattern, LinkedHashMap<String, String>>();
  for (Entry<String, LinkedHashMap<String, String>> e : rules.entrySet()) {
   patterRules.put(Pattern.compile(e.getKey()), e.getValue());
  }
  return patterRules;
 }

 /**
  * Read configuration file and build the URL pattern to Header Map 
  *
  */
 public void init(FilterConfig fc) throws ServletException {
  String confFile = fc.getInitParameter("response-header-file").trim();
  String fullConfigFilePath = fc.getServletContext().getRealPath("/WEB-INF/" + confFile);
  System.out.println("** ResponseHeaderFilter: Loading configuration from: "
      + fullConfigFilePath);
  headerPatternRules = getRules(fullConfigFilePath);
 }

 /**
  * Filter method
  *
  * Checks request URL against Set of Patters from the list of URL pattern Map and
  * applies the headers associated.
  * 
  */
 public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
   throws IOException, ServletException {
  HttpServletResponse response = (HttpServletResponse) res;
  String requestURL = ((HttpServletRequest) req).getRequestURI();

  for (Entry<Pattern, LinkedHashMap<String, String>> rule : headerPatternRules.entrySet()) {
         Matcher matcher = rule.getKey().matcher(requestURL);
         if (matcher.matches()) {
          LinkedHashMap<String, String> headers = rule.getValue();
    for (Entry<String, String> entry : headers.entrySet()) {
     response.setHeader(entry.getKey(), entry.getValue());
    }
         }
  }
  fc.doFilter(req, res);
 }

 public void destroy() {
 }
}


In init() method we read the configuration file (file name is defined in web.xml init-param of filter), then generates rules Map. Key of map is URL pattern and value is list of headers to apply.
In doFilter() method request URI is checked agaist all the rules defined in the configuration for matching of pattern. If match is found the list of header associated with pattern are added to response.
compile this java file and copy it in WEB-INF\classes folder

Modify WEB-INF\web.xml add Filter declaration and Mapping.

<filter>
 <filter-name>ResponseHeaderFilter</filter-name>
 <filter-class>ResponseHeaderFilter</filter-class>
 <init-param>
  <param-name>response-header-file</param-name>
  <param-value>response-headers.xml</param-value>
 </init-param>
</filter>

<filter-mapping>
 <filter-name>ResponseHeaderFilter</filter-name>
 <url-pattern>*</url-pattern>
</filter-mapping>

 

01 October 2014

Creating Shufflled Playlist In java

import java.util.ArrayList;

public class PlayList {

    public static void main(String[] args) {
     for (int k = 0; k < 10; k++) {
         ArrayList songs = new ArrayList(10);
         songs.add("one");
         songs.add("two");
         songs.add("three");
         songs.add("four");
         songs.add("five");
         songs.add("six");
         songs.add("seven");
         songs.add("eight");
         songs.add("nine");
         songs.add("ten");
         String shuffled[] = new String[10];
         int i = 0;
         while (true) {
              if (songs.size() > 1) {
                 Double random = Math.random();
                 int index = (int) (random * songs.size());
                 shuffled[i++] = songs.remove(index);
                 continue;
              }
             shuffled[i++] = songs.remove(0);
             break;
         }
         System.out.print(":: ");
         for (int j = 0; j < shuffled.length; j++) {
               System.out.print(shuffled[j] + ", ");
          }
          System.out.println(" ::");
       }
   }
}

22 May 2014

Export/Import MongoDB database collection

Exporting database collection
$ mongoexport -o /var/tmp/collectioname.dump.json -d databasename -c collectioname
This will export the collection to file collectioname.dump.json

Importing database collection
$mongoimport -d databasename -c collectioname --file /var/tmp/collectioname.dump.json

Issue: When we export the collection using  mongoexport it will export the Datatype information along with the value e.g. if Date is stored in collection then the exported file will show the Date field like

"created_at" : { "$date" : "2014-05-19T20:58:22.000+0530" } instead of "created_at" :  "Date(2014-05-19T20:58:22.000+0530)" and similarly of long numbers.

If we import such exported dump file we will get error. To overcome this problem we have to write our custom script to do the conversion.
 
Sample java code for conversion and insertion in MongoDB :

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;

public class TestMongoDBImport {
  
    private static final String DATABASE   = "databasename";
    private static final String COLLECTION      = "collectioname";
    private MongoClient     client     = null;
    private DB          db     = null;
    private DBCollection    collection = null;

    public TestMongoDBImport() throws UnknownHostException {
        this.client = new MongoClient("localhost", 27017);
        this.db = this.client.getDB(DATABASE);
    }

    private void createTable() {
        if (!db.collectionExists(COLLECTION)) {
            BasicDBObject obj = new BasicDBObject();
            obj.append("capped", false);
            db.createCollection(COLLECTION, obj);
        }
        this.collection = db.getCollection(COLLECTION);
    }

    private void insert(ArrayList obj) {
        this.collection.insert(obj);
    }

    public static void main(String[] args) throws IOException {
        String filename = "/var/tmp/collectioname.dump.json";
        TestMongoDBImport tw = new TestMongoDBImport();
        tw.createTable();
        BufferedReader br = new BufferedReader(new FileReader(filename));
        String line = null;
        long runTime = 0;
        long startTime = (new Date()).getTime();
        int i = 0;
        try {
                StringBuilder sb = new StringBuilder();
                line = br.readLine();
                ArrayList recs = new ArrayList();
                while ((line = br.readLine()) != null) {
                    line = line.replaceAll(line = line.replaceAll("\\{ \"\\$date\" : \"([0-9]{4}\\-[0-9]{2}\\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}\\+[0-9]{4})\" \\},",
            "\"Date($1)\","););
                    line = line.replaceAll("\\{ \"\\$numberLong\" : \"(\\d*)\" \\}", "$1");
                    recs.add((DBObject) JSON.parse(line));
                    i++;
                    if (i % 500 == 0) {
                        tw.insert(recs);
                         recs = new ArrayList();
                        System.out.println(i + ":: Added Till");
                    }
                }
                if (recs != null && recs.size() > 0) {
                    tw.insert(recs);
                }
        } finally {
            br.close();
            long endTime = (new Date()).getTime();
            runTime = endTime - startTime;
            System.out.println("Time to upload records " + i + ":"
                + (runTime / 1000) + " seconds");
        }
    }
}





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>