private void writeEmbedded(PrintWriter out, EObject eObject) throws SerializerException {
   EClass class1 = eObject.eClass();
   out.print(upperCases.get(class1));
   out.print(OPEN_PAREN);
   EStructuralFeature structuralFeature = class1.getEStructuralFeature(WRAPPED_VALUE);
   if (structuralFeature != null) {
     Object realVal = eObject.eGet(structuralFeature);
     if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) {
       Object stringVal =
           eObject.eGet(class1.getEStructuralFeature(structuralFeature.getName() + "AsString"));
       if (stringVal != null && model.isUseDoubleStrings()) {
         out.print(stringVal);
       } else {
         if (((Double) realVal).isInfinite() || (((Double) realVal).isNaN())) {
           LOGGER.info("Serializing infinite or NaN double as 0.0");
           out.print("0.0");
         } else {
           out.print(realVal);
         }
       }
     } else {
       writePrimitive(out, realVal);
     }
   }
   out.print(CLOSE_PAREN);
 }
 protected EObject createInitialModel() {
   EClass eClass = ExtendedMetaData.INSTANCE.getDocumentRoot(dsPackage);
   EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature("data");
   EObject rootObject = dsFactory.create(eClass);
   rootObject.eSet(eStructuralFeature, EcoreUtil.create((EClass) eStructuralFeature.getEType()));
   return rootObject;
 }
 @Override
 public @Nullable Object evaluate(
     @NonNull Executor executor, @NonNull TypeId returnTypeId, @Nullable Object sourceValue) {
   IdResolver idResolver = executor.getIdResolver();
   Property oppositeProperty = idResolver.getProperty(oppositePropertyId);
   ModelManager.ModelManagerExtension modelManager =
       (ModelManager.ModelManagerExtension) executor.getModelManager();
   Type thatType = ClassUtil.nonNullModel(oppositeProperty.getType());
   if (thatType instanceof CollectionType) {
     thatType = ((CollectionType) thatType).getElementType();
   }
   List<Object> results = new ArrayList<Object>();
   if (thatType instanceof org.eclipse.ocl.pivot.Class) {
     for (@NonNull
     Object eObject :
         modelManager.get((org.eclipse.ocl.pivot.Class) thatType)) { // FIXME Use a cache
       EClass eClass = modelManager.eClass(eObject);
       EStructuralFeature eFeature = eClass.getEStructuralFeature(oppositeProperty.getName());
       assert eFeature != null;
       Object eGet = modelManager.eGet(eObject, eFeature);
       if (eGet == sourceValue) {
         results.add(eObject);
       }
     }
   }
   return results;
 }
Example #4
0
 public static boolean isMany(EClass eClass, String featureName) {
   if (eClass == null || featureName == null) {
     return false;
   }
   EStructuralFeature feature = eClass.getEStructuralFeature(featureName);
   return feature != null && feature.isMany();
 }
 /** @param el */
 private static void processWellbehavingExtension(IConfigurationElement el) {
   try {
     String packageUri = el.getAttribute("package-nsUri");
     String classifierName = el.getAttribute("classifier-name");
     String featureName = el.getAttribute("feature-name");
     if (packageUri != null) {
       EPackage pckg = EPackage.Registry.INSTANCE.getEPackage(packageUri);
       if (pckg != null) {
         if (classifierName != null) {
           EClassifier clsr = pckg.getEClassifier(classifierName);
           if (clsr instanceof EClass) {
             if (featureName != null) {
               EClass cls = (EClass) clsr;
               EStructuralFeature feature = cls.getEStructuralFeature(featureName);
               if (feature != null) {
                 contributedWellbehavingDerivedFeatures.add(feature);
               }
             } else {
               contributedWellbehavingDerivedClasses.add((EClass) clsr);
             }
           }
         } else {
           contributedWellbehavingDerivedPackages.add(pckg);
         }
       }
     }
   } catch (Exception e) {
     final Logger logger = Logger.getLogger(WellbehavingDerivedFeatureRegistry.class);
     logger.error("Well-behaving feature registration failed", e);
   }
 }
Example #6
0
 protected EStructuralFeature getEStructuralFeature(String className, String fieldName) {
   for (EPackage ePackage : packages) {
     if (ePackage.getEClassifier(className) != null) {
       EClass eClass = (EClass) ePackage.getEClassifier(className);
       return eClass.getEStructuralFeature(fieldName);
     }
   }
   return null;
 }
Example #7
0
 /**
  * Get the feature for the named parameter
  *
  * @param data
  * @param name
  * @return
  * @throws UndefinedParameterException
  */
 public static EStructuralFeature getParameterFeature(EObject data, String name)
     throws UndefinedParameterException {
   if (data == null) {
     throw new UndefinedParameterException("No activity definition");
   }
   EClass eClass = data.eClass();
   EStructuralFeature feature = eClass.getEStructuralFeature(name);
   if (feature == null) {
     Resource resource = data.eResource();
     String info = (resource != null ? " in resource: " + resource.getURI() : "");
     throw new UndefinedParameterException(name + info);
   }
   return feature;
 }
  void assertStereotypeApplication() {
    assertThat("Stereotype not applied to the class", class1.isStereotypeApplied(stereotype));
    EObject application = class1.getStereotypeApplication(stereotype);
    EClass eclass = application.eClass();

    // Verify an Enumeration value stored as an XML attribute
    Object value = application.eGet(eclass.getEStructuralFeature("alertLevel"));
    assertThat(
        "Alert level is not yellow",
        (value instanceof Enumerator) && ((Enumerator) value).getLiteral().equals("yellow"),
        is(true));

    // Verify a multi-valued attribute stored as XML elements
    value = application.eGet(eclass.getEStructuralFeature("tag"));
    assertThat("Wrong tags found", value, is((Object) Arrays.asList("p2", "silver")));

    // Verify a reference value stored as an XML IDREFS attribute
    value = application.eGet(eclass.getEStructuralFeature("appliesTo"));
    assertThat("Wrong appliesTo found", value, is((Object) class1.getOwnedAttributes()));

    // Verify a contained EObject that is a complex DataType value
    value = application.eGet(eclass.getEStructuralFeature("name"));
    {
      assertThat("Value is not an EList", value, instanceOf(EList.class));
      EList<?> list = (EList<?>) value;

      assertThat("List has wrong number of elements", list.size(), is(1));
      value = list.get(0);

      assertThat("Value is not an EObject", value, instanceOf(EObject.class));
      EObject name = (EObject) value;
      EClass dataType = name.eClass();

      assertThat(
          "Wrong firstName",
          name.eGet(dataType.getEStructuralFeature("firstName")),
          is((Object) "Christian"));
      assertThat(
          "Wrong lastName",
          name.eGet(dataType.getEStructuralFeature("lastName")),
          is((Object) "Damus"));
      assertThat(
          "Wrong initials",
          name.eGet(dataType.getEStructuralFeature("initials")),
          is((Object) Arrays.asList("W")));
    }
  }
Example #9
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.action.Action#run()
   */
  @Override
  public void run() {
    EPackage ePackage = owner.eClass().getEPackage();

    InfoSelectDialog dlg = new InfoSelectDialog(new Shell(), resource, resouceInfo);
    dlg.open();

    //		domain
    if (!dlg.getResult().isEmpty()) {
      EClass masterClass = (EClass) ePackage.getEClassifier(IBasicDataEpacakgeConstant.MasterItem);
      AddCommand command =
          new AddCommand(
              domain,
              owner,
              masterClass.getEStructuralFeature(IBasicDataEpacakgeConstant.Attr_Slave_Items),
              dlg.getResult());
      domain.getCommandStack().execute(command);
    }
  }
Example #10
0
  private static JsonNode findNode(URI nodeURI, EClass eClass, JsonNode root) {
    EAttribute eID = eClass.getEIDAttribute();
    if (eID == null) {
      final EStructuralFeature featureName = eClass.getEStructuralFeature("name");
      if (featureName != null && featureName instanceof EAttribute) {
        eID = (EAttribute) featureName;
      } else {
        return null;
      }
    }

    String fragment =
        nodeURI.fragment().startsWith("//") ? nodeURI.fragment().substring(2) : nodeURI.fragment();

    for (JsonNode node : root.findParents(eID.getName())) {
      String value = node.get(eID.getName()).getTextValue();
      if (value.equals(fragment)) {
        return node;
      }
    }
    return null;
  }
 private void writeWrappedValue(
     PrintWriter out, EObject object, EStructuralFeature feature, EClass ec)
     throws SerializerException {
   Object get = object.eGet(feature);
   boolean isWrapped = ec.getEAnnotation("wrapped") != null;
   EStructuralFeature structuralFeature = ec.getEStructuralFeature(WRAPPED_VALUE);
   if (get instanceof EObject) {
     boolean isDefinedWrapped = feature.getEType().getEAnnotation("wrapped") != null;
     EObject betweenObject = (EObject) get;
     if (betweenObject != null) {
       if (isWrapped && isDefinedWrapped) {
         Object val = betweenObject.eGet(structuralFeature);
         String name = structuralFeature.getEType().getName();
         if ((name.equals(IFC_BOOLEAN) || name.equals(IFC_LOGICAL)) && val == null) {
           out.print(BOOLEAN_UNDEFINED);
         } else if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) {
           Object stringVal =
               betweenObject.eGet(
                   betweenObject.eClass().getEStructuralFeature("wrappedValueAsString"));
           if (stringVal != null && model.isUseDoubleStrings()) {
             out.print(stringVal);
           } else {
             out.print(val);
           }
         } else {
           writePrimitive(out, val);
         }
       } else {
         writeEmbedded(out, betweenObject);
       }
     }
   } else if (get instanceof EList<?>) {
     EList<?> list = (EList<?>) get;
     if (list.isEmpty()) {
       if (!feature.isUnsettable()) {
         out.print(OPEN_CLOSE_PAREN);
       } else {
         out.print("$");
       }
     } else {
       out.print(OPEN_PAREN);
       boolean first = true;
       for (Object o : list) {
         if (!first) {
           out.print(COMMA);
         }
         EObject object2 = (EObject) o;
         Object val = object2.eGet(structuralFeature);
         if (structuralFeature.getEType() == ECORE_PACKAGE_INSTANCE.getEDouble()) {
           out.print(
               object2.eGet(
                   object2
                       .eClass()
                       .getEStructuralFeature("stringValue" + structuralFeature.getName())));
         } else {
           writePrimitive(out, val);
         }
         first = false;
       }
       out.print(CLOSE_PAREN);
     }
   } else {
     if (get == null) {
       EClassifier type = structuralFeature.getEType();
       if (type == IFC_PACKAGE_INSTANCE.getIfcBoolean()
           || type == IFC_PACKAGE_INSTANCE.getIfcLogical()
           || type == ECORE_PACKAGE_INSTANCE.getEBoolean()) {
         out.print(BOOLEAN_UNDEFINED);
       } else {
         SchemaDefinition schema;
         try {
           schema = getPluginManager().requireSchemaDefinition();
         } catch (PluginException e) {
           throw new SerializerException(e);
         }
         EntityDefinition entityBN = schema.getEntityBN(object.eClass().getName());
         if (entityBN != null && entityBN.isDerived(feature.getName())) {
           out.print("*");
         } else {
           out.print(DOLLAR);
         }
       }
     }
   }
 }
 private void writeList(PrintWriter out, EObject object, EStructuralFeature feature)
     throws SerializerException {
   List<?> list = (List<?>) object.eGet(feature);
   List<?> doubleStingList = null;
   if (feature.getEType() == EcorePackage.eINSTANCE.getEDouble() && model.isUseDoubleStrings()) {
     EStructuralFeature doubleStringFeature =
         feature.getEContainingClass().getEStructuralFeature(feature.getName() + "AsString");
     if (doubleStringFeature == null) {
       throw new SerializerException("Field " + feature.getName() + "AsString" + " not found");
     }
     doubleStingList = (List<?>) object.eGet(doubleStringFeature);
   }
   if (list.isEmpty()) {
     if (!feature.isUnsettable()) {
       out.print(OPEN_CLOSE_PAREN);
     } else {
       out.print("$");
     }
   } else {
     out.print(OPEN_PAREN);
     boolean first = true;
     int index = 0;
     for (Object listObject : list) {
       if (!first) {
         out.print(COMMA);
       }
       if ((listObject instanceof IdEObject) && model.contains((IdEObject) listObject)) {
         IdEObject eObject = (IdEObject) listObject;
         out.print(DASH);
         out.print(String.valueOf(getExpressId(eObject)));
       } else {
         if (listObject == null) {
           out.print(DOLLAR);
         } else {
           if (listObject instanceof IdEObject
               && feature.getEType().getEAnnotation("wrapped") != null) {
             IdEObject eObject = (IdEObject) listObject;
             Object realVal = eObject.eGet(eObject.eClass().getEStructuralFeature("wrappedValue"));
             if (realVal instanceof Double) {
               Object stringVal =
                   eObject.eGet(eObject.eClass().getEStructuralFeature("wrappedValueAsString"));
               if (stringVal != null && model.isUseDoubleStrings()) {
                 out.print(stringVal);
               } else {
                 out.print(realVal);
               }
             } else {
               writePrimitive(out, realVal);
             }
           } else if (listObject instanceof EObject) {
             IdEObject eObject = (IdEObject) listObject;
             EClass class1 = eObject.eClass();
             EStructuralFeature structuralFeature = class1.getEStructuralFeature(WRAPPED_VALUE);
             if (structuralFeature != null) {
               Object realVal = eObject.eGet(structuralFeature);
               out.print(upperCases.get(class1));
               out.print(OPEN_PAREN);
               if (realVal instanceof Double) {
                 Object stringVal =
                     eObject.eGet(
                         class1.getEStructuralFeature(structuralFeature.getName() + "AsString"));
                 if (stringVal != null && model.isUseDoubleStrings()) {
                   out.print(stringVal);
                 } else {
                   out.print(realVal);
                 }
               } else {
                 writePrimitive(out, realVal);
               }
               out.print(CLOSE_PAREN);
             } else {
               LOGGER.info(
                   "Unfollowable reference found from "
                       + object
                       + "."
                       + feature.getName()
                       + " to "
                       + eObject);
             }
           } else {
             if (doubleStingList != null) {
               if (index < doubleStingList.size()) {
                 String val = (String) doubleStingList.get(index);
                 if (val == null) {
                   writePrimitive(out, listObject);
                 } else {
                   out.write(val);
                 }
               } else {
                 writePrimitive(out, listObject);
               }
             } else {
               writePrimitive(out, listObject);
             }
           }
         }
       }
       first = false;
       index++;
     }
     out.print(CLOSE_PAREN);
   }
 }
Example #13
0
 private EAttribute getNameAttribute(EClass eClass) {
   return (EAttribute) eClass.getEStructuralFeature(NAME);
 }
Example #14
0
 private EReference getIncomingReference(EClass eClass) {
   return (EReference) eClass.getEStructuralFeature(INCOMING);
 }
Example #15
0
  @Override
  protected void setUp() {
    super.setUp();

    pkg = umlf.createPackage();
    pkg.setName("pkg");

    valueType = pkg.createOwnedPrimitiveType("Value");
    valueType
        .createOwnedOperation(
            "<",
            new BasicEList<String>(Collections.singleton("v")),
            new BasicEList<Type>(Collections.singleton(valueType)),
            getUMLBoolean())
        .setIsQuery(true);
    valueType
        .createOwnedOperation(
            "<=",
            new BasicEList<String>(Collections.singleton("v")),
            new BasicEList<Type>(Collections.singleton(valueType)),
            getUMLBoolean())
        .setIsQuery(true);
    valueType
        .createOwnedOperation(
            ">",
            new BasicEList<String>(Collections.singleton("v")),
            new BasicEList<Type>(Collections.singleton(valueType)),
            getUMLBoolean())
        .setIsQuery(true);
    valueType
        .createOwnedOperation(
            ">=",
            new BasicEList<String>(Collections.singleton("v")),
            new BasicEList<Type>(Collections.singleton(valueType)),
            getUMLBoolean())
        .setIsQuery(true);

    thingType = pkg.createOwnedClass("Thing", false);

    values = thingType.createOwnedAttribute("values", valueType);
    values.setUpper(LiteralUnlimitedNatural.UNLIMITED);
    values.setIsOrdered(true);
    values.setIsUnique(true);

    bdValue = thingType.createOwnedAttribute("bdValue", getEcoreBigDecimal());
    biValue = thingType.createOwnedAttribute("biValue", getEcoreBigInteger());

    numeroType = pkg.createOwnedClass("Numero", false);

    numeroType
        .createOwnedOperation(
            "+",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            numeroType)
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            "-",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            numeroType)
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            "*",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            numeroType)
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            "/",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            numeroType)
        .setIsQuery(true);

    numeroType
        .createOwnedOperation(
            "-", ECollections.<String>emptyEList(), ECollections.<Type>emptyEList(), numeroType)
        .setIsQuery(true);

    numeroType
        .createOwnedOperation(
            "<",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            getUMLBoolean())
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            "<=",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            getUMLBoolean())
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            ">",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            getUMLBoolean())
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            ">=",
            new BasicEList<String>(Collections.singleton("n")),
            new BasicEList<Type>(Collections.singleton(numeroType)),
            getUMLBoolean())
        .setIsQuery(true);
    numeroType
        .createOwnedOperation(
            "asLong",
            ECollections.<String>emptyEList(),
            ECollections.<Type>emptyEList(),
            getEcoreLong())
        .setIsQuery(true);

    numeros = thingType.createOwnedAttribute("numeros", numeroType);
    numeros.setUpper(LiteralUnlimitedNatural.UNLIMITED);
    numeros.setIsOrdered(true);
    numeros.setIsUnique(true);

    comparable = pkg.createOwnedClass("Comparable", true);
    comparable
        .createOwnedOperation(
            "compareTo",
            new BasicEList<String>(Collections.singleton("c")),
            new BasicEList<Type>(Collections.singleton(comparable)),
            getUMLInteger())
        .setIsQuery(true);

    // the Ecore counterpart

    epkg = UMLUtil.convertToEcore(pkg, null).iterator().next();

    ethingType = (EClass) epkg.getEClassifier(thingType.getName());
    enumeros = (EReference) ethingType.getEStructuralFeature(numeros.getName());
    evalues = (EAttribute) ethingType.getEStructuralFeature(values.getName());
    ebdValue = (EAttribute) ethingType.getEStructuralFeature(bdValue.getName());
    ebiValue = (EAttribute) ethingType.getEStructuralFeature(biValue.getName());

    enumeroType = (EClass) epkg.getEClassifier(numeroType.getName());
    enumeroType.setInstanceClass(Numero.class);

    evalueType = (EDataType) epkg.getEClassifier(valueType.getName());
    evalueType.setInstanceClass(Value.class);

    efactory = epkg.getEFactoryInstance();
    thing = efactory.create(ethingType);

    EPackage.Registry.INSTANCE.put(epkg.getNsURI(), epkg);

    @SuppressWarnings("unchecked")
    EList<Numero> list = (EList<Numero>) thing.eGet(enumeros);
    list.add(new Numero(6));
    list.add(new Numero(2));
  }
Example #16
0
 private EReference getTransitionsReference(EClass eClass) {
   return (EReference) eClass.getEStructuralFeature(TRANSITIONS);
 }
Example #17
0
 private EReference getPlacesReference(EClass eClass) {
   return (EReference) eClass.getEStructuralFeature(PLACES);
 }
Example #18
0
 private EReference getOutgoingReference(EClass eClass) {
   return (EReference) eClass.getEStructuralFeature(OUTGOING);
 }
 public StringWrapper(String value) {
   this();
   this.eSet(eClass.getEStructuralFeature("value"), value); // $NON-NLS-1$
 }
  @Override
  public Object execute(Collection<? extends EObject> eObjects, ExecutionEvent event)
      throws ExecutionException {
    Collection<FeatureMappingStrategy> mappingStrategies = new ArrayList<FeatureMappingStrategy>();
    Collection<JvmGenericType> classDeclarations = new ArrayList<JvmGenericType>();
    Collection<EPackage> ePackages = new ArrayList<EPackage>();
    Collection<EClass> eClasses = new ArrayList<EClass>();
    categorizeEObjects(eObjects, mappingStrategies, classDeclarations, ePackages, eClasses);

    String eClassNamePrefix = getEventParameter(event, "eClassNamePrefix", "");

    FacadeModel facadeModel = getEObject(eObjects, FacadeModel.class, null);
    if (mappingStrategies.size() == 0) {
      mappingStrategies.addAll(facadeModel.getFeatureMappingStrategies());
    } else if (facadeModel == null) {
      facadeModel = (FacadeModel) mappingStrategies.iterator().next().eContainer();
    }
    if (ePackages.size() == 0) {
      for (Resource resource : facadeModel.eResource().getResourceSet().getResources()) {
        ePackages.addAll(getEObjects(resource.getContents(), EPackage.class, null, -1));
      }
    }
    for (JvmGenericType classDeclaration : classDeclarations) {
      String eClassName = eClassNamePrefix + classDeclaration.getSimpleName();
      EClass eClass = (EClass) findEClassifier(eClassName, ePackages, eClasses);
      if (eClass == null) {
        eClass = EcoreFactory.eINSTANCE.createEClass();
        eClass.setName(eClassName);
        getEObject(ePackages, EPackage.class, null).getEClassifiers().add(eClass);
      }
      EClassMapping classMapping =
          getEObject(facadeModel.getClassifierMappings(), EClassMapping.class, eClassName);
      if (classMapping == null) {
        classMapping = EmfacadeFactory.eINSTANCE.createEClassMapping();
        classMapping.setEClass(eClass);
        facadeModel.getClassifierMappings().add(classMapping);
      }

      EList<JvmMember> jElements = new BasicEList<JvmMember>(classDeclaration.getMembers());
      EList<JvmMember> matchedElements = new BasicEList<JvmMember>();
      for (FeatureMappingStrategy featureMappingStrategy : mappingStrategies) {
        EList<EFeatureMapping> featureMappings =
            featureMappingStrategy.createFeatureMappings(jElements);
        for (EFeatureMapping featureMapping : featureMappings) {
          EStructuralFeature feature = featureMapping.getEFeature();
          if (feature.getEType() == null) {
            resolveFeatureType(feature, facadeModel.getClassifierMappings(), ePackages);
          }
          EStructuralFeature existingFeature = eClass.getEStructuralFeature(feature.getName());
          if (existingFeature != null) {
            eClass.getEStructuralFeatures().remove(existingFeature);
          }
          eClass.getEStructuralFeatures().add(feature);
          EFeatureMapping existingMapping =
              getEObject(
                  classMapping.getFeatureMappings(),
                  EFeatureMapping.class,
                  featureMapping.getEFeature().getName());
          if (existingMapping != null) {
            classMapping.getFeatureMappings().remove(existingMapping);
          }
          classMapping.getFeatureMappings().add(featureMapping);

          //					matchedElements.addAll(featureMapping.getJElements());
        }
        jElements.removeAll(matchedElements);
      }
    }
    return null;
  }
  /**
   * Creates a list mapper that corresponding to the facilities of the specified type.
   *
   * <p>The mapper is chosen according to the following priorities:
   *
   * <ul>
   *   <li>annotated field
   *   <li>via genmodel label field - requires additional generation of information
   *   <li>by field name: label, name, fullName
   *   <li>by field type: String
   *   <li>{@link #toString()}
   * </ul>
   *
   * @param binding the binding to map
   * @param ec the class to create the mapper for
   * @return the mapper
   */
  public static IClassIdentiferMapper createClassIdentiferMapper(IBinding binding, EClass ec) {
    EStructuralFeature feature;

    /*
     * Any constant string is used first of all...
     *
     * TODO: Problem: if text is specified, icon and other arguments are ignored!
     */
    final String constantText = binding.getArgument(Constants.ARG_TEXT, String.class, null);
    if (constantText != null)
      return new IClassIdentiferMapper() {
        @Override
        public Object map(Object value) {
          return constantText;
        }

        @Override
        public IObservableValue getObservableValue(
            IObservableValue value, EditingDomain editingDomain) {
          return value;
        }
      };

    // Via Annotation
    final String featureNames = binding.getArgument(Constants.ARG_FEATURE_NAME, String.class, null);
    if (featureNames != null) {
      // Pattern.compile("(\\p{L}+)")
      final StringTokenizer st = new StringTokenizer(featureNames, ".");
      EClassifier c = ec;
      final List<EStructuralFeature> sfs = new ArrayList<EStructuralFeature>();
      while (st.hasMoreTokens()) {
        final String name = st.nextToken();
        binding.assertTrue(c instanceof EClass, "Intermidiate features must be references");
        final EClass eClass = (EClass) c;
        feature = eClass.getEStructuralFeature(name);
        binding.assertTrue(
            feature != null,
            "Unknown feature: '"
                + eClass.getName()
                + "."
                + name
                + "' in argument "
                + Constants.ARG_FEATURE_NAME
                + " ("
                + featureNames
                + ")");

        sfs.add(feature);
        c = feature.getEType();
      }

      switch (sfs.size()) {
        case 0:
          LogUtils.error(
              binding,
              "Feature names '" + featureNames + "' does not exist. Ignored.",
              binding.getCreationPoint());
          break;
        case 1:
          return new SingleFeatureMapper(sfs.get(0));
        default:
          return new MultipleFeatureMapper(sfs.toArray(new EStructuralFeature[sfs.size()]));
      }
    }

    // By Field Name
    feature = ec.getEStructuralFeature("label");
    if (feature != null) return new SingleFeatureMapper(feature);
    feature = ec.getEStructuralFeature("name");
    if (feature != null) return new SingleFeatureMapper(feature);
    feature = ec.getEStructuralFeature("fullName");
    if (feature != null) return new SingleFeatureMapper(feature);

    // By Field Type
    for (final EAttribute a : ec.getEAllAttributes()) {
      if (a.getEType() == EcorePackage.Literals.ESTRING) return new SingleFeatureMapper(a);
    }

    // Fall back on toString()....
    return DEFAULT_MAPPER;
  }
Example #22
0
  /**
   * Converts the value of an EReference with isMany==true, the values of the collection are
   * converted to EObjects and added to the list in the correct feature in the eObject.
   *
   * @param modelObject the modelObject from which the value is retrieved.
   * @param eObject the eObject in which the value is set (after it has been converted)
   * @param eReference the eReference which is converted
   */
  protected void convertManyEReference(
      final ModelObject<?> modelObject, final EObject eObject, final EReference eReference) {
    // container feature is always set from the other side, the containment
    // side
    if (eReference.isContainer()) {
      return;
    }

    final Object manyValue = modelObject.eGet(eReference);
    final Collection<EObject> newValues = new ArrayList<EObject>();

    boolean isMap = Map.class.isAssignableFrom(manyValue.getClass());
    EStructuralFeature valueFeature = null;
    EStructuralFeature keyFeature = null;
    if (isMap) {
      final EClass mapEClass = eReference.getEReferenceType();
      valueFeature = mapEClass.getEStructuralFeature("value"); // $NON-NLS-1$
      keyFeature = mapEClass.getEStructuralFeature("key"); // $NON-NLS-1$

      Check.isTrue(
          ModelUtils.isEMap(eReference),
          "Expected emap EReference, but th// case for EReference " //$NON-NLS-1$
              + eReference);

      final Map<?, ?> map = (Map<?, ?>) manyValue;

      for (final Object key : map.keySet()) {
        final Object value = map.get(key);
        final EObject mapEntryEObject = EcoreUtil.create(mapEClass);

        // key and value maybe primitive types but can also be
        // references to model objects.
        if (valueFeature instanceof EReference) {
          mapEntryEObject.eSet(valueFeature, createTarget(value));
        } else {
          mapEntryEObject.eSet(valueFeature, value);
        }
        if (keyFeature instanceof EReference) {
          mapEntryEObject.eSet(keyFeature, createTarget(key));
        } else {
          mapEntryEObject.eSet(keyFeature, key);
        }
        newValues.add(mapEntryEObject);
      }
    } else {

      // a many to many
      if (eReference.getEOpposite() != null && eReference.getEOpposite().isMany()) {
        final ManyToMany mtm = new ManyToMany();
        mtm.setOwner(modelObject);
        mtm.setEReference(eReference);
        toRepairManyToMany.add(mtm);
      }

      @SuppressWarnings("unchecked")
      final Collection<Object> values = (Collection<Object>) manyValue;

      for (final Object value : values) {
        if (value == null) {
          newValues.add(null);
        } else {
          final InternalEObject eValue = (InternalEObject) createTarget(value);
          if (!newValues.contains(eValue)) {
            newValues.add(eValue);
          }
        }
      }
    }

    @SuppressWarnings("unchecked")
    final Collection<EObject> eValues = (Collection<EObject>) eObject.eGet(eReference);

    boolean updateList = false;
    if (newValues.size() == eValues.size()) {
      final Iterator<?> it = eValues.iterator();
      for (Object newValue : newValues) {
        final Object oldValue = it.next();

        if (isMap) {
          final EObject oldMapEntry = (EObject) oldValue;
          final EObject newMapEntry = (EObject) newValue;
          final Object oldMapValue = oldMapEntry.eGet(valueFeature);
          final Object oldMapKey = oldMapEntry.eGet(keyFeature);
          final Object newMapValue = newMapEntry.eGet(valueFeature);
          final Object newMapKey = newMapEntry.eGet(keyFeature);
          if (valueFeature instanceof EReference) {
            updateList = oldMapValue == newMapValue;
          } else {
            updateList =
                oldMapValue != null
                    ? !oldMapValue.equals(newMapValue)
                    : newMapValue != null ? !newMapValue.equals(oldMapValue) : false;
          }
          if (keyFeature instanceof EReference) {
            updateList = updateList || oldMapKey == newMapKey;
          } else {
            updateList =
                updateList
                    || (oldMapKey != null
                        ? !oldMapKey.equals(newMapKey)
                        : newMapKey != null ? !newMapKey.equals(oldMapKey) : false);
          }
        } else {
          updateList = oldValue != newValue;
        }

        if (updateList) {
          break;
        }
      }
    } else {
      updateList = true;
    }

    if (updateList) {
      // clear the evalues so that an empty tag is created in the xml
      eValues.clear();
      eValues.addAll(newValues);
    }
  }
Example #23
0
 private EAttribute getTokenAttribute(EClass eClass) {
   return (EAttribute) eClass.getEStructuralFeature(INITIAL_TOKENS);
 }