Example #1
0
  public void DealGeneralization(org.eclipse.uml2.uml.Generalization gen1) {
    System.out.print("[Generalization]: ");
    RefOntoUML.Generalization gen2 = myfactory.createGeneralization();

    // source (Specific)
    org.eclipse.uml2.uml.Classifier e1 = gen1.getSpecific();
    RefOntoUML.Classifier e2 = (RefOntoUML.Classifier) GetElement(e1);
    System.out.print(e1.getName() + " -> ");

    // Poderia ter setado apenas um dos dois (Generalization::Specific, Classifier::Generalization),
    // ja que sao EOpposites
    gen2.setSpecific(e2);
    // O Specific tem posse do generalization
    e2.getGeneralization().add(gen2);

    // target (General)
    e1 = gen1.getGeneral();
    e2 = (RefOntoUML.Classifier) GetElement(e1);
    System.out.println(e1.getName());

    gen2.setGeneral(e2);

    // Important for GeneralizationSet
    RelateElements(gen1, gen2);
  }
Example #2
0
 /**
  * Tests if the node is an inherited element
  *
  * @param node a node
  * @return <code>true</code> if the node is an inherited element <code>false</code> if not
  */
 protected boolean isInherited(Node node) {
   EObject element = node.getElement();
   if (element instanceof Element) {
     EObject container = node.eContainer();
     EObject graphicalParent = null;
     if (container instanceof DecorationNode) {
       graphicalParent = ((DecorationNode) container).getElement();
     } else if (container instanceof View) {
       graphicalParent = ((View) container).getElement();
     }
     if (graphicalParent instanceof Property || graphicalParent instanceof Classifier) {
       Classifier classifier = null;
       if (graphicalParent instanceof Property) {
         Type type = ((Property) graphicalParent).getType();
         if (type instanceof Classifier) {
           classifier = (Classifier) type;
         }
       } else {
         classifier = (Classifier) graphicalParent;
       }
       if (classifier != null) {
         EList<NamedElement> inheritedMembers = classifier.getInheritedMembers();
         return inheritedMembers.contains(element);
       }
     }
   }
   return false;
 }
 private String getTargetLanguage(InstanceSpecification mainInstance) {
   Classifier cl = DepUtils.getClassifier(mainInstance);
   String targetLanguage = DepUtils.getLanguageFromPackage(cl.getNearestPackage());
   if (targetLanguage == null) {
     targetLanguage = "C++"; // $NON-NLS-1$
   }
   return targetLanguage;
 }
 /**
  *
  * <!-- begin-user-doc -->
  * <!-- end-user-doc -->
  *
  * @generated
  */
 public Classifier getRedefinitionContext(String name, boolean ignoreCase, EClass eClass) {
   redefinitionContextLoop:
   for (Classifier redefinitionContext : getRedefinitionContexts()) {
     if (eClass != null && !eClass.isInstance(redefinitionContext))
       continue redefinitionContextLoop;
     if (name != null
         && !(ignoreCase
             ? name.equalsIgnoreCase(redefinitionContext.getName())
             : name.equals(redefinitionContext.getName()))) continue redefinitionContextLoop;
     return redefinitionContext;
   }
   return null;
 }
 /**
  * @see
  *     org.eclipse.umlgen.reverse.c.CModelChangedEvent#notifyChanges(org.eclipse.umlgen.reverse.c.resource.ModelManager)
  */
 @Override
 public void notifyChanges(ModelManager manager) {
   Classifier matchingClassifier =
       ModelUtil.findClassifierInPackage(manager.getSourcePackage(), getUnitName());
   Classifier localType = ModelUtil.findDataTypeInClassifier(matchingClassifier, getCurrentName());
   if (localType != null) {
     if (ModelUtil.isRemovable(localType)) {
       DiagramUtil.removeGraphicalRepresentation(localType, manager);
       localType.destroy();
     } else {
       ModelUtil.setVisibility(localType, getTranslationUnit(), EventType.REMOVE);
     }
   }
 }
Example #6
0
 public void DealClassifier(org.eclipse.uml2.uml.Classifier c1, RefOntoUML.Classifier c2) {
   DealNamedElement(c1, c2);
   // Important for Generalization, Property
   RelateElements(c1, c2);
   // isAbstract
   c2.setIsAbstract(c1.isAbstract());
 }
 /** Finds an operation in the given classifier. */
 public static Operation findOperation(
     IRepository repository,
     Classifier classifier,
     String operationName,
     List<TypedElement> arguments,
     ParameterSubstitutionMap substitutions,
     boolean ignoreCase,
     boolean recurse) {
   for (Operation operation : classifier.getOperations()) {
     if (isMatch(operation, operationName, ignoreCase)
         && (arguments == null || isMatch(repository, operation, arguments, substitutions)))
       return operation;
   }
   if (!recurse) return null;
   Operation found;
   final EList<TemplateBinding> templateBindings = classifier.getTemplateBindings();
   if (!templateBindings.isEmpty())
     for (TemplateBinding templateBinding : templateBindings) {
       TemplateSignature signature = templateBinding.getSignature();
       ParameterSubstitutionMap newSubstitutions = new ParameterSubstitutionMap(templateBinding);
       found =
           findOperation(
               repository,
               (Classifier) signature.getTemplate(),
               operationName,
               arguments,
               newSubstitutions,
               ignoreCase,
               true);
       if (found != null) return found;
     }
   for (Generalization generalization : classifier.getGeneralizations())
     if ((found =
             findOperation(
                 repository,
                 generalization.getGeneral(),
                 operationName,
                 arguments,
                 substitutions,
                 ignoreCase,
                 true))
         != null) return found;
   return null;
 }
 public static Property findAttribute(
     Classifier classifier, String attributeIdentifier, boolean ignoreCase, boolean recurse) {
   Property found = classifier.getAttribute(attributeIdentifier, null, ignoreCase, null);
   if (found != null || !recurse) return found;
   final EList<TemplateBinding> templateBindings = classifier.getTemplateBindings();
   if (!templateBindings.isEmpty()) {
     for (TemplateBinding templateBinding : templateBindings) {
       TemplateSignature signature = templateBinding.getSignature();
       found =
           findAttribute(
               (Classifier) signature.getTemplate(), attributeIdentifier, ignoreCase, true);
       if (found != null) return found;
     }
   }
   for (Generalization generalization : classifier.getGeneralizations())
     if ((found =
             findAttribute(generalization.getGeneral(), attributeIdentifier, ignoreCase, true))
         != null) return found;
   return null;
 }
  public String getPrintString(IAdaptable element, int flags) {
    if (element instanceof EObjectAdapter) {
      final TemplateParameter templateParam =
          ((TemplateParameter) ((EObjectAdapter) element).getRealObject());
      if (templateParam.getOwnedParameteredElement() == null) {
        return "<UNDEFINED>";
      }
      String out = "";
      if (templateParam.getOwnedParameteredElement() instanceof Classifier) {
        Classifier namedElement = (Classifier) templateParam.getOwnedParameteredElement();
        out = out + namedElement.getName() + ": " + namedElement.eClass().getName();
      }
      if (templateParam instanceof ClassifierTemplateParameter) {
        if (!((ClassifierTemplateParameter) templateParam).getConstrainingClassifiers().isEmpty()) {
          out = out + ">";
          for (int i = 0;
              i < ((ClassifierTemplateParameter) templateParam).getConstrainingClassifiers().size();
              i++) {
            out =
                out
                    + ((ClassifierTemplateParameter) templateParam)
                        .getConstrainingClassifiers()
                        .get(i)
                        .getName();
            if (i
                < ((ClassifierTemplateParameter) templateParam).getConstrainingClassifiers().size()
                    - 1) {
              out = out + ", ";
            }
          }
        }
      }
      return out;
    }

    return "<UNDEFINED>";
  }
 /**
  * Provides custom completion for the specifying the type of a property
  *
  * @see
  *     org.eclipse.papyrus.uml.textedit.property.xtext.ui.contentassist.AbstractUmlPropertyProposalProvider#completePropertyRule_Type(org.eclipse.emf.ecore.EObject,
  *     org.eclipse.xtext.Assignment,
  *     org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext,
  *     org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor)
  */
 @Override
 public void completePortRule_Type(
     EObject model,
     Assignment assignment,
     ContentAssistContext context,
     ICompletionProposalAcceptor acceptor) {
   List<Classifier> allClassifiers = new ArrayList<Classifier>();
   Namespace namespace =
       (Namespace)
           EcoreUtil.getRootContainer(ContextElementUtil.getContextElement(model.eResource()));
   allClassifiers.addAll(getRecursivelyOwnedClassifiers(namespace));
   allClassifiers.addAll(getRecursivelyImportedClassifiers(namespace));
   for (Classifier c : allClassifiers) {
     if (c.getQualifiedName().toLowerCase().contains(context.getPrefix().toLowerCase())) {
       String displayString = c.getQualifiedName();
       String completionString =
           CompletionProposalUtils.getQualifiedNameLabelWithSufficientDepth(c, namespace);
       ICompletionProposal completionProposal =
           CompletionProposalUtils.createCompletionProposalWithReplacementOfPrefix(
               c, completionString, displayString, context);
       acceptor.accept(completionProposal);
     }
   }
 }
  public SignatureFacade createConstructorFacade(InstanceCreationExpression exp) throws Exception {
    List<TypeExpression> arguments = new ArrayList<TypeExpression>();
    Map<String, TypeExpression> argumentsMap = new HashMap<String, TypeExpression>();

    if (exp.getTuple().getInstanceCreationTupleElement() != null) {
      for (InstanceCreationTupleElement tupleElement :
          exp.getTuple().getInstanceCreationTupleElement()) {
        TypeExpression typeOfArgument =
            new TypeUtils().getTypeOfExpression(tupleElement.getObject());
        if (typeOfArgument.getTypeFacade() instanceof ErrorTypeFacade)
          throw new TypeInferenceException(typeOfArgument);
        arguments.add(typeOfArgument);
        argumentsMap.put(tupleElement.getRole(), typeOfArgument);
      }
    }

    // first try to determine if the expression directly refers to a Class or a DataType
    TypeFacade cddClassifier = TypeFacadeFactory.eInstance.createVoidFacade(exp.getConstructor());
    boolean errorInResolutionOfClassifier = false;
    if (cddClassifier instanceof ErrorTypeFacade) {
      errorInResolutionOfClassifier = true;
    } else {
      Classifier referencedType = cddClassifier.extractActualType();
      if (referencedType instanceof PrimitiveType) {
        throw new Exception("Constructor invocations do not apply to primitive types");
      }
      if (referencedType instanceof Enumeration) {
        throw new Exception("Constructor invocations do not apply to enumerations");
      }
      if (referencedType.isAbstract()) {
        throw new Exception("Abstract classifiers cannot be instantiated");
      }

      // The classifier has been resolved. Must determine if arguments match with possible
      // constructors
      if (referencedType instanceof org.eclipse.uml2.uml.Class) {
        List<EObject> visibleConstructor =
            AlfScopeProvider.scopingTool
                .getVisibleOperationsOrBehaviors(referencedType)
                .resolveByName(referencedType.getName());
        if (visibleConstructor.size() > 1) {
          // try to match with arguments
          // if does not match, raise an exception
          List<SignatureFacade> visibleConstructorSignatures = new ArrayList<SignatureFacade>();
          for (EObject cddConstructor : visibleConstructor) {
            SignatureFacade cddConstructorSignature =
                SignatureFacadeFactory.eInstance.createSignatureFacade(cddConstructor);
            if (cddConstructorSignature.isAConstructor())
              visibleConstructorSignatures.add(cddConstructorSignature);
          }
          List<SignatureFacade> matchingSignatures =
              SignatureFacade.findNearestSignature(arguments, visibleConstructorSignatures);
          if (matchingSignatures.size() > 1) {
            String errorMessage = referencedType.getName() + "(";
            boolean first = true;
            for (TypeExpression arg : arguments) {
              if (first) first = false;
              else errorMessage += ", ";
              errorMessage += arg.getLabel();
            }
            errorMessage += ") resolves to multiple constructors";
            throw new Exception(errorMessage);
          } else if (matchingSignatures.size() == 0) {
            String errorMessage = "Constructor " + referencedType.getName() + "(";
            boolean first = true;
            for (TypeExpression arg : arguments) {
              if (first) first = false;
              else errorMessage += ", ";
              errorMessage += arg.getLabel();
            }
            errorMessage += ") is undefined";
            throw new Exception(errorMessage);
          } else { // exactly one match
            return matchingSignatures.get(0);
          }
        } else if (visibleConstructor.size() == 0) {
          if (arguments.size() > 0) {
            // Throw an exception
            String errorMessage = "Constructor " + referencedType.getName() + "(";
            boolean first = true;
            for (TypeExpression t : arguments) {
              if (first) first = false;
              else errorMessage += ", ";
              errorMessage += t.getLabel();
            }
            errorMessage += ") is undefined";
            throw new Exception(errorMessage);
          }
          return new DefaultConstructorFacade((Class) referencedType);
        } else { // exactly one constructor found
          // Tries to determine if arguments match
          SignatureFacade constructor = createSignatureFacade(visibleConstructor.get(0));
          if (!constructor.isAConstructor()) {
            // Throw an exception
            String errorMessage = "Constructor " + referencedType.getName() + "(";
            boolean first = true;
            for (TypeExpression t : arguments) {
              if (first) first = false;
              else errorMessage += ", ";
              errorMessage += t.getLabel();
            }
            errorMessage += ") is undefined";
            throw new Exception(errorMessage);
          }
          String potentialErrorMessage = constructor.isCompatibleWithMe(argumentsMap);
          if (potentialErrorMessage.length() == 0) return constructor;
          else throw new Exception(potentialErrorMessage);
        }
      } else if (referencedType instanceof DataType) { // This is a data type.
        // must match arguments with visible properties of the data type
        SignatureFacade defaultDataTypeConstructor =
            new DefaultConstructorFacade((DataType) referencedType);
        String errorMessage = defaultDataTypeConstructor.isCompatibleWithMe(argumentsMap);
        if (!(errorMessage.length() == 0)) throw new Exception(errorMessage);
        else return defaultDataTypeConstructor;
      }
    }

    if (errorInResolutionOfClassifier) {
      // We can try again, but considering that:
      // - the last element in the qualified name as the name of a constructor
      // - the element before the last element is a class name

      if (exp.getConstructor().getRemaining() == null)
        throw new Exception("Constructor " + exp.getConstructor().getId() + " is undefined");

      QualifiedNameWithBinding remaining = exp.getConstructor();
      QualifiedNameWithBinding cddClassName = exp.getConstructor();
      QualifiedNameWithBinding cddConstructorName = exp.getConstructor();
      EObject previousPackage = null;

      while (cddConstructorName.getRemaining() != null) {
        cddClassName = cddConstructorName;
        cddConstructorName = cddConstructorName.getRemaining();
      }

      if (remaining != cddClassName) {
        List<EObject> visiblePackages =
            AlfScopeProvider.scopingTool.getVisiblePackages(exp).resolveByName(remaining.getId());
        if (visiblePackages.isEmpty()) {
          throw new Exception("Could not resolve package " + remaining.getId());
        } else if (visiblePackages.size() > 1) {
          throw new Exception(remaining.getId() + " resolves to multiple packages");
        } else {
          List<EObject> nestedVisiblePackages;
          previousPackage = visiblePackages.get(0);
          remaining = remaining.getRemaining();
          while (remaining != cddClassName) {
            nestedVisiblePackages =
                AlfScopeProvider.scopingTool
                    .getVisiblePackages(previousPackage)
                    .resolveByName(remaining.getId());
            if (nestedVisiblePackages.isEmpty()) {
              throw new Exception("Could not resolve package " + remaining.getId());
            } else if (nestedVisiblePackages.size() > 1) {
              throw new Exception(remaining.getId() + " resolves to multiple packages");
            }
            previousPackage = nestedVisiblePackages.get(0);
            remaining = remaining.getRemaining();
          }
        }
      }

      // At this point, the (potential) path has been validated
      // cddClassName should resolve to a classifier
      List<EObject> visibleClassifiers = null;
      EObject resolvedClassifier = null;
      if (previousPackage != null)
        visibleClassifiers =
            AlfScopeProvider.scopingTool
                .getVisibleClassifiers(previousPackage)
                .resolveByName(cddClassName.getId());
      else
        visibleClassifiers =
            AlfScopeProvider.scopingTool
                .getVisibleClassifiers(exp)
                .resolveByName(cddClassName.getId());
      if (visibleClassifiers.isEmpty()) {
        throw new Exception("Could not resolve classifier " + cddClassName.getId());
      } else if (visibleClassifiers.size() > 1) {
        throw new Exception(remaining.getId() + " resolves to multiple classifiers.");
      } else {
        resolvedClassifier = visibleClassifiers.get(0);
      }
      List<EObject> visibleConstructor =
          AlfScopeProvider.scopingTool
              .getVisibleOperationsOrBehaviors(resolvedClassifier)
              .resolveByName(cddConstructorName.getId());
      if (visibleConstructor.size() > 1) {
        // try to match with arguments
        // if does not match, raise an exception
        List<SignatureFacade> visibleConstructorSignatures = new ArrayList<SignatureFacade>();
        for (EObject cddConstructor : visibleConstructor) {
          SignatureFacade cddConstructorSignature =
              SignatureFacadeFactory.eInstance.createSignatureFacade(cddConstructor);
          if (cddConstructorSignature.isAConstructor())
            visibleConstructorSignatures.add(cddConstructorSignature);
        }
        List<SignatureFacade> matchingSignatures =
            SignatureFacade.findNearestSignature(arguments, visibleConstructorSignatures);
        if (matchingSignatures.size() > 1) {
          String errorMessage = cddConstructorName.getId() + "(";
          boolean first = true;
          for (TypeExpression arg : arguments) {
            if (first) first = false;
            else errorMessage += ", ";
            errorMessage += arg.getLabel();
          }
          errorMessage += ") resolves to multiple constructors";
          throw new Exception(errorMessage);
        } else if (matchingSignatures.size() == 0) {
          String errorMessage = "Constructor " + cddConstructorName.getId() + "(";
          boolean first = true;
          for (TypeExpression arg : arguments) {
            if (first) first = false;
            else errorMessage += ", ";
            errorMessage += arg.getLabel();
          }
          errorMessage += ") is undefined";
          throw new Exception(errorMessage);
        } else { // exactly one match
          return matchingSignatures.get(0);
        }
      } else if (visibleConstructor.size() == 0) {
        String errorMessage = "Constructor " + cddConstructorName.getId() + "(";
        boolean first = true;
        for (TypeExpression arg : arguments) {
          if (first) first = false;
          else errorMessage += ", ";
          errorMessage += arg.getLabel();
        }
        errorMessage += ") is undefined";
        throw new Exception(errorMessage);
      } else { // exactly one constructor
        // Tries to determine if arguments match
        SignatureFacade constructor = createSignatureFacade(visibleConstructor.get(0));
        if (!constructor.isAConstructor()) {
          // Throw an exception
          String errorMessage = "Constructor " + cddConstructorName.getId() + "(";
          boolean first = true;
          for (TypeExpression t : arguments) {
            if (first) first = false;
            else errorMessage += ", ";
            errorMessage += t.getLabel();
          }
          errorMessage += ") is undefined";
          throw new Exception(errorMessage);
        }
        String potentialErrorMessage = constructor.isCompatibleWithMe(arguments, true);
        if (potentialErrorMessage.length() == 0) return constructor;
        else throw new Exception(potentialErrorMessage);
      }
    }

    throw new Exception("Not supported case");
  }
Example #12
0
 public void ProcessGeneralizations(org.eclipse.uml2.uml.Classifier c1) {
   // Generalizations
   for (org.eclipse.uml2.uml.Generalization gen : c1.getGeneralizations()) {
     DealGeneralization(gen);
   }
 }
Example #13
0
 public void createGeneralization(Classifier special, Classifier general) {
   special.createGeneralization(general);
 }
  /**
   * Returns the string representing the import block for a given classifier.
   *
   * @param aClassifier The classifier
   * @return The string representing the import block for a given classifier.
   */
  public String reqImport(Classifier aClassifier) {
    Set<String> importedTypes = new LinkedHashSet<String>();

    List<Property> attributes = aClassifier.getAttributes();
    for (Property property : attributes) {
      String qualifiedName = this.qualifiedName(property.getType());
      if (qualifiedName != null) {
        importedTypes.add(qualifiedName);
      }
      if (property.getUpper() != 1) {
        String collectionQualifiedName =
            this.collectionQualifiedName(aClassifier, property.isOrdered(), property.isUnique());
        if (collectionQualifiedName != null) {
          importedTypes.add(collectionQualifiedName);
        }
      }
    }

    List<Operation> operations = aClassifier.getOperations();
    for (Operation operation : operations) {
      String qualifiedName = this.qualifiedName(operation.getType());
      if (qualifiedName != null) {
        importedTypes.add(qualifiedName);
      }
      if (operation.getUpper() != 1) {
        String collectionQualifiedName =
            this.collectionQualifiedName(aClassifier, operation.isOrdered(), operation.isUnique());
        if (collectionQualifiedName != null) {
          importedTypes.add(collectionQualifiedName);
        }
      }

      List<Parameter> ownedParameters = operation.getOwnedParameters();
      for (Parameter parameter : ownedParameters) {
        qualifiedName = this.qualifiedName(parameter.getType());
        if (qualifiedName != null) {
          importedTypes.add(qualifiedName);
        }
        if (parameter.getUpper() != 1) {
          String collectionQualifiedName =
              this.collectionQualifiedName(
                  aClassifier, parameter.isOrdered(), parameter.isUnique());
          if (collectionQualifiedName != null) {
            importedTypes.add(collectionQualifiedName);
          }
        }
      }

      List<Type> raisedExceptions = operation.getRaisedExceptions();
      for (Type type : raisedExceptions) {
        String exceptionQualifiedName = this.qualifiedName(type);
        if (exceptionQualifiedName != null) {
          importedTypes.add(exceptionQualifiedName);
        }
      }
    }

    List<String> sortedImportedTypes = new ArrayList<String>(importedTypes);
    Collections.sort(sortedImportedTypes);

    StringBuilder stringBuilder = new StringBuilder();
    for (String importedType : sortedImportedTypes) {
      stringBuilder.append(IMPORT + importedType + END_IMPORT);
    }

    return stringBuilder.toString();
  }
 public static List<Property> getSimpleAttributes(Classifier classifier) {
   List<Property> simpleAttributes = new ArrayList<Property>();
   for (Property current : classifier.getAllAttributes())
     if (current.getAssociation() == null) simpleAttributes.add(current);
   return simpleAttributes;
 }
 @Override
 public Value evaluate() {
   // If the instance specification is for an enumeration, then return the
   // identified enumeration literal.
   // If the instance specification is for a data type (but not a primitive
   // value or an enumeration), then create a data value of the given data
   // type.
   // If the instance specification is for an object, then create an object
   // at the current locus with the specified types.
   // Set each feature of the created value to the result of evaluating the
   // value specifications for the specified slot for the feature.
   // Debug.println("[evaluate] InstanceValueEvaluation...");
   InstanceSpecification instance = ((InstanceValue) this.specification).getInstance();
   // List<Classifier> types = instance.getClassifiers();
   // Classifier myType = types.get(0);
   // Debug.println("[evaluate] type = " + myType.getName());
   Value value;
   if (instance instanceof EnumerationLiteral) {
     // Debug.println("[evaluate] Type is an enumeration.");
     EnumerationValue enumerationValue = new EnumerationValue();
     // enumerationValue.type = (Enumeration)myType;
     enumerationValue.type = ((EnumerationLiteral) instance).getEnumeration(); // ADDED
     enumerationValue.literal = (EnumerationLiteral) instance;
     value = enumerationValue;
     Debug.println("[evaluate] type = " + enumerationValue.type.getName()); // ADDED
   } else {
     // ADDED:
     List<Classifier> types = instance.getClassifiers();
     Classifier myType = types.get(0);
     Debug.println("[evaluate] type = " + myType.getName());
     //
     StructuredValue structuredValue = null;
     if (myType instanceof DataType) {
       // Debug.println("[evaluate] Type is a data type.");
       DataValue dataValue = new DataValue();
       dataValue.type = (DataType) myType;
       structuredValue = dataValue;
     } else {
       Object_ object = null;
       if (myType instanceof Behavior) {
         // Debug.println("[evaluate] Type is a behavior.");
         object = this.locus.factory.createExecution((Behavior) myType, null);
       } else {
         // Debug.println("[evaluate] Type is a class.");
         object = new Object_();
         for (int i = 0; i < types.size(); i++) {
           Classifier type = types.get(i);
           object.types.add((Class) type);
         }
       }
       this.locus.add(object);
       Reference reference = new Reference();
       reference.referent = object;
       structuredValue = reference;
     }
     structuredValue.createFeatureValues();
     // Debug.println("[evaluate] " + instance.slot.size() +
     // " slot(s).");
     List<Slot> instanceSlots = instance.getSlots();
     for (int i = 0; i < instanceSlots.size(); i++) {
       Slot slot = instanceSlots.get(i);
       List<Value> values = new ArrayList<Value>();
       // Debug.println("[evaluate] feature = " +
       // slot.definingFeature.getName() + ", " + slot.value.size() +
       // " value(s).");
       List<ValueSpecification> slotValues = slot.getValues();
       for (int j = 0; j < slotValues.size(); j++) {
         ValueSpecification slotValue = slotValues.get(j);
         // Debug.println("[evaluate] Value = " +
         // slotValue.getClass().getName());
         values.add(this.locus.executor.evaluate(slotValue));
       }
       structuredValue.setFeatureValue(slot.getDefiningFeature(), values, 0);
     }
     value = structuredValue;
   }
   return value;
 }
  private void buildToJson(PropertyWrapper pWrap, OJAnnotatedClass annotatedClass, OJBlock block) {

    // This is very important to be a sorted set. The get and options method need to return the meta
    // data in the same order.
    // This allows the client to merge them easily

    SortedSet<Classifier> sortedConcreteImplementations =
        new TreeSet<Classifier>(
            new Comparator<Classifier>() {
              @Override
              public int compare(Classifier o1, Classifier o2) {
                return o1.getName().compareTo(o2.getName());
              }
            });

    // For derived unions only show tabs for each property that makes up the union.
    if (pWrap.isDerivedUnion()) {
      List<Property> subsettingProperties =
          ModelLoader.INSTANCE.findSubsettingProperties(pWrap.getProperty());
      for (Property subsettingProperty : subsettingProperties) {
        sortedConcreteImplementations.addAll(
            UmlgClassOperations.getConcreteImplementations(
                (Classifier) subsettingProperty.getType()));
      }
    } else {
      // For non derived union show all concrete implementations
      sortedConcreteImplementations =
          UmlgClassOperations.getConcreteImplementations((Classifier) pWrap.getType());
    }

    Set<Classifier> concreteImplementationsFrom =
        UmlgClassOperations.getConcreteImplementations((Classifier) pWrap.getOwningType());
    if (!concreteImplementationsFrom.isEmpty()) {
      annotatedClass.addToImports(UmlgGenerationUtil.ToJsonUtil);
      // block get reassigned for the meta data if statement
      OJBlock returnBlock = block;
      block.addToStatements("StringBuilder json = new StringBuilder()");
      block.addToStatements("json.append(\"[\")");

      int count = 1;
      // For meta data, put where one is navigating to first, then where on is
      // navigating from
      // This is consistent with navigating to a entity with a vertex where
      // there is no navigating from.
      // i.e. the first meta data in the array is the entity navigating to.
      for (Classifier concreteClassifierTo : sortedConcreteImplementations) {
        annotatedClass.addToImports(UmlgClassOperations.getPathName(concreteClassifierTo));
        if (pWrap.isOne()) {
          block.addToStatements("json.append(\"{\\\"data\\\": \")");
        } else {
          block.addToStatements("json.append(\"{\\\"data\\\": [\")");
        }
        if (pWrap.isOne()) {
          OJIfStatement ifOneInstanceOf =
              new OJIfStatement(
                  "parentResource."
                      + pWrap.getter()
                      + "() != null && parentResource."
                      + pWrap.getter()
                      + "().getClass() == "
                      + UmlgClassOperations.getPathName(concreteClassifierTo).getLast()
                      + ".class");
          ifOneInstanceOf.addToThenPart(
              "json.append("
                  + UmlgGenerationUtil.ToJsonUtil.getLast()
                  + ".toJsonWithoutCompositeParent(parentResource."
                  + pWrap.getter()
                  + "()))");
          ifOneInstanceOf.addToElsePart("json.append(\"null\")");
          block.addToStatements(ifOneInstanceOf);
        } else {
          block.addToStatements(
              "json.append("
                  + UmlgGenerationUtil.ToJsonUtil.getLast()
                  + ".toJsonWithoutCompositeParent(parentResource."
                  + pWrap.getter()
                  + "().select(new "
                  + UmlgGenerationUtil.BooleanExpressionEvaluator.getCopy()
                      .addToGenerics(UmlgClassOperations.getPathName(pWrap.getType()))
                      .getLast()
                  + "() {\n			@Override\n			public Boolean evaluate("
                  + UmlgClassOperations.getPathName(pWrap.getType()).getLast()
                  + " e) {\n				return e.getClass() == "
                  + UmlgClassOperations.getPathName(concreteClassifierTo).getLast()
                  + ".class;\n			}\n		})))");
          annotatedClass.addToImports(UmlgGenerationUtil.BooleanExpressionEvaluator);
        }
        annotatedClass.addToImports(UmlgClassOperations.getPathName(pWrap.getType()));
        if (pWrap.isOne()) {
          block.addToStatements("json.append(\",\")");
        } else {
          block.addToStatements("json.append(\"],\")");
        }

        block.addToStatements("json.append(\" \\\"meta\\\" : {\")");
        block.addToStatements(
            "json.append(\"\\\"qualifiedName\\\": \\\"" + pWrap.getQualifiedName() + "\\\"\")");

        block.addToStatements(
            "json.append(\",\\\"qualifiedNameFrom\\\": \\\"\" + parentResource.getQualifiedName() + \"\\\"\")");
        block.addToStatements(
            "json.append(\",\\\"qualifiedNameTo\\\": \\\""
                + concreteClassifierTo.getQualifiedName()
                + "\\\"\")");

        block.addToStatements("json.append(\"}\")");
        if (sortedConcreteImplementations.size() != 1
            && count != sortedConcreteImplementations.size()) {
          block.addToStatements("json.append(\"}, \")");
        }
        block = returnBlock;
        count++;
      }
      returnBlock.addToStatements("json.append(\"}]\")");
      returnBlock.addToStatements(
          "return new "
              + UmlgRestletGenerationUtil.JsonRepresentation.getLast()
              + "(json.toString())");
    } else {
      // TODO not thought through
      block.addToStatements("return null");
    }
  }
Example #18
0
 public Property getAttribute(Classifier classifier, String name, Type type) {
   return classifier.getAttribute(name, type);
 }