/**
   * Checks modelObject.getModelRoot() referred definitions, do match of modelObject's Definition
   *
   * @param modelObject which is supposed to be from referred definition.
   * @return referred Description, or null
   */
  public static IDescription getReferredDescription(IModelObject modelObject) {
    if (modelObject instanceof IFault) {
      final Collection<IParameter> parameters = ((IFault) modelObject).getParameters();
      modelObject = parameters.isEmpty() ? null : parameters.iterator().next();
    }
    if (modelObject == null || !(modelObject.getModelRoot() instanceof IWsdlModelRoot)) {
      return null;
    }

    final IWsdlModelRoot wsdlModelRoot = (IWsdlModelRoot) modelObject.getModelRoot();
    final IDescription description = wsdlModelRoot.getDescription();

    // get referred Definition
    EObject referredDefinition = modelObject.getComponent();
    while (referredDefinition != null && !(referredDefinition instanceof Definition)) {
      referredDefinition = referredDefinition.eContainer();
    }

    if (referredDefinition != null) {
      for (final IDescription referredDescription : description.getReferencedServices()) {
        if (referredDefinition.equals(referredDescription.getComponent())) {
          return referredDescription;
        }
      }
    }
    return null;
  }
  /** Update the Attribute Conversion Panel button enabled states. */
  private void updateAttributeConversionPanelButtons(Binding binding) {
    // ------------------------------------------
    // Set the Apply Button Enabled State
    // ------------------------------------------
    boolean enableApply = false;
    if (binding != null && !this.targetLocked) {
      // Set the Apply button enabled state. Enable if the datatypes are different.
      EObject chooserDatatype = getChooserDatatype();
      EObject bindingDatatype = binding.getCurrentAttrDatatype();
      if (chooserDatatype != null && bindingDatatype != null) {
        if (!chooserDatatype.equals(bindingDatatype)) {
          enableApply = true;
        }
      }
    }
    // Set Apply Button enabled state
    convertSelectedAttrButton.setEnabled(enableApply);

    // ------------------------------------------
    // Set the ConvertAll Button Enabled State
    // ------------------------------------------
    // Enable ConvertAll Button if any Binding has Conflict and target group not locked
    boolean enableConvertAll = false;

    // Enable ConvertAll Button if any Binding has Conflict
    boolean hasTypeConflict = bindingList.hasTypeConflict();
    if (hasTypeConflict && !this.targetLocked) {
      enableConvertAll = true;
    }
    convertAllAttrsButton.setEnabled(enableConvertAll);
  }
  public Collection<StructuredType> getAllBindableElements(ServiceDTO dto) {
    // Collect all entities and dtos
    Collection<StructuredType> bindableElements = new ArrayList<StructuredType>();

    // First, get all semantic resources in session
    Collection<Resource> semanticResources = EcoreService.getAllSemanticResourcesInSession(dto);

    for (Resource resource : semanticResources) {
      TreeIterator<EObject> iterator = EcoreUtil.getAllContents(resource, true);
      while (iterator.hasNext()) {
        EObject eObject = (EObject) iterator.next();
        if (eObject instanceof ServiceDTO || eObject instanceof Entity) {
          if (!eObject.equals(dto)) {
            bindableElements.add((StructuredType) eObject);
          }
        } else if (!(eObject instanceof Root
            || eObject instanceof Block
            || eObject instanceof org.obeonetwork.dsl.overview.Root
            || eObject instanceof System
            || eObject instanceof DTORegistry
            || eObject instanceof Category)) {
          iterator.prune();
        }
      }
    }

    return bindableElements;
  }
 public boolean isEnum(EObject obj) {
   boolean result = false;
   EcorePackage ePack = EcorePackage.eINSTANCE;
   if (obj.equals(ePack.getEEnum())) {
     result = true;
   }
   return result;
 }
  /**
   * @see
   *     org.topcased.modeler.edit.policies.AbstractEdgeCreationEditPolicy#checkTargetForSource(org.topcased.modeler.di.model.GraphElement,
   *     org.topcased.modeler.di.model.GraphElement)
   * @generated
   */
  protected boolean checkTargetForSource(GraphElement source, GraphElement target) {
    EObject sourceObject = Utils.getElement(source);
    EObject targetObject = Utils.getElement(target);

    if (sourceObject instanceof com.bluexml.side.portal.Portlet
        && targetObject instanceof com.bluexml.side.portal.PortletInternal) {
      if (!sourceObject.equals(targetObject)) {
        return true;
      }
    }
    return false;
  }
  /**
   *
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   *
   * @see
   *     org.topcased.modeler.edit.policies.AbstractEdgeCreationEditPolicy#checkTargetForSource(org.topcased.modeler.di.model.GraphElement,
   *     org.topcased.modeler.di.model.GraphElement)
   * @generated
   */
  protected boolean checkTargetForSource(GraphElement source, GraphElement target) {
    EObject sourceObject = Utils.getElement(source);
    EObject targetObject = Utils.getElement(target);

    if (sourceObject instanceof org.eclipse.uml2.uml.Classifier
        && targetObject instanceof org.eclipse.uml2.uml.Component) {
      if (!sourceObject.equals(targetObject)) {
        return true;
      }
    }
    return false;
  }
  public static boolean isManagedByEMFStore(EObject object) {
    Workspace currentWorkspace = WorkspaceManager.getInstance().getCurrentWorkspace();
    for (Resource resource : currentWorkspace.getResourceSet().getResources()) {
      TreeIterator<EObject> allContents = resource.getAllContents();
      while (allContents.hasNext()) {
        EObject currentObject = allContents.next();
        if (object.equals(currentObject)) {
          return true;
        }
      }
    }

    return false;
  }
 /**
  * the goal of this method is to return the node that references the stereotype application
  *
  * @param stereotypeApplication the application of the sterotype
  * @param node the notation node where we look for all subnodes
  * @return the corresponded node or null
  */
 protected View getCoresspondedStereotypeApplication(
     final EObject stereotypeApplication, final View node) {
   View correspondedAppliedStereotype = null;
   int i = 0;
   // wee look for through all sub nodes
   while (correspondedAppliedStereotype == null && i < node.getChildren().size()) {
     if ((node.getChildren().get(i)) instanceof Node) {
       if (stereotypeApplication.equals(((Node) (node.getChildren().get(i))).getElement())) {
         correspondedAppliedStereotype = ((Node) (node.getChildren().get(i)));
       }
     }
     i++;
   }
   return correspondedAppliedStereotype;
 }
  /** Check whether 'modelObject' is part of 'modelRoot' resource. */
  public static boolean isModelObjectPartOfModelRoot(
      final IModelRoot modelRoot, final IModelObject modelObject) {
    if (modelObject == null) {
      return false;
    }

    final EObject childComponent = modelObject.getComponent();
    final EObject rootComponent = modelRoot.getModelObject().getComponent();

    EObject currentComponent = childComponent;
    while (currentComponent != null && !rootComponent.equals(currentComponent)) {
      currentComponent = currentComponent.eContainer();
    }

    return currentComponent != null;
  }
    @Override
    protected void setElementValue(Object element, Object newValue) {
      if (element instanceof Binding && newValue instanceof Boolean) {
        Binding binding = (Binding) element;

        Object attr = binding.getAttribute();

        if (TransformationHelper.isSqlColumn(attr)) {
          Shell shell = UiPlugin.getDefault().getCurrentWorkbenchWindow().getShell();
          DatatypeSelectionDialog dialog =
              new DatatypeSelectionDialog(shell, (EObject) attr, "string"); // $NON-NLS-1$
          Object originalValue = bindingListInput.getTargetDatatype(binding);

          Object[] selection = new Object[] {originalValue};

          selection[0] = originalValue;
          dialog.setInitialSelections(selection);

          int status = dialog.open();
          EObject newDatatype = (EObject) originalValue;
          if (status == Window.OK) {
            Object[] result = dialog.getResult();
            if (result.length == 0) {
              // null out the value
              newDatatype = null;
            } else {
              // return the selected value
              newDatatype = (EObject) result[0];
            }
          }
          // If different datatype was chosen, set it on the binding
          if (newDatatype != null && !newDatatype.equals(originalValue)) {
            bindingListInput.setTargetDatatype(binding, newDatatype);
            updateAttributeConversionPanelButtons(binding);
          }
        }

        // chooserPanel.layout();
        bindingTableViewer.refresh(true);
        updateRowColors();
        updateMessageArea();
      }
    }
 /**
  * Get all the hidden existing diagram elements related to a semantic element.
  *
  * @param semanticElement Semantic element
  * @param containerView Container view
  * @return List of all existing diagram elements for the given semantic element which are
  *     currently hidden in the diagram
  */
 private List<DDiagramElement> getHiddenExistingDiagramElements(
     EObject semanticElement, DSemanticDecorator containerView) {
   final List<DDiagramElement> existingDiagramElements = Lists.newArrayList();
   if (containerView instanceof DSemanticDiagram) {
     for (final DDiagramElement element :
         ((DSemanticDiagram) containerView).getDiagramElements()) {
       if (semanticElement.equals(element.getTarget())) {
         final DDiagramElementQuery query = new DDiagramElementQuery(element);
         if (query.isHidden()) {
           existingDiagramElements.add(element);
         }
         // Get the hidden parent container of the element to reveal,
         // in order to reveal all the
         // hierarchy
         existingDiagramElements.addAll(getHiddenParentContainerViews(element));
       }
     }
   }
   return existingDiagramElements;
 }
 protected boolean _createEqualityHelperHelper_(final EObject left, final EObject right) {
   boolean _xblockexpression = false;
   {
     boolean _and = false;
     if (!(left instanceof Module)) {
       _and = false;
     } else {
       _and = (right instanceof Module);
     }
     if (_and) {
       EObject _eContainer = left.eContainer();
       EList<Module> _modules = ((ModularizationModel) _eContainer).getModules();
       final int leftIndex = _modules.indexOf(left);
       EObject _eContainer_1 = right.eContainer();
       EList<Module> _modules_1 = ((ModularizationModel) _eContainer_1).getModules();
       final int rightIndex = _modules_1.indexOf(right);
       return Integer.valueOf(leftIndex).equals(Integer.valueOf(rightIndex));
     }
     _xblockexpression = left.equals(right);
   }
   return _xblockexpression;
 }
  private List<ModelUnit> getUnusedWiths(PropertySet propertySet) {
    List<ModelUnit> importedUnits = propertySet.getImportedUnits();
    List<ModelUnit> unusedWiths = new ArrayList<ModelUnit>();
    ImportedUnitsLoop:
    for (ModelUnit nextImportedUnit : importedUnits) {
      if (nextImportedUnit.equals(propertySet.eContainer())) {
        unusedWiths.add(nextImportedUnit);
        continue ImportedUnitsLoop;
      }
      if (AadlUtil.isPredeclaredPropertySet(nextImportedUnit.getName())) {
        unusedWiths.add(nextImportedUnit);
        continue ImportedUnitsLoop;
      }

      TreeIterator<EObject> packageContents = propertySet.eAllContents();
      while (packageContents.hasNext()) {
        EObject nextObject = packageContents.next();
        EList<EObject> crossReferences = nextObject.eCrossReferences();
        for (EObject crossReference : crossReferences) {
          EObject container = crossReference.eContainer();
          if (nextImportedUnit.equals(container)) {
            continue ImportedUnitsLoop;
          } else {
            while (container != null
                && !(container instanceof AadlPackage)
                && !(container instanceof PropertySet)) {
              container = container.eContainer();
              if (container.equals(nextImportedUnit)) {
                continue ImportedUnitsLoop;
              }
            }
          }
        }
      }
      unusedWiths.add(nextImportedUnit);
    }
    return unusedWiths;
  }
  /** handler for Datatype chooser dialog */
  void showDatatypeDialogPressed() {
    Binding binding = getSelectedBinding();
    if (binding != null) {
      Object attr = binding.getAttribute();
      if (TransformationHelper.isSqlColumn(attr)) {
        Shell shell = UiPlugin.getDefault().getCurrentWorkbenchWindow().getShell();
        DatatypeSelectionDialog dialog =
            new DatatypeSelectionDialog(shell, (EObject) attr, "string"); // $NON-NLS-1$
        Object originalValue = this.chooserDatatype;
        Object[] selection = new Object[] {originalValue};
        selection[0] = originalValue;
        dialog.setInitialSelections(selection);

        int status = dialog.open();
        EObject newDatatype = (EObject) originalValue;
        if (status == Window.OK) {
          Object[] result = dialog.getResult();
          if (result.length == 0) {
            // null out the value
            newDatatype = null;
          } else {
            // return the selected value
            newDatatype = (EObject) result[0];
          }
        }
        // If different datatype was chosen, set it on the binding
        if (!newDatatype.equals(originalValue)) {
          setChooserDatatype(newDatatype);
          updateAttributeConversionPanelButtons(binding);
        }
      }
      attrGroup.layout();
      // chooserPanel.layout();
      tableViewer.refresh(true);
      updateRowColors();
      updateMessageArea();
    }
  }
  /**
   * Checks modelObject.getModelRoot() referred schemas, do match modelObject's XSDSchema
   *
   * @param modelObject which is supposed to be from referred schema.
   * @return referred ISchema, or null
   */
  public static ISchema getReferredSchema(final IModelObject modelObject) {
    if (modelObject == null || !(modelObject.getModelRoot() instanceof IXSDModelRoot)) {
      return null;
    }

    final IXSDModelRoot xsdModelRoot = (IXSDModelRoot) modelObject.getModelRoot();
    final ISchema schema = xsdModelRoot.getSchema();

    // get referred XSDSchema
    EObject referredXSDSchema = modelObject.getComponent();
    while (referredXSDSchema != null && !(referredXSDSchema instanceof XSDSchema)) {
      referredXSDSchema = referredXSDSchema.eContainer();
    }

    if (referredXSDSchema != null) {
      for (final ISchema referredSchema : schema.getAllReferredSchemas()) {
        if (referredXSDSchema.equals(referredSchema.getComponent())) {
          return referredSchema;
        }
      }
    }
    return null;
  }
  /**
   * Tests if Object passed as parameter is an EditPart, and if true, tests whether this EditPart is
   * a Shortcut
   *
   * @param object : Object to test
   * @return true if Shortcut, false if not EditPart and/or is not Shortcut
   */
  protected final boolean isShortcut(Object object) {
    if (object instanceof EditPart) {
      EditPart editPart = (EditPart) object;
      Diagram diagram = null;
      if (editPart.getModel() instanceof Diagram) {
        return false;
      } else {
        diagram = ((View) editPart.getModel()).getDiagram();
      }

      EObject diagramElement = diagram.getElement();

      View selectedView = (View) editPart.getModel();
      EObject selectedElement = selectedView.getElement();

      EObject eObject = selectedElement;
      while (eObject != null) {
        if (diagramElement.equals(eObject)) return false;
        eObject = eObject.eContainer();
      }
      return true;
    }
    return false;
  }
  /**
   * this method suppress the sub-nodes that references the stereotype application it cleans also
   * all sub-nodes with the type ApplicationStereotype that not references an application of
   * stereotypes (this is the case when a stereotype has been unapplied without suppress the
   * compartment.
   *
   * @param stereotypeApplication
   */
  public void removeAppliedStereotypeCompartment(final EObject stereotypeApplication) {
    if (stereotypeApplication == null) {
      return;
    }
    final GraphicalEditPart editPart = (GraphicalEditPart) getHost();
    final View node = editPart.getNotationView();
    try {
      int i = 0;
      // we go through all sub nodes
      while (i < node.getChildren().size()) {
        if ((node.getChildren().get(i)) instanceof Node) {
          final Node currentNode = (Node) (node.getChildren().get(i));
          // it references the stereotype application?
          if (stereotypeApplication.equals(currentNode.getElement())) {
            // yes, Execution of the Deletion command
            editPart
                .getEditingDomain()
                .runExclusive(
                    new Runnable() {

                      public void run() {
                        Display.getCurrent()
                            .asyncExec(
                                new Runnable() {

                                  public void run() {
                                    DeleteCommand command = new DeleteCommand(currentNode);
                                    editPart
                                        .getEditingDomain()
                                        .getCommandStack()
                                        .execute(new GMFtoEMFCommandWrapper(command));
                                  }
                                });
                      }
                    });
          }
          // the sub nodes has the type appliedStereotypeCompartment but does not references a
          // application of stereotype
          if ((currentNode.getType().equals(AppliedStereotypeConpartmentEditPart.ID))
              && (!(currentNode.getElement() instanceof DynamicEObjectImpl))) {
            // yes, Execution of the Deletion command
            editPart
                .getEditingDomain()
                .runExclusive(
                    new Runnable() {

                      public void run() {
                        Display.getCurrent()
                            .asyncExec(
                                new Runnable() {

                                  public void run() {
                                    DeleteCommand command = new DeleteCommand(currentNode);
                                    editPart
                                        .getEditingDomain()
                                        .getCommandStack()
                                        .execute(new GMFtoEMFCommandWrapper(command));
                                  }
                                });
                      }
                    });
          }
        }
        i++;
      }
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  /**
   * Sets the input for the table.
   *
   * @param sortFilterElements the semantic children for thie <code>IView</code>
   */
  public void setInput(List sortFilterElements) {

    // Remove elements that are not to be shown in the dialog at all.
    List updatedSortFilterElements = new ArrayList();
    for (Iterator iter = sortFilterElements.iterator(); iter.hasNext(); ) {
      SortFilterElement element = (SortFilterElement) iter.next();
      updatedSortFilterElements.add(element);
    }

    // Cache the provided elements for the Reset Default button
    baseElements = new ArrayList(updatedSortFilterElements.size());
    for (Iterator itr = updatedSortFilterElements.iterator(); itr.hasNext(); ) {
      baseElements.add(new SortFilterElement(((SortFilterElement) itr.next()).getData()));
    }

    // For the manual Ahoc sorting and filtering we manually initialize the
    // items
    if (_filtering == Filtering.MANUAL_LITERAL) {
      // Use the list of filtered items to initialize the table.
      // Any new items will not be filtered.
      if (!updatedSortFilterElements.isEmpty()) {
        if (_filteredObjects != null && _filteredObjects.size() > 0) {
          for (int i = 0; i < _filteredObjects.size(); i++) {
            EObject eObject = (EObject) _filteredObjects.get(i);
            for (int j = 0; j < updatedSortFilterElements.size(); j++) {
              SortFilterElement element = (SortFilterElement) updatedSortFilterElements.get(j);
              if (eObject.equals(element.getData())) {
                element.setVisible(false);
              }
            }
          }
        }
      }
    }

    if (_sorting == Sorting.MANUAL_LITERAL) { // Add hoc sorting
      if (!updatedSortFilterElements.isEmpty()) {
        if (_sortedObjects != null && _sortedObjects.size() > 0) {
          // Order the elements by the specified index
          elementCollection = new ArrayList(updatedSortFilterElements.size());
          for (int i = 0; i < _sortedObjects.size(); i++) {
            EObject element = (EObject) _sortedObjects.get(i);
            for (int j = 0; j < updatedSortFilterElements.size(); j++) {
              SortFilterElement e = (SortFilterElement) updatedSortFilterElements.get(j);
              if (element.equals(e.getData())) {
                elementCollection.add(e);
              }
            }
          }
          // Add any new children to the end of the list
          // so they will appear at the botton of the
          // list compartment
          List missingElements = new ArrayList(updatedSortFilterElements);
          missingElements.removeAll(elementCollection);
          elementCollection.addAll(missingElements);
        }
      }

    } else { // Use semantic order
      elementCollection = updatedSortFilterElements;
    }
    createBackUp();
  }
  @Override
  public void resolve(IFragSubHolder fragmentHolderCurrent) throws BasicBVREngineException {
    IAdjacentFragment aFrag = this.adjacentFinder.getAdjacentMap().get(fragmentHolderCurrent);
    if (aFrag == null) return;

    HashSet<IAdjacentFragment> adjacentFragments = aFrag.getAdjacentFragments();
    if (adjacentFragments.isEmpty())
      throw new GeneralBVREngineException(
          "can not find any adjacent fragments to the fragment that seems to be adjacent"
              + fragmentHolderCurrent);

    HashSet<IAdjacentFragment> twinAFrag = aFrag.getTwinFragments();
    for (IAdjacentFragment adjacentFragment : adjacentFragments) {
      IFragSubHolder fragHolderAdjacent = adjacentFragment.getFragmentHolder();
      HashMap<FromBinding, ToBinding> adjacentBindingsToCurrent =
          EngineUtility.reverseMap(aFrag.getAdjacentToBindings(adjacentFragment));
      adjacentBindingsToCurrent =
          (adjacentBindingsToCurrent != null)
              ? adjacentBindingsToCurrent
              : new HashMap<FromBinding, ToBinding>();
      for (Map.Entry<FromBinding, ToBinding> entry : adjacentBindingsToCurrent.entrySet()) {
        FromBinding fromBinding = entry.getKey();
        ToBinding toBinding = entry.getValue();

        EList<ObjectHandle> outsideBOHElmtsPlc =
            fromBinding.getFromPlacement().getOutsideBoundaryElement();
        EList<ObjectHandle> insideBOHElmtsPlcReplaced =
            calculateInsideBoundaryElements(twinAFrag, adjacentFragment, fromBinding, toBinding);

        HashMap<FromPlacement, HashSet<ObjectHandle>> insideBoundaryElementsFromPlacementMap =
            ((FragmentSubstitutionHolder) fragHolderAdjacent)
                .getFromPlacementInsideBoundaryElementMap();
        HashSet<ObjectHandle> insideBoundaryElementsFromPlacement =
            insideBoundaryElementsFromPlacementMap.get(fromBinding.getFromPlacement());
        if (insideBoundaryElementsFromPlacement == null)
          throw new GeneralBVREngineException(
              "failed to find insideBoundaryElements in the map for a given fromPlacement "
                  + fromBinding.getFromPlacement()
                  + " of the fromBinding "
                  + fromBinding);

        HashSet<ObjectHandle> validOutsideOHFromPlacementBElements = new HashSet<ObjectHandle>();

        for (ObjectHandle objectHandle : insideBoundaryElementsFromPlacement) {
          EObject insideBoundaryElementPlc = EngineUtility.resolveProxies(objectHandle);
          String propertyName = fromBinding.getFromReplacement().getPropertyName();
          EStructuralFeature property =
              insideBoundaryElementPlc.eClass().getEStructuralFeature(propertyName);
          if (property == null)
            throw new GeneralBVREngineException(
                "failed to find property to adjust, property name : " + propertyName);

          validOutsideOHFromPlacementBElements.clear();
          validOutsideOHFromPlacementBElements.addAll(insideBOHElmtsPlcReplaced);

          int upperBound = property.getUpperBound();
          if (upperBound == -1 || upperBound > 1) {
            EList<EObject> values =
                EngineUtility.getListPropertyValue(insideBoundaryElementPlc, property);

            SetView<EObject> invalidOutsideBEFromPlacement =
                Sets.difference(
                    new HashSet<EObject>(EngineUtility.resolveProxies(outsideBOHElmtsPlc)),
                    new HashSet<EObject>(values));
            EList<EObject> elementsToRemove =
                new BasicEList<EObject>(invalidOutsideBEFromPlacement);

            EList<ObjectHandle> invalidObjectHandles =
                findObjectHandlesByEObjects(
                    new BasicEList<EObject>(invalidOutsideBEFromPlacement), outsideBOHElmtsPlc);
            validOutsideOHFromPlacementBElements.addAll(
                Sets.difference(
                    new HashSet<ObjectHandle>(outsideBOHElmtsPlc),
                    new HashSet<ObjectHandle>(invalidObjectHandles)));

            EList<EObject> elementsToAdd = EngineUtility.resolveProxies(insideBOHElmtsPlcReplaced);
            EList<EObject> propertyValueNew =
                EngineUtility.subtractAugmentList(values, elementsToRemove, elementsToAdd);

            if (upperBound != -1 && propertyValueNew.size() > upperBound)
              throw new IllegalBVROperation(
                  "cardinality does not correspond for property : "
                      + propertyName
                      + "of"
                      + fragHolderAdjacent.getFragment());

            EngineUtility.setProperty(values, elementsToRemove, elementsToAdd);

            EList<EObject> propertyValueSet =
                EngineUtility.getListPropertyValue(insideBoundaryElementPlc, property);
            if (!propertyValueNew.equals(propertyValueSet))
              throw new UnexpectedOperationFailure(
                  "EPIC FAIL: property has not been adjusted : '"
                      + propertyName
                      + "' of "
                      + fragHolderAdjacent.getFragment());
          } else {
            // property.getUpperBound() == 0 || == 1
            if (upperBound == 0)
              throw new IncorrectBVRModel(
                  "model is incorrect, cardianlity for reference is set to 0, but something is there "
                      + insideBoundaryElementPlc.eGet(property));

            if (insideBOHElmtsPlcReplaced.size() != upperBound)
              throw new IllegalBVROperation(
                  "cardinality does not match for property : '"
                      + propertyName
                      + "' of "
                      + fragHolderAdjacent.getFragment()
                      + " objects: "
                      + EngineUtility.resolveProxies(insideBOHElmtsPlcReplaced));

            EObject propertyValueNew =
                EngineUtility.resolveProxies(insideBOHElmtsPlcReplaced).get(0);
            EngineUtility.setProperty(insideBoundaryElementPlc, property, propertyValueNew);

            Object propertyValueSet = insideBoundaryElementPlc.eGet(property);
            if (!propertyValueNew.equals(propertyValueSet))
              throw new UnexpectedOperationFailure(
                  "EPIC FAIL: property has not been adjusted : "
                      + propertyName
                      + "of"
                      + fragHolderAdjacent.getFragment());
          }
        }

        // update variability model : boundaries so the point to the correct elements
        fromBinding.getFromPlacement().getOutsideBoundaryElement().clear();
        fromBinding
            .getFromPlacement()
            .getOutsideBoundaryElement()
            .addAll(validOutsideOHFromPlacementBElements);

        HashMap<ToPlacement, HashSet<ObjectHandle>> outsideBoundaryElementsToPlacementMap =
            ((FragmentSubstitutionHolder) fragmentHolderCurrent)
                .getToPlacementOutsideBoundaryElementMap();
        HashSet<ObjectHandle> outsideBoundaryElementsToPlacement =
            outsideBoundaryElementsToPlacementMap.get(toBinding.getToPlacement());
        outsideBoundaryElementsToPlacement.clear();
        outsideBoundaryElementsToPlacement.addAll(insideBoundaryElementsFromPlacement);
      }

      HashMap<FromBinding, ToBinding> adjacentBindingsFromCurrent =
          aFrag.getAdjacentFromBindings(adjacentFragment);
      adjacentBindingsFromCurrent =
          (adjacentBindingsFromCurrent != null)
              ? adjacentBindingsFromCurrent
              : new HashMap<FromBinding, ToBinding>();
      for (Map.Entry<FromBinding, ToBinding> entry : adjacentBindingsFromCurrent.entrySet()) {
        FromBinding fromBinding = entry.getKey();
        ToBinding toBinding = entry.getValue();

        ObjectHandle insideBOHElmtsPlcReplaced =
            fromBinding.getFromPlacement().getInsideBoundaryElement();
        toBinding.getToPlacement().setOutsideBoundaryElement(insideBOHElmtsPlcReplaced);

        HashSet<ObjectHandle> insideBoundaryElementsFromPlacement =
            calculateOutsideBoundaryElementsToPlacementAdjacentToCurrent(
                aFrag, fromBinding.getFromPlacement());
        HashMap<ToPlacement, HashSet<ObjectHandle>> outsideBoundaryElementsToPlacementMap =
            ((FragmentSubstitutionHolder) fragHolderAdjacent)
                .getToPlacementOutsideBoundaryElementMap();
        HashSet<ObjectHandle> outsideBoundaryElementsToPlacement =
            outsideBoundaryElementsToPlacementMap.get(toBinding.getToPlacement());
        outsideBoundaryElementsToPlacement.clear();
        outsideBoundaryElementsToPlacement.addAll(insideBoundaryElementsFromPlacement);
      }
      ((FragmentSubstitutionHolder) fragHolderAdjacent).refresh();
    }
    ((FragmentSubstitutionHolder) fragmentHolderCurrent).refresh();
  }
  /**
   * States if the given object is related to the context {@link Classifier}.
   *
   * @param toFilter the candidate to check for relation
   * @param context the classifier context object.
   * @return <code>true</code> if the given object is related to the context {@link Classifier},
   *     <code>false</code> otherwise.
   */
  public boolean isRelated(EObject toFilter, EObject context) {
    boolean res = false;
    if (toFilter.equals(context)) {
      res = true;
    } else if (context instanceof Classifier) {
      if (toFilter instanceof Generalization) {
        res =
            ((Classifier) context).getGeneralizations().contains(toFilter)
                || ((Generalization) toFilter).getGeneral() == context;
      } else if (toFilter instanceof InterfaceRealization && context instanceof Class) {
        res =
            ((Class) context).getInterfaceRealizations().contains(toFilter)
                || ((InterfaceRealization) toFilter).getContract() == context;
      } else if (toFilter instanceof Association) {
        res = ((Classifier) context).getAssociations().contains(toFilter);
      } else if (toFilter instanceof Artifact && context instanceof ExecutionEnvironment) {
        for (final Deployment deployment : ((ExecutionEnvironment) context).getDeployments()) {
          if (deployment.getSuppliers().contains(toFilter)) {
            res = true;
          }
        }
      } else if (toFilter instanceof ExecutionEnvironment && context instanceof Artifact) {
        for (final Deployment deployment : ((ExecutionEnvironment) toFilter).getDeployments()) {
          if (deployment.getSuppliers().contains(context)) {
            res = true;
          }
        }
      } else if (toFilter instanceof PackageableElement && context instanceof Artifact) {
        res = ((Artifact) context).getManifestations().contains(toFilter);
        for (final Manifestation manifestation : ((Artifact) context).getManifestations()) {
          if (manifestation.getTargets().contains(toFilter)) {
            res = true;
          }
        }
      } else if (toFilter instanceof Artifact && context instanceof PackageableElement) {
        res = ((Artifact) toFilter).getManifestations().contains(context);
        for (final Manifestation manifestation : ((Artifact) toFilter).getManifestations()) {
          if (manifestation.getTargets().contains(context)) {
            res = true;
          }
        }
      } else if (toFilter instanceof Feature) {
        res = isRelated(toFilter.eContainer(), context);
      } else if (toFilter instanceof Classifier) {
        if (context == toFilter) {
          return false;
        }
        res = context == toFilter;

        if (context instanceof EncapsulatedClassifier
            && toFilter instanceof EncapsulatedClassifier) {
          if (!res) {
            if (((EncapsulatedClassifier) context).getOwnedElements().contains(toFilter)) {
              res = true;
            } else {
              for (final Port portContext : ((EncapsulatedClassifier) context).getOwnedPorts()) {
                if (portIsRelated(toFilter, portContext)) {
                  res = true;
                  break;
                }
              }
            }
          }
        }

        if (context instanceof EncapsulatedClassifier && toFilter instanceof Property) {
          if (!res) {
            if (((EncapsulatedClassifier) context).getOwnedAttributes().contains(toFilter)) {
              res = true;
            }
          }
        }

        // is it a generalization end
        if (!res) {
          for (final Generalization generalization : ((Classifier) context).getGeneralizations()) {
            if (generalization.getGeneral() == toFilter) {
              res = true;
              break;
            }
          }
        }
        // is it a generalization opposite end
        if (!res) {
          for (final Generalization generalization : ((Classifier) toFilter).getGeneralizations()) {
            if (generalization.getGeneral() == context) {
              res = true;
              break;
            }
          }
        }
        if (toFilter instanceof NamedElement && context instanceof NamedElement) {
          // is it a dependency end
          if (!res) {
            for (final Dependency dependency : ((NamedElement) context).getClientDependencies()) {
              if (dependency.getClients().contains(toFilter)
                  || dependency.getSuppliers().contains(toFilter)) {
                res = true;
                break;
              }
            }
          }
        }
        if (context instanceof NamedElement && toFilter instanceof NamedElement) {
          // is it a dependency end
          if (!res) {
            for (final Dependency dependency : ((NamedElement) toFilter).getClientDependencies()) {
              if (dependency.getClients().contains(context)
                  || dependency.getSuppliers().contains(context)) {
                res = true;
                break;
              }
            }
          }
        }
        if (toFilter instanceof Interface && context instanceof Class) {
          // is it a realization end
          if (!res) {
            for (final InterfaceRealization realization :
                ((Class) context).getInterfaceRealizations()) {
              if (realization.getContract() == toFilter) {
                res = true;
                break;
              }
            }
          }
        }
        if (context instanceof Interface && toFilter instanceof Class) {
          // is it a realization end
          if (!res) {
            for (final InterfaceRealization realization :
                ((Class) toFilter).getInterfaceRealizations()) {
              if (realization.getContract() == context) {
                res = true;
                break;
              }
            }
          }
        }

        // is it an association end
        if (!res) {
          final List<Association> toFilterAsso = ((Classifier) toFilter).getAssociations();
          final List<Association> contextAsso = ((Classifier) context).getAssociations();
          for (final Association association : toFilterAsso) {
            if (contextAsso.contains(association)) {
              res = true;
              break;
            }
          }
        }
      } else if (toFilter instanceof Package) {
        for (final EObject content : toFilter.eContents()) {
          if (isRelated(content, context)) {
            res = true;
            break;
          }
        }
      }
    } else if (context instanceof Package) {
      if (toFilter instanceof Package) {
        res =
            ((Package) context).getNestedPackages().contains(toFilter)
                || ((Package) context).getImportedPackages().contains(toFilter);
        for (final PackageImport packageImport : ((Package) context).getPackageImports()) {
          if (packageImport.getImportedPackage().equals(toFilter)) {
            res = true;
          }
        }
      } else {
        res = ((Package) context).getOwnedElements().contains(toFilter);
      }
    } else if (context instanceof Port) {
      res = portIsRelated(toFilter, (Port) context);
    }

    return res;
  }
  /**
   * get the list of command to put an eobject before or after another EObject It will look for the
   * good role of the child eobject
   *
   * @param domain the Transactional Domain, cannot be null
   * @param targetOwner the eobject that will contain the drop object , cannot be null
   * @param objectLocation the object where we want to drop the object
   * @param newElement that we want to move, cannot be null
   * @return the list of commands to to the drop
   */
  protected List<Command> getOrderChangeCommand(
      TransactionalEditingDomain domain,
      EObject targetOwner,
      EObject objectLocation,
      EObject newElement,
      boolean before) {
    ArrayList<Command> commandList = new ArrayList<Command>();
    ArrayList<EStructuralFeature> possibleEFeatures = new ArrayList<EStructuralFeature>();
    EList<EStructuralFeature> featureList = targetOwner.eClass().getEAllStructuralFeatures();

    // Abort when trying to change order moving the element in one of its children
    if (EcoreUtil.isAncestor(newElement, targetOwner)) {
      return Collections.emptyList();
    }

    // find the feature between childreen and owner
    Iterator<EStructuralFeature> iterator = featureList.iterator();
    while (iterator.hasNext()) {
      EStructuralFeature eStructuralFeature = (EStructuralFeature) iterator.next();

      if (eStructuralFeature instanceof EReference) {
        EReference ref = (EReference) eStructuralFeature;

        if (ref.isContainment()) {

          if (isSubClass(ref.getEType(), newElement.eClass())) {
            possibleEFeatures.add(eStructuralFeature);
          }
        }
      }
    }

    // create the command
    Iterator<EStructuralFeature> iteratorFeature = possibleEFeatures.iterator();
    while (iteratorFeature.hasNext()) {
      EStructuralFeature eStructuralFeature = (EStructuralFeature) iteratorFeature.next();
      ArrayList<EObject> tmp = new ArrayList<EObject>();
      if (targetOwner.eGet(eStructuralFeature) instanceof Collection<?>) {
        // get all element of this efeature
        tmp.addAll((Collection<EObject>) targetOwner.eGet(eStructuralFeature));

        if (!newElement.equals(objectLocation)) {
          tmp.remove(newElement);
          // normally tmp.indexOf(objectLocation)!= -1
          // if this the case objectlocation=new element and
          // it has been removed
          int indexObject = tmp.indexOf(objectLocation);
          if (before && indexObject != -1) {
            tmp.add(tmp.indexOf(objectLocation), newElement);
          } else if (!before && indexObject != -1) {
            tmp.add(tmp.indexOf(objectLocation) + 1, newElement);
          }
        }
      } else {
        tmp.add(newElement);
      }

      SetRequest setRequest = new SetRequest(targetOwner, eStructuralFeature, tmp);
      IElementEditService provider = ElementEditServiceUtils.getCommandProvider(targetOwner);
      if (provider != null) {
        // Retrieve delete command from the Element Edit service
        ICommand command = provider.getEditCommand(setRequest);

        if (command != null) {
          commandList.add(new GMFtoEMFCommandWrapper(command));
        }
      }
    }
    return commandList;
  }
 protected boolean matchesObject(Object notifierObj) {
   return object.equals(notifierObj);
 }