Friday, November 23, 2012

Template for git messages


Good commit messages always makes a difference!!!

Following is the template I generally refer to.

FEATURE/BUGFIX/ENHANCEMENT: KonyOne Studio - <Module name> - <short problem/module description>

<Detailed description of feature/solution description/enhancement comments>

<Fix: #JSP1234>

Reviewed By :  <reviewer name>


Example for Feature:

FEATURE: KonyOne Studio - Sky Data Explorer - Implemented model classes for sky explorer

Provided the offline support capabilities to work offline.

Reviewed by: Rakesh 


Example for BugFix:

BUGFIX: KonyOne Studio - Java Script Module - Heap memory issues with huge number of files.

Java script listener is modified..etc,..

Fix: #JSP12345


Example for Enhancement:

ENHANCEMENT: KonyOne Studio - Java Script Module - code clean for java script model

Unnecessary code has been removed in java script module.

Reviewed by: Rakesh 


Points to be considered:

  • Topic description (first line)
  •  72 characters max for each line.
  •  Give space for title and body
  •  Use present tense.(Generally git uses the same for merge/rebase)


Why 72 characters ??
git log doesn’t do any special special wrapping of the commit messages. 

On an 80 column terminal, if we subtract 4 columns for the indent on the left and 4 more for symmetry on the right, we’re left with 72 columns.


Good commit messages serve at least three important purposes:

  • To speed up the reviewing process.
  • To help us write a good release note.
  • To help the future maintainers of Erlang/OTP (it could be you!), say five years into the future, to find out why a particular change was made to the code or why a specific feature was added.




Tuesday, November 20, 2012

Tooltip on tree viewer items


    ExplorerViewer.getTree().addMouseTrackListener(new ExplorerMouseListener());


private class ExplorerMouseListener implements MouseTrackListener {

@Override
public void mouseEnter(MouseEvent e) {
}

@Override
public void mouseExit(MouseEvent e) {
}

@Override
public void mouseHover(MouseEvent event) {
System.out.println(event.data);
TreeItem item = explorerViewer.getTree().getItem(new Point(event.x, event.y));
if (item != null && item.getData() instanceof MyResource) {
MyResource selectedElement = (MyResource) item.getData();
if (selectedElement.getResourceType() == MyResourceType.APP_GROUP
|| selectedElement.getResourceType() == MyResourceType.DATA) {
if (selectedElement.getData() instanceof INameDescription)
skyExplorerViewer.getTree().setToolTipText(
((INameDescription) selectedElement.getData())
.getDescription());
} else {
skyExplorerViewer.getTree().setToolTipText(null);
}
}
}

}

Friday, November 9, 2012

Thursday, September 20, 2012

Eclipse IAdaptable pattern – Show Properties for Items in a View

This example shows how IAdaptable is used in Eclipse in a real example. To get a taste of how Adapter design pattern works in Eclipse, go to those posts: post1 post2.

Suppose you have created a view by using eclipse “Extension wizard”. (If you do not know this, try to play around and get this done.)


And Now change code in SampleView.java to be the following:
package adapterview.views;
 
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.*;
import org.eclipse.swt.SWT;
 
public class SampleView extends ViewPart {
 
 private TableViewer viewer;
 
 class ViewLabelProvider extends LabelProvider implements
   ITableLabelProvider {
  public String getColumnText(Object obj, int index) {
   TestItem testItem = (TestItem) obj;
   return testItem.getSummary();
  }
 
  public Image getColumnImage(Object obj, int index) {
   return getImage(obj);
  }
 
  public Image getImage(Object obj) {
   return PlatformUI.getWorkbench().getSharedImages()
     .getImage(ISharedImages.IMG_OBJ_ELEMENT);
  }
 }
 
 /**
  * This is a callback that will allow us to create the viewer and initialize it.
  */
 
 public void createPartControl(Composite parent) {
  viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
    | SWT.V_SCROLL);
  viewer.setContentProvider(new ArrayContentProvider());
  viewer.setLabelProvider(new ViewLabelProvider());
  getSite().setSelectionProvider(viewer);
  viewer.setInput(getElements());
 
 }
 
/**
  * Passing the focus request to the viewer's control.
  */
 
 public void setFocus() {
  viewer.getControl().setFocus();
 }
 
 // Build up a simple data model
 private TestItem[] getElements() {
  TestItem[] testItems = new TestItem[2];
  TestItem testItem = new TestItem();
  testItem.setSummary("First Item");
  testItem.setDescription("A very good description");
  testItems[0] = testItem;
  testItem = new TestItem();
  testItem.setSummary("Second Item");
  testItem.setDescription("Another very good description");
  testItems[1] = testItem;
  return testItems;
 }
}
TestItem.java
package adapterview.views;
public class TestItem {
 private String summary;
 private String description;
 public String getSummary() {
  return summary;
 }
 public void setSummary(String summary) {
  this.summary = summary;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
Basically, this will create a view and shown like this figure.

What if I want to show the Summary and Description in a property view when each item is clicked? You may think about changing some part of the code in the SampleView, but Eclipse platform is amazing and there is no need to change in this class.
What we need is to add an adapter for TestItem Class.
Now add the following snippet to the plugin.xml file.
<extension
         point="org.eclipse.core.runtime.adapters">
      <factory
            adaptableType="adapterview.views.TestItem"
            class="adapterplace.TestItemAdapterFactory">
         <adapter
               type="org.eclipse.ui.views.properties.IPropertySource">
         </adapter>
      </factory>
</extension>
This declares the following three classes:
1. adaptableType is TestItem
2. the factory to create adapter for adaptableType(TestItem) is TestItemAdapterFactory
3. adapter is IPropertySource which is required for property view to show properties.
Recall the apple and orange example in my previous post, now here we want to go from TestItem to IPropertySource.
File file hierarchy is like this:

TestItemAdapterFactory.java
package adapterplace;
 
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.ui.views.properties.IPropertySource;
import adapterview.views.*;
 
public class TestItemAdapterFactory implements IAdapterFactory {
 
 @Override
 public Object getAdapter(Object adaptableObject, Class adapterType) {
  if (adapterType== IPropertySource.class && adaptableObject instanceof TestItem){
   return new TestItemAdapter((TestItem) adaptableObject);
  }
  return null;
 }
 
 @Override
 public Class[] getAdapterList() {
  // TODO Auto-generated method stub
  return null;
 }
}
TestItemAdapter.java – this class wrap a TestItem object with IPropertySource’s methods, which in turned are required by Property view.
package adapterplace;
 
import adapterview.views.TestItem;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.TextPropertyDescriptor;
 
 
public class TestItemAdapter implements IPropertySource {
 private final TestItem testItem;
 
 public TestItemAdapter(TestItem testItem) {
  this.testItem = testItem;
 }
 
 
 @Override
 public boolean isPropertySet(Object id) {
  return false;
 }
 
 @Override
 public Object getEditableValue() {
  return this;
 }
 
 @Override
 public IPropertyDescriptor[] getPropertyDescriptors() {
 
  return new IPropertyDescriptor[] {
    new TextPropertyDescriptor("summary", "Summary"),
    new TextPropertyDescriptor("description", "Description") };
 }
 
 @Override
 public Object getPropertyValue(Object id) {
  if (id.equals("summary")) {
   return testItem.getSummary();
  }
  if (id.equals("description")) {
   return testItem.getDescription();
  }
  return null;
 }
 
 @Override
 public void resetPropertyValue(Object id) {
 
 }
 
 @Override
 public void setPropertyValue(Object id, Object value) {
  String s = (String) value;
  if (id.equals("summary")) {
   testItem.setSummary(s);
  }
  if (id.equals("description")) {
   testItem.setDescription(s);
  }
 }
}
Result: when an item in the sample view is selected, property view shows its property.

Chain of Responsibility Design pattern

The Chain of Responsibility (CoR) pattern decouples the sender and receiver of a request by interposing a chain of objects between them.

CoR introduction

The Chain of Responsibility pattern uses a chain of objects to handle a request, which is typically an event. Objects in the chain forward the request along the chain until one of the objects handles the event. Processing stops after an event is handled.
Figure 1 illustrates how the CoR pattern processes requests.

Figure 1. The Chain of Responsibility pattern
In Design Patterns, the authors describe the Chain of Responsibility pattern like this:
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

  • You want to decouple a request's sender and receiver
  • Multiple objects, determined at runtime, are candidates to handle a request
  • You don't want to specify handlers explicitly in your code

If you use the CoR pattern, remember:
  • Only one object in the chain handles a request
  • Some requests might not get handled

Those restrictions, of course, are for a classic CoR implementation. In practice, those rules are bent; for example, servlet filters are a CoR implementation that allows multiple filters to process an HTTP request.




Adapter Design Pattern

Adapter Design Pattern:
 
Software usually consists of a mixture of in-house and purchased software that must work together to produce a seamless user interface. But disparate software packages are not aware of each other's object models, so they can't work together—without adapters. Adapters let objects from unrelated software packages collaborate by adapting one interface to another. Learn how the Adapter design pattern can save you a lot of time and effort by combining disparate software systems.

The Adapter pattern lets disparate object types work together.

Introducing Adapter

Adapters are necessary because dissimilar elements need to interoperate. From wrenches to computer networks, physical adapters are abundant. In software, adapters make dissimilar software packages work together; for example, you might have a tree of objects (call them Nodes) you want to display using Swing's JTree. The JTree class can't display your Nodes directly, but it can display TreeNode instances. With an adapter, you can map your Nodes to TreeNodes. Because Swing trees use the Adapter pattern, you can display any kind of tree—from Document Object Model (DOM) to Swing component hierarchies to a compiler parse tree—just by implementing a simple adapter.


In Design Patterns, the authors describe the Adapter pattern like this:
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Figures 2 and 3 show the Adapter pattern's two standard variations.

Figure 2. Adapter with inheritance. Click on thumbnail to view full-size image.


Figure 3. Adapter with delegation. Click on thumbnail to view full-size image.

Adapters masquerade as one type of object by implementing its interface; they inherit (or delegate) functionality from another class. That way, you can effectively substitute objects (known as Adaptees) for target (Target) objects. For the JTree in Figure 1, I adapt the objects in the tree (UIComponents) to Swing, so a JTree instance can manipulate them. Considering the amount of code that sits behind JTree, this simple adapter provides a huge return on investment. Let's see how it works.

In Eclipse:

This pattern is used a lot in Eclipse, allowing plug-ins to be loosely coupled, yet still be integrated into the Eclipse runtime.


Adapters in the Real World 

A real world analogy always helps with the understanding of a design pattern. The best example for the adapter pattern is based around AC power adapters. Say you're visiting Europe from the US, with your laptop, which expects a US power supply. To get your laptop plugged in, you're going to need to get a power adapter that accepts your US plug and allows it to plug in to the European power outlet. The AC adapter knows how to deal with both sides, acting as a middleman - this is the adapter pattern.

The Adapter Pattern

The Adapter is known as a structural pattern, as it's used to identifying a simple way to realize relationships between entities. The definition of Adapter provided in the original Gang of Four book on Design Patterns states: 
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Let's take a look at the classic diagram definition of  the adapter pattern:

The Target interface defines the domain specific interface that the Client used, so the client collaborates with objects that implement the Target interface. On the other side of things, the Adaptee is the existing interface that needs adapting in order for our client to interact with it. The Adapter adapts the Adaptee to the Target interface - in other words, it translates the request from the client to the adaptee.


Let's take a look at the interactions in a sequence diagram: 

In this example, as far as the Client is concerned it's just calling the request method of the Target interface, which the Adapter has implemented. In the background however, the Adapter knows that to return the right result, it needs to call a different method, specificAdapteeRequest, on the Adaptee.
Note: the pattern described here is the object adapter. There is a class adapter pattern, but you need multiple inheritance to use it. Seeing as Java doesn't support multiple inheritance, I'm going to leave this out.

Where Would I Use This Pattern?

The main use of this pattern is when a class that you need to use doesn't meet the requirements of an interface. As mentioned before, adapters are common across Eclipse plug-ins. For a particular object to contribute to the Properties view, adapters are used display the objects data. The view itself doesn't need to know anything about the object the it is displaying properties for. 

Where Would I Use This Pattern?

The main use of this pattern is when a class that you need to use doesn't meet the requirements of an interface. As mentioned before, adapters are common across Eclipse plug-ins. For a particular object to contribute to the Properties view, adapters are used display the objects data. The view itself doesn't need to know anything about the object the it is displaying properties for. 

So How Does It Work In Java?

The following example shows a simple implementation of the pattern. Consider that we have a third party library that provides sorting functionality through it's NumberSorter class. This is our Adaptee.
01./*
02.* This is our adaptee, a third party implementation of a
03.* number sorter that deals with Lists, not arrays.
04.*/
05.public class NumberSorter
06.{
07.public List<Integer> sort(List<Integer> numbers)
08.{
09.//sort and return
10.return new ArrayList<Integer>();
11.}
12. 
13.}
Our Client deals with primitive arrays rather than Lists. For the sake of this example, lets say we can't change the client to use Lists. 
1.int[] numbers = new int[]{34, 2, 4, 12, 1};
2. 
3.Sorter sorter = new SortListAdapter();
4.sorter.sort(numbers);
We've provided a Sorter interface that expects the client input. This is our target.
1.//this is our Target interface
2.public interface Sorter
3.{
4.public int[] sort(int[] numbers);
5.}
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter

01.public class SortListAdapter implements Sorter
02.{
03. 
04.@Override
05.public int[] sort(int[] numbers)
06.{
07.//convert the array to a List
08.List<Integer> numberList = new ArrayList<Integer>();
09. 
10.//call the adapter
11.NumberSorter sorter = new NumberSorter();
12.numberList = sorter.sort(numberList);
13. 
14.//convert the list back to an array and return
15. 
16.return sortedNumbers;
17.}
18. 
19.}
While this example may be overkill, it illustrates how the adapter pattern can work.

Watch Out for the Downsides

Some say that the Adapter pattern is just a fix for a badly designed system, which didn't consider all possibilties. While this is a fair point, it is an important part of a pluggable architecture.  It can also add a level of complexity to your code, making debugging more difficult.



Wednesday, September 19, 2012

Comparable and Comparator in Java


Employee record with Department, Emp Name and Emp Id:

Original Data:

BI :Kondal :109
HANA :Ban :103
HANA :Anand :115
ERP :Can :102
CRM :Yangi :100
BI :Damn :114

Required Format: Display the emp names in sorted way based on the department name.

BI :Damn :114
BI :Kondal :109
CRM :Yangi :100
ERP :Can :102
HANA :Anand :115
HANA :Ban :103

We can acheive this in two different ways.
1.  By implementing comparable interface in Employee class.
 - Override compareTo method
 - Invoke Collections.sort(arraylist);

2. By implementing comparator interface, as specified below without even touching the employee class
- Override compare method
- Invoke Collections.sort(arraylist, new EmployeeComparator());

Employee class

public
class Employee /* implements Comparable<Employee>*/ {
private int empId;
private String empName;
private String department;

public Employee(int empId, String empName, String department) {
this.empId = empId;
this.empName = empName;
this.department = department;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
/* @Override
public int compareTo(Employee o) {
if (this.getDepartment().compareTo(o.getDepartment()) == 0) {
return this.getEmpName().compareTo(o.getEmpName());
}
return this.getDepartment().compareTo(o.getDepartment());
}*/
}
 
EmployeeComparator class

import
java.util.Comparator;
 
public
class EmployeeComparator implements Comparator<Employee>{
@Override
public
int compare(Employee e1, Employee e2) {
if
(e1.getDepartment().compareTo(e2.getDepartment()) == 0) {
return
e1.getEmpName().compareTo(e2.getEmpName());
}
return
e1.getDepartment().compareTo(e2.getDepartment());
}
}

EmployeProfiles class

import
java.util.ArrayList;
import
java.util.Collections;

public
class EmployeProfiles {
public
static void main(String[] args) {
ArrayList<Employee> empList = new
ArrayList<Employee>();
empList.add(new
Employee(109, "Kondal", "BI"));
empList.add(new
Employee(103, "Ban", "HANA"));
empList.add(new
Employee(115, "Anand", "HANA"));
empList.add(new
Employee(102, "Can", "ERP"));
empList.add(new
Employee(100, "Yangi", "CRM"));
empList.add(new
Employee(114, "Damn", "BI"));
// Natural order in the array list
for
(Employee employee : empList) {
System.out
.println(employee.getDepartment() + " :"
+ employee.getEmpName() + " :" + employee.getEmpId());
}
// Apply sorting
Collections.sort(empList, new
EmployeeComparator());
System.out
.println("------------");
// sorted list
for
(Employee employee : empList) {
System.out
.println(employee.getDepartment() + " :"
+ employee.getEmpName() + " :" + employee.getEmpId());
}
}
}