Example #1
0
 /**
  * Converts this Object to a dynamic object with a new type that is a subtype of the current type,
  * preserving any existing property values.
  *
  * @param newEClass the new type for this Object
  * @throws IllegalArgumentException if newEClass is not a subtype of this Object's current type
  * @see org.eclipse.emf.ecore.InternalEObject#eSetClass(org.eclipse.emf.ecore.EClass)
  */
 public void narrow(EClass newEClass) throws IllegalArgumentException {
   if (!eClass().equals(EcorePackage.eINSTANCE.getEObject())
       && !eClass().isSuperTypeOf(newEClass)) {
     throw new IllegalArgumentException(
         "The class "
             + newEClass.getName()
             + " is not a subtype of the Object's current type "
             + eClass().getName());
   }
   EPropertiesHolder props = eProperties();
   if (props.getEClass() != null && props.hasSettings()) {
     int staticSize = eStaticFeatureCount();
     int oldSize = eClass().getEAllStructuralFeatures().size() - staticSize;
     if (oldSize > 0) {
       int newSize = newEClass.getEAllStructuralFeatures().size() - staticSize;
       if (newSize > oldSize) {
         List oldValues = new ArrayList(oldSize);
         for (int i = 0; i < oldSize; i++) {
           oldValues.add(props.dynamicGet(i));
         }
         props.allocateSettings(newSize);
         for (int i = 0; i < oldSize; i++) {
           props.dynamicSet(i, oldValues.get(i));
         }
       }
     }
   }
   eSetClass(newEClass);
 }
 public EObject resolve(
     ParseTreeNode parseTreeNode,
     Object actual,
     Object value,
     IModelCreatingContext context,
     ReferenceBinding binding)
     throws ModelCreatingException, UnresolveableReferenceErrorException {
   String id = parseTreeNode.getNodeText();
   EObject resolution = null;
   if (actual instanceof PropertyBinding) {
     EClass correspondingMetaClass =
         SyntaxHelper.findCorrespondingElementBinding(
             getContainingRule((EObject) actual),
             (Syntax) context.getResource().getContents().get(0),
             new HashSet<Rule>());
     if (correspondingMetaClass == null) {
       new UnresolvableReferenceError(
               "Cannot resolve the meta-class for the given property", parseTreeNode)
           .throwIt();
       return null;
     }
     for (EStructuralFeature feature : correspondingMetaClass.getEAllStructuralFeatures()) {
       if (feature.getName().equals(id)) {
         resolution = feature;
       }
     }
     if (resolution == null) {
       new UnresolvableReferenceError(
               "Class "
                   + correspondingMetaClass.getName()
                   + " does not contain a structural feature with the given name",
               parseTreeNode)
           .throwIt();
       return null;
     }
   } else {
     try {
       resolution =
           resolve(
               DefaultIdentificationScheme.INSTANCE,
               id,
               null,
               binding.getProperty().getEType(),
               context.getAdapter(IEcoreModel.class).getAllContents());
     } catch (AmbiguousReferenceException ex) {
       context.addError(new Error(parseTreeNode.getPosition(), "Reference is ambiguous"));
     }
   }
   if (resolution != null) {
     return resolution;
   } else {
     new UnresolvableReferenceError("Could not resolve " + id + ".", parseTreeNode).throwIt();
     return null;
   }
 }
 /**
  * @param copyObjs
  * @return 转换为粘贴对象
  */
 private Collection<Object> getPasteObjs(Collection<Object> copyObjs, EClass eclass) {
   List<Object> objs = new ArrayList<Object>();
   Map<EStructuralFeature, EStructuralFeature> map =
       new HashMap<EStructuralFeature, EStructuralFeature>();
   // 由第一个复制对象,找出复制对象和粘贴对象匹配的属性
   Iterator<Object> it = copyObjs.iterator();
   if (it.hasNext()) {
     Object obj = it.next();
     if (obj instanceof EObject) {
       EObject copyObj = (EObject) obj;
       // 如果是同一个编辑器内进行粘贴,直接返回复制对象集合
       if (copyObj.eClass().equals(eclass)) {
         return copyObjs;
       }
       // name一样,则表示属性匹配
       for (EStructuralFeature copyFeature : copyObj.eClass().getEAllStructuralFeatures()) {
         if (!exclude.contains(copyFeature)) {
           for (EStructuralFeature pasteFeature : eclass.getEAllStructuralFeatures()) {
             if (StringUtils.equals(copyFeature.getName(), pasteFeature.getName())) {
               map.put(copyFeature, pasteFeature);
               break;
             }
           }
         }
       }
     }
   }
   // 如果没有匹配的属性,则返回空集合
   if (map.isEmpty()) {
     return objs;
   }
   for (Object obj : copyObjs) {
     EObject copyObj = (EObject) obj;
     EObject pasteObj = eclass.getEPackage().getEFactoryInstance().create(eclass);
     for (Entry<EStructuralFeature, EStructuralFeature> entry : map.entrySet()) {
       EStructuralFeature copyFeature = entry.getKey();
       EStructuralFeature pasteFeature = entry.getValue();
       if (copyFeature instanceof EAttribute) {
         // 设置匹配属性值
         pasteObj.eSet(pasteFeature, copyObj.eGet(copyFeature));
       } else if (copyFeature instanceof EReference) {
         // 设置匹配子集
         Collection<Object> tmp = (Collection<Object>) copyObj.eGet(copyFeature);
         if (tmp != null) {
           pasteObj.eSet(
               pasteFeature,
               getPasteObjs(
                   EcoreUtil.copyAll(tmp), ((EReference) pasteFeature).getEReferenceType()));
         }
       }
     }
     objs.add(pasteObj);
   }
   return objs;
 }
Example #4
0
 @Override
 public boolean isStereotype(
     @NonNull EnvironmentFactoryInternal environmentFactory, @NonNull EClass eClass) {
   for (EStructuralFeature eFeature : eClass.getEAllStructuralFeatures()) {
     EClassifier eType = eFeature.getEType();
     if (eType != null) {
       assert !eType.eIsProxy() : "Unresolved proxy: '" + EcoreUtil.getURI(eType) + "'";
       EPackage ePackage = eType.getEPackage();
       assert !"http://www.eclipse.org/uml2/5.0.0/UML".equals(ePackage.getNsURI());
     }
   }
   return false;
 }
  public void doInstancePropertyInit(Object instance, QvtOperationalEvaluationVisitor evalVisitor) {
    if (false == instance instanceof EObject) {
      return;
    }
    EObject eInstance = (EObject) instance;

    EClass intermediateClass = eInstance.eClass();

    Map<EStructuralFeature, OCLExpression<EClassifier>> clsFeatures =
        myClassifierInitializations.get(intermediateClass);
    if (clsFeatures == null) {
      return;
    }
    for (EStructuralFeature eFeature : intermediateClass.getEAllStructuralFeatures()) {
      IntermediateStaticFieldAdapter adapter =
          (IntermediateStaticFieldAdapter)
              EcoreUtil.getAdapter(eFeature.eAdapters(), IntermediateStaticFieldAdapter.class);
      if (adapter != null && adapter.isInitialized()) {
        continue;
      }

      OCLExpression<EClassifier> expression = clsFeatures.get(eFeature);

      Object evalResult = expression != null ? evalVisitor.visitExpression(expression) : null;

      if (evalResult == null) {
        // no init expression specified for a single-valued feature, or init expression evaluated to
        // null
        EClassifier featureType =
            evalVisitor.getEnvironment().getUMLReflection().getOCLType(eFeature);
        evalResult =
            EvaluationUtil.createInitialValue(
                featureType,
                evalVisitor.getEnvironment().getOCLStandardLibrary(),
                evalVisitor.getEvaluationEnvironment());
      }

      // temporary switch off read-only property
      boolean isChangeable = eFeature.isChangeable();
      eFeature.setChangeable(true);

      boolean isUndefined =
          QvtOperationalUtil.isUndefined(evalResult, evalVisitor.getEvaluationEnvironment());
      evalVisitor
          .getOperationalEvaluationEnv()
          .callSetter(eInstance, eFeature, evalResult, isUndefined, true);

      eFeature.setChangeable(isChangeable);
    }
  }
 private void write(PrintWriter out, IdEObject object) throws SerializerException {
   EClass eClass = object.eClass();
   if (eClass.getEAnnotation("hidden") != null) {
     return;
   }
   out.print(DASH);
   int convertedKey = getExpressId(object);
   if (convertedKey == -1) {
     throw new SerializerException(
         "Going to serialize an object with id -1 (" + object.eClass().getName() + ")");
   }
   out.print(String.valueOf(convertedKey));
   out.print("= ");
   String upperCase = upperCases.get(eClass);
   if (upperCase == null) {
     throw new SerializerException("Type not found: " + eClass.getName());
   }
   out.print(upperCase);
   out.print(OPEN_PAREN);
   boolean isFirst = true;
   for (EStructuralFeature feature : eClass.getEAllStructuralFeatures()) {
     if (!feature.isDerived() && feature.getEAnnotation("hidden") == null) {
       EClassifier type = feature.getEType();
       if (type instanceof EEnum) {
         if (!isFirst) {
           out.print(COMMA);
         }
         writeEnum(out, object, feature);
         isFirst = false;
       } else if (type instanceof EClass) {
         if (!isInverse(feature)) {
           if (!isFirst) {
             out.print(COMMA);
           }
           writeEClass(out, object, feature);
           isFirst = false;
         }
       } else if (type instanceof EDataType) {
         if (!isFirst) {
           out.print(COMMA);
         }
         writeEDataType(out, object, feature);
         isFirst = false;
       }
     }
   }
   out.println(PAREN_CLOSE_SEMICOLON);
 }
  public void cacheClassifierInitExp(EClass clazz) {
    Map<EStructuralFeature, OCLExpression<EClassifier>> clsFeatures =
        myClassifierInitializations.get(clazz);
    if (clsFeatures == null) {
      // Remark: follow the declaration order during feature
      // initialization
      clsFeatures = new LinkedHashMap<EStructuralFeature, OCLExpression<EClassifier>>(2);
      myClassifierInitializations.put(clazz, clsFeatures);
    }

    for (EStructuralFeature next : clazz.getEAllStructuralFeatures()) {
      OCLExpression<EClassifier> initExp = QvtOperationalParserUtil.getInitExpression(next);
      if (initExp != null) {
        clsFeatures.put(next, initExp);
      }
    }
  }
Example #8
0
 /**
  * Return the ValidatableNode node for EObject creating any ValidatableNodes that are required to
  * ensure that the returned ValidatableNode is installed in the root.
  */
 protected @NonNull ValidatableNode getValidatableNode(@NonNull EObject eObject) {
   ValidatableNode validatable = allValidatableNodes.get(eObject);
   if (validatable == null) {
     EObject eContainer = eObject.eContainer();
     if (eContainer != null) {
       //				ValidatableNode parentValidatableNode = getValidatableNode(eContainer);
       //				parentValidatableNode.getChildren().add(validatable);
     } else if (eObject instanceof DynamicEObjectImpl) {
       EClass eClass = eObject.eClass();
       for (EStructuralFeature eStructuralFeature : eClass.getEAllStructuralFeatures()) {
         String featureName = eStructuralFeature.getName();
         if ((featureName != null)
             && featureName.startsWith(
                 "base_") // org.eclipse.uml2.uml.Extension.METACLASS_ROLE_PREFIX)
             && (eStructuralFeature instanceof EReference)
             && eObject.eIsSet(
                 eStructuralFeature)) { // Unset for an applicable stereotype that has not been
           // applied
           eContainer = (EObject) eObject.eGet(eStructuralFeature);
           break;
         }
       }
     }
     if (eContainer != null) {
       validatable = createValidatableNode();
       ValidatableNode parentValidatableNode = getValidatableNode(eContainer);
       parentValidatableNode.getChildren().add(validatable);
     } else {
       RootValidatableNode rootValidatableNode = createRootValidatableNode();
       rootNode.getValidatableNodes().add(rootValidatableNode);
       validatable = rootValidatableNode;
     }
     validatable.setEnabled(true);
     validatable.setLabel(validityManager.getLabel(eObject));
     validatable.setConstrainedObject(eObject);
     allValidatableNodes.put(eObject, validatable);
   }
   return validatable;
 }
 private int estimateBufferSize(EClass eClass) {
   int size = 0;
   for (EStructuralFeature eStructuralFeature : eClass.getEAllStructuralFeatures()) {
     if (eStructuralFeature instanceof EAttribute) {
       EAttribute eAttribute = (EAttribute) eStructuralFeature;
       if (eAttribute.isMany()) {
         size +=
             2 + AVERAGE_PRIMITIVE_LIST_SIZE * getPrimitiveSize((EDataType) eAttribute.getEType());
       } else {
         size += getPrimitiveSize((EDataType) eAttribute.getEType());
       }
     } else if (eStructuralFeature instanceof EReference) {
       EReference eReference = (EReference) eStructuralFeature;
       if (eReference.isMany()) {
         size += 2 + AVERAGE_REFERENCE_LIST_SIZE * 10;
       } else {
         size += 10;
       }
     }
   }
   return size;
 }
Example #10
0
  public EObject getStaticInstance() {
    if (null == staticObj) {
      EClass eClass = eClass();
      if (eClass.isAbstract()) {
        throw new IllegalArgumentException(
            "Cannot create an instance of the abstract type: " + eClass.getName());
      }
      staticObj = eClass.getEPackage().getEFactoryInstance().create(eClass);

      //            System.out.println("New static instance: " + staticObj.hashCode() + " of type "
      // + eClass.getName());

      // Copy over all property values
      EPropertiesHolder props = eProperties();
      if (props.getEClass() != null && props.hasSettings()) {
        List features = eClass.getEAllStructuralFeatures();
        for (Iterator itr = features.iterator(); itr.hasNext(); ) {
          EStructuralFeature feature = (EStructuralFeature) itr.next();

          staticObj.eSet(feature, eGet(feature));
          //                    System.out.println("    F: " + feature.getName());
        }
      }

      // Update all external references
      for (Iterator itr = actions.iterator(); itr.hasNext(); ) {
        Action action = (Action) itr.next();
        action.doIt(staticObj);
      }

      // Update containing resource
      //            List contents = eResource().getContents();
      //            contents.remove(this);
      //            contents.add(staticObj);
    }

    return staticObj;
  }
  public void resolve(
      String identifier,
      org.emftext.language.petrinets.Setting container,
      org.eclipse.emf.ecore.EReference reference,
      int position,
      boolean resolveFuzzy,
      final org.emftext.language.petrinets.resource.petrinets.IPetrinetsReferenceResolveResult<
              org.eclipse.emf.ecore.EStructuralFeature>
          result) {
    EClassifier type;
    if (container.eContainer() instanceof ProducingArc) {
      ProducingArc arc = (ProducingArc) container.eContainer();
      type = FunctionCallAnalysisHelper.getInstance().getType(arc.getOutput());
    } else {
      ConstructorCall cc = (ConstructorCall) container.eContainer();
      type = cc.getType();
    }

    List<EStructuralFeature> candidates = new ArrayList<EStructuralFeature>();
    if (type != null && type instanceof EClass) {
      EClass c = (EClass) type;
      candidates.addAll(c.getEAllStructuralFeatures());
    } else if (type instanceof EDataType) {
      EAttribute dummy = EcoreFactory.eINSTANCE.createEAttribute();
      dummy.setName(type.getName());
      dummy.setEType(type);
      dummy.setUpperBound(1);
      dummy.setLowerBound(1);
      candidates.add(dummy);
    }
    for (EStructuralFeature eStructuralFeature : candidates) {
      if (resolveFuzzy) {
        result.addMapping(eStructuralFeature.getName(), eStructuralFeature);
      } else if (identifier.equals(eStructuralFeature.getName())) {
        result.addMapping(eStructuralFeature.getName(), eStructuralFeature);
      }
    }
  }
    @Override
    public String lookup(String key) {
      String[] formatParts = key.split(",");
      String[] parts = formatParts[0].split("\\.");

      Object value = elements[Integer.parseInt(parts[0])];

      if (value instanceof EObject && parts.length > 1) {
        EClass eClass = ((EObject) value).eClass();
        for (int i = 1; i < parts.length; i++) {
          for (EStructuralFeature feature : eClass.getEAllStructuralFeatures()) {
            if (feature.getName().equals(parts[i])) {
              value = ((EObject) value).eGet(feature);
              break;
            }
          }

          if (value instanceof EObject) {
            eClass = ((EObject) value).eClass();
          } else {
            break;
          }
        }
      }

      if (formatParts.length > 1) {
        String formatString = "{0";
        formatString += "," + formatParts[1];

        if (formatParts.length > 2) {
          formatString += "," + formatParts[2];
        }
        formatString += "}";
        return MessageFormat.format(formatString, value);
      }

      return value != null ? value.toString() : "";
    }
Example #13
0
 public void generateBodyAnnotations(final XPackage pack) {
   final HashSet<ETypedElement> processed = CollectionLiterals.<ETypedElement>newHashSet();
   EList<XClassifier> _classifiers = pack.getClassifiers();
   for (final XClassifier xClassifier : _classifiers) {
     if ((xClassifier instanceof XDataType)) {
       final XDataType xDataType = ((XDataType) xClassifier);
       XDataTypeMapping _mapping = this.mappings.getMapping(xDataType);
       final EDataType eDataType = _mapping.getEDataType();
       final XBlockExpression createBody = xDataType.getCreateBody();
       XDataTypeMapping _mapping_1 = this.mappings.getMapping(xDataType);
       final JvmOperation creator = _mapping_1.getCreator();
       boolean _and = false;
       boolean _notEquals = (!Objects.equal(createBody, null));
       if (!_notEquals) {
         _and = false;
       } else {
         boolean _notEquals_1 = (!Objects.equal(creator, null));
         _and = (_notEquals && _notEquals_1);
       }
       if (_and) {
         final XcoreAppendable appendable = this.createAppendable();
         EList<JvmFormalParameter> _parameters = creator.getParameters();
         JvmFormalParameter _get = _parameters.get(0);
         appendable.declareVariable(_get, "it");
         JvmTypeReference _returnType = creator.getReturnType();
         Set<JvmTypeReference> _emptySet = Collections.<JvmTypeReference>emptySet();
         this.compiler.compile(createBody, appendable, _returnType, _emptySet);
         String _string = appendable.toString();
         String _extractBody = this.extractBody(_string);
         EcoreUtil.setAnnotation(eDataType, GenModelPackage.eNS_URI, "create", _extractBody);
       }
       final XBlockExpression convertBody = xDataType.getConvertBody();
       XDataTypeMapping _mapping_2 = this.mappings.getMapping(xDataType);
       final JvmOperation converter = _mapping_2.getConverter();
       boolean _and_1 = false;
       boolean _notEquals_2 = (!Objects.equal(convertBody, null));
       if (!_notEquals_2) {
         _and_1 = false;
       } else {
         boolean _notEquals_3 = (!Objects.equal(converter, null));
         _and_1 = (_notEquals_2 && _notEquals_3);
       }
       if (_and_1) {
         final XcoreAppendable appendable_1 = this.createAppendable();
         EList<JvmFormalParameter> _parameters_1 = converter.getParameters();
         JvmFormalParameter _get_1 = _parameters_1.get(0);
         appendable_1.declareVariable(_get_1, "it");
         JvmTypeReference _returnType_1 = converter.getReturnType();
         Set<JvmTypeReference> _emptySet_1 = Collections.<JvmTypeReference>emptySet();
         this.compiler.compile(convertBody, appendable_1, _returnType_1, _emptySet_1);
         String _string_1 = appendable_1.toString();
         String _extractBody_1 = this.extractBody(_string_1);
         EcoreUtil.setAnnotation(eDataType, GenModelPackage.eNS_URI, "convert", _extractBody_1);
       }
     } else {
       final XClass xClass = ((XClass) xClassifier);
       XClassMapping _mapping_3 = this.mappings.getMapping(xClass);
       final EClass eClass = _mapping_3.getEClass();
       EList<EStructuralFeature> _eAllStructuralFeatures = eClass.getEAllStructuralFeatures();
       for (final EStructuralFeature eStructuralFeature : _eAllStructuralFeatures) {
         boolean _add = processed.add(eStructuralFeature);
         if (_add) {
           final XStructuralFeature xFeature = this.mappings.getXFeature(eStructuralFeature);
           boolean _notEquals_4 = (!Objects.equal(xFeature, null));
           if (_notEquals_4) {
             final XBlockExpression getBody = xFeature.getGetBody();
             boolean _notEquals_5 = (!Objects.equal(getBody, null));
             if (_notEquals_5) {
               XFeatureMapping _mapping_4 = this.mappings.getMapping(xFeature);
               final JvmOperation getter = _mapping_4.getGetter();
               final XcoreAppendable appendable_2 = this.createAppendable();
               JvmTypeReference _returnType_2 = getter.getReturnType();
               Set<JvmTypeReference> _emptySet_2 = Collections.<JvmTypeReference>emptySet();
               this.compiler.compile(getBody, appendable_2, _returnType_2, _emptySet_2);
               String _string_2 = appendable_2.toString();
               String _extractBody_2 = this.extractBody(_string_2);
               EcoreUtil.setAnnotation(
                   eStructuralFeature, GenModelPackage.eNS_URI, "get", _extractBody_2);
             }
           }
         }
       }
       EList<EOperation> _eAllOperations = eClass.getEAllOperations();
       for (final EOperation eOperation : _eAllOperations) {
         boolean _add_1 = processed.add(eOperation);
         if (_add_1) {
           final XOperation xOperation = this.mappings.getXOperation(eOperation);
           boolean _notEquals_6 = (!Objects.equal(xOperation, null));
           if (_notEquals_6) {
             final XBlockExpression body = xOperation.getBody();
             boolean _notEquals_7 = (!Objects.equal(body, null));
             if (_notEquals_7) {
               XOperationMapping _mapping_5 = this.mappings.getMapping(xOperation);
               final JvmOperation jvmOperation = _mapping_5.getJvmOperation();
               boolean _notEquals_8 = (!Objects.equal(jvmOperation, null));
               if (_notEquals_8) {
                 final XcoreAppendable appendable_3 = this.createAppendable();
                 JvmDeclaredType _declaringType = jvmOperation.getDeclaringType();
                 appendable_3.declareVariable(_declaringType, "this");
                 JvmDeclaredType _declaringType_1 = jvmOperation.getDeclaringType();
                 EList<JvmTypeReference> _superTypes = _declaringType_1.getSuperTypes();
                 final JvmTypeReference superType =
                     IterableExtensions.<JvmTypeReference>head(_superTypes);
                 boolean _notEquals_9 = (!Objects.equal(superType, null));
                 if (_notEquals_9) {
                   JvmType _type = superType.getType();
                   appendable_3.declareVariable(_type, "super");
                 }
                 EList<JvmFormalParameter> _parameters_2 = jvmOperation.getParameters();
                 for (final JvmFormalParameter parameter : _parameters_2) {
                   String _name = parameter.getName();
                   appendable_3.declareVariable(parameter, _name);
                 }
                 JvmTypeReference _returnType_3 = jvmOperation.getReturnType();
                 EList<JvmTypeReference> _exceptions = jvmOperation.getExceptions();
                 HashSet<JvmTypeReference> _hashSet = new HashSet<JvmTypeReference>(_exceptions);
                 this.compiler.compile(body, appendable_3, _returnType_3, _hashSet);
                 String _string_3 = appendable_3.toString();
                 String _extractBody_3 = this.extractBody(_string_3);
                 EcoreUtil.setAnnotation(
                     eOperation, GenModelPackage.eNS_URI, "body", _extractBody_3);
               }
             }
           }
         }
       }
     }
   }
 }