Saturday, November 26, 2011

Retrieving Query Strings in Javascript

Retrieving Query Strings in Javascript
Javascript can be used for retrieves query string values too. We need the following code to get query string pairs (field & value) using Javascript:
window.location.search
The above code will return string started with ampersand in the URL (ampersand included). So if we run the above code against the following URL: http://localhost:8088/postings/QrStr/testjs2.htm?name=alma&role=user
The return value is ?name=alma&role=user
To understand the concept better I have write two simple HTML pages that show how to get query string values using Javascript. This is the first file (testqrstr.htm):
    <html> <head> <title>Test Query Strings: Page 1</title> <script lang=”javascript” type=”text/javascript”> function testQueryStrings() { // change the window.location with your own. window.location = “/…/testjs2.htm?name=alma&role=user”; } </script> </head> <body> <input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” /> </body> </html>
The output produced by testjs.htm is similar like the output of Test.aspx, when we click the button it will bring us to testjs2.htm (of course with the specified query strings!). Here testjs.htm:
    <html> <head> <title>Test Query Strings: Page 2</title> <script lang=”javascript” type=”text/javascript”> var qrStr = window.location.search; var spQrStr = qrStr.substring(1); var arrQrStr = new Array(); // splits each of pair var arr = spQrStr.split(‘&’);for (var i=0;i<arr.length;i++){ // splits each of field-value pair var index = arr[i].indexOf(‘=’); var key = arr[i].substring(0,index); var val = arr[i].substring(index+1); // saves each of field-value pair in an array variable arrQrStr[key] = val; } document.write(“<h1>Name parameter: “+arrQrStr["name"]+”. Role parameter: “+arrQrStr["role"]+”</h1>”); </script> </head> <body> </body> </html>
What I was did in testjs2.htm just retrieve the query strings (through window.location.search), save each of field – value pair in an array variable named arrQrStr and echo the content of arrQrStr variable.

Friday, November 25, 2011

Java - Profiling Or Tracing

1.0 Introduction

This document is a quick starter on how to use the profiling tools available in the Profiling and Logging perspsective. The set of profiling tools provides software developers or testers with the ability to analyze the performance of a Java program or to gain a comprehensive understanding of the overall performance of an application. Crucial data on object allocations, garbage collection cycles, object references, method time stamps, and thread or object interactions can be displayed and aid in determining which components of code are heaveily effecting the overall performance of a program.

2.0 Getting Started

The Profiling Monitor view is the primary view of the Profiling and Logging perspective. It is used to monitor Java applications from any number of hosts.
Illustrate the profiling monitor view Java applications can be profiled by using the workbench to either launch a Java process or attach to a running process. Launching or attaching to a Java process can be done locally or remotely.
To be able to profile a Java application, the Hyades Data Collection Engine needs to be running on the deployment machine. The engine can be downloaded from the Hyades website http://www.eclipse.org/hyades. See the install instructions for Hyades and the Hyades Data Collection Engine for more details.

3.0 Profiling an application on a local machine

This section demonstrates how to profile an application on a local machine.

3.1 Create a Java project

A Java project will be created using the sample Java application listed below.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class CarModel {

    /* Required car parts: 1 Engine, 4 wheels, and 2 doors */ 
    public Engine engine = new Engine();
    public Wheel[] wheel = new Wheel[4];   
    public Door left = new Door(), right = new Door(); 



    public CarModel()
    {
      for(int i = 0; i  < 4; i++)
        wheel[i] = new Wheel();
    }
 
 
 
    /* Launcher */
    public static void main(String[] args) throws IOException
    {
        final String LINE_SEPARATOR = 
        System.getProperty("line.separator");
        final int BORDER_CHAR_LENGTH = 40;
        final int UNREF_OBJ_CREATED = 10;
        StringBuffer menu = new StringBuffer();
        CarModel car = new CarModel();
  
        /* Create the menu */
        for (int i = 0;i < BORDER_CHAR_LENGTH; i++)
          menu.append('-');
        menu.append (LINE_SEPARATOR).append("   (1) Simulate car usage");
        menu.append (LINE_SEPARATOR).append("   (2) Create unreferenced objects");
        menu.append (LINE_SEPARATOR).append("   (q) Quit");
        menu.append (LINE_SEPARATOR);
        for (int i = 0;i < BORDER_CHAR_LENGTH; i++)
          menu.append('-');
  
        /* Display the menu */
        System.out.println ("CarModel started" + LINE_SEPARATOR + "Menu:");
        System.out.println (menu.toString());
        System.out.println ("Choose an option:");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String input = in.readLine().trim();

  
        /* Accept input for the desired option */
        while (!input.equalsIgnoreCase("q"))
        {   
          /* Check for invalid entry */
          if (input == null || input.length() != 1 || !Character.isDigit(input.charAt(0)))
          {
            System.err.println ("Wrong option");
            input = in.readLine().trim();
            continue;
          }
      
          switch(Integer.valueOf(input).intValue())
          {
            case 1:
              simulateCarUsage(car);
              break;
            case 2:
              for (int i = 0; i < UNREF_OBJ_CREATED; i++)
                new CarModel();
              System.out.println (UNREF_OBJ_CREATED + " unreferenced objects of CarModel has been created");
              break;
            default:
              System.err.println ("Wrong option");    
          }
        input = in.readLine().trim();
      }
    
    }

 
    /* Simulates car usage */
    public static void simulateCarUsage(CarModel car)
    {
      car.left.window.rollup();
      car.engine.start();
      car.engine.rev();
      car.wheel[0].align();
      car.engine.stop();
    }
} 


/* Inner classes used to model car parts */
class Engine 
{ 
    public void start() 
      { System.out.println("Start the car.");}
    public void rev()   
      {System.out.println("Rev the engine.");}
    public void stop()  
      {System.out.println("Car stopped.");}
}

class Wheel 
{ 
    public void align() 
      {System.out.println("Tires aligned.");}
}

class Window 
{ 
    public void rollup() 
      {System.out.println("Rollup the window.");}
    public void rolldown() 
      {System.out.println("Rolldown the window.");}
}

class Door 
{
    public Window window = new Window();
    public void open() 
   {System.out.println("Open()");}
    public void close() 
      {System.out.println("Close()");}
}

To create a Java project:
  1. Start an instance of Eclipse.
  2. From the menu, select Window > Open perspective > Other.
  3. In the Select Perspective dialog, select Java and click OK .
  4. From the menu, select File > New.
  5. In the New Wizard, select Java Project. Click Next.
  6. Specify the project name as ProfilingExample.
  7. Click Finish. Your new Java project is created in the Package Explorer view.
  8. From the pop-up menu of the newly created project, select New > Class.
  9. Specify profilingExample as the package name and CarModel as the class name.
  10. Click Finish.
  11. Open the newly created class and replace its content with the code listed in Figure 1.
  12. Save the class. The class will be compiled automatically.

3.2 Launch the sample application

The sample application will be launched from the Profiling and Logging perspective.
  1. Switch to the Profiling and Logging perspective by selecting Window > Open perspective > Other > Profiling and Logging.
  2. Click on the launch profiling button Launch profiling configuration icon and select Profile.
  3. In the Profile configuration dialog, double-click on Java Application. A new configuration is created and the details are shown in the right pane.
  4. Specify the project name as profilingExample.
  5. Click on Search for the main class. The wizard should automatically detect the CarModel class.
  6. Select the CarModel class and click OK.

3.3 Specifiying profiling filters

Profiling filters allow users to limit the amount of data that is collecting in a profiling session. Follow these steps to set up filters for the sample application:
  1. In your profiing configuration, under the Profiling tab, select the Overview tab.
  2. Click Add to add your own profiling set. The Add Profiling Set wizard opens.
  3. On the Profiling Set page, specify a name and a description for your profiling set. Click Next.
  4. On the Profiling Type page, select the Memory Analysis and the Time Analysis check boxes.
  5. Click on Execution Time Analysis. The details of this profiling set are shown in the right pane.
  6. Select the Show execution flow graphical details options.
  7. Click Next.
  8. On the Filter Set page, specify the filter set that you want applied by selecting from the Select a filter set list. You can use the Default set.
  9. Under Contents of selected filter set, click Add.
  10. Specify profilingExample.CarModel as the Class and main as the method.
  11. Select EXCLUDE from the Rule list.
  12. Click OK. The filter criterion is added to the contents list.
  13. Click Finish.
  14. Click Apply to save the changes.
  15. Click Profile to start profiling your application. The Profiling Monitor will show the CarModel application started.
    CarModel application is started and shown in the Profiling Monitor view
    The console will show the following output:
    The CarModel menu will be displayed on the Console output
  16. By default, the hosts and monitors are hidden. To add the hosts and monitor, click on the menu button Arrow head pointing down of the Profiling Monitor view and de-select Hosts. Repeat this step to add Monitors to the Profiling Monitor view.

3.4 Examining the profiling data using the profiling views

This section will demonstrate how to use the different statistics views, and a number of the graphical views to identify usage patterns and code execution.

Memory Statistics view

  1. From the Profiling Monitor view, using the pop-up menu of the profiling agent, select Open with > Memory Statistics.
  2. In the Memory Statistics view, expand the profilingExample package.
  3. Select CarModel. Notice the information provided for the class:
    Total instances: The total number of instances of the CarModel class.
    Live instances: The number of instances that are alive (i.e. instances that were not collected by the garbage collector).
    Collected: The number of instances that have been garbage collected.
    Total Size (bytes): The size of an instances associated with a specific type.
    Active Size (bytes): The size of an instances associated with a specific type.
  4. From the toolbar, select Class Class method icon to open the class levelinformation. Notice that all the non-filtered invoked methods of the CarModel class appear under its name. The filtered main method which has already been invoked at this point, does not appear under the class.
  5. Select Instance level icon from the toolbar to open the instance level information. The number of instances associated with a specific object type are listed beneath the object.
  6. Expand the CarModel class and note that it has only one associated instance.
  7. In the console view, enter 2 to instantiate ten unreferenced objects of the CarModel class.
  8. Switch back to the Memory Statistics view, right-click anywhere in the view, and select Refresh Views.
  9. Note the changes in the instances by the Delta icon. Expand the the CarModel class. There are now eleven instances of the CarModel class listed.

Execution Statistics view

  1. From the Profiling Monitor view, using the pop-up menu of the profiling agent, select Open with > Execution Statistics.
  2. From the toolbar, click method icon to open the method level information. Notice that the base time, average time, cumulative, and number of method calls are shown in this view:
    Base Time: The amount of time (in seconds) the method has taken to execute. Not including the execution time of any other methods called from this method.
    Average base time: The average base time required to execute this method once.
    Cumulative base time: The amount of time (in seconds) this method took to execute. Including the execution time of any other methods called from this method.
    Calls: The number of times this method was invoked.
    The elements in the views can be sorted by simply clicking on a desired column header. for example, click on the Base Time column header to sort the methods by this attribute.
  3. Switch to the console view. If it is not open, select Window > Show view > Console to open the view.
  4. Enter '1' in the console view to invoke a set of methods. The console will show the following output:
    Rollup the window.
    Start the car.
    Rev the engine.
    Tires aligned.
    Car stopped.
  5. In the Profiling Monitor view, click the refresh view button Refresh views icon to refresh the views.
  6. Switch to the Execution Statistics view with the method-level information selected. Note that there are new methods added to this view.
  7. Repeat step 8 and 9. Notice that the number of calls to the start() method has increased from 1 to 2. The changes in the column values are indicated by a delta icon with an up arrow or a down arrow to indicate an increase or a decrease. Refreshing the views is similar to taking snapshots of the running program. The views in the Profiling and Logging perspective provide the ability to compare views and to identify the difference between the snapshots.
  8. Right-click on simulateCarUsage() and select Open source. Notice that the workbench automatically changes the perspective and the cursor is moved to the beginning of the simulateCarUsage() in the Java editor. This option is useful for pinpointing overheads in specific portions of a Java program.

Garbage collection

  1. In the Profiling and Logging perspective, create un-referenced objects by entering 2 in the console view. See step 12 in the previous section.
  2. In the Profiling Monitor view, press the garbage collection button Garbage collection icon to run garbage collection. Verify that the live instances of CarModel has decreased. A good JVM will collect all ten unreferenced objects of CarModel, decreasing the value of the live instances to only 1. Forcing garbage collection in the middle of a program helps to identify memory leaks and the number of unnecessary objects created.

UML2 sequence diagrams

  1. In the console view, enter q to quit the application.
  2. The application can be re-launched by selecting the profiling button in the toolbar.
  3. In the Profiling Monitor view, use the pop-up menu of the monitored profiling agent and select Open with > UML2 Class Interactions.
  4. The sequence diagram should be similar to the one below.

    Sequence diagram showing the application diagram
    The time compression bar along the left edge of the diagram indicates the time elapsed between consecutive events. This bar indicates which part of a method consumes the most time, helping to identify hot spots in the program being monitored. In this example, the creation of the Door object is identified as a hot spot.
    Moving the cursor over any of the blocks will display the name of the invoked method of the class. The thread and object interaction views are two other similar sequence diagrams available in the Profiling and Logging perspective.

Execution flow diagram and table

  1. In the Profiling and Logging perspective, select the toolbar button execution flow view icon to open the Execution flow view diagram.

    Image of the execution flow view graph
    This view indicates the general flow of the Java application, and can help in identifying repetitive coding in a given Java application. Stripes cascade to the right as one method calls another method, whose responding method in turn calls another method, and so on. Stripes are grouped in columns by thread. A thin, black vertical line separates one column from another. The name of each thread appears at the top of its column.
  2. To open the Execution table, right-click anywhere in the Execution Flow diagram view and select Show Execution Table. The execution table shows the same information in a tabulated format.

Object references table

  1. In the Profiling Monitor view, right-click the monitoring agent and select Collect object references.
  2. From the toolbar, click on the Object References button object references table icon to open the Object references table.
  3. Expand the CarModel class to show all the references made in this class.

    Table showing the object references

    Note that there is only one instance of this type that has been instantiated. This type refers to an array of Wheel, Door, and Engine objects. Reviewing the declared instance variables of the CarModel verifies this:
    public Engine engine = new Engine();
        public Wheel[] wheel = new Wheel[4];   
        public Door left = new Door(), right = new Door(); 
  4. To end the process, from the toolbar of the Profiling Monitor view, click the terminate button Terminate icon.

3.5 Attaching to a local Java application

Being able to attach to a running Java process allows users to run applications without any interruptions from the Java profiling agent. The Profiling and Logging perspective can then be used to attach to a running process for determining the reason why the application takes an unusual amount of time or memory to perform a specific task.
The workbench and the Hyades plug-ins will be used to demonstrate how to attach to a Java application for monitoring. For this part of the guide, a different Eclipse workspace will be used.
  1. Switch to the home directory of the Eclipse platform (e.g. D:\Eclipse).
  2. Use the following command to start the eclipse workbench with profile as the workspace name:
    eclipse -data profile
    
    This workbench will be used to profile a second workbench.
  3. The Java Profiling Agent is invoked by specifying the JVM argument - XrunpiAgent:server=enabled on the java command to start the application to be profiled. For example:
    java -XrunpiAgent:server=enabled javaApp
    . In this case we want to profile an instance of the Eclipse workbench and we will use the eclipse program to start the workbench.
    Navigate to the home directory of the Eclipse workbench and run the following command to start a second workbench with the default workspace:
    eclipse -vmargs -XrunpiAgent:server=enabled
    where
    -vmargs
    is how to specify JVM arguments to the JVM used to run Eclipse
    -XrunpiAgent
    invokes the Java Profiling Agent
    :server=enabled
    Specifies the mode of the Java profiling agent. Enabled mode will allow the Java application to run normally with the Java profiling agent running in the background. If the mode is changed to controlled, then the application will be locked (i.e. not executed) until it is attached to.
    For more details on the -XrunpiAgent argument, type java -XrunpiAgent:help in a console window. Note: This command is case-sensitive on most platforms. The profiling agent is installed as part of the Hyades Data Collection Engine. Ensure that the bin directory of the Hyades Data Collection Engine is in the PATH environment variable on Windows systems and the lib directory is in the LD_LIBRARY_PATH environment variable on Linux systems.

  4. Switch to the Profiling and Logging perspective in the workbench launched with the profile workspace.

  5. In the toolbar, click the profile button Launch profiling configuration icon and select Profile.

  6. In the Profile configuration dialog, double-click on Attach - Java Process. A new configuration is created and the details are shown in the right pane.

  7. Under the Agents tab, select the Java Profiling Agent on the left side and use the right arrow to include the selected agent.

    Image showing the Java Profiling Agent added to the selected agent list


  8. Under the Profiling tab, select the Overview tab.

  9. Click Add to add a profiling set called "Hyades plug-ins".

  10. Select the newly created profiling set and click Edit. The Edit Profiling Set dialog opens.

  11. Select the Memory Analysis and the Time Analysis check boxes.

  12. Click on Execution Time Analysis. The details of this profiling set are shown in the right pane.

  13. Select the Show execution flow graphical details option.

  14. Click Next.

  15. On the Edit Filters page, under Contents of selected filter set, use the Remove button to remove all existing filters.

  16. Click Add and add the following two filters:
    Package or class:  org.eclipse.hyades*
    Method name: *
    Rule: Include  
    
    Package or class: *
    Method name: *
    Rule: Exclude
    These filters will ensure that everything but the Hyades packages will be excluded in the profiling session.

  17. Click Finish.

  18. Click Apply to save the changes.

  19. Click Profile to begin profiling. You may be prompted with a message about how the agent should be started. Click OK to close the dialog box if you are prompted with this message.

  20. The initial state of the attached agent will be in an attached mode.

    The agent is in an attached mode.

    Right-click on the agent and select Start Monitoring to start tracing the second workbench. The agent will now be monitored.

    The agent is in a suspend mode.

  21. In the second workbench, switch to the Profiling and Logging perspective. This action will be enough to trigger some data to be collected in the first workbench.
    Note: The 'Pause Monitoring' button at the top of the Profiling Monitor view can be used to pause monitoring of the attached agent at any time. To completely stop monitoring the attached application, use the pop-up menu of the agent and select Detach from Agent.

  22. Exit the second workbench. The status of the profiling agent in the first workbench should eventually change to terminated

  23. Open the package statistics view to verify that some data has been collected from the Hyades plug-ins.

4.0 Profiling a remote Java application

This section discusses how to profile remotely deployed applications.
Prerequisite:
You will need the to have the Hyades Data Collection Engine installed and running on the remote machine in order to be able to remotely launch and profile Java applications. See the Getting started guide for installing the Data Collection Engine.

4.1 Launching a Java application remotely

1.2 Launching a Java Application Remotely To launch a Java application on a remote machine:
  1. Launch the Eclipse workbench.
  2. Switch to the Profiling and Logging perspective.
  3. In the toolbar, click the profile button Launch profiling configuration icon and select Profile.
  4. In the Profile configuration dialog, double-click on External Java Application. A new configuration is created and the details are shown in the right pane.
  5. Under the Hosts tab, enter the name of the desired host and the port number of the data collection engine. By default the port number is 10002.
  6. Click on Add to add the host to the Default Hosts list.
  7. Click on Test Connection to verify that the workbench can communicate with the running engine on the remote machine.
  8. Under the main tab, enter the class name and the class path of the Java application on the remote machine. For example, to launch the Java class under D:\Test\ProfileClass.class, enter ProfileClass for the class name and enter D:\Test for the path of the class. Additional JAR files can be added by separating each path by a semicolon on windows or colon on UNIX platforms, for example:
    Windows:
    D:\Test;D:\Test\mylib.jar
    UNIX platforms:
    /home/user/Test:/home/user/Test/mylib.jar
    
  9. Click Next.
  10. Specify the profiling filters. See section 3.3 for details.
  11. After the profiling filters are specified, click Profile to begin profiling the remote application.
  12. Open a number of profiling views to ensure that data is being collected for the remote application.

4.2 Attaching to a remote Java process

To attach to an application running on a remote machine, the Java Profiling Agent can be used to launch the process on the remote machine.
  1. On the remote host, use same command mentioned in section 1.1 to start the desired application:
    java -XrunpiAgent:server=enabled ProfileClass
    
    where ProfileClass is the name of the class that is intended to be started.
  2. On your local machine, launch the Eclipse workbench.
  3. Switch to the Profiling and Logging perspective.
  4. In the toolbar, click the profile button Launch profiling configuration icon and select Profile.
  5. In the Profile configuration dialog, double-click on Attach - Java Process. A new configuration is created and the details are shown in the right pane.
  6. Under the Hosts tab, enter the name of the desired host and the port number of the data collection engine. By default the port number is 10002.
  7. Click on Add to add the host to the Default Hosts list.
  8. Under the Agents tab, select the profiling agent that is running on the remote host and add it to the Selected agents list.
  9. Under the Profiling tab, specify the profiling filters. See section 3.3 for details.
  10. Click Profile to begin profiling your application.
  11. Open a number of views to ensure that data is being collected on the remote application.
http://blog.zvikico.com/2007/12/tracing-java-ex.html
http://www.eclipse.org/tptp/home/documents/tutorials/profilingtool/profilingexample_32.html

Eclipse RCP

1.1. What is Eclipse RCP

Eclipse was originally started as a modular IDE application. In 2004 the Eclipse 3.0 version was released which supported that the Eclipse platform could be re-used to build standalone applications based on the same technology as the Eclipse IDE.
Eclipse RCP allows developers to use the Eclipse platform to create flexible and extensible desktop applications. Eclipse and Eclipse RCP applications are build upon a plug-in architecture. Plug-ins are the smallest deployable and installable software components of Eclipse.
A plug-in is a collection of files and a configuration file (MANIFEST.MF) which describes the plugin and its dependencies.
This plugin architecture allows Eclipse and Eclipse RCP applications to get extended by third parties.
The following picture shows the content of an example RCP application.

Content of an example RCP project

1.2. Advantages of Eclipse RCP

Eclipse RCP is the basis for the most successful Java IDE and therefore very stable and broadly used. It uses native UI components to provide as much as possible a native look and feel and with its strong modularity approach allow to design component based systems.
Companies like IBM and Google use the Eclipse framework heavily for their products and therefore ensure that Eclipse is flexible, fast and continues to evolve.
Eclipse RCP also fosters a large community of Individuals which provide support, information and extensions to the Eclipse framework. Tapping into this Eco-system allow you to easily find required resources and information you need.

2. Eclipse Plug-in Architecture

2.1. Eclipse IDE vrs. Eclipse RCP

An Eclipse application consists out of plug-ins.
From the Eclipse RCP perspective the Eclipse IDE is only one collection of specific plug-ins. The components of the Eclipse IDE are primary the following.

Primary Eclipse IDE components

An Eclipse RCP application use only parts of these components. An Eclipse RCP application typically uses:

Typical components of an Eclipse RCP application

For a headless Eclipse based applications (without UI) only the runtime is necessary.
The OSGi runtime provides the framework to run the modular application. SWT is the standard UI component library used by Eclipse and JFace provides some convenient API on top of SWT. The workbench provides the framework for your application. The workbench is responsible for displaying all other UI components.

2.2.  Plugins, OSGi, Extension Points

As said Eclipse application are build via a collection of plugins. Plugins define their API and their dependencies. The basis for this architecture is the runtime environment Equinox which is the reference implementation of OSGi. Eclipse uses the term "Plugin" and OSGi uses the term "bundle", but both terms mean the same.
OSGi specifies how Eclipse plugins defines:
  • their API - public classes which can be used by other plugins
  • their dependencies - package or plugins which are required for the plugin to run correctly

OSGi defines also services. Services are dynamic components.
In addition to the OSGi functionality you can also use and define extension-points in Eclipse applications. Extension-points define interfaces for other plug-ins to contribute functionality (code and non-code ).
Another or the same plug-in can use extensions, e.g. provide functionality to these extension points.
Extensions and extension-points are described in the file "plugin.xml". This file is a XML file which provides a user interface for editing this file. The Eclipse IDE provides editors for this file (via the so called Plug-in Development Environment).
Existing extensions (contributions) are collected during the start of an Eclipse RCP application. The information in the extension points is converted into so-called descriptors and stored in registries.

2.3.  Main components of an Eclipse RCP application

The minimal required plug-ins to create and run an minimal Eclipse RCP application (with UI) are the two plugins "org.eclipse.core.runtime" and "org.eclipse.ui". Based on these components an Eclipse RCP application must define the following elements:

  • Main program - A RCP main application class implements the interface "IApplication". This class can be viewed as the equivalent to the main method for standard Java application. Eclipse expects that the application class is defined via the extension point "org.eclipse.core.runtime.application".
  • A Perspective - defines the layout of your application. Must be declared via the extension point "org.eclipse.ui.perspective".
  • Workbench Advisor- invisible technical component which controls the appearance of the application (menus, toolbars, perspectives, etc)

2.4. Configuration files

An Eclipse RCP application has two main configuration files.
  • MANIFEST.MF - contains the OSGi configuration information.
  • plugin.xml - Information about the extensions and extension points

3. Prerequisite

The following assumes that you already have some knowledge in using the Eclipse IDE for standard Java development. See Eclipse IDE Tutorial if you don't have this knowledge.
Is also assume that you are familiar with using the Eclipse update manager. See Eclipse Update Manager to learn how to use it.

4. Installation

4.1. Installation

Browse to Eclipse download site and download the package "Eclipse for RCP and RAP Developers". Extract the download to your harddisk. Avoid having special characters or spaces in the path to Eclipse.

4.2. Update an Eclipse Java IDE

In case you have downloaded the Eclipse Java IDE (or any other non RCP flavor) distribution you can use the Eclipse Update Manager to install the plug-ins required for RCP development.
Install "General Purpose Tools" -> "Eclipse Plug-in Development Environment" and "Eclipse RCP Plug-in Developer Resources" from the Indigo update site. You may have to remove the "Group items by category" flag to see these features.

Update dialog showing how the group by flag can be removed


Selecting the Ecipse RCP development package in the update manager.

5. Tutorial: Create your first RCP application

5.1. Create an RCP application

The following explains how to create a simple RCP application. In Eclipse select File-> New Project. From the list select "Plug-In Project".

Selection the Eclipse Plug-in Wizard

Give your plugin the name "de.vogella.rcp.intro.first" .

First page of the Eclipse Plug-in Wizard specifying the project name.

Press "Next" and make the following settings. As we are going to develop an RCP application, select "Yes" at the question "Would you like to create a rich client application".

Second page of the Eclipse Plug-in Wizard specifying the plug-in ID, version, Name, Activator and the RCP type.

Press next and select the template "Hello RCP" .

Third page of the Eclipse Plug-in Wizard selecting the template "Hello RCP".

Press next and select "Add branding" and press Finish.

Forth page of the Eclipse Plug-in Wizard specifying the branding.

As a result a project with the following project structure will be created. Have a look at the different files especially the Java files to get a first feeling about the project structure.

Screenshot of the created project after the wizard finished

5.2. Start your RCP application

Open the file "MANIFEST.MF" by double-clicking on it. You should see an editor and the tab "Overview" should be selected. Click the link "Launch an Eclipse Application".
Overview tag of the Manifest.mf file highlighting the "Launch an Eclipse RCP application" section
The result should look like the following:
Running example application
Congratulations, you have created and started your first RCP application.

5.3. Convention

In this tutorial we will always create RCP applications. Therefore if the instruction says "Create an RCP project" you should create a new plug-in project with the flag "Would you like to create a rich client application" enabled.

6. Application and Advisor Classes

During the startup of an Eclipse RCP application the Eclipse runtime will evaluate which class is defined via the "org.eclipse.core.runtime.application" extension point. This class is typically called Application and must implement the interface IApplication. This is the equivalent of the main class of standard Java programs. This class is responsible for creating the SWT Display and for starting the event loop for the application.

Display display = PlatformUI.createDisplay();
PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
  

PlatformUI.createAndRunWorkbench() creates and runs a Workbench. The Workbench represents the graphical user interface of Eclipse. The visual part of the Workbench is represented via the class WorkbenchWindow. A Workbench can have several WorkbenchWindows opened. The inner part of the WorkbenchWindow is represented via the class WorkbenchPage.
The Workbench is configured via a class of type "WorkbenchAdvisor". This class defines the initial Perspective and defines the WorkbenchWindowAdvisor class.
WorkbenchWindowAdvisor calls the class ActionBarAdvisor which configures Actions for the Workbench and defines initial attribute for the WorkbenchWindow as initial size, title and visibility of the statusline.

public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
 return new ApplicationActionBarAdvisor(configurer);
}

public void preWindowOpen() {
 IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
 configurer.setInitialSize(new Point(400, 300));
 configurer.setShowCoolBar(false);
 configurer.setShowStatusLine(false);
 configurer.setTitle("Todo"); //$NON-NLS-1$
}
  

For example you could set the initial position of the application via postWindowCreate() method.

// For further info see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84938
@Override
public void postWindowCreate() {
 Shell shell = getWindowConfigurer().getWindow().getShell();
 shell.setLocation(100, 400);
 super.postWindowCreate();
}
  

The ActionBarAdvisor class is as of Eclipse 3.7 not important any more as the Action framework is replaced by the superior command framework.
Each adviser allow to configure certain behavior of the application, e.g. the WorkbenchAdvisor allows to perform certain actions at startup or shutdown by overriding the methods preStartUp() and preShutdown().

7. Run configuration

7.1. Overview

A run configuration in Eclipse defines the environment under which a RCP application will be started. For example it defines compiler flags, plugin (classpath) dependencies etc. Sometimes a run configuration is called "launch configuration". If you start your RCP application a run configuration will be automatically created for you.
To see and edit your run configuration select the file "MANIFEST.MF", right-click on it and select -> Run As -> Run Configurations

How to open the launch configuration menu from the MANIFEST.MF file.

In the field "location" you specify their the files will be created which are necessary to run your RCP application.

Shows the launch configuration, highlighting the location setting

7.2. Check the runtime configuration

On the Plug-ins Tab select "Validate plug-ins prior to launching". This will check if you have all required plugins in your launch configuration. If this check reports that some plugins are missing, try clicking the "Add Required-Plug-Ins" button.

Pressing the "Add required Plug-ins" button in the Eclipse launch configuration


Tip

This may solve errors like "One or more bundles are not resolved because the following root constraints are not resolved" or "java.lang.RuntimeException: No application id has been found."

On the tab Arguments you find the parameter -consoleLog. This option allows to see errors in the RCP application in the console view and is very helpful to identify problems.

-consoleLog in the launch configuration

Other useful parameters are -console (which will give you a OSGI console where you can check the status of your application) and -noExit (which will keep the OSGI console open even if the application ends / crashes).

http://www.vogella.de/articles/EclipseRCP/article.html

Rich Client Tutorial Part 1

Try this experiment: Show Eclipse to some friends or co-workers who haven't seen it before and ask them to guess what language it is written in. Chances are, they'll guess VB, C++, or C#, because those languages are used most often for high quality client side applications. Then watch the look on their faces when you tell them it was created in Java, especially if they are Java programmers.
Because of its unique open source license, you can use the technologies that went into Eclipse to create your own commercial quality programs. Before version 3.0, this was possible but difficult, especially when you wanted to heavily customize the menus, layouts, and other user interface elements. That was because the "IDE-ness" of Eclipse was hard-wired into it. Version 3.0 introduced the Rich Client Platform (RCP), which is basically a refactoring of the fundamental parts of Eclipse's UI, allowing it to be used for non-IDE applications. Version 3.1 updated RCP with new capabilities, and, most importantly, new tooling support to make it easier to create than before.
If you want to cut to the chase and look at the code for this part you can find it in the accompanying zip file. Otherwise, let's take a look at how to construct an RCP application.

Getting started

RCP applications are based on the familiar Eclipse plug-in architecture, (if it's not familiar to you, see the references section). Therefore, you'll need to create a plug-in to be your main program. Eclipse's Plug-in Development Environment (PDE) provides a number of wizards and editors that take some of the drudgery out of the process. PDE is included with the Eclipse SDK download so that is the package you should be using. Here are the steps you should follow to get started.
First, bring up Eclipse and select File > New > Project, then expand Plug-in Development and double-click Plug-in Project to bring up the Plug-in Project wizard. On the subsequent pages, enter a Project name such as org.eclipse.ui.tutorials.rcp.part1, indicate you want a Java project, select the version of Eclipse you're targeting (at least 3.1), and enable the option to Create an OSGi bundle manifest. Then click Next >.
Note: Beginning in Eclipse 3.1 you will get best results by using the OSGi bundle manifest. In contrast to previous versions, this is now the default.
In the next page of the Wizard you can change the Plug-in ID and other parameters. Of particular importance is the question, "Would you like to create a rich client application?". Select Yes. The generated plug-in class is optional but for this example just leave all the other options at their default values. Click Next > to continue.
Note: If you get a dialog asking if Eclipse can switch to the Plug-in Development Perspective click Remember my decision and select Yes (this is optional).
Starting with Eclipse 3.1, several templates have been provided to make creating an RCP application a breeze. We'll use the simplest one available and see how it works. Make sure the option to Create a plug-in using one of the templates is enabled, then select the Hello RCP template. This is RCP's equivalent of "Hello, world". Click Finish to accept all the defaults and generate the project (see Figure 1). Eclipse will open the Plug-in Manifest Editor. The Plug-in Manifest editor puts a friendly face on the various configuration files that control your RCP application.

Figure 1. The Hello World RCP project was created by a PDE wizard.

Taking it for a spin

Trying out RCP applications used to be somewhat tedious. You had to create a custom launch configuration, enter the right application name, and tweak the plug-ins that were included. Thankfully the PDE keeps track of all this now. All you have to do is click on the Launch an Eclipse Application button in the Plug-in Manifest editor's Overview page. You should see a bare-bones Workbench start up (see Figure 2).
Figure 2. By using the templates you can be up and running an RCP application in minutes.

Making it a product

In Eclipse terms a product is everything that goes with your application, including all the other plug-ins it depends on, a command to run the application (called the native launcher), and any branding (icons, etc.) that make your application distinctive. Although as we've just seen you can run a RCP application without defining a product, having one makes it a whole lot easier to run the application outside of Eclipse. This is one of the major innovations that Eclipse 3.1 brought to RCP development.
Some of the more complicated RCP templates already come with a product defined, but the Hello RCP template does not so we'll have to make one.
In order to create a product, the easiest way is to add a product configuration file to the project. Right click on the plug-in project and select New > Product Configuration. Then enter a file name for this new configuration file, such as part1.product. Leave the other options at their default values. Then click Finish. The Product Configuration editor will open. This editor lets you control exactly what makes up your product including all its plug-ins and branding elements.
In the Overview page, select the New... button to create a new product extension. Type in or browse to the defining plug-in (org.eclipse.ui.tutorials.rcp.part1). Enter a Product ID such as product, and for the Product Application select org.eclipse.ui.tutorials.rcp.part1.application. Click Finish to define the product. Back in the Overview page, type in a new Product Name, for example RCP Tutorial 1.
Note: In Eclipse 3.1.0 if you create the product before filling in the Product Name you may see an error appear in the Problems view. The error will go away when you Synchronize (see below). This is a known bug that is fixed in newer versions. Always use the latest available maintenance release for the version of Eclipse you're targeting!
Now select the Configuration tab and click Add.... Select the plug-in you just created (org.eclipse.ui.tutorials.rcp.part1) and then click on Add Required Plug-ins. Then go back to the Overview page and press Ctrl+S or File > Save to save your work.
Tip: If your application needs to reference plug-ins that cannot be determined until run time (for example the tomcat plug-in), then add them manually in the Configuration tab.
At this point you should test out the product to make sure it runs correctly. In the Testing section of the Overview page, click on Synchronize then click on Launch the product. If all goes well, the application should start up just like before.

Plug-ins vs. features

On the Overview page you may have noticed an option that says the product configuration is based on either plug-ins or features. The simplest kind of configuration is one based on plug-ins, so that's what this tutorial uses. If your product needs automatic update or Java Web Start support, then eventually you should convert it to use features. But take my advice and get it working without them first.

Running it outside of Eclipse

The whole point of all this is to be able to deploy and run stand-alone applications without the user having to know anything about the Java and Eclipse code being used under the covers. For a real application you may want to provide a self-contained executable generated by an install program like InstallShield or NSIS. That's really beyond the scope of this article though, so we'll do something simpler.
The Eclipse plug-in loader expects things to be in a certain layout so we'll need to create a simplified version of the Eclipse install directory. This directory has to contain the native launcher program, config files, and all the plug-ins required by the product. Thankfully, we've given the PDE enough information that it can put all this together for us now.
In the Exporting section of the Product Configuration editor, click the link to Use the Eclipse Product export wizard. Set the root directory to something like RcpTutorial1. Then select the option to deploy into a Directory, and enter a directory path to a temporary (scratch) area such as C:\Deploy. Check the option to Include source code if you're building an open source project. Press Finish to build and export the program.
Note: The compiler options for source and class compatibility in the Eclipse Product export wizard will override any options you have specified on your project or global preferences. As part of the Export process, the plug-in is code is recompiled by an Ant script using these options.
The application is now ready to run outside Eclipse. When you're done you should have a structure that looks like this in your deployment directory:
RcpTutorial1
    |    .eclipseproduct
    |    eclipse.exe
    |    startup.jar
    +--- configuration
    |         config.ini
    +--- plugins
              org.eclipse.core.commands_3.1.0.jar
              org.eclipse.core.expressions_3.1.0.jar
              org.eclipse.core.runtime_3.1.2.jar
              org.eclipse.help_3.1.0.jar
              org.eclipse.jface_3.1.1.jar
              org.eclipse.osgi_3.1.2.jar
              org.eclipse.swt.win32.win32.x86_3.1.2.jar
              org.eclipse.swt_3.1.0.jar
              org.eclipse.ui.tutorials.rcp.part1_1.0.0.jar
              org.eclipse.ui.workbench_3.1.2.jar
              org.eclipse.ui_3.1.2.jar
Note: Note that all the plug-ins are deployed as jar files. This is the recommended format starting in Eclipse 3.1. Among other things this saves disk space in the deployed application.
Tip: Previous versions of this tutorial recommended using a batch file or shell script to invoke your RCP program. It turns out this is a bad idea because you will not be able to fully brand your application later on. For example, you won't be able to add a splash screen. Besides, the export wizard does not support the batch file approach so just stick with the native launcher.
Give it a try! Execute the native launcher (eclipse or eclipse.exe by default) outside Eclipse and watch the application come up. The name of the launcher is controlled by branding options in the product configuration.

Troubleshooting

Error: Launching failed because the org.eclipse.osgi plug-in is not included...
You can get this error when testing the product if you've forgotten to list the plug-ins that make up the product. In the Product Configuration editor, select the Configuration tab, and add all your plug-ins plus all the ones they require as instructed above.

Compatibility and migration

If you are migrating a plug-in from version 2.1 to version 3.1 there are number of issues covered in the on-line documentation that you need to be aware of. If you're making the smaller step from 3.0 to 3.1, the number of differences is much smaller. See the References section for more information.
Tip: One word of advice: be careful not to duplicate any information in both plug-in.xml and MANIFEST.MF. Typically this would not occur unless you are converting an older plug-in that did not use MANIFEST.MF into one that does, and even then only if you are editing the files by hand instead of going through the PDE.

http://www.eclipse.org/articles/Article-RCP-1/tutorial1.html