Enable/disable handlers

There are two options to enable or disable handler in Eclipse RCP:

  • Declarative by using enabledWhen. This also requires a PropertyTester specified by the org.eclipse.core.expressions.propertyTesters extension point.
  // plugin.xml
  ...
   <extension
         point="org.eclipse.core.expressions.propertyTesters">
      <propertyTester
            class="org.pubcurator.core.testers.DatabaseTester"
            id="org.pubcurator.core.databaseTester"
            namespace="org.pubcurator.core.database"
            properties="connected, remoteServerUp"
            type="java.lang.Object">
      </propertyTester>
   </extension>
 
   <extension
         point="org.eclipse.ui.handlers">
      <handler
            class="org.pubcurator.documentor.handlers.ImportDocumentsHandler"
            commandId="org.pubcurator.documentor.commands.importDocuments">
         <enabledWhen>
            <test
                  forcePluginActivation="true"
                  property="org.pubcurator.core.database.connected"
                  value="true">
            </test>
         </enabledWhen>
      </handler>
   </extension>
...
  • Programmatically by implementing a listener inside the handler.
package org.pubcurator.documentor.handlers;
 
import java.awt.Desktop.Action;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
 
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.HandlerEvent;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.pubcurator.core.managers.DbManager;
import org.pubcurator.core.ui.ExtWizardDialog;
import org.pubcurator.documentor.Activator;
import org.pubcurator.documentor.importers.wizards.DocumentImportWizard;
 
public class ImportDocumentsHandler extends AbstractHandler implements PropertyChangeListener {
 
	private DbManager dbManager = DbManager.getInstance();
 
	public ImportDocumentsHandler() {
		dbManager.addPropertyChangeListener(this);
		System.out.println("here: "+dbManager.isConnected());
		setBaseEnabled(dbManager.isConnected());
	}
 
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		DocumentImportWizard documentImportWizard = new DocumentImportWizard();
		ExtWizardDialog wizardDialog = new ExtWizardDialog(HandlerUtil.getActiveShell(event), documentImportWizard);
		wizardDialog.open();
		return null;
	}
 
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("connected")) {
			setBaseEnabled((Boolean) evt.getNewValue());
		}
	}
}