/**
   * Returns a valid instance selection for the current selection of the tree viewer. Returns <code>
   * null</code> if there is none.
   *
   * @return a valid instance selection for the current selection of the tree viewer or <code>null
   *     </code>
   */
  private InstanceSelection getValidSelection() {
    ISelection viewerSelection = treeViewer.getSelection();
    if (!(viewerSelection instanceof ITreeSelection) || viewerSelection.isEmpty()) return null;

    ITreeSelection treeSelection = (ITreeSelection) treeViewer.getSelection();
    TreePath firstPath = treeSelection.getPaths()[0]; // XXX use all paths
    // instead of first
    // only?

    InstanceValidationMessage firstMessage;
    Iterator<InstanceValidationMessage> restIter;

    if (firstPath.getLastSegment() instanceof InstanceValidationMessage) {
      firstMessage = (InstanceValidationMessage) firstPath.getLastSegment();
      restIter = Iterators.emptyIterator();
    } else {
      Collection<InstanceValidationMessage> messages =
          contentProvider.getMessages(treeSelection.getPaths()[0]);
      if (messages.isEmpty()) return null; // shouldn't happen, but doesn't really matter
      restIter = messages.iterator();
      firstMessage = restIter.next();
    }

    InstanceService is = PlatformUI.getWorkbench().getService(InstanceService.class);
    // check first message for valid instance reference
    if (firstMessage.getInstanceReference() == null
        || is.getInstance(firstMessage.getInstanceReference()) == null) return null;

    Set<InstanceReference> references = new HashSet<InstanceReference>();
    references.add(firstMessage.getInstanceReference());
    while (restIter.hasNext()) references.add(restIter.next().getInstanceReference());

    return new DefaultInstanceSelection(references.toArray());
  }