Tuesday, April 15, 2014

Hibernate : Using ResultTransformer

If we want to get the column name in hibernate for a table with results then we use setResultTransformer() and pass AliasedTupleSubsetResultTransformer.
For some reason if want to see the column name in same order the way it is with create table then we need to have our own AliasedTupleSubsetResultTransformer. We can define our own class which will extend AliasedTupleSubsetResultTransformer and we can override behaviour to use LinkedHashMap to get the columns in order.

Example:

public class AliasToEntityOrderedMapResultTransformer extends AliasedTupleSubsetResultTransformer {

public static final AliasToEntityOrderedMapResultTransformer INSTANCE = new AliasToEntityOrderedMapResultTransformer();

/**
 * Disallow instantiation of AliasToEntityOrderedMapResultTransformer .
 */
private AliasToEntityOrderedMapResultTransformer () {
}

/**
 * {@inheritDoc}
 */
public Object transformTuple(Object[] tuple, String[] aliases) {
//linkedhashmap to get table column name in order        
    Map result = new LinkedHashMap(tuple.length);
    for ( int i=0; i<tuple.length; i++ ) {
        String alias = aliases[i];
        if ( alias!=null ) {
            result.put( alias, tuple[i] );
        }
    }
    return result;
}

/**
 * {@inheritDoc}
 */
public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
    return false;
}

/**
 * Serialization hook for ensuring singleton uniqueing.
 *
 * @return The singleton instance : {@link #INSTANCE}
 */
private Object readResolve() {
    return INSTANCE;
}
}


Using the custom implementation - AliasedTupleSubsetResultTransformer 

     Session session = sessionFactory.getCurrentSession();
        String queryStr = "select * from EMPLOYEE;
        Query query = session.createSQLQuery(queryStr);
//set the custom implementation
        query.setResultTransformer(AliasToEntityOrderedMapResultTransformer.INSTANCE);
//get the ordered column name and value
        List<Map<String,Object>> aliasToValueMapList = query.list();

Saturday, March 29, 2014

Dojo Menu example

A simple dojo menu example using MenuBar, MenuBarItem and DropDownMenu combination. This example also highlights use of disabled and menu separator.

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dojo Menu Example</title>
<link rel="stylesheet" href="../js/1_8_3/dijit/themes/claro/claro.css">
<style type="text/css">
@import "../js/1_8_3/dojo/resources/dojo.css";
@import "../js/1_8_3/dijit/themes/claro/claro.css";
@import "../js/1_8_3/dijit/themes/claro/document.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/claro/EnhancedGrid.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css";
</style>
<script>dojoConfig = {parseOnLoad: true}</script>
    <script src='../js/1_8_3/dojo/dojo.js'></script>
    <script src='../js/menu.js'></script>
</head>
<body class="claro">
<div style="width:450px;height:200px;margin-left:200px;">
<br>
<div id="menuId">Menu examples using MenuBar and Dropdown menu</div>
</div>
</body>
</html>

JS file - menu.js

 require(["dijit/MenuBar",
         "dijit/PopupMenuBarItem",
         "dijit/Menu",
    "dijit/DropDownMenu",
    "dijit/MenuItem", 
    "dijit/MenuSeparator",
    "dijit/PopupMenuItem",
    "dojo/domReady!"
], function(MenuBar,PopupMenuBarItem,Menu,DropDownMenu, MenuItem, MenuSeparator, PopupMenuItem){
 
    var menubar = new MenuBar({});
  
      
    var ddMenu = new DropDownMenu();
  
  
    ddMenu.addChild(new MenuItem({
        label: "Menu Item 1"
    }));
    ddMenu.addChild(new MenuItem({
        label: "Menu item 2 - Disabled",
        disabled: true
    }));
 

    ddMenu.addChild(new MenuSeparator());
  
    var ddSubMenu = new DropDownMenu();

    var pmItem = new PopupMenuItem({
        label: "Submenu option",
        popup: ddSubMenu
    });
  
    ddSubMenu.addChild(new MenuItem({
        label: "menu item"
      
    }));
  
    ddMenu.addChild(pmItem);
 
    menubar.addChild(new PopupMenuBarItem({
        label: "Menu Examples",
        popup: ddMenu
    }));

    menubar.placeAt("menuId");
    menubar.startup();
  
});

Image:





Thursday, March 27, 2014

Single Filter Select and Combo Box - Dojo

Single Filter Select and Combo box looks same however difference is with the value that is returned by these two components. Filter Select will return id and combo box will return the value displayed. Combo Box will let user enter any value which may or may not be in the list butsame will be submitted when form is submitted.

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Single Filter Select And Combo Box</title>
<link rel="stylesheet" href="../js/1_8_3/dijit/themes/claro/claro.css">
<style type="text/css">
@import "../js/1_8_3/dojo/resources/dojo.css";
@import "../js/1_8_3/dijit/themes/claro/claro.css";
@import "../js/1_8_3/dijit/themes/claro/document.css";
</style>
<script>dojoConfig = {parseOnLoad: true}</script>
    <script src='../js/1_8_3/dojo/dojo.js'></script>
    <script src='../js/combo.js'></script>
</head>
<body class="claro">
<div style="width:450px;height:200px;margin-left:200px;">
<br><br>
<b>Single Filtering Select:</b><br><br>
City : <input id="city" /> <br><br>
<b>Combo Box:</b><br><br>
City : <input id="comboCity"/>


</div>

</body>
</html>

JS : combo.js

 var cities = [ {name:"Bangalore", id:"1"},
               {name:"Delhi", id:"2"},
               {name:"Vadodara", id:"3"},
               {name:"Chennai", id:"4"},
               {name:"Hyderabad", id:"5"}];
require([
    "dojo/store/Memory", "dijit/form/FilteringSelect", "dojo/domReady!"
], function(Memory, FilteringSelect){
    var cityStore = new Memory({
        data: cities
    });

    var filteringSelect = new FilteringSelect({
        id: "city",
        name: "city",
        value: "1",
        store: cityStore,
        searchAttr: "name"
    }, "city");
});

require([
         "dojo/store/Memory", "dijit/form/ComboBox", "dojo/domReady!"
     ], function(Memory, ComboBox){
         var comboStore = new Memory({
             data: cities
         });

         var comboBox = new ComboBox({
             id: "comboCity",
             name: "comboCity",
             value: "Bangalore",
             store: comboStore,
             searchAttr: "name"
         }, "comboCity");
     });


-------------code ends-----
To get the value we can use following:
dijit.byId('city').get('value') //for single filter select
dijit.byId('comboCity').get('value') //for combo box
For more details please see dojo APIs.

Image:



Wednesday, March 26, 2014

Dojo Confirm Box

A simple dojo confirm box

We will create a simple dojo confirm box. Confirm box will have "Yes" and "No" buttons. We can define actions for Yes/No buttons and also we can add custom message and title for confirm box.
Have a look to following html and js file to get a dojo confirm box.

HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dojo Confirm Box Example</title>
<link rel="stylesheet" href="../js/1_8_3/dijit/themes/claro/claro.css">
<style type="text/css">
@import "../js/1_8_3/dojo/resources/dojo.css";
@import "../js/1_8_3/dijit/themes/claro/claro.css";
@import "../js/1_8_3/dijit/themes/claro/document.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/claro/EnhancedGrid.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css";
</style>
<script>dojoConfig = {parseOnLoad: true}</script>
    <script src='../js/1_8_3/dojo/dojo.js'></script>
    <script src='../js/confirm.js'></script>
</head>
<body class="claro">
<div style="width:450px;height:200px;margin-left:200px;">
<br>
<a href='#' onClick="openConfirmBox();">Open Confirm Box</a>
</div>
</body>
</html>

Js file - confirm.js


/**
     * confirmation dialog box.
     */
  function openConfirmBox() {
       
      require(["dojo/ready", "dojox/widget/DialogSimple",
               "dijit/form/Button"
           ],
          
               function(ready, 
                   Dialog,Button ){
                   ready(function(){
            var confirmBox = new dojox.widget.DialogSimple({
                title: "Confirm Box",
                style: "width: 275px;height:auto; font-weight:bold",
                content: "<div>Click Yes to confirm.<br/>"
               
            });
           
            var div = dojo.create('div', {
                id:"btn"
            }, confirmBox.containerNode);

            var noBtn = new dijit.form.Button({
                label: "NO",
                onClick: function() {
                    //action for no button
                    confirmBox.hide();                   
                    dojo.destroy(confirmBox);
                }
            });

            var yesBtn = new dijit.form.Button({
                label: "YES",
                onClick: function() {
                    //call action for Yes
                    confirmBox.hide();
                    dojo.destroy(confirmBox);
            }

            });
           
            dojo.create(yesBtn.domNode, {}, div);
            dojo.create(noBtn.domNode, {}, div);       
            confirmBox.show();
                   });
      });
    }

Confirm Box :



Formatter - EnhancedGrid

Formatter is very useful feature to format specific column data. I will use the same grid example from my previous post and will add formatter to "Last Name" column for making the last name in upper case.

HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cell Formatter - Enhanced Grid</title>
<link rel="stylesheet" href="../js/1_8_3/dijit/themes/claro/claro.css">
<style type="text/css">
@import "../js/1_8_3/dojo/resources/dojo.css";
@import "../js/1_8_3/dijit/themes/claro/claro.css";
@import "../js/1_8_3/dijit/themes/claro/document.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/claro/EnhancedGrid.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css";
</style>
<script>dojoConfig = {parseOnLoad: true}</script>
    <script src='../js/1_8_3/dojo/dojo.js'></script>
    <script src='../js/formatter.js'></script>
</head>
<body class="claro">
<div style="width:450px;height:200px;margin-left:200px;">
Enhanced Grid with Formatter Example<br>
<div id="gridDiv">
</div>
</div>
</body>
</html>

Js file - formatter.js

 var gridLayout = [[
                       {
                           'name': 'S.No',
                           'field': 'id',
                           'width': '10%'
                       },
                       {
                           'name': 'First Name',
                           'field': 'fName',
                           'width': '45%'
                         
                       },
                    {
                        'name': 'Last Name',
                        'field': 'lName',
                        'width': '45%',
                        'formatter': function(item, rowIndex, cell) {
                             return formatLastName(item, rowIndex, cell); }
                    }
                      
                    ]];

function formatLastName(item, rowIndex, cell) {
    //lets make last name in caps for all records
    //we can use formatter to format cell, like adding a hyper link or image.
    item = item.toUpperCase();
    return item;
}

require(["dojo/ready", "dojox/grid/EnhancedGrid",
         "dojo/data/ItemFileWriteStore","dojox/grid/enhanced/plugins/Filter","dojox/grid/enhanced/plugins/Pagination"       
     ],
   
         function(ready,EnhancedGrid,ItemFileWriteStore,filter,pagination ){
             ready(function(){
             var grid1 = new dojox.grid.EnhancedGrid({
                      id: 'grid1',
                      columnReordering: true,
                      store:null,
                      noDataMessage: '<span class="dojoxGridNoData"> No Feature Data available </span>',
                      structure: gridLayout,
                      escapeHTMLInData: false,
                      rowSelector: '20px',                                  
                      plugins: {
                          filter: {
                              // Show the closeFilterbarButton at the filter bar
                              //closeFilterbarButton: true,
                              // Set the maximum rule count to 5
                              ruleCount: 5,
                              // Set the name of the items
                              itemsName: "items"
                              },
                       pagination: {
                       defaultPageSize: 15,
                       pageSizes: ["15", "30", "50", "All"],
                       description: true,
                       sizeSwitch: true,
                       pageStepper: true,
                       gotoButton: true,
                       maxPageStep: 4,
                       position: "bottom"
                       }
                       }
                      },dojo.byId("gridDiv"));
                 grid1.startup();
                 var tempArr = [{"id":1,"fName":"First Name","lName":"Last Name"}];
                 var taskData = {
                        identifier: 'id',
                        items: tempArr
                    };
                    var store = new dojo.data.ItemFileWriteStore({ data: taskData });
                    grid1.setStore(store);
              
                        });
                });
                 
                 
Image:


                 
                 


Tuesday, March 25, 2014

dojo Enhanced Grid - Simple example

A simple dojo enhanced grid with filter ang paging option enabled. In this example grid store data is hard coded, same can be retrieve from dojo xhr calls in similar format.

Prerequisite: Extract dojo lib files and keep them under js/1_8_3 folder in your web app.

HTML file:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Enhanced Grid Example</title>
<link rel="stylesheet" href="../js/1_8_3/dijit/themes/claro/claro.css">
<style type="text/css">
@import "../js/1_8_3/dojo/resources/dojo.css";
@import "../js/1_8_3/dijit/themes/claro/claro.css";
@import "../js/1_8_3/dijit/themes/claro/document.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/claro/EnhancedGrid.css";
@import "../js/1_8_3/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css";
</style>
<script>dojoConfig = {parseOnLoad: true}</script>
    <script src='../js/1_8_3/dojo/dojo.js'></script>
    <script src='../js/grid.js'></script>
</head>
<body class="claro">
<div style="width:450px;height:200px;margin-left:200px;">
Simple Enhanced Grid Example<br>
<div id="gridDiv">
</div>
</div>
</body>
</html>

JS file: grid.js

var gridLayout = [[
                       {
                           'name': 'S.No',
                           'field': 'id',
                           'width': '10%'
                       },
                       {
                           'name': 'First Name',
                           'field': 'fName',
                           'width': '45%'
                          
                       },
                    {
                        'name': 'Last Name',
                        'field': 'lName',
                        'width': '45%'
                    }
                       
                    ]];

require(["dojo/ready", "dojox/grid/EnhancedGrid",
         "dojo/data/ItemFileWriteStore","dojox/grid/enhanced/plugins/Filter","dojox/grid/enhanced/plugins/Pagination"        
     ],
    
         function(ready,EnhancedGrid,ItemFileWriteStore,filter,pagination ){
             ready(function(){ 
             var grid1 = new dojox.grid.EnhancedGrid({
                      id: 'grid1',
                      columnReordering: true,
                      store:null,
                      noDataMessage: '<span class="dojoxGridNoData"> No Feature Data available </span>',
                      structure: gridLayout,
                      escapeHTMLInData: false,
                      rowSelector: '20px',                                   
                      plugins: {
                          filter: {
                              // Show the closeFilterbarButton at the filter bar
                              //closeFilterbarButton: true,
                              // Set the maximum rule count to 5
                              ruleCount: 5,
                              // Set the name of the items
                              itemsName: "items"
                              },
                       pagination: {
                       defaultPageSize: 15,
                       pageSizes: ["15", "30", "50", "All"],
                       description: true,
                       sizeSwitch: true,
                       pageStepper: true,
                       gotoButton: true,
                       maxPageStep: 4,
                       position: "bottom"
                       }
                       }
                      },dojo.byId("gridDiv"));
                 grid1.startup();
                 var tempArr = [{"id":1,"fName":"First Name","lName":"Last Name"}];
                 var taskData = {
                        identifier: 'id',
                        items: tempArr
                    };
                    var store = new dojo.data.ItemFileWriteStore({ data: taskData });
                    grid1.setStore(store);
               
                        });
                });
                 

Image: