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.

No comments:

Post a Comment