Tuesday, October 9, 2012

Integrating a custom builder

A builder can be used to trigger custom actions during a project build. You can use it to update resource files, generate documentation or to twitter every piece of code you write...

Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online.

Step 1: Creating the builder

This is the easy part. Create a new Plug-in project named com.codeandme.custombuilder and switch to the Extensions tab of the plugin.xml.

Add an extension for org.eclipse.core.resources.builders. Set the ID to com.codeandme.custombuilder.myBuilder, leave the builder settings empty and create a run entry below. There set the class to com.codeandme.custombuilder.MyBuilder. Implement the class with following code:
package com.codeandme.custombuilder.builders;

import java.util.Map;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;

public class MyBuilder extends IncrementalProjectBuilder {

 public static final String BUILDER_ID = "com.codeandme.custombuilder.myBuilder";

 @Override
 protected IProject[] build(final int kind, final Map<String, String> args, final IProgressMonitor monitor)
   throws CoreException {

  System.out.println("Custom builder triggered");

  // get the project to build
  getProject();

  switch (kind) {

  case FULL_BUILD:
   break;

  case INCREMENTAL_BUILD:
   break;

  case AUTO_BUILD:
   break;
  }

  return null;
 }
}

Do not forget to add a plug-in dependency for org.eclipse.core.runtime.

Your builder is done. Sure you need to add functionality to it, but this is your part. So now what? We need to add the builder to projects. To selectively add a builder eclipse suggests to use the Configure entry in the popup menu of projects.

Step 2: Create context menu entries

First lets create the commands to add and remove our builder.

Add the command definitions to your plugin.xml

      <command
            defaultHandler="com.codeandme.custombuilder.commands.AddBuilder"
            id="com.codeandme.custombuilder.addBuilder"
            name="Add Custom Builder">
      </command>
      <command
            defaultHandler="com.codeandme.custombuilder.commands.RemoveBuilder"
            id="com.codeandme.custombuilder.removeBuilder"
            name="Remove Custom Builder">
      </command>

At the same time we can add some additional dependencies:
  • org.eclipse.core.commands
  • org.eclipse.jface
  • org.eclipse.ui
Now implement the commands:

package com.codeandme.custombuilder.commands;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import com.codeandme.custombuilder.builders.MyBuilder;

public class AddBuilder extends AbstractHandler implements IHandler {

 @Override
 public Object execute(final ExecutionEvent event) {
  final IProject project = getProject(event);

  if (project != null) {
   try {
    // verify already registered builders
    if (hasBuilder(project))
     // already enabled
     return null;

    // add builder to project properties
    IProjectDescription description = project.getDescription();
    final ICommand buildCommand = description.newCommand();
    buildCommand.setBuilderName(MyBuilder.BUILDER_ID);

    final List<ICommand> commands = new ArrayList<ICommand>();
    commands.addAll(Arrays.asList(description.getBuildSpec()));
    commands.add(buildCommand);

    description.setBuildSpec(commands.toArray(new ICommand[commands.size()]));
    project.setDescription(description, null);

   } catch (final CoreException e) {
    // TODO could not read/write project description
    e.printStackTrace();
   }
  }

  return null;
 }

 public static IProject getProject(final ExecutionEvent event) {
  final ISelection selection = HandlerUtil.getCurrentSelection(event);
  if (selection instanceof IStructuredSelection) {
   final Object element = ((IStructuredSelection) selection).getFirstElement();

   return (IProject) Platform.getAdapterManager().getAdapter(element, IProject.class);
  }

  return null;
 }

 public static final boolean hasBuilder(final IProject project) {
  try {
   for (final ICommand buildSpec : project.getDescription().getBuildSpec()) {
    if (MyBuilder.BUILDER_ID.equals(buildSpec.getBuilderName()))
     return true;
   }
  } catch (final CoreException e) {
  }

  return false;
 }
}

package com.codeandme.custombuilder.commands;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;

import com.codeandme.custombuilder.builders.MyBuilder;

public class RemoveBuilder extends AbstractHandler implements IHandler {

 @Override
 public Object execute(final ExecutionEvent event) throws ExecutionException {
  final IProject project = AddBuilder.getProject(event);

  if (project != null) {
   try {
    final IProjectDescription description = project.getDescription();
    final List<ICommand> commands = new ArrayList<ICommand>();
    commands.addAll(Arrays.asList(description.getBuildSpec()));

    for (final ICommand buildSpec : description.getBuildSpec()) {
     if (MyBuilder.BUILDER_ID.equals(buildSpec.getBuilderName())) {
      // remove builder
      commands.remove(buildSpec);
     }
    }

    description.setBuildSpec(commands.toArray(new ICommand[commands.size()]));
    project.setDescription(description, null);
   } catch (final CoreException e) {
    // TODO could not read/write project description
    e.printStackTrace();
   }
  }

  return null;
 }
}

When retrieving the selected project we need to use the AdapterManager as some project types do not directly implement IProject (that is, if I remember correctly). Then we parse the build specification to add or remove our custom builder.

To add those commands to the Configure context menu we create a new menu contribution for popup:org.eclipse.ui.projectConfigure?after=additions

   <extension
         point="org.eclipse.ui.menus">
      <menuContribution
            allPopups="false"
            locationURI="popup:org.eclipse.ui.projectConfigure?after=additions">
         <command
               commandId="com.codeandme.custombuilder.addBuilder"
               style="push">
         </command>
         <command
               commandId="com.codeandme.custombuilder.removeBuilder"
               style="push">
         </command>
      </menuContribution>
   </extension>
Now you should be able to add and remove your builder.

Step 3: Selectively activate context menu entries

Only one of the commands makes sense regarding the current builder settings of a project. To enrich the user experience we will hide the invalid one.

Therefore we need to use a PropertyTester and some visibleWhen expressions as we did before in Property testers and Expression examples.

Create a new propertyTesters extension.

   <extension
         point="org.eclipse.core.expressions.propertyTesters">
      <propertyTester
            class="com.codeandme.custombuilder.propertytester.TestBuilderEnabled"
            id="com.codeandme.custombuilder.myBuilderTester"
            namespace="com.codeandme.custombuilder"
            properties="isEnabled"
            type="java.lang.Object">
      </propertyTester>
   </extension>

We leave the type to java.lang.Object as not all project types use a common base class (except Object of course). Implementing the property tester is straight forward:

package com.codeandme.custombuilder.propertytester;

import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Platform;

import com.codeandme.custombuilder.commands.AddBuilder;

public class TestBuilderEnabled extends PropertyTester {

 private static final String IS_ENABLED = "isEnabled";

 @Override
 public boolean test(final Object receiver, final String property, final Object[] args, final Object expectedValue) {

  if (IS_ENABLED.equals(property)) {
   final IProject project = (IProject) Platform.getAdapterManager().getAdapter(receiver, IProject.class);

   if (project != null)
    return AddBuilder.hasBuilder(project);
  }

  return false;
 }
}

Now add some visibleWhen expressions to your menu entries. View the final version of the plugin.xml online.

Monday, August 6, 2012

Setting up a dedicated git server


This tutorial explains how to set up a git server on linux. My distribution of choice is Gentoo, but the setup will be similar for other distributions.

Git allows to connect using several protocols:
  • git://
    Generally used to allow for anonymous access to a repository. As it does not support user authentication it is generally used for read access only.
  • ssh://
    The default protocol to use for git access. SSH logon will be done with the same username for all users. Git users will be diversified by the key they are using for authentication. So no password authentication shall be used here.
  • http://
    Access over a web frontend. Again for anonymous read access.
There are even more protocols available, but in this tutorial we will focus on these connection types.

As some of you might not want to install this on their own, I provide a ready to use VM image at the end of this post.

Step 1: Setup Gitolite

Gitolite is currently the git server of choice for the gentoo community. Set it up with
emerge gitolite

[ebuild  N     ] dev-vcs/gitolite-2.3.1  USE="-contrib -vim-syntax"
Portage will automatically create a user 'git' and set its homedir to /var/lib/gitolite, which is where we will host our git repositories.

Step 2: Configure Gitolite

As we need to login with our git user during setup provide some password for the user:
passwd git
For administration of repositories, git users and access rights we need an administration user. This can be any user on any system. Further on I will call this user GitAdmin.

So login with GitAdmin and create a public/private key pair if you don't have one yet.
ssh-keygen
Copy the public key to the git account
scp ~/.ssh/id_rsa.pub git@localhost:admin.pub
Login with your git account and initialize the git repositories:
su git
cd ~
gl-setup admin.pub
The setup will fire up an editor with the default settings. Change the repositories mask to
$REPO_UMASK = 0027;
This will allow group access to the repositories. It is important to set this during gl-setup as otherwise some generated folders would have too strict access conditions.

Now we can delete admin.pub and leave the git account.
rm ~/admin.pub
exit
Step 3: Managing users & repositories

Git keeps its own repository for administration. Switch back to your GitAdmin account and clone the gitolite-admin repository:
git clone git@localhost:gitolite-admin.git
Now you can change your master configuration file ~/gitolite-admin/conf/gitolite.conf
repo    gitolite-admin
        RW+     =   admin

repo    testing
        RW+     =   @all
You can add/remove repositories and users by changing this file. Gitolite tracks changes on that file and triggers all the required actions from that. See the documentation for details on the syntax.

For each username used in the gitolite.conf file there should exist an adequate public key file under ~/gitolite-admin/keydir. Eg for a user 'testuser' there should exist a file testuser.pub. Again you can find more info in the documentation.

After changing the configuration file we need to commit and push those changes.
cd ~/gitolite-admin
git add keydir conf
git commit -m 'adding some new users/repos'
git push origin master
The push triggers creation of new repositories or changing access rights.

ssh setup is complete and you can connect to a repository by using ssh://git@localhost/repositoryName.git.

The private key used for authentication will be used by git to grant correct repository access rights.

Optional: Setup git:// access

For git:// access we need to run the git daemon. First change some settings in /etc/conf.d/git-daemon
GITDAEMON_OPTS="--syslog --export-all --base-path=/var/lib/gitolite/repositories"

GIT_USER="gitdaemon"
GIT_GROUP="git"

Add the gitdaemon user.
useradd -g git -G git -s /sbin/nologin -d /dev/null gitdaemon
Start the service now and at boot time:
rc-update add git-daemon default 
/etc/init.d/git-daemon start

Hint: Please read the git-daemon documentation (man git-daemon) as you might not want to export all repositories found under --base-path. Eg. you normally would not export gitolite-admin.git this way.

Hint: If you run on a trusted network you might add --enable=receive-pack to GITDAEMON_OPTS which would allow for anonymous write access over git://.

Optional: Setup CGit web interface (http:// access)

CGit offers access to repositories over http. You need a webserver to run this cgi script. For this tutorial we will use a default apache installation.

At the time of writing cgit is masked by the ~x86 keyword, so you need to unmask it before emerging.
emerge cgit apache

[ebuild  N     ] www-servers/apache-2.2.22-r1  USE="ssl -debug -doc -ldap (-selinux) -static -suexec -threads" APACHE2_MODULES="actions alias auth_basic authn_alias authn_anon authn_dbm authn_default authn_file authz_dbm authz_default authz_groupfile authz_host authz_owner authz_user autoindex cache cgi cgid dav dav_fs dav_lock deflate dir disk_cache env expires ext_filter file_cache filter headers include info log_config logio mem_cache mime mime_magic negotiation rewrite setenvif speling status unique_id userdir usertrack vhost_alias -asis -auth_digest -authn_dbd -cern_meta -charset_lite -dbd -dumpio -ident -imagemap -log_forensic -proxy -proxy_ajp -proxy_balancer -proxy_connect -proxy_ftp -proxy_http -proxy_scgi -reqtimeout -substitute -version" APACHE2_MPMS="-event -itk -peruser -prefork -worker" 0 kB
[ebuild  N     ] app-admin/webapp-config-1.50.16-r4  102 kB
[ebuild  N     ] virtual/httpd-cgi-0  0 kB
[ebuild  N    ~] www-apps/cgit-0.9.0.2-r1  USE="vhosts -doc -highlight" 2,704 kB
Install it using webapp-config.
webapp-config -I -h localhost -d git cgit 0.9.0.2-r1
Edit the cgit configuration file /etc/cgitrc
# Enable caching of up to 1000 output entries
cache-size=1000 

# Specify the css url 
css=/git/cgit.css

# Use a custom logo
logo=/git/cgit.png

## List of repositories.
include=/etc/cgit-repos
As mentioned by webapp-config we will create our own file to manage available repositories: Execute following command on demand or run it using cron.
/usr/share/webapps/cgit/0.9.0.2-r1/hostroot/cgi-bin/cgit.cgi --scan-tree=/var/lib/gitolite/repositories >/etc/cgit-repos
Now add the apache user to the git group, start apache and add it to your default runlevel.
usermod -a -G git apache
/etc/init.d/apache2 start
rc-update add apache2 default
Point your favorite browser to http://<your-server>/cgi-bin/cgit.cgi and watch cgit in action.

Hint: You might want to hide the cgi-bin path within your urls. Therefore you can change /etc/apache2/vhosts.d/default_vhost.include and append some aliases at the end of the alias_module section
<IfModule alias_module>
        # Redirect: Allows you to tell clients about documents that used to
        # ... snip ...

        ScriptAlias /cgi-bin/ "/var/www/localhost/cgi-bin/"

        Alias /git/cgit.css "/var/www/localhost/htdocs/git/cgit.css"
        Alias /git/cgit.png "/var/www/localhost/htdocs/git/cgit.png"
        ScriptAlias /git/ "/var/www/localhost/cgi-bin/cgit.cgi/"
</IfModule>
After restarting apache you can use http://<your-server>/git/ as a starting point.

Further reading:

  1. Install gitolite on Debian and Gentoo 
  2. How gitolite uses ssh
  3. Configuring repositories
  4. Configuring users
  5. What your users need to know
VM image:

For your convenience you can download an OVA image, created with VirtualBox. I guess it will run with other virtualizers too.

Root password is "gentoo", I used the root user as GitAdmin.

In case your network is missing refer to the gentoo wiki on vmware and delete your udev persistent net rules file.

If you want to use portage you need to emerge --sync first as I deleted the tree for a smaller image size.

Thursday, August 2, 2012

Mirroring a p2 repository

For builds or for resolving a target platform eclipse often needs to connect to remote update sites. If you are behind a proxy or on a slow connection this can be annoying. A solution to that could be a local mirror of an update site.

Eclipse provides two applications to do exactly that (executed on a shell):
<eclipse install dir>/eclipse -nosplash -verbose -consoleLog -application org.eclipse.equinox.p2.artifact.repository.mirrorApplication -source <update site> -destination<local folder>
<eclipse install dir>/eclipse -nosplash -verbose -consoleLog -application org.eclipse.equinox.p2.metadata.repository.mirrorApplication -source <update site> -destination<local folder>
The first one mirrors artifacts like, plugins, features, additional libraries and so on. The second one mirrors metadata like bundle dependencies or repository content overview.

You can add proxy settings by providing http.proxyHost / http.proxyPort properties to the command. To mirror the Juno repository to C:\p2\Juno you would use:
<eclipse install dir>/eclipse -Dhttp.proxyHost=proxy.nowhere.com -Dhttp.proxyPort=80 -nosplash -verbose -consoleLog -application org.eclipse.equinox.p2.artifact.repository.mirrorApplication -source http://download.eclipse.org/releases/juno -destination file:/C:/p2/Juno/
<eclipse install dir>/eclipse -Dhttp.proxyHost=proxy.nowhere.com -Dhttp.proxyPort=80 -nosplash -verbose -consoleLog -application org.eclipse.equinox.p2.metadata.repository.mirrorApplication -source http://download.eclipse.org/releases/juno -destination file:/C:/p2/Juno/

For details see the online documentation or the wiki entry.

Tuesday, July 24, 2012

Reusing Platform images

The eclipse platform comes with a huge amount of ready to use images. Often when you need a nice icon for a toolbar or menu there is already one available within some other plug-in. Therefore plug-in programmers often copy over these icons to their own plug-in to reuse them. When you can be sure that the base plug-in will be available on your target installation you can use platform scheme URIs (see related post by Marcelo Paternostro) to reference such resources.

Still the hard part is to locate those images in other plug-ins. Therefore I wrote a plug-in, that allows you to search for such images.

Update:

This plugin is now part of Eclipse PDE and is maintained by the PDE team.

A screenshot is better than a 1000 words, so see for yourself:


Just select a source to browse, locate your desired image and click on it to update the Image Information.

Install it from the reopsitory: http://codeandme.googlecode.com/svn/trunk/at.pontesegger.updatesite/p2/

The view can be activated with Window -> Show View -> Other... and is located under Plug-in Development.

Be aware that some images you may find might be released under a restrictive license that forbids reuse.

Update 2012-07-29

* Fixed issue with memory errors when parsing too much images
* partially fixed support for e4 -> still you cannot browse the target platform there
* raised Bug 386197 to add this tool to PDE

Monday, July 2, 2012

A convenient toggle handler

Toggle buttons always seemed a bit awkward to me as there seems to be no uniform interface to store the toggle state. In the past I used Ralf Eberts ToggleHandler. But reading/setting and persisting the toggle state programmatically was always painful.

Now I rediscovered a post by Prakash G.R. and built my own ToggleHandler (view online) on top of this.

Using the handler

As stated in the referenced post the command contribution needs a state definition to store the current toggle state to:
<command      ...>       
   <state       
         class="org.eclipse.ui.handlers.RegistryToggleState:true"       
         id="org.eclipse.ui.commands.toggleState">       
   </state>       
</command> 

Then your handler just needs to extend AbstractToggleHandler. The toggle state will automatically be preserved when you close your application.

You can programmatically set the state of any such toggle command by executing
ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
Command command = commandService.getCommand(commandId);
AbstractToggleHandler.setCommandState(command, true);

This will also toggle a visible button using this command.

Monday, April 16, 2012

Expression Examples

The previous post about the Expression Framework might be a bit confusing. Therefore I will provide some expression examples for eclipse built in source providers and tester and for the custom property tester provided in the previous post.

Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online. 

Preparations

Create a new Plug-in Project called com.codeandme.coreexpressions.samples. Add dependencies to org.eclipse.ui, org.eclipse.core.runtime and com.codeandme.coreexpressions. Set the content of plugin.xml to
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension
         point="org.eclipse.ui.commands">
      <command
            defaultHandler="com.codeandme.coreexpressions.samples.Login"
            id="com.codeandme.coreexpressions.commands.login"
            name="login">
      </command>
      <command
            defaultHandler="com.codeandme.coreexpressions.samples.Logout"
            id="com.codeandme.coreexpressions.commands.logout"
            name="logout">
      </command>
   </extension>
</plugin>
Add a new class com.codeandme.coreexpressions.samples.Login
package com.codeandme.coreexpressions.samples;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.ui.ISourceProvider;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.services.ISourceProviderService;

import com.codeandme.coreexpressions.ExampleSourceProvider;

public class Login extends AbstractHandler implements IHandler {

 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {

  ISourceProviderService service = (ISourceProviderService) PlatformUI.getWorkbench().getService(
    ISourceProviderService.class);
  ISourceProvider provider = service.getSourceProvider(ExampleSourceProvider.CURRENT_USER);
  if (provider instanceof ExampleSourceProvider)
   ((ExampleSourceProvider) provider).setCurrentUser("John Doe");

  return null;
 }
}
and another class com.codeandme.coreexpressions.samples.Logout
package com.codeandme.coreexpressions.samples;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.ui.ISourceProvider;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.services.ISourceProviderService;

import com.codeandme.coreexpressions.ExampleSourceProvider;

public class Logout extends AbstractHandler implements IHandler {

 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
  ISourceProviderService service = (ISourceProviderService) PlatformUI.getWorkbench().getService(
    ISourceProviderService.class);
  ISourceProvider provider = service.getSourceProvider(ExampleSourceProvider.CURRENT_USER);
  if (provider instanceof ExampleSourceProvider)
   ((ExampleSourceProvider) provider).setCurrentUser(null);

  return null;
 }
}
We will use these commands in a later step of our tutorial.

The first commands we use will simply bind to the commandId=org.eclipse.ui.file.exit.

Test 1: Enable for a specific view

Our first expression will reveal a toolbar item in the Project Explorer view when the view is active.
      <menuContribution
            allPopups="false"
            locationURI="toolbar:org.eclipse.ui.navigator.ProjectExplorer">
            <command
                  commandId="org.eclipse.ui.file.exit"
                  label="Test1"
                  style="push">
               <visibleWhen
                     checkEnabled="false">
                  <with
                        variable="activePartId">
                     <equals
                           value="org.eclipse.ui.navigator.ProjectExplorer">
                     </equals>
                  </with>
               </visibleWhen>
            </command>
      </menuContribution>
We need to set checkEnabled on the visibleWhen element to false, otherwise the expression will not be active. The with section uses activePartId as source. It is a string containing the ID of the active view/editor (see description).

The equals section compares the source value with org.eclipse.ui.navigator.ProjectExplorer, returning true when the Project Explorer View is active.

Run your Plug-in as a new Eclipse application and activate the Project Explorer to see the toolbar entry appear/disappear.

Test 2: Enable when Projects are selected


Next we want a button to be visible when at least one project is selected.
            <command
                  commandId="org.eclipse.ui.file.exit"
                  label="Test2"
                  style="push">
               <visibleWhen
                     checkEnabled="false">
                  <with
                        variable="selection">
                     <iterate
                           operator="or">
                        <adapt
                              type="org.eclipse.core.resources.IProject">
                        </adapt>
                     </iterate>
                  </with>
               </visibleWhen>
            </command>
Now we use the selection source provider, which provides the current selection. The iterate operator is nice as it tests all elements of a collection. By setting operator to or we define that at least one element of the collection has to pass the test.

There exists an instanceof operator which we could use to check against org.eclipse.core.resources.IProject. Unfortunately not all projects implement that interface. Instead they use the adapter framework. Therefore we use the adapt operator to see if the element can be adapted to an IProject. Of course this works for all classes implementing the interface directly too.


Test 3: Enable when exactly 2 txt Files are selected


Now for something more complex. A button shall be visible when exactly two resources are selected and both have an extension of .txt.
            <command
                  commandId="org.eclipse.ui.file.exit"
                  label="Test3"
                  style="push">
               <visibleWhen
                     checkEnabled="false">
                  <with
                        variable="selection">
                     <and>
                        <iterate
                              operator="and">
                           <test
                                 property="org.eclipse.core.resources.extension "
                                 value="txt">
                           </test>
                        </iterate>
                        <count
                              value="2">
                        </count>
                     </and>
                  </with>
               </visibleWhen>
            </command>
The property tester for file extensions is described in the documentation. The count operator counts the elements within a collection.


Test 4: Login/Logout

Let's add two more buttons for a very basic user login.
   <extension
         point="org.eclipse.ui.menus">
      <menuContribution
            allPopups="false"
            locationURI="menu:file?after=additions">
         <command
               commandId="com.codeandme.coreexpressions.commands.login"
               label="Login"
               style="push">
            <visibleWhen
                  checkEnabled="false">
               <with
                     variable="com.codeandme.coreexpressions.currentStatus">
                  <or>
                     <equals
                           value="startup">
                     </equals>
                     <equals
                           value="logged off">
                     </equals>
                  </or>
               </with>
            </visibleWhen>
         </command>
         <command
               commandId="com.codeandme.coreexpressions.commands.logout"
               label="Logoff"
               style="push">
            <visibleWhen
                  checkEnabled="false">
               <with
                     variable="com.codeandme.coreexpressions.currentUser">
                  <equals
                        value="John Doe">
                  </equals>
               </with>
            </visibleWhen>
         </command>
      </menuContribution>
We use dedicated commands that will set/reset the current user of our source provider from the previous post. The different source providers for both buttons do not necessarily make sense - we could achieve the same with just one source. Its just to give you an idea how it works.


We use our custom property tester to verify the current logon state and the current user.

Source Provider, Property Tester and the Expressions Framework

The expressions framework provides powerful means to declare expressions via XML and query them at runtime. Such expressions can be used without loading the defining Plug-in. You can find them in command/menu enablements. There you find visibleWhen, enabledWhen, activeWhen expressions. But you also can use them for your own needs.

In this example we will create our own Source Provider with a custom property tester (don't worry, I will explain this right ahead).

There is good documentation available for further reading.

Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online. 

Introduction

The expression framework can create/evaluate boolean expressions - something that in the end evaluates to true or false. To evaluate we need an object to work with (a source) and operators which return a boolean value.

Eclipse already defines commonly used sources and operators.

A simple example of an expression looks like this:
<visibleWhen>
     <and>
        <systemTest
              property="os.name"
              value="Linux">
        </systemTest>
        <systemTest
              property="os.arch"
              value="i386">
        </systemTest>
     </and>
<visibleWhen>

and is a basic operator that - of course - performs a boolean and operation. systemTest queries a java system property and compares it to a given value. So this expression evaluates to true only if we are working on an i386 linux machine.

Our source is not explicitely defined in the expression as the operator queries a static source System.getProperties().

Step 1: Creating a SourceProvider

For most expressions we will need sources that contain modifiable content. Use the predefined sources to get the active editor, the active selection or similar workbench related items. In this tutorial we will create a custom source to denote the current user.

Create a new Plug-in Project called com.codeandme.coreexpressions. In the plugin.xml create a new extension for org.eclipse.ui.services and add a new sourceProvider to it. Create two new variables for the sourceProvider:
set name to com.codeandme.coreexpressions.currentStatus and com.codeandme.coreexpressions.currentUser and leave priorityLevel set to workbench.

Now implement the sourceProvider by creating a class com.codeandme.coreexpressions.ExampleSourceProvider:
package com.codeandme.coreexpressions;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.ui.AbstractSourceProvider;
import org.eclipse.ui.ISources;

public class ExampleSourceProvider extends AbstractSourceProvider {

 public static final String CURRENT_STATUS = "com.codeandme.coreexpressions.currentStatus";
 public static final String CURRENT_USER = "com.codeandme.coreexpressions.currentUser";

 private Object fUser = null;
 private String fStatus = "startup";

 public ExampleSourceProvider() {
 }

 @Override
 public void dispose() {
 }

 @Override
 public Map getCurrentState() {
  HashMap<String, Object> map = new HashMap<String, Object>();
  map.put(CURRENT_USER, fUser);
  map.put(CURRENT_STATUS, fStatus);

  return map;
 }

 @Override
 public String[] getProvidedSourceNames() {
  return new String[] { CURRENT_USER, CURRENT_STATUS };
 }
}
We need to implement two methods:
  • getProvidedSourceNames()
    returns an array of source identifiers (variables). These are the same we already defined as variables in the plugin.xml.
  • getCurrentState()
    returns a Map<String, Object> with entries for each defined variable.

Step 2: Creating a property tester

Eclipse provides a generic expression operator test which allows to register custom tests.

Create a new extension for org.eclipse.core.expressions.propertyTesters with a unique id.

The type reflects to the kind of objects you'd get from the source provider. For now leave it to java.lang.Object.

The identifier of a specific property to check should be a fully qualified name. It consists of a namespace part and a properties name. It is good practice to set the namespace to your Plug-in identifier. Therefore set namespace to com.codeandme.coreexpressions and add two specific properties name,validated to properties. Hence our properties are named:
  • com.codeandme.coreexpressions.name
  • com.codeandme.coreexpressions.validated
Finally implement the class com.codeandme.coreexpressions.ExamplePropertyTester:
package com.codeandme.coreexpressions;

import org.eclipse.core.expressions.PropertyTester;

public class ExamplePropertyTester extends PropertyTester {

 private static final String NAME = "name";
 private static final String VALIDATED = "validated";

 public ExamplePropertyTester() {
 }

 @Override
 public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
  if (NAME.equals(property))
   return receiver.toString().equals(expectedValue);

  if (VALIDATED.equals(property)) {
   // do some background checks to see if user is validated
   return true;
  }

  return false;
 }
}
The receiver of the test() implementation is some object from a source provider. If you set your property tester to only accept objects of a certain type you need to add an instanceof check in the test() method.

Step 3: Your own expression

To use our source provider and property tester we can either create an expression for some activeWhen, enabledWhen or visibleWhen statement or we can extend org.eclipse.core.expressions.definitions to store the expression for later usage.

Create a new extension for org.eclipse.core.expressions.definitions with a unique id. Add a with section to define which source to use. Set variable to the name of our currentUser source: com.codeandme.coreexpressions.currentUser.

Add a test section to define our custom test. Set property to com.codeandme.coreexpressions.name and value to a string to compare against. In the sample I use "John Doe".

Make sure you activate forcePluginActivation. This defines that the Plug-in defining the property tester should be activated. If it is not activated, the property test cannot be performed.

The final definition:
         <with
               variable="com.codeandme.coreexpressions.currentUser">
            <test
                  forcePluginActivation="true"
                  property="com.codeandme.coreexpressions.name"
                  value="John Doe">
            </test>
         </with>
Step 4: Updating your source

Expressions do work right now, but our source is some kind of static. It won't change its status. Open ExampleSourceProvider and add following code:
 public void setCurrentUser(Object user) {
  fUser = user;
  fStatus = (user == null) ? "logged off" : "logged on";

  fireSourceChanged(ISources.WORKBENCH, CURRENT_USER, fUser);
  fireSourceChanged(ISources.WORKBENCH, CURRENT_STATUS, fStatus);
 }
fireSourceChanged() will tell Eclipse that a source changed and therefore forces expressions using this source to be re-evaluated.

To get an instance of your source provider you can query the ISourceProviderService:
ISourceProviderService service =(ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class);
ISourceProvider provider = service.getSourceProvider(ExampleSourceProvider.CURRENT_USER);