Skip to main content

Posts

Showing posts from 2011

Guava: Multimap, Bimap

Multimap Multimap   is a collection similar to a Map, but which may associate multiple values with a single key. So if you put the two value with the same key then multimap will map both value with the same key. Multimap   has some very useful extension like ListMultimap , SetMultimap ArrayListMultimap implements the ListMultimap interface and uses an ArrayList to store the values for a given key. And  HashMultimap implements the SetMultimap interface and it will not store the duplicate key-value pairs, same as Set behave. Here is the ArrayListMultimap example. Multimap<String, String> map1 = ArrayListMultimap.create(); map1.put("A", "Test1"); map1.put("B", "Test2"); map1.put("B", "Test3"); map1.put("A", "Test4"); map1.put("C", "Test5"); map1.put("X", "Test6"); Multimap<String, String> map2 = ArrayListMultimap.create(); map2.put(&quo

JavaScript [ExtJs3]: Loading complex data in EditorGridPanel with Dynamic Combo Box

Grid is always an important widget of any project and many time we find a situation where we have to render the complex data in grid panel. And another use-case of dynamic combo box where the combo data comes with the record. To handle a complex object we have to define a new data type. Ext.data.Types.COMPLEXDATA = { convert: function(v){ v.toString = function(){ return v.display; }; return v; }, sortType: Ext.data.SortTypes.none, type: 'complexdata' }; This extended class will take care of dynamic combo box loading. It’s a plugin class so after creating the object we have to add this to “plugins” property of grid panel. Ext.ux.ComplexDataColumn = Ext.extend(Ext.grid.Column, { dataField: 'options', displayField: 'display', valueField: 'id', constructor: function (c) { c.editor = this.buildComboEditor(); Ext.ux.ComplexDataColumn.superclass.constructor.call(this, c); }, init: function(grid){ g

Java: Create message with MessageFormat class

Creating a message string is very easy, but creating it with more effective way that's matter. Most of time when we write the code for message string, we use "+" operator on string. But it become complex when we have to deal with lots of pieces of string. It can be worse when we have to deal with number, date and currency type data with locale setting. Below are few test data which use common way of creating the message string. DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT); DateFormat tf = DateFormat.getTimeInstance(DateFormat.DEFAULT); Date today = new Date(); String text = "Work"; int num = 7; String meesage1 = "Time= " + tf.format(today) + ", Date= " + df.format(today) + ", Text= " + text + ", Number= " + num + "."; System.out.println(meesage1); String message2 = new StringBuffer("Time= ").append(tf.format(today)) .append(", Date= ").append(df.form

Guava: String Manipulation with CharMatcher, Spliter and Joiner

Guava has very simple and powerful string manipulation mechanism. Here are some classes like CharMatcher , Splitter and Joiner provides very simple way to perform some complex operation on string collections. CharMatcher Determines a true or false value for any Java char value, just as Predicate does for any Object.[from guava doc] Use a predefined constant (predefine CharMatcher) CharMatcher.WHITESPACE ( Java whitespace character ) CharMatcher.JAVA_DIGIT CharMatcher.JAVA_LETTER CharMatcher.JAVA_LOWER_CASE  CharMatcher.JAVA_UPPER_CASE  CharMatcher.ASCII CharMatcher.ANY ... String str = "FirstName LastName +1 123 456 789 !@#$%^&*()_+|}{:\"?><"; CharMatcher.DIGIT.retainFrom(str); Output:-> "1123456789" CharMatcher.JAVA_LETTER.retainFrom(str); Output:-> "FirstNameLastName" CharMatcher.JAVA_LETTER_OR_DIGIT.retainFrom(str); Output:-> "FirstNameLastName1123456789" CharMatcher.ANY.countIn(str) Out

Guava: Function, Predicate and Ordering

Function and Predicate are just interfaces but plays key roll in many use-cases. Function: Determines an output value based on an input value Predicate: Determines a true or false value for a given input. Ordering: It's a comparator with added methods to support common functions. Assume we have some User Object List User{firstName=userA, lastName=B, salary=1234567.0} User{firstName=userB, lastName=C, salary=1234577.0} User{firstName=userB, lastName=D, salary=1234777.0} User{firstName=userE, lastName=A, salary=1237777.0} User{firstName=userD, lastName=A, salary=1237778.0} User{firstName=userA, lastName=D, salary=1237788.0} User Function Class public enum UserFunctions implements Function<User, String>{ FIRSTNAME{ @Override public String apply(User user){ return user == null ? "" : user.getFirstName(); } }, LASTNAME{ @Override public String apply(User user){ return user == null ? "" : user.getLastName(); } }, FIRSTN

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 (Ext.fly(t).hasClass(this.createId())) { e.stopEvent(); var me = this, grid = me.grid, view = grid.getView(), index = view.findRowIndex(t), colindex = view.findCellIndex(t), record = grid.store.getAt(index); if (!grid.isReadOnly && grid.colModel.isCellEditable(colindex, index)) { record.set(me.dataIndex, !record.data[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 () { Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); var sm = this, grid = sm.grid, store = grid.store, handler = sm.onSelectionChangeHandler; grid.on('render', function () { Ext.fly(this.grid.getView().innerHd).on('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 = sm.grid.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 = Object.prototype.toString.call(param); 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.  http://myapp.com/static/my_js_file.js?v=370 //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.

JavaScript: Context or Scope

Scope is very confusing specially when we are working on big application. But it's a very useful feature. When function is the part of the object var obj = { isUsed: false, use: function(){ this.isUsed = true; } }; -> obj.use(); -> obj.isUsed; //ans: true What is the context or scope Context or Scope is the boundary where your code executes. var x = 10; function test(){ x = 20; //updated the global vlaue } -> alert(x); //ans: 10 -> test(); -> alert(x); //ans: 20 When 'x' is local variable !!! var x = 10; function test(){ var x = 20; //now x is a local variable of test function } -> alert(x); //ans: 10 -> test(); -> alert(x); //ans: 20 We can change the scope of the function while calling it function fn(){ this.myProperty = 'test'; } -> fn(); -> this.myProperty; //ans: test -> window.myProperty: //ans: test -> myProperty; //ans: test When you run the function 'fn' it will run in globa

JavaScript: Variable type or Object type

In any language it's important and useful to know object type you are dealing with. Here are few ways to identify the object type in java-script var myVar = {}; var myArr = [0,1]; var myStr = ""; var myNum = 1; var myFloat = 1.2; var myBool = true; var myRegx = /abc/; var myClassObj = new function Neeraj(){}; This is widely use method to identify the object type Some well known JS Lib. (ie. jquery, extjs etc.. ) use this technique By Using Object.prototype.toString Object.prototype.toString.apply(myVar); //ans: [object Object] Object.prototype.toString.apply(myArr); //ans: [object Array] Object.prototype.toString.apply(myStr); //ans: [object String] Object.prototype.toString.apply(myNum); //ans: [object Number] Object.prototype.toString.apply(myFloat); //ans: [object Number] Object.prototype.toString.apply(myBool); //ans: [object Boolean] Object.prototype.toString.apply(myRegx); //ans: [object RegExp] Object.prototype.toString.apply(myClassObj);//an

javascript: functions

Creating a function function isNimble(){ return true; } var canFly = function(){ return true; }; window.isDeadly = function(){ return true; }; function call by itself function hello(n){ return n>0? hello(n-1)+"a":"hiy"; } if you don't want to give function name function hello(n){ return n>0?arguments.callee(n-1)+"a":"hiy"; } Named Functions function hello(){return "hiyaa";} //what is the name of the function ? var emp = function myEmp(){return "emp";}; Functions as Objects //Normal JavaScript Object var obj = {}; //Simple function declarication var fn = function(){}; //both has properties obj.prop = "some value"; fn.prop = "some value"; //other existing properties in function -> length, call, apply example: //without cache function isPrime( num ) { var prime = num != 1; // Everything but 1 can be prime for ( var i = 2; i < num; i++