/Library/Java/JavaVirtualMachines/1.6.0_*/Contents/Home
that can be added as JRE in Eclipse:Tuesday, May 24, 2011
Eclipse on MacOS
Thursday, April 28, 2011
Dynamic access of EClipse workbench resources
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
Acquire the Ifile in the avtice editor accessed above:
IFile ifile = (IFile) editor.getEditorInput().getAdapter(IFile.class);
Access File from the Ifile accessed above:
File file = ifile.getLocation().toFile();
Sunday, April 3, 2011
JUnit in Eclipse
Unit testing is done for small pieces of Code to test the correct working of its functionality.
JUnit is a test framework with a set of APIs which is used to make it unit testing more simple. This API uses annotation to identify the methods which contain tests. JUnit assumes that all test methods can be performed in an arbitrary order. Therefore tests should not depend other tests.
Steps to write a JUnit testclass:
1)Annotate a method with @org.JUnit.Test
example: here a tester class with annotation test
------------
@Test------------
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
2) Use a method provided by JUnit(say - tester...) to check the expected result of the code execution versus the actual result
To run a JUnit test case you can either use :
A) Eclipse (the run as.. option to execute Junit tests)
(or)
B)the class "org.junit.runner.JUnitCore"
In both cases, you will need the Junit framework jar file which you will need to download from the link : https://github.com/KentBeck/junit/downloads
Once downloaded, you need to add this jar file into the Project's Buildpath. This is done as :
**rt click on the project>>select 'build path'>>select 'libraries' tab >> 'add the Junit downloaded jar file.
-----------------------------------
A)Considering the first option :To run a JUnit test case
(i)Create a Java project with a method which needs testing which implements a simple 'multiply' operation as a class file with code as below:***********
package testing.junit;
public class MultiplyClass {
public int multiply(int x, int y) {
return x / y;
}
}
***********
(ii)Now create a JunitTest for this class. Rt click on this class, select JUnit Test from the JUnit category. But remember to change the Source folder from 'src' to 'test'.
(iii)Press 'Next' and select the method which you want to test. INour case, we are testing the 'Multiply' method as below.
(iv)If you have not yet JUnit in your classpath, Eclipse will ask you if it should be added to the classpath.
(v)Once created, modify the code of the Junit test case with the below code:
****
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyClassTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}
****
(vi) Now run the test case....rtclick on the testcase class>>run as...>>JUnit test
the assertEqual method in the above code will check with the expected result value (50) and the actual result obtained by calling the method intended for testing.
If the test case fails, a red light will glow.. In this case, the codes needs to be rechecked.. and corrected. Once corrected, the execution will return a green glow.
In this way we can create multiple JUnit test cases. However, if you want to test all cases at once.. you could use the
JUnit test case: Once you have created multiple test cases, rtclcik on selected testclasses>>new>>JUnit test suite>> select all the methods for testing.
Now modify the testSuite class as below,
*******
import org.junit.runner.RunWith;*******
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses( { MyClassTest.class })
public class AllTests {
}
If you later develop another test you can add it to @Suite.SuiteClasses
--------------------------------------------------
B)Considering the first option :To run a JUnit via code
The class "org.junit.runner.JUnitCore" provides the method runClasses() which allows you to run one or several tests classes.
As a return parameter you receive an object of type "org.junit.runner.Result". This object can be used to retrieve information about the tests and provides information about the failed tests.
To create a JUnit test case via code, follow the same steps as above from (i) through creating a src folder for the test classes
Then, Create in your "test" folder a new class "MyTestRunner" with the following coding:
****
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class MyTestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MyClassTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
}
****
------------------------------------------
Static imports with Eclipse
JUnit uses a lot of static methods and Eclipse cannot automatically import static imports. You can make the JUnit test methods available via the content assists.
Open the Preferences via Window -> Preferences and select Java > Editor > Content Assist > Favorites. Add then via "New Member" the methods you need. For example this makes the assertTrue, assertFalse and assertEquals method available.
You can now use Content Assist (Ctrl+Space) to add the method and the import.
I suggest to add at least the following new members.
-
org.junit.Assert.assertTrue
-
org.junit.Assert.assertFalse
-
org.junit.Assert.assertEquals
-
org.junit.Assert.fail
------------------------------------------
Assert statements/available test methods in JUnit testing:
Statement | Description |
---|---|
fail(String) | Let the method fail, might be usable to check that a certain part of the code is not reached. |
assertTrue(true); | True |
assertsEquals([String message], expected, actual) | Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays |
assertsEquals([String message], expected, actual, tolerance) | Usage for float and double; the tolerance are the number of decimals which must be the same |
assertNull([message], object) | Checks if the object is null |
assertNotNull([message], object) | Check if the object is not null |
assertSame([String], expected, actual) | Check if both variables refer to the same object |
assertNotSame([String], expected, actual) | Check that both variables refer not to the same object |
assertTrue([message], boolean condition) | Check if the boolean condition is true. |
-------------------------------
Annotations in Junit
Annotation | Description |
---|---|
@Test public void method() | Annotation @Test identifies that this method is a test method. |
@Before public void method() | Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class) |
@After public void method() | Test method must start with test |
@BeforeClass public void method() | Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database |
@AfterClass public void method() | Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database |
@Ignore | Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included. |
@Test(expected=IllegalArgumentException.class) | Tests if the method throws the named exception |
@Test(timeout=100) | Fails if the method takes longer then 100 milliseconds |
-------------------------------------------------------
Current Junit version is 4.9.... dated 5th Apr, 2011
________________________________________________________________
Apache Ant in Eclipse
Ant is a simple Build tool in the form of an XML file used in executing repeatetive build tasks using a single xml document.
Build task such as , Compiling, creating a jar, Running Junit tests, etc...
_____
Installation:
Ubuntu : On Debian /Ubuntu use "apt-get install ant" to install it.
Windows :
- Download Apache Ant from http://ant.apache.org/ .
- Extract the zip file and Set the "ANT_HOME" environment variable to this location and include the "ANT_HOME/bin" directory in your path.
- Make sure that JAVA_HOME environment variable is set to the JDK, which is required for running Ant.
_____
Test the Installation:
Check your installation by opening a command line and typing "ant -version" into the commend line.
_____
Creating the Ant, build.xml:-Create a java project with a simple java class file.. say (test.java), which is in a package 1.2.3.test
-Now create an xml file, build.xml , which is your ant file and paste the xml source(in figure below) from section 3.2 of the reference link page into this xml document within this project.
In the source below, the 'Target' tag specifies the task that needs to be executed.
A single build fil ecan have multiple task within it. If your observe the below source, you can see that each target tag consists of a certain execution such as , "Javac" - Compiling java source, "mkdir" - creating directories, etc.
The "depends" attribute of the target tag specifies the other targets that needs to be existing or executed prior to the current specified targets.
Last but not the least, the Ant file can also be used in executing JUnit test.
********************


************************ Main target
********************
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.
____________________________________
>>>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 to | Description | Uri |
---|---|---|
Application menu | Displays the command in the menu of the application | "menu:org.eclipse.ui.main.menu" |
Application toolbar | displays 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-up | Command is displayed in a content menu, e.g. right mouse click on an object | n.a. |
3.now, add "menu" to the "menuContribution" and set the parameters as below:
***************************
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
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.
--------_____________________________Hence testing the project :
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();
}
}
_________________________________________________________________________________________________________________
>> 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.
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,
|
IWorkbench
|
IWorkbenchWindow
|
IWorkbenchPage (also know as perspective)
>>Opening a Resource perspective programatically
// fWindow is an IWorkbenchWindow.
fWindow.openPage("org.eclipse.ui.resourcePerspective", ResourcesPlugin.getWorkspace());
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.
- Create a plug-in.
- Add a perspective extension to the plugin.xml file.
- Define a perspective class for the extension within the plug-in.
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">
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 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.
// 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);
}
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.