Skip to main content


Showing posts from October, 2011

Guava: Defensive coding with Preconditions class

Basic idea behind Defensive coding is not making any assumptions while writing the code  and  escalating the problem in it's early stage (known as  fail fast  technique ). This is very simple and effective technique for securing your code from unseen defects. Guava provide very useful utility class Preconditions for these type of check. public static void salaryHike(User user, float salaryHike){ Preconditions.checkNotNull(user); //assuming user will never demoted :)) Preconditions.checkArgument(salaryHike > 0, "salary hike must be positive"); Preconditions.checkState(Validator.validateUser(user), "User is not valid"); user.salary = user.salary + salaryHike; }

Guava: Useful Objects class

In Effective Java Book, Joshua Bloch advocate about the overriding the methods which are common to all Objects Some common methods are hasCode equals compareTo toString Overriding the method are good but overriding correctly is must else it will create unwanted errors. Here Guava Objects class comes very handy public class User implements Comparable<User>{ public String firstName; public String lastName; public String userId; public String emailId; public Date dateOfBirth; public boolean active; @Override public int hashCode() { return Objects.hashCode(firstName, lastName, emailId, userId, dateOfBirth, active); } @Override public boolean equals(Object obj) { if(obj instanceof User){ User that = (User)obj; return Objects.equal(this.firstName, that.firstName) && Objects.equal(this.lastName, that.lastName) &&

JavaScript [ExtJs3]: EditorGridPanel Read-Only (dynamically)

Many time we face the scenerio where we have to make the editor grid read-only dynamically. Ext.override(Ext.ux.grid.CheckColumn, { editable: true, onMouseDown: function (e, t) { if ( { e.stopEvent(); var me = this, grid = me.grid, view = grid.getView(), index = view.findRowIndex(t), colindex = view.findCellIndex(t), record =; if (!grid.isReadOnly && grid.colModel.isCellEditable(colindex, index)) { record.set(me.dataIndex, ![me.dataIndex]); } } } }); var grid = new Ext.grid.EditorGridPanel({ ... isReadOnly: true, //set to flag to make check column readonly ... }); //to make other column readonly grid.on('beforeedit', function () { return false; });

Loading dynamic image into PDF or HTML

Loading the dynamic image files into PDF or HTML Java code to generate Chart in base64 encoding //Using JFree Chart library XYSeries series = new XYSeries("Users Incentive"); series.add(75, 4.5); series.add(100, 6.0); series.add(105, 6.0); series.add(110, 7.2); series.add(115, 7.6); series.add(125, 8.5); series.add(150, 9); series.add(200, 12.3); XYDataset dataset = new XYSeriesCollection(series); JFreeChart chart = ChartFactory.createXYAreaChart( "Users Incentive", "Attainment in (%)", "Incentive (10K)", dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL, true, false, false); byte[] buf = EncoderUtil.encode( chart.createBufferedImage(500, 300), ImageFormat.PNG); String encodedImage = "data:image/png;base64," + new sun.misc.BASE64Encoder().encode

JavaScript [ExtJs3]: Interactive Ext.grid.CheckboxSelectionModel

"Ext.grid.CheckboxSelectionModel" Override class to make check-box header more interactive when use select and deselect the row. Ext.override(Ext.grid.CheckboxSelectionModel, { initEvents: function () {; var sm = this, grid = sm.grid, store =, handler = sm.onSelectionChangeHandler; grid.on('render', function () {'mousedown', this.onHdMouseDown, this); }, sm); sm.on('selectionchange', handler, sm); grid.getView().on('refresh', handler, sm); store.on({ 'add': handler, 'datachanged': handler, //to track filter scope: sm }); },, onSelectionChangeHandler: function () { var sm = this, store =, count = sm.getCount(), in

JavaScript: Flexible Arguments

In many use-cases it's very useful to know total number of in-parameter and there type of param. function testArgs(){ var args = arguments, param = args[0], type =; console.log('total number of in param: '+args.length); console.log('type of first param: '+type); } -> testArgs('test'); //ans: //total number of in param: 1 //type of first param: [object String] -> testArgs(3, 3); //ans:  //total number of in param: 2 //type of first param: [object Number] Above function will print the number of parameter pass to it and first parameter type. Jquery use this trick to deal with optional parameter (like. jQuery.extend, jQuery.when etc.) Few more example on this concept. ##Add function with flexible argument function add(){ var total = 0, arg = arguments; for(var i =0; i< arg.length; i++){ total += arg[i]; } return total; } ->add(1, 2, 5, 22); //ans: 30 ->add(1, 2); //ans: 3 ##find

JavaScript: Serialize json object to date

Code snipt: Change WCF date format to normal date format function rxFn(str,m1) { var d = new Date(parseInt(m1,10)); return d.format('M d,Y') } var d = {"date": "/Date(-62135596800000)/"}; //WCF date format var str = Ext.encode(d); var result = str.replace(/\/Date\(([-+]?\d+)\)\//gi, rxFn); -> console.log(result); //ans: {"date": "Jan 01,1"}

JS file Cashing problem !!!

JS file cashing create lots trouble some time. And it's more irritating when you spend 1 hour to debug the problem and find out it's the cashed copy on client end. So it's recommend that you use “cache-blockers” in your CSS and JavaScript code. //here 370 is build number Simple change in URI will force the browser to reload it and you can track the build number detail as well.