Monday, February 21, 2011

Eclipse - Commands, Handlers, UI correspondent fo rthe command

________________________________________
Reference Link: http://www.vogella.de/articles/EclipseCommands/article.html

Command is generally a certain operation that can be performed based on a certain UI component in the Eclipse workbench.

Commands are extended via "org.eclipse.ui.commands". The behavior of a command can be defined via a handler.While programming for Eclipse Commands, you will need the following 3 items.
  • Command - Declarative description of the component

  • Handler - Defines the behavior of the command. The handler is the class which will be executed once the command is called and must implement the interface "org.eclipse.core.commands.IHandler". In most cases you extend "org.eclipse.core.commands.AbstractHandler" which provides a default implementation for most of the IHandler methods.

  • UI - Where and how should the command be included.

Once created Commands can be used at many locations in an eclipse workbench, such as (menus, toolbars and / or context menus). Menu's are similar to Actions, but not exactly the same.

____________________________________


Steps to Implement Commands:

>>>Defining commands :

Let's create a command that will exit an application.
1. Create an RCP project with th e"Hello" template.
2. Add "org.eclipse.ui.commands" to the "extensions".
3. now, add "command" to this extension in the plugin.xml.
4. Set the Id & Name parameters of thsi 'command' based on your required operation. In our case, it is "Exit"
5. Press the hyperlink "defaultHandler" to create the class which should extend
"org.eclipse.core.commands.AbstractHandler".
(Or)
You could extend another plugin, "org.eclipse.ui.handlers" and add "handler" to it. Now, specify the enter the command ID text with the ID of your previously created "Command" and Press the hyperlink "class" to create the class for the handler.

Now, our handler class can be implemented with 2 options:

(i) Exit the application when the menu item from our main menu(in the menu bar) is clicked
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Properties",
"MyCommand Msg Box");
return null;
}


or

(ii) pop up a message dialog

public Object execute(ExecutionEvent event) throws ExecutionException {
// TODO Auto-generated method stub
HandlerUtil.getActiveWorkbenchWindow(event).close();

return null;
}


The Handler class could be modified based on one of the 2 options above.

The "execute" method in your Handler class is responsible for the action performed when your command is executed.

We have now created a command. NOw we need to use it.
*****************************

>>>>Using commands in menus :

Let's add our 'exit' command to the MainMenu of our application.
1. Add "org.eclipse.ui.menus" to the "extensions".
2. now, add "menuContribution" to this extension in the plugin.xml with the location URI "menu:org.eclipse.ui.main.menu". This will add your command to the main menu of yoru application.. Similarly, your could modify the URI field for adding yoru command to the toolbar or to the View-toolbar, etc based on the table below:
Contribution toDescriptionUri
Application menuDisplays the command in the menu of the application"menu:org.eclipse.ui.main.menu"
Application toolbardisplays the command in the toolbar of the application "toolbar:org.eclipse.ui.main.toolbar"
View toolbar displays the command in the toolbar of the view "toolbar:viewId". For example to display a menu to view with the Id "View1" use "toolbar:View1".
Context menu / pop-upCommand is displayed in a content menu, e.g. right mouse click on an objectn.a.

3.now, add "menu" to the "menuContribution" and set the parameters as below:


4. Now, add "Command" for "menu" and set parameters for this as below :.. Take care to assign the command id to this command



Now.. Have a look at your plugin.xml file to learn on this.

***************************

You have now
1.created a command
2. created a file menu with the command as its functionality.


Now run your application as an RCP application/Eclipse-Workbench and check to see that the file closes when the filemenu is clicked.


If your application is run , then you could access your command from the main menu.

Thursday, February 17, 2011

'Properties' of resources in eclipse

Reference Link : http://www.eclipsepluginsite.com/properties.html

In order to demonstrate the Property feature of eclipse, Lets first create a view which updates as below. Once the view is ready and in place, we could proceed to access th eproperty features form the view.
________________

Reference Link: http://www.eclipsepluginsite.com/views.html
Note : This view lists the files from the package Explorer , with th e.properties extension
Property File Manager View will search the entire workspace for all the projects. In each project it will search for "Property Files" folder, In each such folder it will look out for all the files with ".properties" extension and display it to the user. This way we will end up with a view as shown in the figure below. Please note that a property file gets displayed in the Property File Manager view only when it is created inside Property Files folder.


The feature to automatically update the View when more .properties files added to the 'Property Files' folder is also implemented.

Refer the comments...
***************************************
import java.util.ArrayList;

//for REsource Changes Acknowledgement - implement listener
public class MyPropertyManagerView extends ViewPart implements IResourceChangeListener{

private TreeViewer viewer;
private TreeParent invisibleRoot;

//for PropertyPage - change of access from default to public
public class TreeObject implements IAdaptable {
private String name;
private TreeParent parent;
private IResource resource;
My_PropertyDialogPage propertyPage;
public TreeObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setParent(TreeParent parent) {
this.parent = parent;
}
public TreeParent getParent() {
return parent;
}
public String toString() {
return getName();
}
public Object getAdapter(Class key) {
return null;
}

//for property page from protected to public
public IResource getResource() {
return resource;
}
protected void setResource(IResource resource) {
this.resource = resource;
}
}

class TreeParent extends TreeObject {
private ArrayList children;
public TreeParent(String name) {
super(name);
children = new ArrayList();
}
public void addChild(TreeObject child) {
children.add(child);
child.setParent(this);
}
public void removeChild(TreeObject child) {
children.remove(child);
child.setParent(null);
}
public TreeObject [] getChildren() {
return (TreeObject [])children.toArray(new TreeObject[children.size()]);
}
public boolean hasChildren() {
return children.size()>0;
}
}

class ViewContentProvider implements //IStructuredContentProvider,
ITreeContentProvider {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
}
public void dispose() {
}
public Object[] getElements(Object parent) {
if (parent.equals(getViewSite())) {
if (invisibleRoot==null) initialize();
return getChildren(invisibleRoot);
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof TreeObject) {
return ((TreeObject)child).getParent();
}
return null;
}
public Object [] getChildren(Object parent) {
if (parent instanceof TreeParent) {
return ((TreeParent)parent).getChildren();
}
return new Object[0];
}
public boolean hasChildren(Object parent) {
if (parent instanceof TreeParent)
return ((TreeParent)parent).hasChildren();
return false;
}
}

class ViewLabelProvider extends LabelProvider {

public String getText(Object obj) {
return obj.toString();
}
public Image getImage(Object obj) {
String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
if (obj instanceof TreeParent)
imageKey = ISharedImages.IMG_OBJ_FOLDER;
return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
}
}

//For PropertiesPage
public void initialize() {
TreeParent root = new TreeParent("WorkSpace Property Files");
try {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject[] projects = workspace.getRoot().getProjects();

for (int i = 0; i lessthan projects।length; i++) {
IResource[] folderResources = projects[i].members();

for (int j = 0; j lessthan folderResources.length; j++) {
if (folderResources[j] instanceof IFolder) {
IFolder resource = (IFolder) folderResources[j];
if (resource.getName().equalsIgnoreCase("Property Files")) {
IResource[] fileResources = resource.members();
for (int k = 0; k < obj =" new" invisibleroot =" new"> public MyPropertyManagerView() {
}

//For PropertiesPage - commented
public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(getViewSite());
//For Resource Change acknowledgement - 1
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
hookContextMenu();
hookDoubleClickAction();
}


private void hookDoubleClickAction() {
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
ISelection selection = event.getSelection();
Object obj = ((IStructuredSelection) selection).getFirstElement();
if (!(obj instanceof TreeObject)) {
return;
}else {
TreeObject tempObj = (TreeObject) obj;
IFile ifile = ResourcesPlugin.getWorkspace().getRoot(). getFile(tempObj.getResource().getFullPath());
IWorkbenchPage dpage =MyPropertyManagerView.this.getViewSite().getWorkbenchWindow().getActivePage();
if (dpage != null) {
try {
IDE.openEditor(dpage, ifile,true);
}catch (Exception e) {
// log exception
}
}
}
}
});
}

//for ResourceChanged acknowledgement
@Override
public void resourceChanged(IResourceChangeEvent event) {
try{
if(event.getType() == IResourceChangeEvent.POST_CHANGE){
event.getDelta().accept(new IResourceDeltaVisitor(){
public boolean visit(IResourceDelta delta) throws CoreException {
if(delta.getResource().getName().endsWith(".properties")){
initialize();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
viewer.refresh();
viewer.expandAll();
}
});
}
return true;
}
});
}
}catch(CoreException e){
// log it
e.printStackTrace();
}
}


private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
//For PropertiesPage - Action refresh
Action refresh = new Action()
{
public void run()
{
initialize();
viewer.refresh();
}
};
refresh.setText("Refresh");
menuMgr.add(refresh);
//for PropertyPage -2
menuMgr.add(new Separator());
menuMgr.add(new PropertyDialogAction(getSite(), viewer));
//getSite().registerContextMenu(menuMgr, viewer);
}

public void setFocus() {
viewer.getControl().setFocus();
}

public void dispose() {
super.dispose();
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
}


***************************************

There are 2 ways to access Resource properties in Eclipse ;

A) Rightclk on the resource >> select properties from context menu >> a properties dialog of the resource will pop up

B) Select the resource >> ShowView>> Properties >> A view displaying properties of the resource will open in the workbench

How to create property on a particular resource and display it's properties in properties dialog as well as properties view???

Problem Example :
-we will associate properties with property files displayed in Property Manager View.
-We will create a context menu option to open properties dialog.
-And then, will see how to display properties in property view whenever user selects a property file in Property Manager View.

**********
A)
**********
* Add org.eclipse.ui.propertyPages in the extensions tab of the Plugin.xml >> Finish
* Now rtclk>add a new
'page', to this extension
* Click on new page declaration and edit its properties as shown in figure below। Refer to each of the fiels and input accordingly as in figure.. Very important.
* Generate class for this page by clicking on the 'class' link

* Modify the propertyPage class as below.

--------_____________________________
package com.myplugin.rmp;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPropertyPage;
import org.eclipse.ui.dialogs.PropertyPage;
import com.myplugin.rmp.views.PropertyManagerView.TreeObject;

public class propertyPage extends PropertyPage implements
IWorkbenchPropertyPage {
private Text textField;
public static QualifiedName AUTHOR_PROP_KEY = new QualifiedName("Author", "Author");
public propertyPage() {
super();
}
protected Control createContents(Composite parent) {
Composite myComposite = new Composite(parent, SWT.NONE);
GridLayout mylayout = new GridLayout();
mylayout.marginHeight = 1;
mylayout.marginWidth = 1;
myComposite.setLayout(mylayout);
Label mylabel = new Label(myComposite, SWT.NONE);
mylabel.setLayoutData(new GridData());
mylabel.setText("Author");
textField = new Text(myComposite, SWT.BORDER);
textField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
textField.setText(getAuthor());
return myComposite;
}
protected String getAuthor() {
IResource resource =
((TreeObject) getElement()).getResouce();
try {
String value =
resource.getPersistentProperty(
AUTHOR_PROP_KEY);
if (value == null)
return "";
return value;
}
catch (CoreException e) {
return e.getMessage();
}
}
protected void setAuthor(String author) {
IResource resource =
((TreeObject) getElement()).getResouce();
String value = author;
if (value.equals(""))
value = null;
try {
resource.setPersistentProperty(
AUTHOR_PROP_KEY,
value);
}
catch (CoreException e) {
}
}

public boolean performOk() {

setAuthor(textField.getText());
return super.performOk();
}
}
_________________________________________________________________________________________________________________

Hence testing the project :
>> create a project in project explorer with a folder named , "Property Files"
>> Add a *.properties file in the
"Property Files" folder
>> Window>>Show View>>PropertyManagerViewCategory>> YOur view
>> The newly added .properties file is now updated in the view.

However, to check the dynamic update done using IResource changedListener, do the following testing..
>>Keep your view open....
>>Update the project with a new .properties file...
You will see the view getting dynamically updated

Now, rtclk on the view and open >> Properties to view the Properties Dialog as below..


__________________________________________________________________________

**********
B)
**********
Step 1: Modify PropertyManagerView such that it starts broadcasting selection changed events. ie... modify createPartControl method as shown in source below. Hence, PropertyManagerView will start broadcasting selection changed events. Whenever user selects/deselects “.properties” file in view an event will be generated.

Eclipse Properties View listen to these selection change events and display properties of currently selected object.

Eclipse Properties View will display properties for only those objects which implement
org.eclipse.ui.views.properties.IPropertySource Interface.

public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(getViewSite());
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
getSite().setSelectionProvider(viewer);
hookContextMenu();
hookDoubleCLickAction();
}

Step 2:In our case “.properties” files are essentially TreeObject. So we need to modify TreeObject class so that it implements IPropertySource Interface. However, in order to use org.eclipse.ui.views.properties.IPropertySource you need to add org.eclipse.ui.views in plug-in dependencies.

Step 3 : Add the below source in View class,
private static final String AUTHOR_ID = "RMP.author";
private static final TextPropertyDescriptor AUTHOR_PROP_DESC = new TextPropertyDescriptor(AUTHOR_ID,"author");
private static final IPropertyDescriptor[] DESCRIPTORS = { AUTHOR_PROP_DESC };

Step 4 : Next, modify PropertyManagerView$TreeObject as source below

**********************
public class TreeObject implements IAdaptable,IPropertySource {
private String name;
private TreeParent parent;
private IResource resouce;


public TreeObject(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setParent(TreeParent parent) {
this.parent = parent;
}

public TreeParent getParent() {
return parent;
}

public String toString() {
return getName();
}

public Object getAdapter(Class key) {
return null;
}

public IResource getResouce() {
return resouce;
}

public void setResouce(IResource resouce) {
this.resouce = resouce;
}

public Object getEditableValue() {
return null;
}

public IPropertyDescriptor[] getPropertyDescriptors() {
return DESCRIPTORS;
}

public Object getPropertyValue(Object id) {
try{
if(AUTHOR_ID.equals(id)){
return resouce.getPersistentProperty(propertyPage.AUTHOR_PROP_KEY);
}
}catch(Exception e){

}
return null;
}

public boolean isPropertySet(Object id) {
return false;
}

public void resetPropertyValue(Object id) {

}

public void setPropertyValue(Object id, Object value) {
try{
if(AUTHOR_ID.equals(id)){
resouce.setPersistentProperty(propertyPage.AUTHOR_PROP_KEY,(String)value);
}
}catch(Exception e){

}
}


}
**********************
Now, whenever a “.properties” file is selected in Property Manager View. Its properties are shown in Eclipse Properties View as shown in figure
below.

Defining a new perspective/extend existing / or instantiate a new perspective at runtime within the workbench.

Reference Link : http://www.eclipse.org/articles/using-perspectives/PerspectiveArticle.html

Introduction:

A perspective is a visual container for a set of views and editors (parts). Each perspective has an input and a type. The input attribute is used to define which resources are visible in the workspace and the type attribute is used to define which actions and views are visible in the user interface.

The root of the user interface is accessed by invoking PlatformUI.getWorkbench( ). returns an object of type IWorkbench. A workbench has one or more windows of type IWorkbenchWindow. And each window has a collection of pages of type IWorkbenchPage.In the user interface a page is known as a "perspective". Within each window there is at most one active and visible page.

So,
PlatformUI.getWorkbench( )
|
IWorkbench
|
IWorkbenchWindow
|
IWorkbenchPage (also know as perspective)

A page can also be created programmatically using public API on IWorkbenchWindow. For instance, the following code demonstrates the creation of a new page.

>>Opening a Resource perspective programatically
// fWindow is an IWorkbenchWindow.
fWindow.openPage("org.eclipse.ui.resourcePerspective", ResourcesPlugin.getWorkspace());
here,
input = resource perspective( ie..org.eclipse.ui.resourcePerspective)
type = may be any object of type IAdaptable. In this case the input is the entire workspace.

>> Given a page, you can get the input and perspective type by using the following methods.
public IAdaptable getInput();
public IPerspectiveDescriptor getPerspective();

>> To retrieve Perspective info on(id, label, icon) :
The getPerspective method on IWorkbenchPage returns an object of type IPerspectiveDescriptor. This object has accessor methods for the perspective id, label and icon.

---------------------
Adding a New Perspective

____________________________

The definition of a new perspective is a three step process.

  1. Create a plug-in.
  2. Add a perspective extension to the plugin.xml file.
  3. Define a perspective class for the extension within the plug-in.
Consider teh creation of a new perspective with the below layotu:

so, the first step :

1. create a plug-in

2. Add a perspective to your plug-in through the extensions tab of the plug-in.xml as below


            name="Test"
class="org.eclipse.ui.articles.perspective.TestPerspective"
id="org.eclipse.ui.articles.perspective.Test">

3. Define perspective class by clicking at the 'class' hypertext' in the extensions tab

The createInitialLayout method is called on the IPerspectiveFactory. This method defines the initial layout for a page. Implementors may add views, folders, actions and action sets to the page layout.

In the example below you can see how createInitialLayout is implemented in the TestPerspective class. For clarity the algorithm has been split into two parts which define

3.(i)the actions - defineActions : This method adds a number of items and action sets to the window.

3.(ii)layout: - defineLayout.

public void createInitialLayout(IPageLayout layout) {
defineActions(layout);
defineLayout(layout);
}
----
>> add items to the File > New, Show View, or Perspective > Open menus of the window. You can also add complete action sets to the menu or toolbar of the window. In this example a few File > New and Show View items are added.
public void defineActions(IPageLayout layout) {
// Add "new wizards".
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");

// Add "show views".
layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
layout.addShowViewShortcut(IPageLayout.ID_BOOKMARKS);
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_PROP_SHEET);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
}
>>add views to the layout. When createInitialLayout is called the page layout consists of an editor area with no additional views. Additional views are added using the editor area as the initial point of reference. In defineLayout the factory gets the id of the editor area. Then it creates a folder to the left of this area and adds the Navigator view and Outline view to this folder.

public void defineLayout(IPageLayout layout) {
// Editors are placed for free.
String editorArea = layout.getEditorArea();

// Place navigator and outline to left of
// editor area.
IFolderLayout left =
layout.createFolder("left", IPageLayout.LEFT, (float) 0.26, editorArea);
left.addView(IPageLayout.ID_RES_NAV); -- deprecated
left.addView(IPageLayout.ID_OUTLINE); - adds the default eclipse views to your perspective
}

createFolder - adds a new folder to the page layout.
The positioning constants are defined on IPageLayout, and include TOP, BOTTOM, LEFT and RIGHT.

------------------------

>>you can invoke IPageLayout.setEditorAreaVisible(boolean) to hide or show the editor area.




Thursday, February 10, 2011

Java Annotations

Reference Link : http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm

One of the new ease-of-development features in JDK5 are annotations. Ther 're like meta-tags that you can add to your code. As a result, you will have helpful ways to indicate whether your methods are dependent on other methods, whether they are incomplete, whether your classes have references to other classes, and so on.

Annotation is a mechanism for associating a meta-tag with program elements and allowing the compiler or the VM to extract program behaviors from these annotated elements and generate interdependent codes when necessary.

Simple Annotations

There are only three types of simple annotations provided by JDK5. They are:

  • Override
  • Deprecated
  • Suppresswarnings

The Override annotation :An override annotation indicates that the annotated method is required to override a method in a super class. If a method with this annotation does not override its super-class's method, the compiler will generate an error. Example 1 demonstrates the override annotation:

Example 1

public class Test_Override {
@Override
public String toString()
{
return super.toString() + " Testing annotation name: 'Override'";
}
}

What happens if a spelling mistake occurs with the method name? For example, if you change the name of the toString method to "tostring" and compile the code, you will get something like the following:

Compiling 1 source file to D:tempNew Folder (2)
TestJavaApplication1buildclasses
D:tempNew Folder (2)TestJavaApplication1srctest
myannotationTest_Override.java:24: method does not override
a method from its superclass
@Override
1 error
BUILD FAILED (total time: 0 seconds)


The Deprecated annotation :This annotation indicates that when a deprecated program element is used, the compiler should warn you about it. Example 2 shows you the deprecated annotation.

Example 2 :First, create a class with the deprecated method as follows:

public class Test_Deprecated {
@Deprecated
public void doSomething() {
System.out.println("Testing annotation name: 'Deprecated'");
}
}

Next, try to invoke this method from another class:

public class TestAnnotations {
public static void main(String arg[]) throws Exception {
new TestAnnotations();
}
public TestAnnotations() {
Test_Deprecated t2=new Test_Deprecated();
t2.doSomething();
}

The doSomething() method in this example is declared as a deprecated method. Therefore, this method should not be used when this class is instantiated by other classes. If you compile Test_Deprecated.java, no warning messages will be generated by the compiler. But, if you try to compile TestAnnotations.java where the deprecated method is used, you will see something like this:

Compiling 1 source file to D:tempNew Folder
(2)TestJavaApplication1buildclasses
D:tempNew Folder
(2)TestJavaApplication1srctestmyannotation
TestAnnotations.java:27:
warning: [deprecation] doSomething() in
test.myannotation.Test_Deprecated has been deprecated
t2.doSomething();
1 warning


The Suppresswarnings annotation

This annotation indicates that compiler warnings should be shielded in the annotated element and all of its sub-elements. The set of warnings suppressed in an element is the superset of the warnings in all of its containing sub-elements. As an example, if you annotate a class to suppress one warning and one of its methods to suppress another warning, both warnings will be suppressed at the method level only. See Example 3 for the suppresswarnings annotation.

Example 3

public class TestAnnotations {
public static void main(String arg[]) throws Exception {
new TestAnnotations().doSomeTestNow();
}
@SuppressWarnings({"deprecation"})
public void doSomeTestNow() {
Test_Deprecated t2 = new Test_Deprecated();
t2.doSomething();
}
}

In this example, you are suppressing the deprecation warning for the method listing shown in Example 2. Because the method is suppressed, you are unlikely to view the "deprecation" warning any more.

Note: It is a good idea to use this annotation at the most deeply nested element where it is effective. Therefore, if you want to suppress a warning in a particular method, you should annotate that method rather than its class.

-----------------------------------------------------------------------------------------------------------

The Inherited annotation

This is a bit of a complex annotation type. It indicates that the annotated class with this type is automatically inherited. More specifically, if you define an annotation with the @Inherited tag, then annotate a class with your annotation, and finally extend the class in a subclass, all properties of the parent class will be inherited into its subclass. With Example 7, you will get an idea about the benefits of using the @Inherited tag.

Example 7

First, define your annotation:

@Inherited
public @interface myParentObject {
boolean isInherited() default true;
String doSomething() default "Do what?";
}

Next, annotate a class with your annotation:

@myParentObject
public Class myChildObject {
}

As you can see, you do not have to define the interface methods inside the implementing class. These are automatically inherited because of using the @Inherited tag. What would happen if you define the implementing class in old-fashioned Java-style? Take a look at this—defining the implementation class in an old-style-java way:

public class myChildObject implements myParentObject {
public boolean isInherited() {
return false;
}
public String doSomething() {
return "";
}
public boolean equals(Object obj) {
return false;
}
public int hashCode() {
return 0;
}
public String toString() {
return "";
}
public Class annotationType() {
return null;
}
}

Do you see the difference? You can see that you will have to implement all the methods that the parent interface owns. Besides the isInherited() and doSomething() methods from myParentObject, you will have to implement the equals(), toString(), and hasCode() methods of java.lang.Object and also the annotationType() method of java.lang.annotation.Annotation class. It does not matter whether you want to implement these methods or not; you will have to include these in your inherited object.










Customised Input validation for SWT text - RCP Toolbox - part 2

NOTE: for this source to work.. you need to include SWT and RCP toolkit libraries...

---------
package my.org.eclipse.swt.snippets;

import java.util.Date;

import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.richclientgui.toolbox.validation.IFieldErrorMessageHandler;
import com.richclientgui.toolbox.validation.ValidatingField;
import com.richclientgui.toolbox.validation.ValidationToolkit;
import com.richclientgui.toolbox.validation.converter.DateStringConverter;
import com.richclientgui.toolbox.validation.converter.IntegerStringConverter;
import com.richclientgui.toolbox.validation.string.StringValidationToolkit;
import com.richclientgui.toolbox.validation.validator.IFieldValidator;
import com.richclientgui.toolbox.validation.validator.TelephoneNumberValidator;

public class TestingRCPToolkitValidators extends WizardPage{

private final IFieldErrorMessageHandler errorMessageHandler;

private static final int DECORATOR_POSITION = SWT.TOP | SWT.LEFT;
private static final int DECORATOR_MARGIN_WIDTH = 1;
private static final int DEFAULT_WIDTH_HINT = 150;

private ValidationToolkit intValToolkit = null;
private StringValidationToolkit strValToolkit = null;
private ValidationToolkit dateValToolkit = null;

public TestingRCPToolkitValidators() {
super("booking.pageone","New Booking Entry", null);
errorMessageHandler = new WizardPageErrorHandler();
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(2, false));
createControl(shell);
shell.pack();
shell.open();

while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}

}

class WizardPageErrorHandler implements IFieldErrorMessageHandler {
public void handleErrorMessage(String message, String input) {
setMessage(null, DialogPage.WARNING);
setErrorMessage(message);
}
public void handleWarningMessage(String message, String input) {
setErrorMessage(null);
setMessage(message, DialogPage.WARNING);
}
public void clearMessage() {
setErrorMessage(null);
setMessage(null, DialogPage.WARNING);
}
}

public static void main(String[] args) {
new TestingRCPToolkitValidators();
}

@Override
public void createControl(Composite shell) {
strValToolkit = new StringValidationToolkit(DECORATOR_POSITION, DECORATOR_MARGIN_WIDTH, true);
strValToolkit.setDefaultErrorMessageHandler(errorMessageHandler);

intValToolkit = new ValidationToolkit(new IntegerStringConverter(), DECORATOR_POSITION, DECORATOR_MARGIN_WIDTH, true);
intValToolkit.setDefaultErrorMessageHandler(errorMessageHandler);

dateValToolkit = new ValidationToolkit(new DateStringConverter(),DECORATOR_POSITION, DECORATOR_MARGIN_WIDTH, true);
dateValToolkit.setDefaultErrorMessageHandler(errorMessageHandler);


// TODO Auto-generated method stub
//GridData gridData;
createNameField(shell);
//createAddressField(shell);
//createSportsListWidget(shell);
createTelephoneNumberField(shell);


}

private void createSportsListWidget(Composite shell) {
GridData gridData;
Label sportsLabel = new Label(shell, SWT.NONE);
sportsLabel.setText("Sports played:");
gridData = new GridData();
gridData.horizontalSpan = 2;
sportsLabel.setLayoutData(gridData);

List sportsList = new List(shell, SWT.BORDER | SWT.MULTI);
gridData = new GridData();
gridData.horizontalSpan = 2;
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.verticalAlignment = SWT.FILL;
gridData.grabExcessVerticalSpace = true;
sportsList.setLayoutData(gridData);
sportsList.add("Hockey");
sportsList.add("Street Hockey");
}

private void createAddressField(Composite shell) {
GridData gridData;
Label addressLabel = new Label(shell, SWT.NONE);
addressLabel.setText("Address:");
gridData = new GridData();
gridData.verticalAlignment = SWT.TOP;
addressLabel.setLayoutData(gridData);

Text addressText = new Text(shell, SWT.BORDER | SWT.WRAP | SWT.MULTI);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.verticalAlignment = SWT.FILL;
gridData.grabExcessVerticalSpace = true;
addressText.setLayoutData(gridData);
addressText.setText("This text field and the List\nbelow share any excess space.");
}

private void createNameField(Composite shell) {
// Label nameLabel = new Label(shell, SWT.NONE);
// nameLabel.setText("Name:");
//
// Text nameText = new Text(shell, SWT.BORDER);
// GridData gridData = new GridData();
// gridData.horizontalAlignment = SWT.FILL;
// gridData.grabExcessHorizontalSpace = true;
// nameText.setLayoutData(gridData);
// nameText.setText("Text grows horizontally");
new Label(shell, SWT.NONE).setText("Name:");
final ValidatingField nameField = strValToolkit.createTextField( shell, new IFieldValidator(){

public String getErrorMessage() {
return "Name may not be empty.";
}

public String getWarningMessage() {
return "That's a very short name...";
}

public boolean isValid(String contents) {
return !(contents.length()==0);
}

public boolean warningExist(String contents) {
return contents.length() < 3;
}

}, true, "");
GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false);
gd.widthHint = DEFAULT_WIDTH_HINT;
nameField.getControl().setLayoutData(gd);



}

private void createTelephoneNumberField(Composite shell) {
// Label nameLabel = new Label(shell, SWT.NONE);
// nameLabel.setText("Telephone #:");
//
// Text nameText = new Text(shell, SWT.BORDER);
// GridData gridData = new GridData();
// gridData.horizontalAlignment = SWT.FILL;
// gridData.grabExcessHorizontalSpace = true;
// nameText.setLayoutData(gridData);

new Label(shell, SWT.NONE).setText("Contact Telephone Nr:");
final ValidatingField telephoneField= strValToolkit.createTextField(
shell,
new TelephoneNumberValidator(true),
true,
"+44 (55) 555-4321");

GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false);
gd.widthHint = DEFAULT_WIDTH_HINT;
telephoneField.getControl().setLayoutData(gd);
}

}

---------